text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use a 'with' statement instead of manual resource management strategy
# -*- coding: utf-8 -*- from __future__ import with_statement from setuptools import setup from urwid_stackedwidget import __version__ def readme(): with open('README.rst') as f: return f.read() setup( name='urwid-stackedwidget', version=__version__, license='MIT', author='Sumin Byeon', author_email='suminb@gmail.com', maintainer='', url='https://github.com/suminb/urwid-stackedwidget', description='A widget container that presents one child widget at a time.', long_description=readme(), platforms='any', py_modules=['urwid_stackedwidget'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: Public Domain', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Internet', 'Topic :: Software Development :: Libraries :: Python Modules'], install_requires=['urwid'], )
# -*- coding: utf-8 -*- from __future__ import with_statement from setuptools import setup from urwid_stackedwidget import __version__ def readme(): try: f = open('README.rst') content = f.read() f.close() return content except Exception: pass setup( name='urwid-stackedwidget', version=__version__, license='MIT', author='Sumin Byeon', author_email='suminb@gmail.com', maintainer='', url='https://github.com/suminb/urwid-stackedwidget', description='A widget container that presents one child widget at a time.', long_description=readme(), platforms='any', py_modules=['urwid_stackedwidget'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: Public Domain', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Internet', 'Topic :: Software Development :: Libraries :: Python Modules'], install_requires=['urwid'], )
Update atol on precision at k test.
import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) np.testing.assert_allclose(precision, expected, atol=1e-05)
import numpy as np import pytest import tensorflow as tf from tensorflow_similarity.retrieval_metrics import PrecisionAtK testdata = [ ( "micro", tf.constant(0.583333333), ), ( "macro", tf.constant(0.5), ), ] @pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"]) def test_compute(avg, expected): query_labels = tf.constant([1, 1, 1, 0]) match_mask = tf.constant( [ [True, True, False], [True, True, False], [True, True, False], [False, False, True], ], dtype=bool, ) rm = PrecisionAtK(k=3, average=avg) precision = rm.compute(query_labels=query_labels, match_mask=match_mask) np.testing.assert_allclose(precision, expected)
Fix declaring extra constants when `intl` is loaded
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Php54 as p; if (PHP_VERSION_ID >= 50400) { return; } if (!function_exists('trait_exists')) { function trait_exists($class, $autoload = true) { return $autoload && \class_exists($class, $autoload) && false; } } if (!function_exists('class_uses')) { function class_uses($class, $autoload = true) { if (\is_object($class) || \class_exists($class, $autoload) || \interface_exists($class, false)) { return array(); } return false; } } if (!function_exists('hex2bin')) { function hex2bin($data) { return p\Php54::hex2bin($data); } } if (!function_exists('session_register_shutdown')) { function session_register_shutdown() { register_shutdown_function('session_write_close'); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Php54 as p; if (PHP_VERSION_ID < 50400) { if (!function_exists('trait_exists')) { function trait_exists($class, $autoload = true) { return $autoload && \class_exists($class, $autoload) && false; } } if (!function_exists('class_uses')) { function class_uses($class, $autoload = true) { if (\is_object($class) || \class_exists($class, $autoload) || \interface_exists($class, false)) { return array(); } return false; } } if (!function_exists('hex2bin')) { function hex2bin($data) { return p\Php54::hex2bin($data); } } if (!function_exists('session_register_shutdown')) { function session_register_shutdown() { register_shutdown_function('session_write_close'); } } }
Change User ID to use the JSON (hex) representation throughout the site
var wompt = require("./includes"); function MetaUser(doc){ var me = this; this.clients = new wompt.ClientPool(); this.doc = doc; this.visible = !!doc; this.readonly = !doc; this.touch(); this.clients.on('added', function(client){ me.clients.broadcast({ action: 'new_client', channel: client.meta_data.channel.name },client); }); }; MetaUser.prototype.id = function(){ return this.doc ? this.doc._id.toJSON() : null; } MetaUser.prototype.touch = function(){ this.touched = new Date(); } MetaUser.prototype.authenticated = function(){ return !!this.doc; } MetaUser.prototype.new_session = function(session){ this.clients.broadcast({ action: 'new_session' }); } MetaUser.prototype.end_session = function(session){ this.clients.broadcast({ action: 'end_session' }); this.clients.each(function(client, index){ if(client.meta_data && client.meta_data.token == session.token) client._onDisconnect(); }); } module.exports = MetaUser
var wompt = require("./includes"); function MetaUser(doc){ var me = this; this.clients = new wompt.ClientPool(); this.doc = doc; this.visible = !!doc; this.readonly = !doc; this.touch(); this.clients.on('added', function(client){ me.clients.broadcast({ action: 'new_client', channel: client.meta_data.channel.name },client); }); }; MetaUser.prototype.id = function(){ return this.doc ? this.doc._id.toString() : null; } MetaUser.prototype.touch = function(){ this.touched = new Date(); } MetaUser.prototype.authenticated = function(){ return !!this.doc; } MetaUser.prototype.new_session = function(session){ this.clients.broadcast({ action: 'new_session' }); } MetaUser.prototype.end_session = function(session){ this.clients.broadcast({ action: 'end_session' }); this.clients.each(function(client, index){ if(client.meta_data && client.meta_data.token == session.token) client._onDisconnect(); }); } module.exports = MetaUser
Remove version 1.9.6 from test of PhanthomJS versions
/* * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package io.github.bonigarcia.wdm.test; import org.junit.Before; import io.github.bonigarcia.wdm.PhantomJsDriverManager; import io.github.bonigarcia.wdm.base.BaseVersionTst; /** * Test asserting PhatomJS versions. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.4.0 */ public class PhantomJsVersionTest extends BaseVersionTst { @Before public void setup() { browserManager = PhantomJsDriverManager.getInstance(); specificVersions = new String[] { "1.9.7", "1.9.8", "2.1.1" }; } }
/* * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package io.github.bonigarcia.wdm.test; import org.junit.Before; import io.github.bonigarcia.wdm.PhantomJsDriverManager; import io.github.bonigarcia.wdm.base.BaseVersionTst; /** * Test asserting PhatomJS versions. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.4.0 */ public class PhantomJsVersionTest extends BaseVersionTst { @Before public void setup() { browserManager = PhantomJsDriverManager.getInstance(); specificVersions = new String[] { "1.9.6", "1.9.7", "1.9.8", "2.1.1" }; } }
Update the Chrome extension more aggressively Request a chrome update when the extension starts and reload the extension when it's installed.
(function () { 'use strict'; var browserExtension = new h.HypothesisChromeExtension({ chromeTabs: chrome.tabs, chromeBrowserAction: chrome.browserAction, extensionURL: function (path) { return chrome.extension.getURL(path); }, isAllowedFileSchemeAccess: function (fn) { return chrome.extension.isAllowedFileSchemeAccess(fn); }, }); browserExtension.listen(window); chrome.runtime.onInstalled.addListener(onInstalled); chrome.runtime.requestUpdateCheck(function (status) { chrome.runtime.onUpdateAvailable.addListener(onUpdateAvailable); }); function onInstalled(installDetails) { if (installDetails.reason === 'install') { browserExtension.firstRun(); } // We need this so that 3rd party cookie blocking does not kill us. // See https://github.com/hypothesis/h/issues/634 for more info. // This is intended to be a temporary fix only. var details = { primaryPattern: 'https://hypothes.is/*', setting: 'allow' }; chrome.contentSettings.cookies.set(details); chrome.contentSettings.images.set(details); chrome.contentSettings.javascript.set(details); browserExtension.install(); } function onUpdateAvailable() { chrome.runtime.reload(); } })();
(function () { 'use strict'; var browserExtension = new h.HypothesisChromeExtension({ chromeTabs: chrome.tabs, chromeBrowserAction: chrome.browserAction, extensionURL: function (path) { return chrome.extension.getURL(path); }, isAllowedFileSchemeAccess: function (fn) { return chrome.extension.isAllowedFileSchemeAccess(fn); }, }); browserExtension.listen(window); chrome.runtime.onInstalled.addListener(onInstalled); chrome.runtime.onUpdateAvailable.addListener(onUpdateAvailable); function onInstalled(installDetails) { if (installDetails.reason === 'install') { browserExtension.firstRun(); } // We need this so that 3rd party cookie blocking does not kill us. // See https://github.com/hypothesis/h/issues/634 for more info. // This is intended to be a temporary fix only. var details = { primaryPattern: 'https://hypothes.is/*', setting: 'allow' }; chrome.contentSettings.cookies.set(details); chrome.contentSettings.images.set(details); chrome.contentSettings.javascript.set(details); browserExtension.install(); } function onUpdateAvailable() { // TODO: Implement a "reload" notification that tears down the current // tabs and calls chrome.runtime.reload(). } })();
Revert using input event, change seems good enough
"use strict"; if (typeof localStorage !== "undefined"){ for(var key in localStorage){ if (localStorage.hasOwnProperty(key) && key != "debug") exports[key] = localStorage[key]; } } exports.register = function(opt, ele, nopersist){ var field = ele.type == "checkbox" ? "checked" : "value"; if (exports[opt]) ele[field] = exports[opt]; if (!nopersist && typeof localStorage !== "undefined"){ ele.addEventListener("change", function() { if (this[field]){ exports[opt] = localStorage[opt] = this[field]; }else{ delete localStorage[opt]; delete exports[opt]; } }); }else{ ele.addEventListener("change", function() { exports[opt] = field == "checked" && !this.checked ? "" : this[field]; }); } }
"use strict"; if (typeof localStorage !== "undefined"){ for(var key in localStorage){ if (localStorage.hasOwnProperty(key) && key != "debug") exports[key] = localStorage[key]; } } exports.register = function(opt, ele, nopersist){ var field = ele.type == "checkbox" ? "checked" : "value"; if (exports[opt]) ele[field] = exports[opt]; if (!nopersist && typeof localStorage !== "undefined"){ ele.addEventListener("input", function() { if (this[field]){ exports[opt] = localStorage[opt] = this[field]; }else{ delete localStorage[opt]; delete exports[opt]; } }); }else{ ele.addEventListener("input", function() { exports[opt] = field == "checked" && !this.checked ? "" : this[field]; }); } }
Handle no snr information in snr file. (for fake simualtions mainly)
import os import simulators import numpy as np import json import warnings """Calculate Errors on the Spectrum. For a first go using an fixed SNR of 200 for all observations. """ def get_snrinfo(star, obs_num, chip): """Load SNR info from json file.""" snr_file = os.path.join(simulators.paths["spectra"], "detector_snrs.json") with open(snr_file, "r") as f: snr_data = json.load(f) try: return snr_data[str(star)][str(obs_num)][str(chip)] except KeyError as e: warnings.warn("No snr data present for {0}-{1}_{2}. " "Setting error to None instead".format(star, obs_num, chip)) return None def spectrum_error(star, obs_num, chip, error_off=False): """Return the spectrum error. errors = None will perform a normal chi**2 statistic. """ if error_off: errors = None else: snr = get_snrinfo(star, obs_num, chip) if snr is None: errors = None elif len(snr) == 1: errors = 1 / np.float(snr[0]) else: raise NotImplementedError("Haven't checked if an error array can be handled yet.") return errors
import os import simulators import numpy as np import json """Calculate Errors on the Spectrum. For a first go using an fixed SNR of 200 for all observations. """ def get_snrinfo(star, obs_num, chip): """Load SNR info from json file.""" snr_file = os.path.join(simulators.paths["spectra"], "detector_snrs.json") with open(snr_file, "r") as f: snr_data = json.load(f) try: return snr_data[str(star)][str(obs_num)][str(chip)] except KeyError as e: print("No snr data present for {0}-{1}_{2}".format(star, obs_num, chip)) raise e def spectrum_error(star, obs_num, chip, error_off=False): """Return the spectrum error. errors = None will perform a normal chi**2 statistic. """ if error_off: errors = None else: snr = get_snrinfo(star, obs_num, chip) if len(snr) == 1: errors = 1 / np.float(snr[0]) else: raise NotImplementedError("Haven't checked if an error array can be handled yet.") return errors
Correct author to oemof developER group
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1', 'requests'])
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developing group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1', 'requests'])
Use newer twilio API to fix 160 character limit See http://stackoverflow.com/questions/22028278/send-sms-of-more-than-160-characters-in-python-using-twilio
#-*- coding: utf-8 -*- """ this backend requires the twilio python library: http://pypi.python.org/pypi/twilio/ """ from twilio.rest import TwilioRestClient from django.conf import settings from sendsms.backends.base import BaseSmsBackend TWILIO_ACCOUNT_SID = getattr(settings, 'SENDSMS_TWILIO_ACCOUNT_SID', '') TWILIO_AUTH_TOKEN = getattr(settings, 'SENDSMS_TWILIO_AUTH_TOKEN', '') class SmsBackend(BaseSmsBackend): def send_messages(self, messages): client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) for message in messages: for to in message.to: try: msg = client.messages.create( to=to, from_=message.from_phone, body=message.body ) except: if not self.fail_silently: raise
#-*- coding: utf-8 -*- """ this backend requires the twilio python library: http://pypi.python.org/pypi/twilio/ """ from twilio.rest import TwilioRestClient from django.conf import settings from sendsms.backends.base import BaseSmsBackend TWILIO_ACCOUNT_SID = getattr(settings, 'SENDSMS_TWILIO_ACCOUNT_SID', '') TWILIO_AUTH_TOKEN = getattr(settings, 'SENDSMS_TWILIO_AUTH_TOKEN', '') class SmsBackend(BaseSmsBackend): def send_messages(self, messages): client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) for message in messages: for to in message.to: try: msg = client.sms.messages.create( to=to, from_=message.from_phone, body=message.body ) except: if not self.fail_silently: raise
Add of getPrompt function to redisplay the prompt when search field is empty. git-svn-id: 36dcc065b18e9ace584b1c777eaeefb1d96b1ee8@290116 13f79535-47bb-0310-9956-ffa450edef68
/* * Copyright 2002-2004 The Apache Software Foundation or its licensors, * as applicable. * * 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. */ /** * getBlank script - when included in a html file and called from a form text field, will set the value of this field to "" * if the text value is still the standard value. * getPrompt script - when included in a html file and called from a form text field, will set the value of this field to the prompt * if the text value is empty. * * Typical usage: * <script type="text/javascript" language="JavaScript" src="getBlank.js"></script> * <input type="text" id="query" value="Search the site:" onFocus="getBlank (this, 'Search the site:');" onBlur="getBlank (this, 'Search the site:');"/> */ <!-- function getBlank (form, stdValue){ if (form.value == stdValue){ form.value = ''; } return true; } function getPrompt (form, stdValue){ if (form.value == ''){ form.value = stdValue; } return true; } //-->
/* * Copyright 2002-2004 The Apache Software Foundation or its licensors, * as applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This script, when included in a html file and called from a form text field, will set the value of this field to "" * if the text value is still the standard value. * * Typical usage: * <script type="text/javascript" language="JavaScript" src="getBlank.js"></script> * <input type="text" id="query" value="Search the site:" onFocus="getBlank (this, 'Search the site:');"/> */ <!-- function getBlank (form, stdValue){ if (form.value == stdValue){ form.value = ''; } return true; } //-->
Use display.show instead of display.animate
from microbit import * hands = Image.ALL_CLOCKS #A centre dot of brightness 2. ticker_image = Image("2\n").crop(-2,-2,5,5) #Adjust these to taste MINUTE_BRIGHT = 0.1111 HOUR_BRIGHT = 0.55555 #Generate hands for 5 minute intervals def fiveticks(): fivemins = 0 hours = 0 while True: yield hands[fivemins]*MINUTE_BRIGHT + hands[hours]*HOUR_BRIGHT fivemins = (fivemins+1)%12 hours = (hours + (fivemins == 0))%12 #Generate hands with ticker superimposed for 1 minute intervals. def ticks(): on = True for face in fiveticks(): for i in range(5): if on: yield face + ticker_image else: yield face - ticker_image on = not on #Run a clock speeded up 60 times, so we can watch the animation. display.show(ticks(), 1000)
from microbit import * hands = Image.ALL_CLOCKS #A centre dot of brightness 2. ticker_image = Image("2\n").crop(-2,-2,5,5) #Adjust these to taste MINUTE_BRIGHT = 0.1111 HOUR_BRIGHT = 0.55555 #Generate hands for 5 minute intervals def fiveticks(): fivemins = 0 hours = 0 while True: yield hands[fivemins]*MINUTE_BRIGHT + hands[hours]*HOUR_BRIGHT fivemins = (fivemins+1)%12 hours = (hours + (fivemins == 0))%12 #Generate hands with ticker superimposed for 1 minute intervals. def ticks(): on = True for face in fiveticks(): for i in range(5): if on: yield face + ticker_image else: yield face - ticker_image on = not on #Run a clock speeded up 60 times, so we can watch the animation. display.animate(ticks(), 1000)
Use a separate lock path
from subprocess import getoutput from random import randrange from filelock import FileLock LOCK_PATH = '/tmp/ifixit_dict.lock' DICT_PATH = './dict.txt' OOPS_SEEK_TOO_FAR = 48 DICT_LENGTH = 61973 # don't run on OS X def randomize(): out = getoutput('sort -R ' + DICT_PATH) with FileLock(LOCK_PATH): with open(DICT_PATH, 'w') as f: f.write(out) f.close() def getwords(): with open(DICT_PATH, 'r') as f: f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR))) out = f.readlines(OOPS_SEEK_TOO_FAR) out = [x.replace('\n', '') for x in out] return '_'.join(out[1:4]) if __name__ == '__main__': while True: print(getwords())
from subprocess import getoutput from random import randrange from filelock import FileLock DICT_PATH = './dict.txt' OOPS_SEEK_TOO_FAR = 48 DICT_LENGTH = 61973 # don't run on OS X def randomize(): out = getoutput('sort -R ' + DICT_PATH) with FileLock(DICT_PATH): with open(DICT_PATH, 'w') as f: f.write(out) f.close() def getwords(): with open(DICT_PATH, 'r') as f: f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR))) out = f.readlines(OOPS_SEEK_TOO_FAR) out = [x.replace('\n', '') for x in out] return '_'.join(out[1:4]) if __name__ == '__main__': while True: print(getwords())
Fix default value for dropdown field (when no value matches)
<?php namespace Craft; use Cake\Utility\Hash as Hash; class DropdownFeedMeFieldType extends BaseFeedMeFieldType { // Templates // ========================================================================= // Public Methods // ========================================================================= public function prepFieldData($element, $field, $fieldData, $handle, $options) { $preppedData = null; $data = Hash::get($fieldData, 'data'); if (empty($data)) { return; } $settings = $field->getFieldType()->getSettings(); $options = $settings->getAttribute('options'); foreach ($options as $option) { if ($data == $option['value']) { $preppedData = $option['value']; break; } } return $preppedData; } }
<?php namespace Craft; use Cake\Utility\Hash as Hash; class DropdownFeedMeFieldType extends BaseFeedMeFieldType { // Templates // ========================================================================= // Public Methods // ========================================================================= public function prepFieldData($element, $field, $fieldData, $handle, $options) { $preppedData = array(); $data = Hash::get($fieldData, 'data'); if (empty($data)) { return; } $settings = $field->getFieldType()->getSettings(); $options = $settings->getAttribute('options'); // find matching option label foreach ($options as $option) { if ($data == $option['value']) { $preppedData = $option['value']; break; } } return $preppedData; } }
Switch sort direction of index in order to improve performance
exports.index = function (collection) { collection.getIndexes(function(err, indexes) { if (err) { if (err.code === 26) { // MongoError: no collection return; } return console.log(err); } dropIndex('status_1_queue_1_enqueued_1'); dropIndex('status_1_queue_1_enqueued_1_delay_1'); function dropIndex(name) { if (indexes.some(function(index) { return index.name == name; })) { collection.dropIndex(name, function(err) { if (err) { console.error(err); } }); } } }); // Ensures there's a reasonable index for the poling dequeue // Status is first b/c querying by status = queued should be very selective collection.ensureIndex({ status: 1, queue: 1, priority: -1, _id: 1, delay: 1 }, function (err) { if (err) console.error(err); }); };
exports.index = function (collection) { collection.getIndexes(function(err, indexes) { if (err) { if (err.code === 26) { // MongoError: no collection return; } return console.log(err); } dropIndex('status_1_queue_1_enqueued_1'); dropIndex('status_1_queue_1_enqueued_1_delay_1'); function dropIndex(name) { if (indexes.some(function(index) { return index.name == name; })) { collection.dropIndex(name, function(err) { if (err) { console.error(err); } }); } } }); // Ensures there's a reasonable index for the poling dequeue // Status is first b/c querying by status = queued should be very selective collection.ensureIndex({ status: 1, queue: 1, priority: 1, _id: 1, delay: 1 }, function (err) { if (err) console.error(err); }); };
Duplicate binding names are allowed in param lists
import Term from "./terms"; import { CloneReducer } from "shift-reducer"; import { gensym } from "./symbol"; import { VarBindingTransform } from "./transforms"; export default class ScopeApplyingReducer extends CloneReducer { constructor(scope, context, phase = 0) { super(); this.context = context; this.scope = scope; this.phase = phase; } reduceBindingIdentifier(node, state) { let name = node.name.addScope(this.scope, this.context.bindings); let newBinding = gensym(name.val()); this.context.env.set(newBinding.toString(), new VarBindingTransform(name)); this.context.bindings.add(name, { binding: newBinding, phase: this.phase, skipDup: true }); return new Term("BindingIdentifier", { name: name }); } }
import Term from "./terms"; import { CloneReducer } from "shift-reducer"; import { gensym } from "./symbol"; import { VarBindingTransform } from "./transforms"; export default class ScopeApplyingReducer extends CloneReducer { constructor(scope, context, phase = 0) { super(); this.context = context; this.scope = scope; this.phase = phase; } reduceBindingIdentifier(node, state) { let name = node.name.addScope(this.scope, this.context.bindings); let newBinding = gensym(name.val()); this.context.env.set(newBinding.toString(), new VarBindingTransform(name)); this.context.bindings.add(name, { binding: newBinding, phase: this.phase }); return new Term("BindingIdentifier", { name: name }); } }
Disable querystring auth for s3
from default_settings import * import dj_database_url DATABASES = { 'default': dj_database_url.config(), } SECRET_KEY = os.environ['SECRET_KEY'] STATICFILES_STORAGE = 's3storage.S3HashedFilesStorage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_KEY', '') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_BUCKET_NAME', '') AWS_QUERYSTRING_AUTH = False STATIC_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME SENTRY_DSN = os.environ.get('SENTRY_DSN', '') # Run the site over SSL MIDDLEWARE_CLASSES = ( 'sslify.middleware.SSLifyMiddleware', ) + MIDDLEWARE_CLASSES SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True
from default_settings import * import dj_database_url DATABASES = { 'default': dj_database_url.config(), } SECRET_KEY = os.environ['SECRET_KEY'] STATICFILES_STORAGE = 's3storage.S3HashedFilesStorage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_KEY', '') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_BUCKET_NAME', '') STATIC_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME SENTRY_DSN = os.environ.get('SENTRY_DSN', '') # Run the site over SSL MIDDLEWARE_CLASSES = ( 'sslify.middleware.SSLifyMiddleware', ) + MIDDLEWARE_CLASSES SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True
Rename method all to getAll on repository interface.
<?php namespace Enzyme\Axiom\Repositories; use Enzyme\Axiom\Instances\InstanceInterface; use Enzyme\Axiom\Atoms\AtomInterface; /** * Manages a collection of instances. */ interface RepositoryInterface { /** * Get a collection of all instances for this type. * * @return array */ public function getAll(); /** * Get an instance by the given id. * * @param AtomInterface $id The instance's id. * * @return Enzyme\Axiom\Instances\InstanceInterface */ public function getById(AtomInterface $id); /** * Save the given instance to the underlying persistence layer. * * @param InstanceInterface $instance * * @return void */ public function save(InstanceInterface $instance); }
<?php namespace Enzyme\Axiom\Repositories; use Enzyme\Axiom\Instances\InstanceInterface; use Enzyme\Axiom\Atoms\AtomInterface; /** * Manages a collection of instances. */ interface RepositoryInterface { /** * Get a collection of all instances for this type. * * @return array */ public function all(); /** * Get an instance by the given id. * * @param AtomInterface $id The instance's id. * * @return Enzyme\Axiom\Instances\InstanceInterface */ public function getById(AtomInterface $id); /** * Save the given instance to the underlying persistence layer. * * @param InstanceInterface $instance * * @return void */ public function save(InstanceInterface $instance); }
Refactor HttpThrottlingView to be defined inside an anonymous namespace. BUG=90857 Review URL: http://codereview.chromium.org/7544009 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@94909 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information related to HTTP throttling. */ var HttpThrottlingView = (function() { // IDs for special HTML elements in http_throttling_view.html const MAIN_BOX_ID = 'http-throttling-view-tab-content'; const ENABLE_CHECKBOX_ID = 'http-throttling-view-enable-checkbox'; // We inherit from DivView. var superClass = DivView; function HttpThrottlingView() { // Call superclass's constructor. superClass.call(this, MAIN_BOX_ID); this.enableCheckbox_ = $(ENABLE_CHECKBOX_ID); this.enableCheckbox_.onclick = this.onEnableCheckboxClicked_.bind(this); g_browser.addHttpThrottlingObserver(this); } cr.addSingletonGetter(HttpThrottlingView); HttpThrottlingView.prototype = { // Inherit the superclass's methods. __proto__: superClass.prototype, /** * Gets informed that HTTP throttling has been enabled/disabled. * @param {boolean} enabled HTTP throttling has been enabled. */ onHttpThrottlingEnabledPrefChanged: function(enabled) { this.enableCheckbox_.checked = enabled; }, /** * Handler for the onclick event of the checkbox. */ onEnableCheckboxClicked_: function() { g_browser.enableHttpThrottling(this.enableCheckbox_.checked); } }; return HttpThrottlingView; })();
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information related to HTTP throttling. * @constructor */ function HttpThrottlingView() { const mainBoxId = 'http-throttling-view-tab-content'; const enableCheckboxId = 'http-throttling-view-enable-checkbox'; DivView.call(this, mainBoxId); this.enableCheckbox_ = $(enableCheckboxId); this.enableCheckbox_.onclick = this.onEnableCheckboxClicked_.bind(this); g_browser.addHttpThrottlingObserver(this); } inherits(HttpThrottlingView, DivView); /** * Gets informed that HTTP throttling has been enabled/disabled. * @param {boolean} enabled HTTP throttling has been enabled. */ HttpThrottlingView.prototype.onHttpThrottlingEnabledPrefChanged = function( enabled) { this.enableCheckbox_.checked = enabled; }; /** * Handler for the onclick event of the checkbox. */ HttpThrottlingView.prototype.onEnableCheckboxClicked_ = function() { g_browser.enableHttpThrottling(this.enableCheckbox_.checked); };
Update the comment spelling :-p git-svn-id: 8aef34885c21801cc977f98956a081c938212632@12 1678c8a9-8d33-0410-b0a4-d546c816ed44
package org.jsmpp.session; import org.jsmpp.bean.DeliverSm; import org.jsmpp.extra.ProcessMessageException; /** * This listener will listen to every incoming short message, recognized by * deliver_sm command. The logic on this listener should be accomplish in a * short time, because the deliver_sm_resp will be processed after the logic * executed. Normal logic will be return the deliver_sm_resp with zero valued * command_status, or throw {@link ProcessMessageException} that gave non-zero * valued command_status (in means negative response) depends on the given error * code specified on the {@link ProcessMessageException}. * * @author uudashr * @version 1.0 * @since 2.0 * */ public interface MessageReceiverListener { /** * Event that called when an short message accepted. * * @param deliverSm is the deliver_sm command. * @throws ProcessMessageException throw if there should be return Non-OK * command_status for the response. */ public void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessMessageException; }
package org.jsmpp.session; import org.jsmpp.bean.DeliverSm; import org.jsmpp.extra.ProcessMessageException; /** * This listener will listen to every incomming short message, recognized by * deliver_sm command. The logic on this listener should be accomplish in a * short time, because the deliver_sm_resp will be processed after the logic * executed. Normal logic will be return the deliver_sm_resp with zero valued * command_status, or throw {@link ProcessMessageException} that gave non-zero * valued command_status (in means negative response) depends on the given error * code specified on the {@link ProcessMessageException}. * * @author uudashr * @version 1.0 * @since 2.0 * */ public interface MessageReceiverListener { /** * Event that called when an short message accepted. * * @param deliverSm is the deliver_sm command. * @throws ProcessMessageException throw if there should be return Non-OK * command_status for the response. */ public void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessMessageException; }
Update the query time indicator to indicate when queries are in progress.
if (pulse === undefined) { var pulse = {}; } pulse.dataPointsQuery = function (metricQuery, callback) { var startTime = new Date(); var $queryTime = $("#queryTime"); $queryTime.html(""); $queryTime.html("<i>in progress...</i>"); $.ajax({ type: "POST", url: "/api/v1/datapoints/query", headers: { 'Content-Type': ['application/json']}, data: JSON.stringify(metricQuery), dataType: 'json', success: function (data, textStatus, jqXHR) { $queryTime.html(""); $queryTime.append(new Date().getTime() - startTime.getTime() + " ms"); callback(data.queries); }, error: function (jqXHR, textStatus, errorThrown) { var $errorContainer = $("#errorContainer"); $errorContainer.show(); $errorContainer.html(""); $errorContainer.append("Status Code: " + jqXHR.status + "</br>"); $errorContainer.append("Status: " + jqXHR.statusText + "<br>"); $errorContainer.append("Return Value: " + jqXHR.responseText); } }); };
if (pulse === undefined) { var pulse = {}; } pulse.dataPointsQuery = function (metricQuery, callback) { var startTime = new Date(); $.ajax({ type: "POST", url: "/api/v1/datapoints/query", headers: { 'Content-Type': ['application/json']}, data: JSON.stringify(metricQuery), dataType: 'json', success: function (data, textStatus, jqXHR) { var $queryTime = $("#queryTime"); $queryTime.html(""); $queryTime.append(new Date().getTime() - startTime.getTime() + " ms"); callback(data.queries); }, error: function (jqXHR, textStatus, errorThrown) { var $errorContainer = $("#errorContainer"); $errorContainer.show(); $errorContainer.html(""); $errorContainer.append("Status Code: " + jqXHR.status + "</br>"); $errorContainer.append("Status: " + jqXHR.statusText + "<br>"); $errorContainer.append("Return Value: " + jqXHR.responseText); } }); };
Use auto generated celery queues
# -*- coding: utf-8 -*- """Asynchronous task queue module.""" from celery import Celery from celery.utils.log import get_task_logger from raven import Client from raven.contrib.celery import register_signal from website import settings app = Celery() # TODO: Hardcoded settings module. Should be set using framework's config handler app.config_from_object('website.settings') if settings.SENTRY_DSN: client = Client(settings.SENTRY_DSN) register_signal(client) @app.task def error_handler(task_id, task_name): """logs detailed message about tasks that raise exceptions :param task_id: TaskID of the failed task :param task_name: name of task that failed """ # get the current logger logger = get_task_logger(__name__) # query the broker for the AsyncResult result = app.AsyncResult(task_id) excep = result.get(propagate=False) # log detailed error mesage in error log logger.error('#####FAILURE LOG BEGIN#####\n' 'Task {0} raised exception: {0}\n\{0}\n' '#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))
# -*- coding: utf-8 -*- """Asynchronous task queue module.""" from celery import Celery from celery.utils.log import get_task_logger from kombu import Exchange, Queue from raven import Client from raven.contrib.celery import register_signal from website import settings app = Celery() # TODO: Hardcoded settings module. Should be set using framework's config handler app.config_from_object('website.settings') app.conf.CELERY_QUEUES = ( Queue( settings.CELERY_DEFAULT_QUEUE, Exchange(settings.CELERY_DEFAULT_QUEUE), routing_key=settings.CELERY_DEFAULT_QUEUE), ) if settings.SENTRY_DSN: client = Client(settings.SENTRY_DSN) register_signal(client) @app.task def error_handler(task_id, task_name): """logs detailed message about tasks that raise exceptions :param task_id: TaskID of the failed task :param task_name: name of task that failed """ # get the current logger logger = get_task_logger(__name__) # query the broker for the AsyncResult result = app.AsyncResult(task_id) excep = result.get(propagate=False) # log detailed error mesage in error log logger.error('#####FAILURE LOG BEGIN#####\n' 'Task {0} raised exception: {0}\n\{0}\n' '#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))
Upgrade Beaker 1.6.4 => 1.8.1
from setuptools import setup setup( name='tangled.session', version='0.1a3.dev0', description='Tangled session integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.session/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=[ 'tangled', 'tangled.session', 'tangled.session.tests', ], install_requires=[ 'tangled>=0.1a9', 'Beaker>=1.8.1', ], extras_require={ 'dev': [ 'tangled[dev]>=0.1a9', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
from setuptools import setup setup( name='tangled.session', version='0.1a3.dev0', description='Tangled session integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.session/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=[ 'tangled', 'tangled.session', 'tangled.session.tests', ], install_requires=[ 'Beaker>=1.6.4', 'tangled>=0.1a9', ], extras_require={ 'dev': [ 'tangled[dev]>=0.1a9', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
Move chickens to other app
from django.conf.urls import patterns, url from django.views.generic import TemplateView from .views import ( PizzaCreateView, PizzaDeleteView, PizzaDetailView, PizzaListView, PizzaUpdateView ) urlpatterns = patterns('', # NOQA url(r'^$', PizzaListView.as_view(), name='list'), url(r'^create/$', PizzaCreateView.as_view(), name='create'), url(r'^created/$', TemplateView.as_view( template_name='pizzagigi/pizza_created.html'), name='created'), url(r'^detail/(?P<pk>[0-9]*)$', PizzaDetailView.as_view(), name='detail'), url(r'^update/(?P<pk>[0-9]*)$', PizzaUpdateView.as_view(), name='update'), url(r'^updated/$', TemplateView.as_view( template_name='pizzagigi/pizza_updated.html'), name='updated'), url(r'^delete/(?P<pk>[0-9]*)$', PizzaDeleteView.as_view(), name='delete'), url(r'^deleted/$', TemplateView.as_view( template_name='pizzagigi/pizza_deleted.html'), name='deleted'), )
from django.conf.urls import patterns, url from django.views.generic import TemplateView from .views import ( PizzaCreateView, PizzaDeleteView, PizzaDetailView, PizzaListView, PizzaUpdateView, ChickenWingsListView ) urlpatterns = patterns('', # NOQA url(r'^$', PizzaListView.as_view(), name='list'), url(r'^create/$', PizzaCreateView.as_view(), name='create'), url(r'^created/$', TemplateView.as_view( template_name='pizzagigi/pizza_created.html'), name='created'), url(r'^detail/(?P<pk>[0-9]*)$', PizzaDetailView.as_view(), name='detail'), url(r'^update/(?P<pk>[0-9]*)$', PizzaUpdateView.as_view(), name='update'), url(r'^updated/$', TemplateView.as_view( template_name='pizzagigi/pizza_updated.html'), name='updated'), url(r'^delete/(?P<pk>[0-9]*)$', PizzaDeleteView.as_view(), name='delete'), url(r'^deleted/$', TemplateView.as_view( template_name='pizzagigi/pizza_deleted.html'), name='deleted'), url(r'^wings/$', ChickenWingsListView.as_view(), name='chickenwings_list'), )
Add newline in file to keep github happy
/** * Return an array of function of the form x => { type, payload = x } */ export function createActions(...types) { return types.map(createAction) } /** * Create a single action of the form x => { type, payload = x } * * @returns {Array} */ export function createAction(type) { return (payload, error) => (Object.assign({ type }, payload ? { payload } : {}, error ? { error } : {})) } /** * Create a single action of the form x => { type } * Use this for actions that do not carry any payload, this is useful especially if the action is * going to be used as an event handler to avoid accidentally including the DOM event as payload. */ export function createAction0(type) { return () => ({ type }) } /** * Return an array of action creators. * Use this for actions that do not carry any payload. * * @returns {Array} */ export function creactActions0(...types) { return types.map(createAction0) }
/** * Return an array of function of the form x => { type, payload = x } */ export function createActions(...types) { return types.map(createAction) } /** * Create a single action of the form x => { type, payload = x } */ export function createAction(type) { return (payload, error) => (Object.assign({ type }, payload ? { payload } : {}, error ? { error } : {})) } /** * Create a single action of the form x => { type } * Use this for actions that do not carry any payload, this is useful especially if the action is * going to be used as an event handler to avoid accidentally including the DOM event as payload. */ export function createAction0(type) { return () => ({ type }) } /** * Return an array of action creators. * Use this for actions that do not carry any payload. * * @returns {Array} */ export function creactActions0(...types) { return types.map(createAction0) }
Make scheduler do primary reads only
from tapiriik.database import db from tapiriik.messagequeue import mq from tapiriik.sync import Sync from datetime import datetime from pymongo.read_preferences import ReadPreference import kombu import time Sync.InitializeWorkerBindings() producer = kombu.Producer(Sync._channel, Sync._exchange) while True: queueing_at = datetime.utcnow() users = db.users.find( { "NextSynchronization": {"$lte": datetime.utcnow()} }, { "_id": True, "SynchronizationHostRestriction": True }, read_preference=ReadPreference.PRIMARY ) scheduled_ids = set() for user in users: producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "") scheduled_ids.add(user["_id"]) print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow())) db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True) time.sleep(1)
from tapiriik.database import db from tapiriik.messagequeue import mq from tapiriik.sync import Sync import kombu from datetime import datetime import time Sync.InitializeWorkerBindings() producer = kombu.Producer(Sync._channel, Sync._exchange) while True: queueing_at = datetime.utcnow() users = db.users.find( { "NextSynchronization": {"$lte": datetime.utcnow()} }, { "_id": True, "SynchronizationHostRestriction": True } ) scheduled_ids = set() for user in users: producer.publish(str(user["_id"]), routing_key=user["SynchronizationHostRestriction"] if "SynchronizationHostRestriction" in user and user["SynchronizationHostRestriction"] else "") scheduled_ids.add(user["_id"]) print("Scheduled %d users at %s" % (len(scheduled_ids), datetime.utcnow())) db.users.update({"_id": {"$in": list(scheduled_ids)}}, {"$set": {"QueuedAt": queueing_at}, "$unset": {"NextSynchronization": True}}, multi=True) time.sleep(1)
Refactor monkey-patch to include less duplication.
(function() { function componentHasBeenReopened(Component, className) { return Component.prototype.classNames.indexOf(className) > -1; } function reopenComponent(_Component, className) { var Component = _Component.reopen({ classNames: [className] }); return Component; } function ensureComponentCSSClassIncluded(_Component, _name) { var Component = _Component; var name = name.replace(".","/"); var className = Ember.COMPONENT_CSS_LOOKUP[name]; if (!componentHasBeenReopened(Component)) { Component = reopenComponent(Component, className); } return Component; } Ember.ComponentLookup.reopen({ lookupFactory: function(name) { var Component = this._super.apply(this, arguments); if (!Component) { return; } return ensureComponentCSSClassIncluded(Component, name); }, componentFor: function(name) { var Component = this._super.apply(this, arguments); if (!Component) { return; } return ensureComponentCSSClassIncluded(Component, name); } }); })()
Ember.ComponentLookup.reopen({ lookupFactory: function(name) { var Component = this._super.apply(this, arguments); if (!Component) { return; } name = name.replace(".","/"); if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){ return Component; } return Component.reopen({ classNames: [Ember.COMPONENT_CSS_LOOKUP[name]] }); }, componentFor: function(name) { var Component = this._super.apply(this, arguments); if (!Component) { return; } name = name.replace(".","/"); if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){ return Component; } return Component.reopen({ classNames: [Ember.COMPONENT_CSS_LOOKUP[name]] }); } });
Add test to ensure err returned for missing files
package prefer import ( "strings" "testing" ) func TestLoadCreatesNewConfiguration(t *testing.T) { type Mock struct { Name string `json:"name"` Age int `json:"age"` } mock := Mock{} configuration, err := Load("share/fixtures/example", &mock) checkTestError(t, err) file_path_index := strings.Index(configuration.Identifier, "share/fixtures/example.") expected_index := len(configuration.Identifier) - 27 if file_path_index != expected_index { t.Error("Loaded unexpected configuration file:", configuration.Identifier) } if mock.Name != "Bailey" || mock.Age != 30 { t.Error("Got unexpected values from configuration file.") } } func TestLoadReturnsErrorForFilesWhichDontExist(t *testing.T) { type Mock struct { Name string `json:"name"` Age int `json:"age"` } mock := Mock{} _, err := Load("this/is/a/fake/filename", &mock) if err == nil { t.Error("Expected an error but one was not returned.") } } func TestWatchReturnsChannelForWatchingFileForUpdates(t *testing.T) { type Mock struct { Name string `json:"name"` Age int `json:"age"` } mock := Mock{} channel, err := Watch("share/fixtures/example", &mock) checkTestError(t, err) <-channel if mock.Name != "Bailey" || mock.Age != 30 { t.Error("Got unexpected values from configuration file.") } }
package prefer import ( "strings" "testing" ) func TestLoadCreatesNewConfiguration(t *testing.T) { type Mock struct { Name string `json:"name"` Age int `json:"age"` } mock := Mock{} configuration, err := Load("share/fixtures/example", &mock) checkTestError(t, err) file_path_index := strings.Index(configuration.Identifier, "share/fixtures/example.") expected_index := len(configuration.Identifier) - 27 if file_path_index != expected_index { t.Error("Loaded unexpected configuration file:", configuration.Identifier) } if mock.Name != "Bailey" || mock.Age != 30 { t.Error("Got unexpected values from configuration file.") } } func TestWatchReturnsChannelForWatchingFileForUpdates(t *testing.T) { type Mock struct { Name string `json:"name"` Age int `json:"age"` } mock := Mock{} channel, err := Watch("share/fixtures/example", &mock) checkTestError(t, err) <-channel if mock.Name != "Bailey" || mock.Age != 30 { t.Error("Got unexpected values from configuration file.") } }
Add long_description field to avoid PyPi page error.
#!/bin/env python from setuptools import setup # Load module version from ovr/version.py exec(open('src/openvr/version.py').read()) setup( name='openvr', version=__version__, author='Christopher Bruns and others', author_email='cmbruns@rotatingpenguin.com', description='Valve OpenVR SDK python bindings using ctypes', long_description='Valve OpenVR SDK python bindings using ctypes', url='https://github.com/cmbruns/pyopenvr', download_url='https://github.com/cmbruns/pyopenvr/tarball/' + __version__, package_dir={'': 'src'}, packages=['openvr', 'openvr.glframework'], package_data={'openvr': ['*.dll', '*.so', '*.dylib']}, keywords='openvr valve htc vive vr virtual reality 3d graphics', license='BSD', classifiers="""\ Environment :: Win32 (MS Windows) Intended Audience :: Developers License :: OSI Approved :: BSD License Operating System :: Microsoft :: Windows Operating System :: Microsoft :: Windows :: Windows 7 Operating System :: POSIX :: Linux Operating System :: MacOS :: MacOS X Programming Language :: Python :: 2.7 Programming Language :: Python :: 3.5 Programming Language :: Python :: Implementation :: CPython Topic :: Multimedia :: Graphics :: 3D Rendering Topic :: Scientific/Engineering :: Visualization Development Status :: 4 - Beta """.splitlines(), )
#!/bin/env python from setuptools import setup # Load module version from ovr/version.py exec(open('src/openvr/version.py').read()) setup( name='openvr', version=__version__, author='Christopher Bruns and others', author_email='cmbruns@rotatingpenguin.com', description='Valve OpenVR SDK python bindings using ctypes', url='https://github.com/cmbruns/pyopenvr', download_url='https://github.com/cmbruns/pyopenvr/tarball/' + __version__, package_dir={'': 'src'}, packages=['openvr', 'openvr.glframework'], package_data={'openvr': ['*.dll', '*.so', '*.dylib']}, keywords='openvr valve htc vive vr virtual reality 3d graphics', license='BSD', classifiers="""\ Environment :: Win32 (MS Windows) Intended Audience :: Developers License :: OSI Approved :: BSD License Operating System :: Microsoft :: Windows Operating System :: Microsoft :: Windows :: Windows 7 Operating System :: POSIX :: Linux Operating System :: MacOS :: MacOS X Programming Language :: Python :: 2.7 Programming Language :: Python :: 3.5 Programming Language :: Python :: Implementation :: CPython Topic :: Multimedia :: Graphics :: 3D Rendering Topic :: Scientific/Engineering :: Visualization Development Status :: 4 - Beta """.splitlines(), )
Check RSS feed on startup
$(function(){ readFileIntoBuffer(batotoJSONFile, function(buffer){ if (buffer){ batotoJSON = JSON.parse(buffer); if ('chapters' in batotoJSON){ $.each(batotoJSON.chapters, function(index, val) { addRowToTable(val); }); } } $("#urlEntry").keypress(function (e) { if (e.which == 13){ var val = $(this).val(); parseUrl(val); $(this).val(''); return false; } }); if (isReadClipboard()){ readClipboard(); } checkRssFeed(true); }); }); function readClipboard(){ var data = clipboard.readText(); console.log('Clipboard: '+data); if (data.length > 0 && batotoRegex.test(data)){ console.log('test succeeded'); clipboard.writeText(''); //Clear clipboard, so we don't parse the same url twice var matches = data.match(batotoRegex); console.log(matches); var len = matches.length; for (var index = 0; i < len; index++){ parseUrl(matches[index]); } } setTimeout(readClipboard,1000); }
$(function(){ readFileIntoBuffer(batotoJSONFile, function(buffer){ if (buffer){ batotoJSON = JSON.parse(buffer); if ('chapters' in batotoJSON){ $.each(batotoJSON.chapters, function(index, val) { addRowToTable(val); }); } } $("#urlEntry").keypress(function (e) { if (e.which == 13){ var val = $(this).val(); parseUrl(val); $(this).val(''); return false; } }); if (isReadClipboard()){ readClipboard(); } }); }); function readClipboard(){ var data = clipboard.readText(); console.log('Clipboard: '+data); if (data.length > 0 && batotoRegex.test(data)){ console.log('test succeeded'); clipboard.writeText(''); //Clear clipboard, so we don't parse the same url twice var matches = data.match(batotoRegex); console.log(matches); var len = matches.length; for (var index = 0; i < len; index++){ parseUrl(matches[index]); } } setTimeout(readClipboard,1000); }
Add title for code list selection within single response
import React, { PropTypes } from 'react' import CodeListSelector from './code-list-selector' import VisHintPicker from './vis-hint-picker' import { updateSingle, newCodeListSingle } from '../actions/response-format' import { connect } from 'react-redux' function SingleResponseFormatEditor( { id, qrId, format: { codeListReference, visHint }, updateSingle, newCodeListSingle, locale }) { return ( <div> <CodeListSelector id={codeListReference} title={locale.selectCl} select={codeListReference => updateSingle(id, { codeListReference })} create={() => newCodeListSingle(id, qrId)} locale={locale} /> <VisHintPicker visHint={visHint} locale={locale} select={visHint => updateSingle(id, { visHint})}/> </div> ) } const mapStateToProps = state => ({ qrId: state.appState.questionnaire }) const mapDispatchToProps = { updateSingle, newCodeListSingle } SingleResponseFormatEditor.propTypes = { id: PropTypes.string.isRequired, /** * Id of the current questionnaire */ qrId: PropTypes.string.isRequired, format: PropTypes.object.isRequired, locale: PropTypes.object.isRequired, updateSingle: PropTypes.func.isRequired, newCodeListSingle: PropTypes.func.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(SingleResponseFormatEditor)
import React, { PropTypes } from 'react' import CodeListSelector from './code-list-selector' import VisHintPicker from './vis-hint-picker' import { updateSingle, newCodeListSingle } from '../actions/response-format' import { connect } from 'react-redux' function SingleResponseFormatEditor( { id, qrId, format: { codeListReference, visHint }, updateSingle, newCodeListSingle, locale }) { return ( <div> <CodeListSelector id={codeListReference} select={codeListReference => updateSingle(id, { codeListReference })} create={() => newCodeListSingle(id, qrId)} locale={locale} /> <VisHintPicker visHint={visHint} locale={locale} select={visHint => updateSingle(id, { visHint})}/> </div> ) } const mapStateToProps = state => ({ qrId: state.appState.questionnaire }) const mapDispatchToProps = { updateSingle, newCodeListSingle } SingleResponseFormatEditor.propTypes = { id: PropTypes.string.isRequired, /** * Id of the current questionnaire */ qrId: PropTypes.string.isRequired, format: PropTypes.object.isRequired, locale: PropTypes.object.isRequired, updateSingle: PropTypes.func.isRequired, newCodeListSingle: PropTypes.func.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(SingleResponseFormatEditor)
Return null for injected prestations
var _ = require('lodash'); var periods = require('./periods'); var PRESTATIONS = require('../prestations'); module.exports = function reverseMap(openFiscaFamille, date, injectedRessources) { var period = periods.map(date); var injectedPrestations = _.intersection(_.keys(PRESTATIONS), injectedRessources) return _.mapValues(PRESTATIONS, function(format, prestationName) { // For prestations that have been injected by the user and not calculated by the simulator, put null to allow specific treatment in the ui if (_.contains(injectedPrestations, prestationName)) { return null; } var type = format.type, computedPrestation = openFiscaFamille[prestationName], result = computedPrestation[period]; var uncomputabilityReason = openFiscaFamille[prestationName + '_non_calculable'] && openFiscaFamille[prestationName + '_non_calculable'][period]; if (uncomputabilityReason) { return uncomputabilityReason; } if (format.montantAnnuel) { result *= 12; } if (type == Number) { result = Number(result.toFixed(2)); } return result; }); };
var _ = require('lodash'); var periods = require('./periods'); var PRESTATIONS = require('../prestations'); module.exports = function reverseMap(openFiscaFamille, date, injectedRessources) { var period = periods.map(date); var prestationsToDisplay = _.cloneDeep(PRESTATIONS); var injectedPrestations = _.intersection(_.keys(prestationsToDisplay), injectedRessources); // Don't show prestations that have been injected by the user, and not calculated by the simulator _.forEach(injectedPrestations, function(resource) { delete prestationsToDisplay[resource]; }); return _.mapValues(prestationsToDisplay, function(format, prestationName) { var type = format.type, computedPrestation = openFiscaFamille[prestationName], result = computedPrestation[period]; var uncomputabilityReason = openFiscaFamille[prestationName + '_non_calculable'] && openFiscaFamille[prestationName + '_non_calculable'][period]; if (uncomputabilityReason) { return uncomputabilityReason; } if (format.montantAnnuel) { result *= 12; } if (type == Number) { result = Number(result.toFixed(2)); } return result; }); };
Fix bug with storing locked buildings
/** * This function toggle the locked state of a building * @param {number} index Index of the row to change */ export default function toggleBuildingLock(index) { if (l(`productLock${index}`).innerHTML === 'Lock') { // Add to storing array Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.push( index.toString(), ); // Update styles l(`row${index}`).style.pointerEvents = 'none'; l(`row${index}`).style.opacity = '0.4'; l(`productLock${index}`).innerHTML = 'Unlock'; l(`productLock${index}`).style.pointerEvents = 'auto'; } else { // Remove from storing array if ( Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.includes( index.toString(), ) ) { Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames = Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.filter( (value) => value !== index.toString(), ); } // Update styles l(`productLock${index}`).innerHTML = 'Lock'; l(`row${index}`).style.pointerEvents = 'auto'; l(`row${index}`).style.opacity = '1'; } }
/** * This function toggle the locked state of a building * @param {number} index Index of the row to change */ export default function toggleBuildingLock(index) { if (l(`productLock${index}`).innerHTML === 'Lock') { Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.push( index.toString(), ); l(`row${index}`).style.pointerEvents = 'none'; l(`row${index}`).style.opacity = '0.4'; l(`productLock${index}`).innerHTML = 'Unlock'; l(`productLock${index}`).style.pointerEvents = 'auto'; } else { Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames = Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.filter( (value) => value !== index.toString(), ); l(`productLock${index}`).innerHTML = 'Lock'; l(`row${index}`).style.pointerEvents = 'auto'; l(`row${index}`).style.opacity = '1'; } }
Add v prefix to version.
/** * exported PageHeader * * A page header component. * **/ var React = require('react'); var PropTypes = require('prop-types'); // ES5 with npm var createReactClass = require('create-react-class'); exports.PageHeader = createReactClass({ propTypes: { title: PropTypes.string, version: PropTypes.string }, getDefaultProps: function () { return { title: 'PageHeader title' }; }, render: function () { /*jshint ignore:start*/ return ( <nav className="navbar navbar-default navbar-fixed-top"> <div className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="/"> <img alt="Brand" src="images/logo-192.png" width="20" height="20"/> <span>{this.props.title} v{this.props.version}</span> </a> </div> </div> </nav> ); /*jshint ignore:end*/ } });
/** * exported PageHeader * * A page header component. * **/ var React = require('react'); var PropTypes = require('prop-types'); // ES5 with npm var createReactClass = require('create-react-class'); exports.PageHeader = createReactClass({ propTypes: { title: PropTypes.string, version: PropTypes.string }, getDefaultProps: function () { return { title: 'PageHeader title' }; }, render: function () { /*jshint ignore:start*/ return ( <nav className="navbar navbar-default navbar-fixed-top"> <div className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="/"> <img alt="Brand" src="images/logo-192.png" width="20" height="20"/> <span>{this.props.title} {this.props.version}</span> </a> </div> </div> </nav> ); /*jshint ignore:end*/ } });
Fix irregular whitespace linter error.
import React, {PropTypes, Component} from 'react' import Dropdown from 'shared/components/Dropdown' import {showDatabases} from 'shared/apis/metaQuery' import showDatabasesParser from 'shared/parsing/showDatabases' class DatabaseDropdown extends Component { constructor(props) { super(props) this.state = { databases: [], } } componentDidMount() { const {source} = this.context const {database, onSelectDatabase} = this.props const proxy = source.links.proxy showDatabases(proxy).then(resp => { const {databases} = showDatabasesParser(resp.data) this.setState({databases}) const selected = databases.includes(database) ? database : databases[0] || 'No databases' onSelectDatabase({text: selected}) }) } render() { const {databases} = this.state const {database, onSelectDatabase} = this.props return ( <Dropdown items={databases.map(text => ({text}))} selected={database} onChoose={onSelectDatabase} /> ) } } const {func, shape, string} = PropTypes DatabaseDropdown.contextTypes = { source: shape({ links: shape({ proxy: string.isRequired, }).isRequired, }).isRequired, } DatabaseDropdown.propTypes = { database: string, onSelectDatabase: func.isRequired, } export default DatabaseDropdown
import React, {PropTypes, Component} from 'react' import Dropdown from 'shared/components/Dropdown' import {showDatabases} from 'shared/apis/metaQuery' import showDatabasesParser from 'shared/parsing/showDatabases' class DatabaseDropdown extends Component { constructor(props) { super(props) this.state = { databases: [], } } componentDidMount() { const {source} = this.context const {database, onSelectDatabase} = this.props const proxy = source.links.proxy showDatabases(proxy).then(resp => { const {databases} = showDatabasesParser(resp.data) this.setState({databases}) const selected = databases.includes(database) ? database : databases[0] || 'No databases' onSelectDatabase({text: selected}) }) } render() { const {databases} = this.state const {database, onSelectDatabase} = this.props return ( <Dropdown items={databases.map(text => ({text}))} selected={database} onChoose={onSelectDatabase} /> ) } } const {func, shape, string} = PropTypes DatabaseDropdown.contextTypes = { source: shape({ links: shape({ proxy: string.isRequired, }).isRequired, }).isRequired, } DatabaseDropdown.propTypes = { database: string, onSelectDatabase: func.isRequired, } export default DatabaseDropdown
Correct default value of attribute 'enabled'.
<?php /** * @link https://github.com/thinker-g/yii2-ishtar-gate * @copyright Copyright (c) Thinker_g (Jiyan.guo@gmail.com) * @author Thinker_g * @license MIT * * This file return a sample configuration array with all supported options and their default values. * You may use this as a template to customize your module in application's config array. * */ return [ 'class' => 'thinkerg\IshtarGate\Module', 'enabled' => false, 'blockerRoute' => [], 'useRedirection' => false, 'layout' => 'main', 'exceptRoutes' => [], 'onlyRoutes' => [], 'tipVersion' => true, 'privIPs' => [], 'credentials' => ['tester' => 'tester'], 'hashCallable' => 'thinkerg\IshtarGate\Module::dummyHash', 'logoutPublic' => false, 'siteLogoutRoute' => ['site/logout'], 'newsTicker' => 'thinkerg\IshtarGate\INewsTickerAsset', 'news' => [], 'errActionRoute' => 'site/error', 'sessKey' => 'ishtar', 'customField' => 'System is down for maintenance. We\'ll return in a moment' ];
<?php /** * @link https://github.com/thinker-g/yii2-ishtar-gate * @copyright Copyright (c) Thinker_g (Jiyan.guo@gmail.com) * @author Thinker_g * @license MIT * * This file return a sample configuration array with all supported options and their default values. * You may use this as a template to customize your module in application's config array. * */ return [ 'class' => 'thinkerg\IshtarGate\Module', 'enabled' => true, 'blockerRoute' => [], 'useRedirection' => false, 'layout' => 'main', 'exceptRoutes' => [], 'onlyRoutes' => [], 'tipVersion' => true, 'privIPs' => [], 'credentials' => ['tester' => 'tester'], 'hashCallable' => 'thinkerg\IshtarGate\Module::dummyHash', 'logoutPublic' => false, 'siteLogoutRoute' => ['site/logout'], 'newsTicker' => 'thinkerg\IshtarGate\INewsTickerAsset', 'news' => [], 'errActionRoute' => 'site/error', 'sessKey' => 'ishtar', 'customField' => 'System is down for maintenance. We\'ll return in a moment' ];
Fix bug: if code cannot be formatted the format returns null
package org.eclipse.incquery.examples.cps.m2t.proto.distributed.generator.utils; import org.eclipse.incquery.examples.cps.m2t.proto.distributed.generator.exceptions.CPSGeneratorException; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; public class FormatterUtil { public static String formatCode(CharSequence code) throws CPSGeneratorException{ CodeFormatter formatter = ToolFactory.createCodeFormatter(null); TextEdit textEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code.toString(), 0, code.length(), 0, null); if(textEdit == null){ // TODO handle... return code.toString(); } IDocument doc = new Document(code.toString()); try { textEdit.apply(doc); } catch (MalformedTreeException e) { throw new CPSGeneratorException("Cannot complete codeformatting", e); } catch (BadLocationException e) { throw new CPSGeneratorException("Cannot complete codeformatting", e); } return doc.get(); } }
package org.eclipse.incquery.examples.cps.m2t.proto.distributed.generator.utils; import org.eclipse.incquery.examples.cps.m2t.proto.distributed.generator.exceptions.CPSGeneratorException; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; public class FormatterUtil { public static String formatCode(CharSequence code) throws CPSGeneratorException{ CodeFormatter formatter = ToolFactory.createCodeFormatter(null); TextEdit textEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code.toString(), 0, code.length(), 0, null); IDocument doc = new Document(code.toString()); try { textEdit.apply(doc); } catch (MalformedTreeException e) { throw new CPSGeneratorException("Cannot complete codeformatting", e); } catch (BadLocationException e) { throw new CPSGeneratorException("Cannot complete codeformatting", e); } return doc.get(); } }
Fix NullPointerException when searched text is not set via a system property
package com.github.sulir.runtimesearch.shared; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class SearchOptions implements Serializable { public static final String PROPERTY_PREFIX = "runtimesearch."; private static final long serialVersionUID = 1L; private String text = ""; public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isActive() { return !text.isEmpty(); } public Map<String, String> toProperties() { Map<String, String> result = new HashMap<>(); result.put(PROPERTY_PREFIX + "text", text); return result; } public static SearchOptions fromProperties(Properties properties) { SearchOptions options = new SearchOptions(); String text = properties.getProperty(PROPERTY_PREFIX + "text"); if (text != null) options.setText(text); return options; } }
package com.github.sulir.runtimesearch.shared; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class SearchOptions implements Serializable { public static final String PROPERTY_PREFIX = "runtimesearch."; private static final long serialVersionUID = 1L; private String text = ""; public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isActive() { return !text.isEmpty(); } public Map<String, String> toProperties() { Map<String, String> result = new HashMap<>(); result.put(PROPERTY_PREFIX + "text", text); return result; } public static SearchOptions fromProperties(Properties properties) { SearchOptions options = new SearchOptions(); options.setText(properties.getProperty(PROPERTY_PREFIX + "text")); return options; } }
Replace react-apollo with redux compose
import React from "react"; import { compose } from "redux"; import hoistStatics from "hoist-non-react-statics"; import BaseProvider from "../components/BaseProvider"; import applyRedirect from "../router/applyRedirect"; import withCookies from "../cookies/withCookiesPage"; import withLocale from "../i18n/withLocalePage"; export default Page => compose(withLocale, applyRedirect, withCookies)( hoistStatics( props => ( <BaseProvider cookies={props.cookies} locale={props.locale} defaultLocale={props.defaultLocale} siteLocales={props.siteLocales} > <Page {...props} /> </BaseProvider> ), Page ) );
import React from "react"; import { compose } from "react-apollo"; import hoistStatics from "hoist-non-react-statics"; import BaseProvider from "../components/BaseProvider"; import applyRedirect from "../router/applyRedirect"; import withCookies from "../cookies/withCookiesPage"; import withLocale from "../i18n/withLocalePage"; export default Page => compose(withLocale, applyRedirect, withCookies)( hoistStatics( props => ( <BaseProvider cookies={props.cookies} locale={props.locale} defaultLocale={props.defaultLocale} siteLocales={props.siteLocales} > <Page {...props} /> </BaseProvider> ), Page ) );
Add name to differentiate R and RW on quads/datatset.
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.fuseki.server; public enum OperationName { // Fixed names give the codebase some resilience. Query("SPARQL Query"), Update("SPARQL Update"), Upload("File Upload"), GSP_RW("Graph Store Protocol"), GSP_R("Graph Store Protocol (Read)"), Quads_RW("HTTP Quads"), Quads_R("HTTP Quads (Read)") ; private final String description ; private OperationName(String description) { this.description = description ; } public String getDescription() { return description ; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.fuseki.server; public enum OperationName { // Fixed names give the codebase some resilience. Query("SPARQL Query"), Update("SPARQL Update"), Upload("File Upload"), GSP("Graph Store Protocol"), GSP_R("Graph Store Protocol (Read)"), Quads("HTTP Quads") ; private final String description ; private OperationName(String description) { this.description = description ; } public String getDescription() { return description ; } }
Add test for collapsed text
import ExpandablePanelModule from "./expandablePanel"; const { module } = angular.mock; describe("ExpandablePanel", () => { beforeEach(module(ExpandablePanelModule)); let $log; beforeEach(inject(($injector) => { $log = $injector.get("$log"); $log.reset(); })); afterEach(() => { $log.assertEmpty(); }); describe("Module", () => { it("is named expandablePanel", () => { expect(ExpandablePanelModule).to.equal("expandablePanel"); }); }); describe("Controller", () => { let $componentController; beforeEach(inject(($injector) => { $componentController = $injector.get("$componentController"); })); it("renders markdown", () => { let $ctrl = $componentController("expandablePanel", { }, { markdown: true }); $ctrl.$onChanges({ content: { currentValue: "sometext" } }); expect($ctrl.parsed).to.equal("<p>sometext</p>\n"); }); it("collapses long text", () => { let $ctrl = $componentController("expandablePanel", { }); $ctrl.$onChanges({ content: { currentValue: new Array(20).join("text\n") } }); expect($ctrl.collapsed).to.be.true; }); }); });
import ExpandablePanelModule from "./expandablePanel"; const { module } = angular.mock; describe("ExpandablePanel", () => { beforeEach(module(ExpandablePanelModule)); let $log; beforeEach(inject(($injector) => { $log = $injector.get("$log"); $log.reset(); })); afterEach(() => { $log.assertEmpty(); }); describe("Module", () => { it("is named expandablePanel", () => { expect(ExpandablePanelModule).to.equal("expandablePanel"); }); }); describe("Controller", () => { let $componentController; beforeEach(inject(($injector) => { $componentController = $injector.get("$componentController"); })); it("renders markdown", () => { let $ctrl = $componentController("expandablePanel", { }, { markdown: true }); $ctrl.$onChanges({ content: { currentValue: "sometext" } }); expect($ctrl.parsed).to.equal("<p>sometext</p>\n"); }); }); });
Allow team num players column to be ordered
from django.contrib import admin from django.db.models import Count from .models import Team from nucleus.admin import TeamMemberInline class TeamAdmin(admin.ModelAdmin): inlines = (TeamMemberInline, ) raw_id_fields = ('captain', 'creator', ) list_display = ( 'name', 'get_player_count', 'get_player_list', 'created', 'updated', ) search_fields = ('name', ) def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.prefetch_related('players').annotate( player_count=Count('players') ) def get_player_count(self, obj): return obj.player_count get_player_count.short_description = 'Num Players' get_player_count.admin_order_field = 'player_count' def get_player_list(self, obj): return ', '.join([p.username for p in obj.players.all()]) get_player_list.short_description = 'Players' admin.site.register(Team, TeamAdmin)
from django.contrib import admin from .models import Team from nucleus.admin import TeamMemberInline class TeamAdmin(admin.ModelAdmin): inlines = (TeamMemberInline, ) raw_id_fields = ('captain', 'creator', ) list_display = ( 'name', 'get_player_count', 'get_player_list', 'created', 'updated', ) search_fields = ('name', ) def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.prefetch_related('players') def get_player_count(self, obj): return obj.players.count() get_player_count.short_description = 'Num Players' def get_player_list(self, obj): return ', '.join([p.username for p in obj.players.all()]) get_player_list.short_description = 'Players' admin.site.register(Team, TeamAdmin)
Switch login flow a little
$(document).ready(function(){ facebookSdk(loginLink); sphere(); nav(); $("#os-phrases > h2").lettering('words').children("span").lettering().children("span").lettering(); $('.stopButton').on( "click", function() { var playing = true; var music = document.getElementById("Drone"); if(playing == true){ music.muted = true; }; }); $('.playButton').on( "click", function() { var playing = false; var music = document.getElementById("Drone"); if(playing == false){ music.muted = false; }; }); }); function loginLink() { if (fbUser.access_token) { window.location = "/views/board.html"; } console.log('FB callback'); $('#boardLink').on('click', function (e) { console.log('#boardlink'); //e.stopImmediatePropagation(); if (!fbUser) { console.log('No current FB user'); FB.login(function (response) { setUser(response); if (fbUser.access_token) { window.location = "/views/board.html"; } else { console.log('No token.'); } }, { scope: 'public_profile,email' }); } }); }
$(document).ready(function(){ facebookSdk(loginLink); sphere(); nav(); $("#os-phrases > h2").lettering('words').children("span").lettering().children("span").lettering(); $('.stopButton').on( "click", function() { var playing = true; var music = document.getElementById("Drone"); if(playing == true){ music.muted = true; }; }); $('.playButton').on( "click", function() { var playing = false; var music = document.getElementById("Drone"); if(playing == false){ music.muted = false; }; }); }); function loginLink() { $('#boardLink').on('click', function (e) { console.log('#boardlink'); e.stopImmediatePropagation(); if (!fbUser) { console.log('No current FB user'); FB.login(function (response) { setUser(response); if (fbUser.access_token) { window.location = "/views/board.html"; } else { console.log('No token.'); } }, { scope: 'public_profile,email' }); } }); }
Change version from 2.2 to 2.3
<?php require_once dirname(__FILE__).'/omise-plugin/helpers/charge.php'; require_once dirname(__FILE__).'/omise-plugin/helpers/currency.php'; require_once dirname(__FILE__).'/omise-plugin/helpers/transfer.php'; // Define version of Omise-OpenCart if (!defined('OMISE_OPENCART_VERSION')) define('OMISE_OPENCART_VERSION', '2.3'); // Just mockup $datetime = new DateTime('now'); $datetime->format('Y-m-d\TH:i:s\Z'); if (!defined('OMISE_OPENCART_RELEASED_DATE')) define('OMISE_OPENCART_RELEASED_DATE', $datetime->format('Y-m-d\TH:i:s\Z')); $opencart_version = defined('VERSION') ? " OpenCart/".VERSION : ""; // Define 'OMISE_USER_AGENT_SUFFIX' if (!defined('OMISE_USER_AGENT_SUFFIX')) define('OMISE_USER_AGENT_SUFFIX', "OmiseOpenCart/".OMISE_OPENCART_VERSION.$opencart_version); // Define 'OMISE_API_VERSION' if(!defined('OMISE_API_VERSION')) define('OMISE_API_VERSION', '2014-07-27'); ?>
<?php require_once dirname(__FILE__).'/omise-plugin/helpers/charge.php'; require_once dirname(__FILE__).'/omise-plugin/helpers/currency.php'; require_once dirname(__FILE__).'/omise-plugin/helpers/transfer.php'; // Define version of Omise-OpenCart if (!defined('OMISE_OPENCART_VERSION')) define('OMISE_OPENCART_VERSION', '2.2'); // Just mockup $datetime = new DateTime('now'); $datetime->format('Y-m-d\TH:i:s\Z'); if (!defined('OMISE_OPENCART_RELEASED_DATE')) define('OMISE_OPENCART_RELEASED_DATE', $datetime->format('Y-m-d\TH:i:s\Z')); $opencart_version = defined('VERSION') ? " OpenCart/".VERSION : ""; // Define 'OMISE_USER_AGENT_SUFFIX' if (!defined('OMISE_USER_AGENT_SUFFIX')) define('OMISE_USER_AGENT_SUFFIX', "OmiseOpenCart/".OMISE_OPENCART_VERSION.$opencart_version); // Define 'OMISE_API_VERSION' if(!defined('OMISE_API_VERSION')) define('OMISE_API_VERSION', '2014-07-27'); ?>
Use next to propagate err
import User from 'src/models/UserModel'; import jwt from 'jsonwebtoken'; export const list = (req, res, next) => User.find({}) .then(data => res.json(data)) .catch(err => next(err)); export const getUser = (req, res) => { res.json(req.user); } export const registerUser = (req, res, next) => { const { email, password, displayName } = req.body; const user = new User({ email, password, displayName }); user.save() .then(newUser => res.json(newUser)) .catch(err => next(err)); } export const authenticateUser = (req, res, next) => { User.findOne({ email: req.body.email, }) .select('password') .then((user) => { if (!user) { res.status = 401; return next(new Error('You shall not pass')); } return user.comparePassword(req.body.password); }) .then((user) => { const token = jwt.sign(user.toJSON(), process.env.JWT_SECRET, { expiresIn: '7 days', }); return res.json({ token }); }) .catch((err) => { res.status = 401; next(err); }); } export const remove = (req, res, next) => User.remove({ _id: req.params.id, }) .then(data => res.json(data)) .catch(err => next(err));
import User from 'src/models/UserModel'; import jwt from 'jsonwebtoken'; export const list = (req, res, next) => User.find({}) .then(data => res.json(data)) .catch(err => next(err)); export const getUser = (req, res) => { res.json(req.user); } export const registerUser = (req, res, next) => { const { email, password, displayName } = req.body; const user = new User({ email, password, displayName }); user.save() .then(newUser => res.json(newUser)) .catch(err => next(err)); } export const authenticateUser = (req, res, next) => { User.findOne({ email: req.body.email, }) .select('password') .then((user) => { if (!user) { res.status = 401; throw new Error('You shall not pass'); } return user.comparePassword(req.body.password); }) .then((user) => { const token = jwt.sign(user.toJSON(), process.env.JWT_SECRET, { expiresIn: '7 days', }); return res.json({ token }); }) .catch((err) => { res.status = 401; next(err); }); } export const remove = (req, res, next) => User.remove({ _id: req.params.id, }) .then(data => res.json(data)) .catch(err => next(err));
Change the comments about jQuery and require.js
document.addEventListener("DOMContentLoaded", function() { var acosAplusResizeIframe = function($, window, document, undefined) { var exerciseWrapper = $('#exercise-page-content'); // A+ adds this around exercise content var newWidth = Math.max(exerciseWrapper.width(), 500); // full width of the exercise area in the A+ page var newHeight = Math.max($(window).height() * 0.8, 500); // 80% of viewport height $('.acos-iframe').width(newWidth).height(newHeight); }; var init = function($, window, document) { acosAplusResizeIframe($, window, document); $(window).on('resize', function() { acosAplusResizeIframe($, window, document); }); }; if (typeof require === 'function') { // in a require.js environment, import jQuery require(["jquery"], function(jQuery) { init(jQuery, window, document); }); } else { // in A+ (jQuery defined in the global namespace) init(jQuery, window, document); } });
document.addEventListener("DOMContentLoaded", function() { var acosAplusResizeIframe = function($, window, document, undefined) { var exerciseWrapper = $('#exercise-page-content'); // A+ adds this around exercise content var newWidth = Math.max(exerciseWrapper.width(), 500); // full width of the exercise area in the A+ page var newHeight = Math.max($(window).height() * 0.8, 500); // 80% of viewport height $('.acos-iframe').width(newWidth).height(newHeight); }; var init = function($, window, document) { acosAplusResizeIframe($, window, document); $(window).on('resize', function() { acosAplusResizeIframe($, window, document); }); }; if (typeof require === 'function') { // in Moodle require(["jquery"], function(jQuery) { init(jQuery, window, document); }); } else { // in A+ init(jQuery, window, document); } });
Remove default params for fetchThread
import Axios from 'axios'; import { THREAD_REQUEST, THREAD_LOADED, THREAD_DESTROY, THREAD_POST_LOAD } from '../constants'; function requestThread(threadID) { console.log("Action RequestThread wth ID:", threadID); return { type: THREAD_REQUEST, threadID } } function receiveThread(thread) { console.log("Action RecieveThread:", thread); return { type: THREAD_LOADED, payload: thread.data } } function destroyThread() { console.log('Action DestroyThread'); return { type: THREAD_DESTROY } } export function fetchThread(provider, boardID, threadID) { console.log(`Action FetchThread() to /${provider}/${boardID}/${threadID}`); return dispatch => { dispatch(requestThread(threadID)); return Axios.get(`/${provider}/${boardID}/${threadID}`) .then(data => dispatch(receiveThread(data))) .catch( e => console.error(e)); } } export function closeThread() { return dispatch => { return dispatch(destroyThread()) } }
import Axios from 'axios'; import { THREAD_REQUEST, THREAD_LOADED, THREAD_DESTROY, THREAD_POST_LOAD } from '../constants'; function requestThread(threadID) { console.log("Action RequestThread wth ID:", threadID); return { type: THREAD_REQUEST, threadID } } function receiveThread(thread) { console.log("Action RecieveThread:", thread); return { type: THREAD_LOADED, payload: thread.data } } function destroyThread() { console.log('Action DestroyThread'); return { type: THREAD_DESTROY } } export function fetchThread(threadID, provider="4chan", boardID="g") { console.log(`Action FetchThread() to /${provider}/${boardID}/${threadID}`); return dispatch => { dispatch(requestThread(threadID)); return Axios.get(`/${provider}/${boardID}/${threadID}`) .then(data => dispatch(receiveThread(data))) .catch( e => console.error(e)); } } export function closeThread() { return dispatch => { return dispatch(destroyThread()) } }
Fix error with generate URL
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True)
Tests: Improve error message for Promise rejections
'use strict'; const path = require('path'); const fs = require('fs'); const noop = () => {}; before('initialization', function () { process.on('unhandledRejection', err => { // I'd throw the err, but we have a heisenbug on our hands and I'd // rather not have it screw with Travis in the interim console.log(err); }); // Load and override configuration before starting the server let config; try { require.resolve('../config/config'); } catch (err) { if (err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ENOENT') throw err; // Should never happen console.log("config.js doesn't exist - creating one with default settings..."); fs.writeFileSync(path.resolve(__dirname, '../config/config.js'), fs.readFileSync(path.resolve(__dirname, '../config/config-example.js')) ); } finally { config = require('../config/config'); } require('./../lib/process-manager').disabled = true; // Actually crash if we crash config.crashguard = false; // Don't allow config to be overridden while test is running config.watchconfig = false; // Don't try to write to file system config.nofswriting = true; // Don't create a REPL require('../lib/repl').start = noop; // Start the server. require('../app'); LoginServer.disabled = true; });
'use strict'; const path = require('path'); const fs = require('fs'); const noop = () => {}; before('initialization', function () { // Load and override configuration before starting the server let config; try { require.resolve('../config/config'); } catch (err) { if (err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ENOENT') throw err; // Should never happen console.log("config.js doesn't exist - creating one with default settings..."); fs.writeFileSync(path.resolve(__dirname, '../config/config.js'), fs.readFileSync(path.resolve(__dirname, '../config/config-example.js')) ); } finally { config = require('../config/config'); } require('./../lib/process-manager').disabled = true; // Actually crash if we crash config.crashguard = false; // Don't allow config to be overridden while test is running config.watchconfig = false; // Don't try to write to file system config.nofswriting = true; // Don't create a REPL require('../lib/repl').start = noop; // Start the server. require('../app'); LoginServer.disabled = true; });
Add validation check before renting parking space
<?php namespace App\Http\Controllers; class ParkingController { public function getAll() { return Response::json('success', $this->table()->get()); } public function get($id) { $parking = $this->table()->where('id', $id)->get(); return Response::json('success', $parking); } public function rentSpace() { // Add server side validation check if space is rented $id = input('id'); $parking = $this->getParking($id)->first(); if ($parking->rented === 'true') { return Response::json('fail', [ 'message' => 'The parking space has been rented' ]); } $this->getParking($id)->update(['rented' => 'true']); return Response::json('success'); } private function table() { return \Builder::table('parking'); } private function getParking($id) { return $this->table()->where('id', $id); } }
<?php namespace App\Http\Controllers; class ParkingController { public function getAll() { return Response::json('success', $this->table()->get()); } public function get($id) { $parking = $this->table()->where('id', $id)->get(); return Response::json('success', $parking); } public function rentSpace() { // Add server side validation check if space is rented $id = input('id'); $this->table()->where('id', $id)->update(['rented' => 'true']); return Response::json('success'); } private function table() { return \Builder::table('parking'); } }
Fix error that prevented scrolling
import Ember from 'ember'; import layout from '../../templates/components/power-select/options'; export default Ember.Component.extend({ layout: layout, tagName: 'ul', attributeBindings: ['role', 'aria-controls'], role: 'listbox', init() { this._super(...arguments); this._touchMoveHandler = this._touchMoveHandler.bind(this); }, // Actions actions: { handleTouchStart(e) { this.element.addEventListener('touchmove', this._touchMoveHandler); }, handleTouchEnd(option, e) { e.preventDefault(); if (this.hasMoved) { this.hasMoved = false; return; } this.get('select.actions.choose')(option, e); } }, // Methods _touchMoveHandler() { this.hasMoved = true; this.element.removeEventListener('touchmove', this._touchMoveHandler); } });
import Ember from 'ember'; import layout from '../../templates/components/power-select/options'; export default Ember.Component.extend({ layout: layout, tagName: 'ul', attributeBindings: ['role', 'aria-controls'], role: 'listbox', init() { this._super(...arguments); this._touchMoveHandler = this._touchMoveHandler.bind(this); }, // Actions actions: { handleTouchStart(e) { e.preventDefault(); this.element.addEventListener('touchmove', this._touchMoveHandler); }, handleTouchEnd(option, e) { if (this.hasMoved) { this.hasMoved = false; return; } this.get('select.actions.choose')(option, e); } }, // Methods _touchMoveHandler() { this.hasMoved = true; this.element.removeEventListener('touchmove', this._touchMoveHandler); } });
refactor: Reset input values in controller when clear button clicked
import Ember from 'ember'; // import $ from 'jquery'; export default Ember.Component.extend({ expense: { sum: '', category: '', name: '' }, currency: '£', expenseCategories: [ 'Charity', 'Clothing', 'Education', 'Events', 'Food', 'Gifts', 'Healthcare', 'Household', 'Leisure', 'Hobbies', 'Trasportation', 'Utilities', 'Vacation' ], errorMessagesSum: { emRequired: 'This field can\'t be blank', emPattern: 'Must be a number!' }, errorMessagesCategory: { emRequired: 'Must select a category' }, didInsertElement () { componentHandler.upgradeAllRegistered(); }, actions: { clearInputs () { this.set('expense', { sum: '', category: '', name: '' }); this.$('.mdl-textfield').removeClass('is-dirty is-invalid is-touched'); }, addExpense () { this.sendAction('action', this.get('expense')); this.send('clearInputs'); } } });
import Ember from 'ember'; // import $ from 'jquery'; export default Ember.Component.extend({ expense: { sum: null, category: '', name: '' }, currency: '£', expenseCategories: [ 'Charity', 'Clothing', 'Education', 'Events', 'Food', 'Gifts', 'Healthcare', 'Household', 'Leisure', 'Hobbies', 'Trasportation', 'Utilities', 'Vacation' ], errorMessagesSum: { emRequired: 'This field can\'t be blank', emPattern: 'Must be a number!' }, errorMessagesCategory: { emRequired: 'Must select a category' }, didInsertElement () { componentHandler.upgradeAllRegistered(); }, actions: { clearInputs () { this.$('.mdl-textfield input[type=text]').val(''); this.$('.mdl-textfield').removeClass('is-dirty'); }, addExpense () { this.sendAction('action', this.get('expense')); this.send('clearInputs'); } } });
Disable logging on test runner process
import logging import mock import oauth2u import oauth2u.server.log def teardown_function(func): logging.disable(logging.INFO) def test_should_have_optional_port(): server = oauth2u.Server() assert 8000 == server.port def test_should_accept_custom_port(): server = oauth2u.Server(8888) assert 8888 == server.port def test_should_configure_log_with_default_configurations(monkeypatch): log_mock = mock.Mock() monkeypatch.setattr(oauth2u.server, 'log', log_mock) server = oauth2u.Server() assert 1 == log_mock.configure.call_count log_mock.configure.assert_called_with() def test_should_override_default_log_parameters(monkeypatch): log_mock = mock.Mock() monkeypatch.setattr(oauth2u.server, 'log', log_mock) server = oauth2u.Server(log_config={'format': '%(message)s'}) assert 1 == log_mock.configure.call_count log_mock.configure.assert_called_with(format='%(message)s')
import logging import mock import oauth2u import oauth2u.server.log def test_should_have_optional_port(): server = oauth2u.Server() assert 8000 == server.port def test_should_accept_custom_port(): server = oauth2u.Server(8888) assert 8888 == server.port def test_should_configure_log_with_default_configurations(monkeypatch): log_mock = mock.Mock() monkeypatch.setattr(oauth2u.server, 'log', log_mock) server = oauth2u.Server() assert 1 == log_mock.configure.call_count log_mock.configure.assert_called_with() def test_should_override_default_log_parameters(monkeypatch): log_mock = mock.Mock() monkeypatch.setattr(oauth2u.server, 'log', log_mock) server = oauth2u.Server(log_config={'format': '%(message)s'}) assert 1 == log_mock.configure.call_count log_mock.configure.assert_called_with(format='%(message)s')
Use TeX magic to allow bulder override
'use babel' import _ from 'lodash' import fs from 'fs-plus' import path from 'path' import MagicParser from './parsers/magic-parser' export default class BuilderRegistry { getBuilder (filePath) { const builders = this.getAllBuilders() const candidates = builders.filter((builder) => builder.canProcess(filePath)) switch (candidates.length) { case 0: return null case 1: return candidates[0] } return this.resolveAmbiguousBuilders(candidates, this.getBuilderFromMagic(filePath)) } getBuilderFromMagic (filePath) { const magic = new MagicParser(filePath).parse() if (magic && magic.builder) { return magic.builder } return null } getAllBuilders () { const moduleDir = path.join(__dirname, 'builders') const entries = fs.readdirSync(moduleDir) const builders = entries.map((entry) => require(path.join(moduleDir, entry))) return builders } resolveAmbiguousBuilders (builders, builderOverride) { const name = builderOverride || atom.config.get('latex.builder') const namePattern = new RegExp(`^${name}Builder$`, 'i') const builder = _.find(builders, builder => builder.name.match(namePattern)) if (builder) return builder latex.log.warning(`Unable to resolve builder named ${name} using fallback ${builders[0].name}.`) return builders[0] } }
'use babel' import fs from 'fs-plus' import path from 'path' export default class BuilderRegistry { getBuilder (filePath) { const builders = this.getAllBuilders() const candidates = builders.filter((builder) => builder.canProcess(filePath)) switch (candidates.length) { case 0: return null case 1: return candidates[0] } return this.resolveAmbigiousBuilders(candidates) } getAllBuilders () { const moduleDir = path.join(__dirname, 'builders') const entries = fs.readdirSync(moduleDir) const builders = entries.map((entry) => require(path.join(moduleDir, entry))) return builders } resolveAmbigiousBuilders (builders) { const names = builders.map((builder) => builder.name) const indexOfLatexmk = names.indexOf('LatexmkBuilder') const indexOfTexify = names.indexOf('TexifyBuilder') if (names.length === 2 && indexOfLatexmk >= 0 && indexOfTexify >= 0) { switch (atom.config.get('latex.builder')) { case 'latexmk': return builders[indexOfLatexmk] case 'texify': return builders[indexOfTexify] } } throw Error('Unable to resolve ambigous builder registration') } }
Fix for $.ajaxSetup not working in Chrome. Usage is not recommended. This caused changes to custom request headers to be ignored. Calling ajaxSetup wasn't updating the headers used by the next AJAX call. The jQuery docs recommend not using ajaxSetup.
HAL.Http.Client = function(opts) { this.vent = opts.vent; this.defaultHeaders = { 'Accept': 'application/hal+json, application/json, */*; q=0.01' }; }; HAL.Http.Client.prototype.get = function(url) { var self = this; this.vent.trigger('location-change', { url: url }); var jqxhr = $.ajax({ url: url, dataType: 'json', headers: this.defaultHeaders, success: function(resource, textStatus, jqXHR) { self.vent.trigger('response', { resource: resource, jqxhr: jqXHR, headers: jqXHR.getAllResponseHeaders() }); } }).error(function() { self.vent.trigger('fail-response', { jqxhr: jqxhr }); }); }; HAL.Http.Client.prototype.request = function(opts) { var self = this; opts.dataType = 'json'; self.vent.trigger('location-change', { url: opts.url }); return jqxhr = $.ajax(opts); }; HAL.Http.Client.prototype.updateDefaultHeaders = function(headers) { this.defaultHeaders = headers; }; HAL.Http.Client.prototype.getDefaultHeaders = function() { return this.defaultHeaders; };
HAL.Http.Client = function(opts) { this.vent = opts.vent; $.ajaxSetup({ headers: { 'Accept': 'application/hal+json, application/json, */*; q=0.01' } }); }; HAL.Http.Client.prototype.get = function(url) { var self = this; this.vent.trigger('location-change', { url: url }); var jqxhr = $.ajax({ url: url, dataType: 'json', success: function(resource, textStatus, jqXHR) { self.vent.trigger('response', { resource: resource, jqxhr: jqXHR, headers: jqXHR.getAllResponseHeaders() }); } }).error(function() { self.vent.trigger('fail-response', { jqxhr: jqxhr }); }); }; HAL.Http.Client.prototype.request = function(opts) { var self = this; opts.dataType = 'json'; self.vent.trigger('location-change', { url: opts.url }); return jqxhr = $.ajax(opts); }; HAL.Http.Client.prototype.updateDefaultHeaders = function(headers) { this.defaultHeaders = headers; $.ajaxSetup({ headers: headers }); }; HAL.Http.Client.prototype.getDefaultHeaders = function() { return this.defaultHeaders; };
Update library version to 0.1.0
Package.describe({ name: 'toystars:elasticsearch-sync', version: '0.1.0', // Brief, one-line summary of the package. summary: 'ElasticSearch utility wrapper for mongoDB integration and sync', // URL to the Git repository containing the source code for this package. git: 'https://github.com/toystars/elasticsearch-sync', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Npm.depends({ 'mongo-oplog': '1.0.1', 'elasticsearch': '10.0.1', 'mongodb': '2.1.16', 'dot-object': '1.4.1' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use([ 'ecmascript', 'underscore' ]); api.addFiles([ 'lib/util.js', "lib/index.js" ], ['server']); api.export("ESMongoSync", 'server'); });
Package.describe({ name: 'toystars:elasticsearch-sync', version: '0.0.9', // Brief, one-line summary of the package. summary: 'ElasticSearch utility wrapper for mongoDB integration and sync', // URL to the Git repository containing the source code for this package. git: 'https://github.com/toystars/elasticsearch-sync', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Npm.depends({ 'mongo-oplog': '1.0.1', 'elasticsearch': '10.0.1', 'mongodb': '2.1.16', 'dot-object': '1.4.1' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use([ 'ecmascript', 'underscore' ]); api.addFiles([ 'lib/util.js', "lib/index.js" ], ['server']); api.export("ESMongoSync", 'server'); });
Correct name for the shopping search api
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Search API for Shopping. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main()
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Shopping API. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main()
Add a version sanity check
import sys if sys.version < '3.4': print('Sorry, this is not a compatible version of Python. Use 3.4 or later.') exit(1) import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages with open('README.md') as f: description = f.read() setup(name='WebShack', version='0.0.1', description='Web Component/Polymer distribution system', author='Alistair Lynn', author_email='arplynn@gmail.com', license="MIT", long_description=description, url='https://github.com/prophile/webshack', entry_points = { 'console_scripts': [ 'webshack = webshack.cli:main' ] }, zip_safe=True, package_data = { 'webshack': ['*.yaml'] }, install_requires=[ 'tinycss >=0.3, <0.4', 'PyYAML >=3.11, <4', 'docopt >=0.6.2, <0.7', 'termcolor >=1.1.0, <2' ], packages=find_packages())
import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages with open('README.md') as f: description = f.read() setup(name='WebShack', version='0.0.1', description='Web Component/Polymer distribution system', author='Alistair Lynn', author_email='arplynn@gmail.com', license="MIT", long_description=description, url='https://github.com/prophile/webshack', entry_points = { 'console_scripts': [ 'webshack = webshack.cli:main' ] }, zip_safe=True, package_data = { 'webshack': ['*.yaml'] }, install_requires=[ 'tinycss >=0.3, <0.4', 'PyYAML >=3.11, <4', 'docopt >=0.6.2, <0.7', 'termcolor >=1.1.0, <2' ], packages=find_packages())
Test commit, magnus tok ikke feil
package models; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import com.fasterxml.jackson.annotation.JsonIgnore; import play.db.ebean.Model; import play.db.ebean.Model.Finder; @Entity public class Guest extends Model { @Id public Long id; @OneToMany(cascade = CascadeType.ALL, mappedBy = "guest") @JsonIgnore public List<Booking> booking =new ArrayList<Booking>(); /** TODO REMOVE TEST **/ public Guest(long id) { this.id = id; } /** END TEST **/ public static Finder<Long, Guest> find = new Finder<Long, Guest>(Long.class, Guest.class); }
package models; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import com.fasterxml.jackson.annotation.JsonIgnore; import play.db.ebean.Model; import play.db.ebean.Model.Finder; //tar magnus feil? @Entity public class Guest extends Model { @Id public Long id; @OneToMany(cascade = CascadeType.ALL, mappedBy = "guest") @JsonIgnore public List<Booking> booking =new ArrayList<Booking>(); /** TODO REMOVE TEST **/ public Guest(long id) { this.id = id; } /** END TEST **/ public static Finder<Long, Guest> find = new Finder<Long, Guest>(Long.class, Guest.class); }
Allow "-" as a char in a filename
'''Constants used by TRender. :copyright: 2015, Jeroen van der Heijden (Transceptor Technology) ''' LINE_IF = 1 LINE_ELSE = 2 LINE_ELIF = 4 LINE_END = 8 LINE_MACRO = 16 LINE_COMMENT = 32 LINE_BLOCK = 64 LINE_FOR = 128 LINE_PASTE = 256 LINE_TEXT = 512 LINE_INCLUDE = 1024 LINE_EXTEND = 2048 LINE_EMPTY = 4096 EOF_TEXT = 8192 ALWAYS_ALLOWED = ( LINE_IF | LINE_MACRO | LINE_PASTE | LINE_TEXT | LINE_COMMENT | LINE_FOR | LINE_BLOCK | LINE_INCLUDE | LINE_EXTEND | LINE_EMPTY) MAP_LINE_TYPE = { True: LINE_TEXT, None: LINE_EMPTY, 'if': LINE_IF, 'else': LINE_ELSE, 'elif': LINE_ELIF, 'end': LINE_END, 'for': LINE_FOR, 'macro': LINE_MACRO, 'block': LINE_BLOCK, 'include': LINE_INCLUDE, 'extend': LINE_EXTEND, '': LINE_COMMENT } VAR = 'a-zA-Z0-9_' VAR_DOTS = VAR + '\.' FILENAME = 'a-zA-Z0-9_\-\./'
'''Constants used by TRender. :copyright: 2015, Jeroen van der Heijden (Transceptor Technology) ''' LINE_IF = 1 LINE_ELSE = 2 LINE_ELIF = 4 LINE_END = 8 LINE_MACRO = 16 LINE_COMMENT = 32 LINE_BLOCK = 64 LINE_FOR = 128 LINE_PASTE = 256 LINE_TEXT = 512 LINE_INCLUDE = 1024 LINE_EXTEND = 2048 LINE_EMPTY = 4096 EOF_TEXT = 8192 ALWAYS_ALLOWED = ( LINE_IF | LINE_MACRO | LINE_PASTE | LINE_TEXT | LINE_COMMENT | LINE_FOR | LINE_BLOCK | LINE_INCLUDE | LINE_EXTEND | LINE_EMPTY) MAP_LINE_TYPE = { True: LINE_TEXT, None: LINE_EMPTY, 'if': LINE_IF, 'else': LINE_ELSE, 'elif': LINE_ELIF, 'end': LINE_END, 'for': LINE_FOR, 'macro': LINE_MACRO, 'block': LINE_BLOCK, 'include': LINE_INCLUDE, 'extend': LINE_EXTEND, '': LINE_COMMENT } VAR = 'a-zA-Z0-9_' VAR_DOTS = VAR + '\.' FILENAME = 'a-zA-Z0-9_\./'
Fix support of custom background on icons
import React from 'react'; import IconSVG from './IconSVG'; import { iconClass } from './util'; import { prefixable } from '../../decorators'; export const Icon = (props) => { const { sprite, icon, title, circle, background, size, div, prefix } = props; const backgroundClass = !background ? `icon-${sprite}-${iconClass(sprite, icon)}` : `icon-${background}`; const sldsClasses = [ { icon_container: true }, { 'icon_container--circle': circle }, { [`${backgroundClass}`]: true }, ]; const WrapperElement = div ? 'div' : 'span'; return ( <WrapperElement className={prefix(sldsClasses, props)} title={title}> <IconSVG sprite={sprite} icon={icon} size={size} background={background} /> <span className={prefix(['assistive-text'])}>{title}</span> </WrapperElement> ); }; Icon.propTypes = { /** * the prefix function from the prefixable HOC */ prefix: React.PropTypes.func, sprite: React.PropTypes.oneOf(['action', 'custom', 'doctype', 'standard', 'utility']).isRequired, icon: React.PropTypes.string.isRequired, title: React.PropTypes.string, circle: React.PropTypes.bool, div: React.PropTypes.bool, background: React.PropTypes.string, size: React.PropTypes.oneOf(['x-small', 'small', 'medium', 'large']), }; export default prefixable(Icon);
import React from 'react'; import IconSVG from './IconSVG'; import { iconClass } from './util'; import { prefixable } from '../../decorators'; export const Icon = (props) => { const { sprite, icon, title, circle, background, size, div, prefix } = props; const backgroundClass = !background ? `icon-${sprite}-${iconClass(sprite, icon)}` : `icon-${background}`; const sldsClasses = [ { icon_container: true }, { 'icon_container--circle': circle }, { [`${backgroundClass}`]: true }, ]; const WrapperElement = div ? 'div' : 'span'; return ( <WrapperElement className={prefix(sldsClasses, props)} title={title}> <IconSVG sprite={sprite} icon={icon} size={size} /> <span className={prefix(['assistive-text'])}>{title}</span> </WrapperElement> ); }; Icon.propTypes = { /** * the prefix function from the prefixable HOC */ prefix: React.PropTypes.func, sprite: React.PropTypes.oneOf(['action', 'custom', 'doctype', 'standard', 'utility']).isRequired, icon: React.PropTypes.string.isRequired, title: React.PropTypes.string, circle: React.PropTypes.bool, div: React.PropTypes.bool, background: React.PropTypes.string, size: React.PropTypes.oneOf(['x-small', 'small', 'medium', 'large']), }; export default prefixable(Icon);
Fix to typing of loop variables
important: Set[str] = {"Albert Einstein" , "Alan Turing"} texts: Dict[str, str] = input() # {"<author >" : "<t e x t >"} freqdict: Dict[str, int] = {} # defaultdict(int) err: int recognized as varId #initialized to 0 a: str = "" #necessary? b: str = "" for a, b in texts.items(): if a in important: #texts of important authors weighted twice weight: int = 2 else: weight: int = 1 words: List[str] = a.split() #Bug A: Should be `b' (values) word: str = "" for word in words: #and Bug B: Wrong indentation word: str = word.lower() freqdict[word]: int = freqdict[word] + weight print(freqdict) #outputs <word>:<count>, ...
important: Set[str] = {"Albert Einstein" , "Alan Turing"} texts: Dict[str, str] = input() # {"<author >" : "<t e x t >"} freqdict: Dict[str, int] = {} # defaultdict(int) err: int recognized as varId #initialized to 0 a: str = "" #necessary? b: str = "" for a, b in texts.items(): if a in important: #texts of important authors weighted twice weight: int = 2 else: weight: int = 1 words: List[str] = a.split() #Bug A: Should be `b' (values) for word in words: #and Bug B: Wrong indentation word: str = word.lower() freqdict[word]: int = freqdict[word] + weight print(freqdict) #outputs <word>:<count>, ...
Fix theme lookup in OTU form module Was causing application crash.
import React from "react"; import styled from "styled-components"; import { ModalBody, ModalFooter, Input, InputError, InputGroup, InputLabel, SaveButton } from "../../base"; const OTUFormBody = styled(ModalBody)` display: grid; grid-template-columns: 9fr 4fr; grid-column-gap: ${props => props.theme.gap.column}; `; export const OTUForm = ({ abbreviation, name, error, onChange, onSubmit }) => ( <form onSubmit={onSubmit}> <OTUFormBody> <InputGroup> <InputLabel>Name</InputLabel> <Input error={error} name="name" value={name} onChange={onChange} /> <InputError>{error}</InputError> </InputGroup> <InputGroup> <InputLabel>Abbreviation</InputLabel> <Input name="abbreviation" value={abbreviation} onChange={onChange} /> </InputGroup> </OTUFormBody> <ModalFooter> <SaveButton /> </ModalFooter> </form> );
import React from "react"; import styled from "styled-components"; import { ModalBody, ModalFooter, Input, InputError, InputGroup, InputLabel, SaveButton } from "../../base"; const OTUFormBody = styled(ModalBody)` display: grid; grid-template-columns: 9fr 4fr; grid-column-gap: ${props => props.gap.column}; `; export const OTUForm = ({ abbreviation, name, error, onChange, onSubmit }) => ( <form onSubmit={onSubmit}> <OTUFormBody> <InputGroup> <InputLabel>Name</InputLabel> <Input error={error} name="name" value={name} onChange={onChange} /> <InputError>{error}</InputError> </InputGroup> <InputGroup> <InputLabel>Abbreviation</InputLabel> <Input name="abbreviation" value={abbreviation} onChange={onChange} /> </InputGroup> </OTUFormBody> <ModalFooter> <SaveButton /> </ModalFooter> </form> );
Use the replacement data source
package org.bridgedb.examples; import org.bridgedb.BridgeDb; import org.bridgedb.IDMapper; import org.bridgedb.IDMapperException; import org.bridgedb.Xref; import org.bridgedb.bio.BioDataSource; public class ChebiPubchemExample { public static void main (String[] args) throws ClassNotFoundException, IDMapperException { // We'll use the BridgeRest webservice in this case, as it does compound mapping fairly well. // We'll use the human database, but it doesn't really matter which species we pick. Class.forName ("org.bridgedb.webservice.bridgerest.BridgeRest"); IDMapper mapper = BridgeDb.connect("idmapper-bridgerest:http://webservice.bridgedb.org/Human"); // Start with defining the Chebi identifier for // Methionine, id 16811 Xref src = new Xref("16811", BioDataSource.CHEBI); // the method returns a set, but in actual fact there is only one result for (Xref dest : mapper.mapID(src, BioDataSource.PUBCHEM_COMPOUND)) { // this should print 6137, the pubchem identifier for Methionine. System.out.println ("" + dest.getId()); } } }
package org.bridgedb.examples; import org.bridgedb.BridgeDb; import org.bridgedb.IDMapper; import org.bridgedb.IDMapperException; import org.bridgedb.Xref; import org.bridgedb.bio.BioDataSource; public class ChebiPubchemExample { public static void main (String[] args) throws ClassNotFoundException, IDMapperException { // We'll use the BridgeRest webservice in this case, as it does compound mapping fairly well. // We'll use the human database, but it doesn't really matter which species we pick. Class.forName ("org.bridgedb.webservice.bridgerest.BridgeRest"); IDMapper mapper = BridgeDb.connect("idmapper-bridgerest:http://webservice.bridgedb.org/Human"); // Start with defining the Chebi identifier for // Methionine, id 16811 Xref src = new Xref("16811", BioDataSource.CHEBI); // the method returns a set, but in actual fact there is only one result for (Xref dest : mapper.mapID(src, BioDataSource.PUBCHEM)) { // this should print 6137, the pubchem identifier for Methionine. System.out.println ("" + dest.getId()); } } }
Create intermidate dirs if they do not exist when moving files
""" Script to move corrupt images to 'dirty' directory Reads list of images to move. Does not verify that images are corrupt - Simply moves to 'dirty' directory of appropriate data-release creating the required directory structure """ import os import argparse parser = argparse.ArgumentParser( description="Move corrupt images to 'dirty' dir") parser.add_argument('-i', dest='inputFiles', required=True, help='File containing list of images to move' ) parser.add_argument('-s', dest='splitString', help='token to separate the basedir from input files' ) parser.add_argument('-r', dest='replacementString', help='String to replace the split string with' ) parser.add_argument('-d', dest='destDirBase', required=True, help='Path to the base of the destination dir' ) args = parser.parse_args() input_files = args.inputFiles split_string = "" if args.splitString is None else args.splitString replacement_string = "" if args.replacementString is None else args.replacementString with open(input_files,'rt') as f: fnames = [fname.strip('\n') for fname in f.readlines()] for fname in fnames: fname2 = fname.replace(split_string, replacement_string) os.renames(fname, fname2)
""" Script to move corrupt images to 'dirty' directory Reads list of images to move. Does not verify that images are corrupt - Simply moves to 'dirty' directory of appropriate data-release creating the required directory structure """ import os import argparse parser = argparse.ArgumentParser( description="Move corrupt images to 'dirty' dir") parser.add_argument('-i', dest='inputFiles', required=True, help='File containing list of images to move' ) parser.add_argument('-s', dest='splitString', help='token to separate the basedir from input files' ) parser.add_argument('-r', dest='replacementString', help='String to replace the split string with' ) parser.add_argument('-d', dest='destDirBase', required=True, help='Path to the base of the destination dir' ) args = parser.parse_args() input_files = args.inputFiles split_string = "" if args.splitString is None else args.splitString replacement_string = "" if args.replacementString is None else args.replacementString with open(input_files,'rt') as f: fnames = [fname.strip('\n') for fname in f.readlines()] for fname in fnames: fname2 = fname.replace(split_string, replacement_string) os.rename(fname, fname2)
Add simple tests for matrix operands for distance measure.
import numpy as np import nearpy.distances class MatrixCosineDistance(nearpy.distances.CosineDistance): """ A distance measure for calculating the cosine distance between matrices. """ def distance(self, x, y): if len(x.shape) <= 1: return super(MatrixCosineDistance, self).distance(x, y) k = x.shape[1] if len(y.shape) > 1: m = y.shape[1] else: m = 1 d = np.empty((k, m), dtype=np.dtype(x[0, 0])) for i in xrange(k): d[i, :] = super(MatrixCosineDistance, self).distance(x[:, i], y) return d
import numpy as np import nearpy.distances class MatrixCosineDistance(nearpy.distances.CosineDistance): """ A distance measure for calculating the cosine distance between matrices. """ def distance(self, x, y): if len(x.shape) <= 1: return super(MatrixCosineDistance, self).distance(x, y) k = x.shape[1] if len(y.shape) > 1: m = y.shape[1] else: m = 1 d = np.empty((k, m), dtype=np.dtype(x[0,0])) for i in xrange(k): d[i,:] = super(MatrixCosineDistance, self).distance(x[:,i], y) return d
Add support for "egulias/email-validator" 2.x
<?php /* * This file is part of Respect/Validation. * * (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace Respect\Validation\Rules; use Egulias\EmailValidator\EmailValidator; use Egulias\EmailValidator\Validation\RFCValidation; class Email extends AbstractRule { public function __construct(EmailValidator $emailValidator = null) { $this->emailValidator = $emailValidator; } public function getEmailValidator() { if (!$this->emailValidator instanceof EmailValidator && class_exists('Egulias\\EmailValidator\\EmailValidator')) { $this->emailValidator = new EmailValidator(); } return $this->emailValidator; } public function validate($input) { $emailValidator = $this->getEmailValidator(); if (!$emailValidator instanceof EmailValidator) { return is_string($input) && filter_var($input, FILTER_VALIDATE_EMAIL); } if (!class_exists('Egulias\\EmailValidator\\Validation\\RFCValidation')) { return $emailValidator->isValid($input); } return $emailValidator->isValid($input, new RFCValidation()); } }
<?php /* * This file is part of Respect/Validation. * * (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace Respect\Validation\Rules; use Egulias\EmailValidator\EmailValidator; class Email extends AbstractRule { public function __construct(EmailValidator $emailValidator = null) { $this->emailValidator = $emailValidator; } public function getEmailValidator() { if (!$this->emailValidator instanceof EmailValidator && class_exists('Egulias\EmailValidator\EmailValidator')) { $this->emailValidator = new EmailValidator(); } return $this->emailValidator; } public function validate($input) { $emailValidator = $this->getEmailValidator(); if (null !== $emailValidator) { return $emailValidator->isValid($input); } return is_string($input) && filter_var($input, FILTER_VALIDATE_EMAIL); } }
Update stream name to Replay
from index import app from flask import render_template, request from config import BASE_URL from query import get_callout, get_billboard SHEET_ID = 'tzE2PsqJoWRpENlMr-ZlS8A' #SHEET_ID = 'tIk5itVcfOHUmakkmpjCcxw' # Demo sheet @app.route('/') def index(): page_url = BASE_URL + request.path page_title = 'Audio Player' stream_name = "Replay" social = { 'title': "VPR Audio Player", 'subtitle': "", 'img': "static/img/logo/vpr-logo-share.jpg", 'description': "Listen to the live streams of VPR News, VPR Classical, the BBC, Jazz24 and My Place.", 'twitter_text': "News, Classical, the BBC and more. The VPR Audio Player:", 'twitter_hashtag': "" } return render_template('content.html', page_title=page_title, social=social, stream_name=stream_name, page_url=page_url) @app.route('/billboard') def billboard(): billboard = get_billboard(SHEET_ID) return render_template('billboard.html', billboard=billboard) @app.route('/callout') def callout(): callout = get_callout(SHEET_ID) return render_template('callout.html', callout=callout)
from index import app from flask import render_template, request from config import BASE_URL from query import get_callout, get_billboard SHEET_ID = 'tzE2PsqJoWRpENlMr-ZlS8A' #SHEET_ID = 'tIk5itVcfOHUmakkmpjCcxw' # Demo sheet #@app.route('/') #def index(): # page_url = BASE_URL + request.path # page_title = 'Audio Player' # stream_name = "My Place" # # social = { # 'title': "VPR Audio Player", # 'subtitle': "", # 'img': "static/img/logo/vpr-logo-share.jpg", # 'description': "Listen to the live streams of VPR News, VPR Classical, the BBC, Jazz24 and My Place.", # 'twitter_text': "News, Classical, the BBC and more. The VPR Audio Player:", # 'twitter_hashtag': "" # } # # return render_template('content.html', # page_title=page_title, # social=social, # stream_name=stream_name, # page_url=page_url) # @app.route('/billboard') def billboard(): billboard = get_billboard(SHEET_ID) return render_template('billboard.html', billboard=billboard) @app.route('/callout') def callout(): callout = get_callout(SHEET_ID) return render_template('callout.html', callout=callout)
Delete store purchases when the related store is deleted
<?php class Kohana_Model_Store extends Jam_Model { /** * @codeCoverageIgnore */ public static function initialize(Jam_Meta $meta) { $meta ->behaviors(array( 'paranoid' => Jam::behavior('paranoid'), )) ->associations(array( 'store_purchases' => Jam::association('hasmany', array( 'inverse_of' => 'store', 'foreign_model' => 'store_purchase', 'delete_on_remove' => Jam_Association::DELETE, 'dependent' => Jam_Association::DELETE, )), 'purchases' => Jam::association('manytomany', array( 'foreign_model' => 'purchase', 'join_table' => 'store_purchases', )), )) ->fields(array( 'id' => Jam::field('primary'), 'name' => Jam::field('string'), 'currency' => Jam::field('string'), )) ->validator('name', array( 'present' => TRUE )); } public function purchases_total_price($types) { $prices = array_map(function($purchase) use ($types) { return $purchase->total_price($types); }, $this->purchases->as_array()); return Jam_Price::sum($prices, $this->currency); } }
<?php class Kohana_Model_Store extends Jam_Model { /** * @codeCoverageIgnore */ public static function initialize(Jam_Meta $meta) { $meta ->behaviors(array( 'paranoid' => Jam::behavior('paranoid'), )) ->associations(array( 'store_purchases' => Jam::association('hasmany', array( 'inverse_of' => 'store', 'foreign_model' => 'store_purchase', )), 'purchases' => Jam::association('manytomany', array( 'foreign_model' => 'purchase', 'join_table' => 'store_purchases', )), )) ->fields(array( 'id' => Jam::field('primary'), 'name' => Jam::field('string'), 'currency' => Jam::field('string'), )) ->validator('name', array( 'present' => TRUE )); } public function purchases_total_price($types) { $prices = array_map(function($purchase) use ($types) { return $purchase->total_price($types); }, $this->purchases->as_array()); return Jam_Price::sum($prices, $this->currency); } }
Fix typo on job module
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def queue_update_job(): q.enqueue(jobs.update_graph) @sched.scheduled_job('interval', minutes=1) def queue_stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', minutes=1) def queue_export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() # Wait a bit for Sesame to start time.sleep(10) # Queue the stats job first. This creates the repository before any other # jobs are run. q.enqueue(jobs.calculate_stats) # Start the scheduler sched.start()
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def queue_update_job(): q.enqueue(jobs.update_graph) @sched.scheduled_job('interval', minutes=1) def queue_stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', minutes=1) def queue_export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() # Wait a bit for Sesame to start time.sleep(10) # Queue the stats job first. This creates the repository before any other # jobs are run. q.enequeue(jobs.calculate_stats) # Start the scheduler sched.start()
Disable fires in the last 7 days on map
import { fetchFireAlertsByGeostore } from 'services/analysis'; import { POLITICAL_BOUNDARIES_DATASET, FIRES_VIIRS_DATASET, } from 'data/datasets'; import { DISPUTED_POLITICAL_BOUNDARIES, POLITICAL_BOUNDARIES, FIRES_ALERTS_VIIRS, } from 'data/layers'; import getWidgetProps from './selectors'; export default { widget: 'fires', title: 'Fires in {location}', categories: ['forest-change', 'summary'], admins: ['adm0', 'adm1', 'adm2'], types: [], metaKey: 'widget_fire_alert_location', type: 'fires', colors: 'fires', sortOrder: { summary: 7, forestChange: 11, }, visible: ['analysis'], chartType: 'listLegend', sentences: { initial: '{count} active fires detected in {location} in the last 7 days.', }, datasets: [ { dataset: POLITICAL_BOUNDARIES_DATASET, layers: [DISPUTED_POLITICAL_BOUNDARIES, POLITICAL_BOUNDARIES], boundary: true, }, // fires { dataset: FIRES_VIIRS_DATASET, layers: [FIRES_ALERTS_VIIRS], }, ], getData: (params) => fetchFireAlertsByGeostore(params).then((response) => ({ fires: response.data.data.attributes.value, })), getWidgetProps, };
import { fetchFireAlertsByGeostore } from 'services/analysis'; import { POLITICAL_BOUNDARIES_DATASET, FIRES_VIIRS_DATASET, } from 'data/datasets'; import { DISPUTED_POLITICAL_BOUNDARIES, POLITICAL_BOUNDARIES, FIRES_ALERTS_VIIRS, } from 'data/layers'; import getWidgetProps from './selectors'; export default { widget: 'fires', title: 'Fires in {location}', categories: ['forest-change', 'summary'], admins: ['adm0', 'adm1', 'adm2'], types: ['geostore', 'use'], metaKey: 'widget_fire_alert_location', type: 'fires', colors: 'fires', sortOrder: { summary: 7, forestChange: 11, }, visible: ['analysis'], chartType: 'listLegend', sentences: { initial: '{count} active fires detected in {location} in the last 7 days.', }, datasets: [ { dataset: POLITICAL_BOUNDARIES_DATASET, layers: [DISPUTED_POLITICAL_BOUNDARIES, POLITICAL_BOUNDARIES], boundary: true, }, // fires { dataset: FIRES_VIIRS_DATASET, layers: [FIRES_ALERTS_VIIRS], }, ], getData: (params) => fetchFireAlertsByGeostore(params).then((response) => ({ fires: response.data.data.attributes.value, })), getWidgetProps, };
Send result as json instead of plaintext
import flask import json from flask import jsonify from donut.modules.groups import blueprint, helpers @blueprint.route("/1/groups/") def get_groups_list(): # Create a dict of the passed in attribute which are filterable filterable_attrs = ["group_id", "group_name", "group_desc", "type"] attrs = { tup: flask.request.args[tup] for tup in flask.request.args if tup in filterable_attrs } fields = None if "fields" in flask.request.args: fields = [f.strip() for f in flask.request.args["fields"].split(',')] return jsonify(helpers.get_group_list_data(fields=fields, attrs=attrs)) @blueprint.route("/1/groups/<int:group_id>/") def get_groups(group_id): """GET /1/groups/<int:group_id>/""" return jsonify(helpers.get_group_data(group_id)) @blueprint.route("/1/groups/<int:group_id>/members/") def get_group_members(group_id): """GET /1/groups/<int:group_id>/""" return json.dumps(helpers.get_members_by_group(group_id))
import flask import json from flask import jsonify from donut.modules.groups import blueprint, helpers @blueprint.route("/1/groups/") def get_groups_list(): # Create a dict of the passed in attribute which are filterable filterable_attrs = ["group_id", "group_name", "group_desc", "type"] attrs = { tup: flask.request.args[tup] for tup in flask.request.args if tup in filterable_attrs } fields = None if "fields" in flask.request.args: fields = [f.strip() for f in flask.request.args["fields"].split(',')] return jsonify(helpers.get_group_list_data(fields=fields, attrs=attrs)) @blueprint.route("/1/groups/<int:group_id>/") def get_groups(group_id): """GET /1/groups/<int:group_id>/""" return jsonify(helpers.get_group_data(group_id)) @blueprint.route("/1/groups/<int:group_id>/members/") def get_group_members(group_id): """GET /1/groups/<int:group_id>/""" return str(helpers.get_members_by_group(group_id))
Update testing frontend a bit
/* global: io */ const socket = io.connect('http://localhost:3000'); socket.on('connection', () => {}); socket.on('meeting', (data) => { let title = 'Ingen aktiv generalforsamling.'; if (data && data.title) { title = data.title; } document.getElementById('meeting-title').innerHTML = title; socket.emit('my other event', { my: 'data' }); const node = document.createElement('p'); node.innerHTML = title; document.getElementById('log').appendChild(node); console.log('emitting issue thingy'); socket.emit('issue', { action: 'open', title: 'Mitt spørsmål' }); setTimeout(() => { socket.emit('issue', { action: 'close', title: 'Mitt spørsmål' }); }, 10000); }); socket.on('public', (data) => { console.log('public', data); }); socket.on('private', (data) => { console.log('priv', data); }); socket.on('issue', (data) => { console.log('issue', data); let question = 'Ingen aktiv sak for øyeblikket.'; if (data && data.title && data.action !== 'close') { question = data.title; } document.getElementById('question').innerHTML = question; });
/* global: io */ const socket = io.connect('http://localhost:3000'); socket.on('connection', () => {}); socket.on('meeting', (data) => { let title = 'Ingen aktiv generalforsamling.'; if (data && data.title) { title = data.title; } document.getElementById('meeting-title').innerHTML = title; socket.emit('my other event', { my: 'data' }); const node = document.createElement('p'); node.innerHTML = title; document.getElementById('log').appendChild(node); console.log('emitting issue thingy'); socket.emit('issue', { action: 'open', title: 'Mitt spørsmål' }); setTimeout(() => { socket.emit('issue', { action: 'close', title: 'Mitt spørsmål' }); }, 10000) }); socket.on('issue', (data) => { let question = 'Ingen aktiv sak for øyeblikket.'; if (data && data.title && data.action !== 'close') { question = data.title; } document.getElementById('question').innerHTML = question; });
Enable building hybrid capsule/non-capsule packages (CNY-3271)
# # Copyright (c) 2009 rPath, Inc. # # This program is distributed under the terms of the Common Public License, # version 1.0. A copy of this license should have been distributed with this # source file in a file called LICENSE. If it is not present, the license # is always available at http://www.rpath.com/permanent/licenses/CPL-1.0. # # This program is distributed in the hope that it will be useful, but # without any warranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the Common Public License for # full details. # import inspect from conary.build import action, defaultrecipes from conary.build.recipe import RECIPE_TYPE_CAPSULE from conary.build.packagerecipe import BaseRequiresRecipe, AbstractPackageRecipe class AbstractCapsuleRecipe(AbstractPackageRecipe): internalAbstractBaseClass = 1 internalPolicyModules = ( 'packagepolicy', 'capsulepolicy' ) _recipeType = RECIPE_TYPE_CAPSULE def __init__(self, *args, **kwargs): klass = self._getParentClass('AbstractPackageRecipe') klass.__init__(self, *args, **kwargs) from conary.build import build for name, item in build.__dict__.items(): if inspect.isclass(item) and issubclass(item, action.Action): self._addBuildAction(name, item) def loadSourceActions(self): self._loadSourceActions(lambda item: item._packageAction is True) exec defaultrecipes.CapsuleRecipe
# # Copyright (c) 2009 rPath, Inc. # # This program is distributed under the terms of the Common Public License, # version 1.0. A copy of this license should have been distributed with this # source file in a file called LICENSE. If it is not present, the license # is always available at http://www.rpath.com/permanent/licenses/CPL-1.0. # # This program is distributed in the hope that it will be useful, but # without any warranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the Common Public License for # full details. # from conary.build import defaultrecipes from conary.build.recipe import RECIPE_TYPE_CAPSULE from conary.build.packagerecipe import BaseRequiresRecipe, AbstractPackageRecipe class AbstractCapsuleRecipe(AbstractPackageRecipe): internalAbstractBaseClass = 1 internalPolicyModules = ( 'packagepolicy', 'capsulepolicy' ) _recipeType = RECIPE_TYPE_CAPSULE def __init__(self, *args, **kwargs): klass = self._getParentClass('AbstractPackageRecipe') klass.__init__(self, *args, **kwargs) from conary.build import source self._addSourceAction('source.addCapsule', source.addCapsule) self._addSourceAction('source.addSource', source.addSource) exec defaultrecipes.CapsuleRecipe
Cover direct mailer with stub fn
var assert = require('chai').assert; var Promise = require('bluebird'); var sinon = require('sinon'); var DirectMailer = require('../lib/DirectMailer'); describe('DirectMailer', function () { it('Should properly export', function () { assert.isFunction(DirectMailer); }); it('Should properly instantiate', function () { var mailer = new DirectMailer(); assert.instanceOf(mailer, DirectMailer); }); it('Should properly send mail', function (done) { var mailer = new DirectMailer({ from: 'no-reply@ghaiklor.com' }); sinon.stub(mailer._transporter, 'sendMail', function (config, cb) { cb(); }); mailer .send({ to: 'another@mail.com' }) .then(function () { assert(mailer._transporter.sendMail.calledOnce); assert.equal(mailer._transporter.sendMail.getCall(0).args[0].from, 'no-reply@ghaiklor.com'); assert.equal(mailer._transporter.sendMail.getCall(0).args[0].to, 'another@mail.com'); assert.isFunction(mailer._transporter.sendMail.getCall(0).args[1]); mailer._transporter.sendMail.restore(); done(); }) .catch(done); }); });
var assert = require('chai').assert; var Promise = require('bluebird'); var sinon = require('sinon'); var DirectMailer = require('../lib/DirectMailer'); describe('DirectMailer', function () { it('Should properly export', function () { assert.isFunction(DirectMailer); }); it('Should properly instantiate', function () { var mailer = new DirectMailer(); assert.instanceOf(mailer, DirectMailer); }); it('Should properly send mail', function (done) { var sendMailStub = sinon.stub().returns(Promise.resolve()); var mailer = new DirectMailer({ from: 'no-reply@ghaiklor.com' }); mailer._transporter.sendMail = sendMailStub; mailer .send() .then(done) .catch(done); }); });
Disable session for api modules
<?php namespace app\modules\api; use yii\base\BootstrapInterface; class Api extends \yii\base\Module implements BootstrapInterface { public $controllerNamespace = 'app\modules\api\controllers'; private static $_defaultVersion = 'v1'; public static function getDefaultVersion() { return self::$_defaultVersion; } public function bootstrap($app) { $app->getUrlManager()->addRules([ [ 'class' => 'yii\rest\UrlRule', 'controller' => [ 'api/v1/default' ] ] ], false); } function init() { parent::init(); \Yii::$app->user->enableSession = false; $this->modules = [ 'v1' => 'app\modules\api\versions\v1\ApiV1' ]; } }
<?php namespace app\modules\api; use yii\base\BootstrapInterface; class Api extends \yii\base\Module implements BootstrapInterface { public $controllerNamespace = 'app\modules\api\controllers'; private static $_defaultVersion = 'v1'; public static function getDefaultVersion() { return self::$_defaultVersion; } public function bootstrap($app) { $app->getUrlManager()->addRules([ [ 'class' => 'yii\rest\UrlRule', 'controller' => [ 'api/v1/default' ] ] ], false); } function init() { parent::init(); $this->modules = [ 'v1' => 'app\modules\api\versions\v1\ApiV1' ]; } }
Fix goto simple sections at sidebar
import ServerboardView from 'app/components/project' import store from 'app/utils/store' import { projects_update_info } from 'app/actions/project' var Project=store.connect({ state(state){ if (state.project.current != "/" && localStorage.last_project != state.project.current){ localStorage.last_project = state.project.current } return { shortname: state.project.current, project: state.project.project, projects_count: (state.project.projects || []).length } }, handlers: (dispatch, props) => ({ goto(url){ console.log(url) store.goto(url.pathname || url, url.state) }, onAdd(){ dispatch( store.set_modal("project.add") ) }, onUpdate(){ dispatch( projects_update_info(props.params.project) ) } }), store_enter: (state, props) => [ () => projects_update_info(state.project.current), ], store_exit: (state, props) => [ () => projects_update_info(), ], subscriptions: ["service.updated"], watch: ["shortname"] }, ServerboardView) export default Project
import ServerboardView from 'app/components/project' import store from 'app/utils/store' import { projects_update_info } from 'app/actions/project' var Project=store.connect({ state(state){ if (state.project.current != "/" && localStorage.last_project != state.project.current){ localStorage.last_project = state.project.current } return { shortname: state.project.current, project: state.project.project, projects_count: (state.project.projects || []).length } }, handlers: (dispatch, props) => ({ goto(url){ console.log(url) store.goto(url.pathname, url.state) }, onAdd(){ dispatch( store.set_modal("project.add") ) }, onUpdate(){ dispatch( projects_update_info(props.params.project) ) } }), store_enter: (state, props) => [ () => projects_update_info(state.project.current), ], store_exit: (state, props) => [ () => projects_update_info(), ], subscriptions: ["service.updated"], watch: ["shortname"] }, ServerboardView) export default Project
Correct the translation domain for loading messages Change-Id: If7fa8fd1915378bda3fc6e361049c2d90cdec8af
# Copyright 2014 Mirantis Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo import i18n _translators = i18n.TranslatorFactory(domain='oslo.concurrency') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
# Copyright 2014 Mirantis Inc. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo import i18n _translators = i18n.TranslatorFactory(domain='oslo_concurrency') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
Remove all children of a folder when it is deleted
import syncClient from '../db/sync_client'; import { DELETE_BOOKMARK, DELETE_FOLDER } from '../constants'; export function deleteBookmark(id) { return (dispatch) => { syncClient .bookmarks .delete(id) .then(() => { dispatch({ type: DELETE_BOOKMARK, payload: id, }); }) .catch((e) => { console.log(e); }); }; } export function deleteFolder(id) { return (dispatch) => { syncClient .transaction('rw', syncClient.folders, syncClient.bookmarks, () => { syncClient.folders.where('parentID').equals(id).delete(); syncClient.bookmarks.where('parentID').equals(id).delete(); syncClient.folders.delete(id); }) .then(() => { dispatch({ type: DELETE_FOLDER, payload: id, }); }) .catch((e) => { console.log(e); }); }; }
import syncClient from '../db/sync_client'; import { DELETE_BOOKMARK, DELETE_FOLDER } from '../constants'; export function deleteBookmark(id) { return (dispatch) => { syncClient .bookmarks .delete(id) .then(() => { dispatch({ type: DELETE_BOOKMARK, payload: id, }); }) .catch((e) => { console.log(e); }); }; } export function deleteFolder(id) { return (dispatch) => { syncClient .folders .delete(id) .then(() => { dispatch({ type: DELETE_FOLDER, payload: id, }); }) .catch((e) => { console.log(e); }); }; }
Use jQuery directly instead of $ in plugin
/** * Initialize Pattern builder plugin. */ ;(function () { var pluginName = 'patternMaker', pluginDefaults = { palette: [] }; /** * Constructor. * * @param {dom} element Drawing board * @param {object} options Plugin options */ function Plugin(element, options) { this.element = element; this.$element = $(element); this.options = $.extend({}, pluginDefaults, options); this.init(); } /** * Launch it */ Plugin.prototype.init = function() { this._palette = new RandomColor(this.options.palette); }; /** * Attach to jQuery plugin namespace. * * @param {object} options Initialization options */ jQuery.fn[pluginName] = function(options) { return this.each(function () { if (!jQuery.data(this, "plugin_" + pluginName)) { jQuery.data(this, "plugin_" + pluginName); new Plugin(this, options); } }); }; })();
/** * Initialize Pattern builder plugin. */ ;(function ($) { var pluginName = 'patternMaker', pluginDefaults = { palette: [] }; /** * Constructor. * * @param {dom} element Drawing board * @param {object} options Plugin options */ function Plugin(element, options) { this.element = element; this.$element = $(element); this.options = $.extend({}, pluginDefaults, options); this.init(); } /** * Launch it */ Plugin.prototype.init = function() { this._palette = new RandomColor(this.options.palette); }; /** * Attach to jQuery plugin namespace. * * @param {object} options Initialization options */ $.fn[pluginName] = function(options) { return this.each(function () { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName); new Plugin(this, options); } }); }; })(jQuery);
Add comments to solution to better understand
// Sieve of Eratosthenes /*RULES: Function takes one parameter Return an array of all prime numbers from 0-parameter */ /*PSEUDOCODE: 1) Find square root of parameter 2) Create an array of numbers from 0-parameter 3) Loop through numbers, but stop until square root (if a float, stop after number rounded up?) 4) Return array */ function sieveOfEratosthenes(n){ var squareRoot = Math.sqrt(n); var primes = []; //Turn all elements to true by default for (var i = 0; i <= n; i++){ primes[i] = true; } //These are never prime so mark those false primes[0] = false; primes[1] = false; //Nested loop. For each number, starting from index 2, for (var i = 2; i <= squareRoot; i++){ // check and see if the multiples are found within the original array (make sure they don't exceed the max). If they are, mark them false; for (var j = 2; j * i <= n; j++){ primes[i * j] = false; } } //Create new array var result = [] //Check all values from original array. If they are true, push their index to the new array for (var i = 0; i < primes.length; i++){ if (primes[i]){ result.push(i) } } //Return new array return result; }
// Sieve of Eratosthenes /*RULES: Function takes one parameter Return an array of all prime numbers from 0-parameter */ /*PSEUDOCODE: 1) Find square root of parameter 2) Create an array of numbers from 0-parameter 3) Loop through numbers, but stop until square root (if a float, stop after number rounded up?) 4) Return array */ function sieveOfEratosthenes(n){ var squareRoot = Math.sqrt(n); var primes = []; for (var i = 0; i <= n; i++){ primes[i] = true; } primes[0] = false; primes[1] = false; for (var i = 2; i <= squareRoot; i++){ for (var j = 2; j * i <= n; j++){ primes[i * j] = false; } } var result = [] for (var i = 0; i < primes.length; i++){ if (primes[i]){ result.push(i) } } return result; }
Change command prefix to $, so that's like a tip.
#!/usr/bin/python3 import asyncio import configparser import discord import os from discord.ext import commands # Parse the config and stick in global "config" var config = configparser.ConfigParser() for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','bayohwoolph.local.ini','bayohwoolph.ini']: if os.path.isfile(inifile): config.read(inifile) break # First config file wins MAIN = config['MAIN'] description = '''Dark Echo's barkeep''' bot = commands.Bot(command_prefix='$', description=description) @bot.event @asyncio.coroutine def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') bot.run(MAIN.get('login_token'))
#!/usr/bin/python3 import asyncio import configparser import discord import os from discord.ext import commands # Parse the config and stick in global "config" var config = configparser.ConfigParser() for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','bayohwoolph.local.ini','bayohwoolph.ini']: if os.path.isfile(inifile): config.read(inifile) break # First config file wins MAIN = config['MAIN'] description = '''Dark Echo's barkeep''' bot = commands.Bot(command_prefix='%', description=description) @bot.event @asyncio.coroutine def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') bot.run(MAIN.get('login_token'))
Use div instead of h1 for site title
<?php /** * Header top template * * @package ZnWP Bootstrap Theme */ global $znwp_theme; ?> <div class="container"> <div class="row"> <div class="<?php echo $znwp_theme->get_full_width_class(); ?>"> <?php if ($znwp_theme->display_header_text()): ?> <div id="header-text"> <div class="site-title"><?php bloginfo('name'); ?></div> <div class="tagline"><?php bloginfo('description'); ?></div> </div> <?php endif; ?> </div> </div> </div>
<?php /** * Header top template * * @package ZnWP Bootstrap Theme */ global $znwp_theme; ?> <div class="container"> <div class="row"> <div class="<?php echo $znwp_theme->get_full_width_class(); ?>"> <?php if ($znwp_theme->display_header_text()): ?> <div id="header-text"> <h1 class="site-title"><?php bloginfo('name'); ?></h1> <div class="tagline"><?php bloginfo('description'); ?></div> </div> <?php endif; ?> </div> </div> </div>
Resolve some error messages due to unnecessarily retrieved data
module.exports = function(grunt) { grunt.registerTask('bundleEPUB', function() { var done = this.async(); grunt.config.requires('akasha'); // grunt.config.requires('config'); var akasha = grunt.config('akasha'); // var config = grunt.config('config'); var epubversion = "epub3"; if (this.flags.epub2) epubversion = "epub2"; else if (this.flags.epub3) epubversion = "epub3"; akasha.plugin('akashacms-epub').bundleEPUB(epubversion, function(err) { if (err) done(err); else done(); }); }); };
module.exports = function(grunt) { grunt.registerTask('bundleEPUB', function() { var done = this.async(); grunt.config.requires('akasha'); grunt.config.requires('config'); var akasha = grunt.config('akasha'); var config = grunt.config('config'); var epubversion = "epub3"; if (this.flags.epub2) epubversion = "epub2"; else if (this.flags.epub3) epubversion = "epub3"; akasha.plugin('akashacms-epub').bundleEPUB(config, epubversion, function(err) { if (err) done(err); else done(); }); }); };
Remove invalid value of parameter
<?php declare(strict_types = 1); /* * This file is part of the FiveLab Resource package * * (c) FiveLab * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code */ namespace FiveLab\Component\Resource\Resource; use FiveLab\Component\Resource\Resource\Relation\RelationCollection; use FiveLab\Component\Resource\Resource\Relation\RelationInterface; /** * The abstract class for support resource. * * @author Vitaliy Zhuk <v.zhuk@fivelab.org> */ abstract class AbstractResourceSupport implements ResourceInterface, RelatedResourceInterface { /** * @var \SplObjectStorage|RelationInterface[] */ private $relations; /** * Constructor. */ public function __construct() { $this->relations = new \SplObjectStorage(); } /** * {@inheritdoc} */ public function addRelation(RelationInterface $relation): void { $this->relations->attach($relation); } /** * {@inheritdoc} */ public function getRelations(): RelationCollection { return new RelationCollection(...iterator_to_array($this->relations)); } /** * {@inheritdoc} */ public function removeRelation(RelationInterface $relation): void { $this->relations->detach($relation); } }
<?php declare(strict_types = 1); /* * This file is part of the FiveLab Resource package * * (c) FiveLab * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code */ namespace FiveLab\Component\Resource\Resource; use FiveLab\Component\Resource\Resource\Relation\RelationCollection; use FiveLab\Component\Resource\Resource\Relation\RelationInterface; /** * The abstract class for support resource. * * @author Vitaliy Zhuk <v.zhuk@fivelab.org> */ abstract class AbstractResourceSupport implements ResourceInterface, RelatedResourceInterface { /** * @var \SplObjectStorage|RelationInterface[] */ private $relations = []; /** * Constructor. */ public function __construct() { $this->relations = new \SplObjectStorage(); } /** * {@inheritdoc} */ public function addRelation(RelationInterface $relation): void { $this->relations->attach($relation); } /** * {@inheritdoc} */ public function getRelations(): RelationCollection { return new RelationCollection(...iterator_to_array($this->relations)); } /** * {@inheritdoc} */ public function removeRelation(RelationInterface $relation): void { $this->relations->detach($relation); } }
Handle the new signature of will-navigate
import { remote } from 'electron'; const webview = document.querySelector('webview'); if (webview) { let once = true; webview.addEventListener('did-start-loading', () => { if (once) { once = false; webview.src = Settings.get('lastPage', 'https://play.google.com/music/listen'); document.body.setAttribute('loading', 'loading'); } }); const savePage = (param) => { const url = param.url || param; if (!/https?:\/\/play\.google\.com\/music/g.test(url)) return; Emitter.fire('settings:set', { key: 'lastPage', value: url.url, }); }; webview.addEventListener('dom-ready', () => { setTimeout(() => { document.body.removeAttribute('loading'); webview.focus(); webview.addEventListener('did-navigate', savePage); webview.addEventListener('did-navigate-in-page', savePage); const focusWebview = () => { document.querySelector('webview::shadow object').focus(); }; window.addEventListener('beforeunload', () => { remote.getCurrentWindow().removeListener('focus', focusWebview); }); remote.getCurrentWindow().on('focus', focusWebview); }, 400); }); }
import { remote } from 'electron'; const webview = document.querySelector('webview'); if (webview) { let once = true; webview.addEventListener('did-start-loading', () => { if (once) { once = false; webview.src = Settings.get('lastPage', 'https://play.google.com/music/listen'); document.body.setAttribute('loading', 'loading'); } }); const savePage = (url) => { if (!/https?:\/\/play\.google\.com\/music/g.test(url)) return; Emitter.fire('settings:set', { key: 'lastPage', value: url.url, }); }; webview.addEventListener('dom-ready', () => { setTimeout(() => { document.body.removeAttribute('loading'); webview.focus(); webview.addEventListener('did-navigate', savePage); webview.addEventListener('did-navigate-in-page', savePage); const focusWebview = () => { document.querySelector('webview::shadow object').focus(); }; window.addEventListener('beforeunload', () => { remote.getCurrentWindow().removeListener('focus', focusWebview); }); remote.getCurrentWindow().on('focus', focusWebview); }, 400); }); }
Use Ember.observer over named properties The named properties are a convenience but makes it harder to overload later on. It is better to use observers and in the case of an addon the Ember.observer() pattern
import Ember from 'ember'; import SelectPickerMixin from 'ember-cli-select-picker/mixins/select-picker'; var I18nProps = (Ember.I18n && Ember.I18n.TranslateableProperties) || {}; var SelectPickerComponent = Ember.Component.extend( SelectPickerMixin, I18nProps, { selectAllLabel: 'All', selectNoneLabel: 'None', nativeMobile: true, classNames: ['select-picker'], setupDom: Ember.observer( 'didInsertElement', function() { var eventName = 'click.' + this.get('elementId'); var _this = this; $(document).on(eventName, function (e) { if (_this.get('keepDropdownOpen')) { _this.set('keepDropdownOpen', false); return; } if (_this.element && !$.contains(_this.element, e.target)) { _this.set('showDropdown', false); } }); } ), teardownDom: Ember.observer( 'willDestroyElement', function() { $(document).off('.' + this.get('elementId')); } ), actions: { showHide: function () { this.toggleProperty('showDropdown'); } } }); export default SelectPickerComponent;
import Ember from 'ember'; import SelectPickerMixin from 'ember-cli-select-picker/mixins/select-picker'; var I18nProps = (Ember.I18n && Ember.I18n.TranslateableProperties) || {}; var SelectPickerComponent = Ember.Component.extend( SelectPickerMixin, I18nProps, { selectAllLabel: 'All', selectNoneLabel: 'None', nativeMobile: true, classNames: ['select-picker'], didInsertElement: function() { var eventName = 'click.' + this.get('elementId'); var _this = this; $(document).on(eventName, function (e) { if (_this.get('keepDropdownOpen')) { _this.set('keepDropdownOpen', false); return; } if (_this.element && !$.contains(_this.element, e.target)) { _this.set('showDropdown', false); } }); }, willDestroyElement: function() { $(document).off('.' + this.get('elementId')); }, actions: { showHide: function () { this.toggleProperty('showDropdown'); } } }); export default SelectPickerComponent;
Adjust event to match the doc
'use strict'; var uuid = require('uuid'); /** * Handle the socket connections. * * @class * @param {Socket.io} io - The listening object */ function SocketHandler(io) { /** * The states of all the users. */ var states = { players: {} }; // send the users position on a regular time basis setInterval(function() { io.emit('states', states); }, 50/*ms*/); /** * Called on each new user connection. */ io.on('connection', function(socket) { var user = { id: uuid.v4() }; // give the user its information socket.emit('handshake', user); // inform the other users socket.broadcast.emit('new_player', user); /** * Called when a player sends its position. */ socket.on('state', function(data) { // store the user state states.players[user.id] = data; }); /** * Called when the user disconnects. */ socket.on('disconnect', function() { // delete the user state delete states.players[user.id]; }); }); } module.exports = SocketHandler;
'use strict'; var uuid = require('uuid'); /** * Handle the socket connections. * * @class * @param {Socket.io} io - The listening object */ function SocketHandler(io) { /** * The states of all the users. */ var states = {}; // send the users position on a regular time basis setInterval(function() { io.emit('states', states); }, 50/*ms*/); /** * Called on each new user connection. */ io.on('connection', function(socket) { var user = { id: uuid.v4() }; // give the user its information socket.emit('handshake', user); // inform the other users socket.broadcast.emit('new_player', user); /** * Called when a player sends its position. */ socket.on('state', function(data) { // store the user state states[user.id] = data; }); /** * Called when the user disconnects. */ socket.on('disconnect', function() { // delete the user state delete states[user.id]; }); }); } module.exports = SocketHandler;
Add more detail to initialize include. Change-Id: I339e8e2a19e783dcf0b252e37b70b54910e55cc8
// [START initialize_firebase_in_sw] // Give the service worker access to Firebase Messaging. // Note that you can only use Firebase Messaging here, other Firebase libraries // are not available in the service worker. importScripts('https://www.gstatic.com/firebasejs/3.5.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js'); // Initialize the Firebase app in the service worker by passing in the // messagingSenderId. firebase.initializeApp({ 'messagingSenderId': 'YOUR-SENDER-ID' }); // Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = firebase.messaging(); // [END initialize_firebase_in_sw] // If you would like to customize notifications that are received in the // background (Web app is closed or not in browser focus) then you should // implement this optional method. // [START background_handler] messaging.setBackgroundMessageHandler(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here const notificationTitle = 'Background Message Title'; const notificationOptions = { body: 'Background Message body.', icon: '/firebase-logo.png' }; return self.registration.showNotification(notificationTitle, notificationOptions); }); // [END background_handler]
// Give the service worker access to Firebase Messaging. // Note that you can only use Firebase Messaging here, other Firebase libraries // are not available in the service worker. importScripts('https://www.gstatic.com/firebasejs/3.5.0/firebase.js'); // [START initialize_firebase_in_sw] // Initialize the Firebase app in the service worker by passing in the // messagingSenderId. firebase.initializeApp({ 'messagingSenderId': 'YOUR-SENDER-ID' }); // [END initialize_firebase_in_sw] // Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = firebase.messaging(); // If you would like to customize notifications that are received in the // background (Web app is closed or not in browser focus) then you should // implement this optional method. // [START background_handler] messaging.setBackgroundMessageHandler(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here const notificationTitle = 'Background Message Title'; const notificationOptions = { body: 'Background Message body.', icon: '/firebase-logo.png' }; return self.registration.showNotification(notificationTitle, notificationOptions); }); // [END background_handler]
Use a lambda as a proxy.
import asyncore import util try: import simplejson as json except ImportError: import json class ChannelServer(asyncore.dispatcher): def __init__(self, sock, dest): asyncore.dispatcher.__init__(self, sock) self.dest = dest dest.register('close', lambda x, y: self.close()) def handle_accept(self): client = self.accept() SideChannel(client[0], self.dest) class SideChannel(asyncore.dispatcher): def __init__(self, sock, dest): asyncore.dispatcher.__init__(self, sock) self.dest = dest self.buffer = None def handle_close(self): self.close() def handle_read(self): raw = self.recv(8192) if raw: msg = util.json_decode(json.loads(raw)) self.dest.queue(msg) self.buffer = {'result': 'done'} def writable(self): return self.buffer def handle_write(self): self.send(json.dumps(self.buffer)) self.close()
import asyncore import util try: import simplejson as json except ImportError: import json class ChannelServer(asyncore.dispatcher): def __init__(self, sock, dest): asyncore.dispatcher.__init__(self, sock) self.dest = dest dest.register('close', self.closehook) def handle_accept(self): client = self.accept() SideChannel(client[0], self.dest) def closehook(self, hook, data): print 'HOOK-CLOSE' self.close() class SideChannel(asyncore.dispatcher): def __init__(self, sock, dest): asyncore.dispatcher.__init__(self, sock) self.dest = dest self.buffer = None def handle_close(self): self.close() def handle_read(self): raw = self.recv(8192) if raw: msg = util.json_decode(json.loads(raw)) self.dest.queue(msg) self.buffer = {'result': 'done'} def writable(self): return self.buffer def handle_write(self): self.send(json.dumps(self.buffer)) self.close()
Refactor test to use cool py.test's fixture
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import io import pytest from octane import app as o_app @pytest.fixture def octane_app(): return o_app.OctaneApp(stdin=io.BytesIO(), stdout=io.BytesIO(), stderr=io.BytesIO()) def test_help(octane_app): try: octane_app.run(["--help"]) except SystemExit as e: assert e.code == 0 assert not octane_app.stderr.getvalue() assert 'Could not' not in octane_app.stdout.getvalue()
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import io from octane import app as o_app def test_help(): out, err = io.BytesIO(), io.BytesIO() app = o_app.OctaneApp(stdin=io.BytesIO(), stdout=out, stderr=err) try: app.run(["--help"]) except SystemExit as e: assert e.code == 0 assert not err.getvalue() assert 'Could not' not in out.getvalue()
Improve error reporting in client.
package client import ( "github.com/ibrt/go-oauto/oauto/api" "net/http" "fmt" "encoding/json" "github.com/go-errors/errors" "bytes" "io/ioutil" ) func Authenticate(baseURL string, request *api.AuthenticateRequest) (*api.AuthenticateResponse, error) { body, err := json.Marshal(request) if err != nil { return nil, errors.Wrap(err, 0) } resp, err := http.Post(fmt.Sprintf("%v/api/authenticate", baseURL), "application/json", bytes.NewBuffer(body)) if err != nil { return nil, errors.Wrap(err, 0) } respBytes, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, errors.Wrap(err, 0) } if resp.StatusCode != http.StatusOK { return nil, errors.Errorf("Authenticate request failed with status %v: '%s'.", resp.StatusCode, respBytes) } authResp := &api.AuthenticateResponse{} if err := json.Unmarshal(respBytes, &authResp); err != nil { return nil, errors.WrapPrefix(err, string(respBytes), 0) } return authResp, nil }
package client import ( "github.com/ibrt/go-oauto/oauto/api" "net/http" "fmt" "encoding/json" "github.com/go-errors/errors" "bytes" "io/ioutil" ) func Authenticate(baseURL string, request *api.AuthenticateRequest) (*api.AuthenticateResponse, error) { body, err := json.Marshal(request) if err != nil { return nil, errors.Wrap(err, 0) } resp, err := http.Post(fmt.Sprintf("%v/api/authenticate", baseURL), "application/json", bytes.NewBuffer(body)) if err != nil { return nil, errors.Wrap(err, 0) } respBytes, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, errors.Wrap(err, 0) } if resp.StatusCode != http.StatusOK { return nil, errors.Errorf("Authenticate request failed with status %v: '%+v'.", resp.StatusCode, respBytes) } authResp := &api.AuthenticateResponse{} if err := json.Unmarshal(respBytes, &authResp); err != nil { return nil, errors.WrapPrefix(err, string(respBytes), 0) } return authResp, nil }
Fix update progress pane with correct overlay method
package ui import ( "image" "image/color" "image/draw" "github.com/ninjasphere/go-gestic" "github.com/ninjasphere/sphere-go-led-controller/util" ) type UpdateProgressPane struct { progressImage util.Image loopingImage util.Image progress float64 } func NewUpdateProgressPane(progressImage string, loopingImage string) *UpdateProgressPane { return &UpdateProgressPane{ progressImage: util.LoadImage(progressImage), loopingImage: util.LoadImage(loopingImage), } } func (p *UpdateProgressPane) Gesture(gesture *gestic.GestureData) { } func (p *UpdateProgressPane) Render() (*image.RGBA, error) { frame := image.NewRGBA(image.Rect(0, 0, 16, 16)) draw.Draw(frame, frame.Bounds(), &image.Uniform{color.RGBA{ R: 0, G: 0, B: 0, A: 255, }}, image.ZP, draw.Src) draw.Draw(frame, frame.Bounds(), p.loopingImage.GetNextFrame(), image.Point{0, 0}, draw.Over) draw.Draw(frame, frame.Bounds(), p.progressImage.GetPositionFrame(p.progress, true), image.Point{0, 0}, draw.Over) return frame, nil } func (p *UpdateProgressPane) IsDirty() bool { return true }
package ui import ( "image" "image/draw" "github.com/ninjasphere/go-gestic" "github.com/ninjasphere/sphere-go-led-controller/util" ) type UpdateProgressPane struct { progressImage util.Image loopingImage util.Image progress float64 } func NewUpdateProgressPane(progressImage string, loopingImage string) *UpdateProgressPane { return &UpdateProgressPane{ progressImage: util.LoadImage(progressImage), loopingImage: util.LoadImage(loopingImage), } } func (p *UpdateProgressPane) Gesture(gesture *gestic.GestureData) { } func (p *UpdateProgressPane) Render() (*image.RGBA, error) { frame := image.NewRGBA(image.Rect(0, 0, 16, 16)) draw.Draw(frame, frame.Bounds(), p.loopingImage.GetNextFrame(), image.Point{0, 0}, draw.Src) draw.Draw(frame, frame.Bounds(), p.progressImage.GetPositionFrame(p.progress, true), image.Point{0, 0}, draw.Src) return frame, nil } func (p *UpdateProgressPane) IsDirty() bool { return true }
Add dumpStack for cleanupStorage in java tests.
package org.hyperledger.indy.sdk.utils; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class StorageUtils { private static void cleanDirectory(File path) throws IOException { if (path.isDirectory()) { FileUtils.cleanDirectory(path); } } public static void cleanupStorage() throws IOException { System.out.println("cleanupStorage >>"); Thread.dumpStack(); File tmpDir = new File(getTmpPath()); File homeDir = new File(getIndyHomePath()); StorageUtils.cleanDirectory(tmpDir); StorageUtils.cleanDirectory(homeDir); System.out.println("cleanupStorage <<"); } public static String getIndyHomePath() { return FileUtils.getUserDirectoryPath() + "/.indy/"; } public static String getIndyHomePath(String filename) { return getIndyHomePath() + filename; } public static String getTmpPath() { return FileUtils.getTempDirectoryPath() + "/indy/"; } public static String getTmpPath(String filename) { return getTmpPath() + filename; } }
package org.hyperledger.indy.sdk.utils; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class StorageUtils { private static void cleanDirectory(File path) throws IOException { if (path.isDirectory()) { FileUtils.cleanDirectory(path); } } public static void cleanupStorage() throws IOException { System.out.println("cleanupStorage >>"); File tmpDir = new File(getTmpPath()); File homeDir = new File(getIndyHomePath()); StorageUtils.cleanDirectory(tmpDir); StorageUtils.cleanDirectory(homeDir); System.out.println("cleanupStorage <<"); } public static String getIndyHomePath() { return FileUtils.getUserDirectoryPath() + "/.indy/"; } public static String getIndyHomePath(String filename) { return getIndyHomePath() + filename; } public static String getTmpPath() { return FileUtils.getTempDirectoryPath() + "/indy/"; } public static String getTmpPath(String filename) { return getTmpPath() + filename; } }
Integrate the hashtable Unit testcases. * tests/AllTests.java (suite): added HashtableTests git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@841027 13f79535-47bb-0310-9956-ffa450edef68
package org.tigris.subversion.lib; /** * ==================================================================== * Copyright (c) 2000-2001 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * */ public class StatusKind { public final static int NONE=1; public final static int NORMAL=2; public final static int ADDED=3; public final static int ABSENT=4; public final static int DELETED=5; public final static int REPLACED=6; public final static int MODIFIED=7; public final static int MERGED=8; public final static int CONFLICTED=9; private int kind = NONE; public StatusKind(int kind) { super(); this.kind = kind; } public StatusKind() { this(NONE); } public void setKind(int _kind) { kind = _kind; } public int getKind() { return kind; } }
package org.tigris.subversion.lib; /** * ==================================================================== * Copyright (c) 2000-2001 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * */ public class StatusKind { public final static int NONE=1; public final static int NORMAL=2; public final static int ADDED=3; public final static int ABSENT=4; public final static int DELETED=5; public final static int REPLACED=6; public final static int MODIFIED=7; public final static int MERGED=8; public final static int CONFLICTED=9; public final int kind; public StatusKind(int kind) { this.kind = kind; } }
Add environmental config for root repo
var queue = require('queue-async'); var express = require('express'); var request = require('request'); var app = express(); app.use(express.static(__dirname + '/static')); function renderStargazes(req, res, next) { var q = queue(); for (var i=1; i<=10; i++) { q.defer(request,{ url:'https://api.github.com/repos/' + res.local.repoName + '/events', qs: {page: i}, json: true }); } q.awaitAll(function(err, pages) { if (err) return next(err); res.locals.stargazes = [].concat.apply([], pages).filter(function(v) { return v.type == 'WatchEvent'; }); res.set('content-type','text/html'); res.render('starwatchcats.jade'); }); } app.get('/:owner/:repo', function(req, res, next) { res.locals.repoName = req.params.owner + '/' + req.params.repo; renderStargazes(req, res, next); }); if (process.env.DEFAULT_REPO) { app.get('/', function(req, res, next) { res.locals.repoName = process.env.DEFAULT_REPO; renderStargazes(req, res, next); }); } var server = require('http').createServer(app); server.listen(process.env.PORT || 5000, process.env.IP);
var queue = require('queue-async'); var express = require('express'); var request = require('request'); var app = express(); app.use(express.static(__dirname + '/static')); app.get('/:owner/:repo', function(req, res, next) { var q = queue(); var repoName = req.params.owner + '/' + req.params.repo; res.locals.repoName = repoName; for (var i=1; i<=10; i++) { q.defer(request,{ url:'https://api.github.com/repos/' + repoName + '/events', qs: {page: i}, json: true }); } q.awaitAll(function(err, pages) { if (err) return next(err); res.locals.stargazes = [].concat.apply([], pages).filter(function(v) { return v.type == 'WatchEvent'; }); res.set('content-type','text/html'); res.render('starwatchcats.jade'); }); }); var server = require('http').createServer(app); server.listen(process.env.PORT || 5000, process.env.IP);
[auth] Allow Authenticate package function to take multiple Methods. R=ef4933a197ef7b4b3f55f1bec4942aead3637a2a@chromium.org, vadimsh@chromium.org Bug: 782460 Change-Id: I288d88d184cd7411d5df084407a11864e1d2a18a Reviewed-on: https://chromium-review.googlesource.com/803672 Reviewed-by: Nodir Turakulov <ef4933a197ef7b4b3f55f1bec4942aead3637a2a@chromium.org> Commit-Queue: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
// Copyright 2017 The LUCI Authors. // // 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 auth import ( "go.chromium.org/luci/server/router" ) // Authenticate returns a middleware that performs authentication. // // Typically you only one one Method, but you may specify multiple Methods to be // tried in order (see Authenticator). // // This middleware either updates the context by injecting the authentication // state into it (enabling functions like CurrentIdentity and IsMember), or // aborts the request with an HTTP 401 or HTTP 500 error. // // Note that it passes through anonymous requests. CurrentIdentity returns // identity.AnonymousIdentity in this case. Use separate authorization layer to // further restrict the access, if necessary. func Authenticate(m ...Method) router.Middleware { a := &Authenticator{Methods: m} return a.GetMiddleware() }
// Copyright 2017 The LUCI Authors. // // 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 auth import ( "go.chromium.org/luci/server/router" ) // Authenticate returns a middleware that performs authentication. // // This is simplest form of this middleware that uses only one authentication // method. It is sufficient in most cases. // // This middleware either updates the context by injecting the authentication // state into it (enabling functions like CurrentIdentity and IsMember), or // aborts the request with an HTTP 401 or HTTP 500 error. // // Note that it passes through anonymous requests. CurrentIdentity returns // identity.AnonymousIdentity in this case. Use separate authorization layer to // further restrict the access, if necessary. func Authenticate(m Method) router.Middleware { a := &Authenticator{Methods: []Method{m}} return a.GetMiddleware() }
scripts: Print names of missing migrations in compatibility check. This will make it much easier to debug any situations where this happens.
#!/usr/bin/env python3 import logging import os import sys ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, ZULIP_PATH) from scripts.lib.setup_path import setup_path from scripts.lib.zulip_tools import DEPLOYMENTS_DIR, assert_not_running_as_root, parse_version_from from version import ZULIP_VERSION as new_version assert_not_running_as_root() setup_path() os.environ["DJANGO_SETTINGS_MODULE"] = "zproject.settings" import django from django.db import connection from django.db.migrations.loader import MigrationLoader django.setup() loader = MigrationLoader(connection) missing = set(loader.applied_migrations) for key, migration in loader.disk_migrations.items(): missing.discard(key) missing.difference_update(migration.replaces) if not missing: sys.exit(0) for migration in missing: print(f"Migration {migration} missing in new version.") current_version = parse_version_from(os.path.join(DEPLOYMENTS_DIR, "current")) logging.error( "This is not an upgrade -- the current deployment (version %s) " "contains %s database migrations which %s (version %s) does not.", current_version, len(missing), ZULIP_PATH, new_version, ) sys.exit(1)
#!/usr/bin/env python3 import logging import os import sys ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, ZULIP_PATH) from scripts.lib.setup_path import setup_path from scripts.lib.zulip_tools import DEPLOYMENTS_DIR, assert_not_running_as_root, parse_version_from from version import ZULIP_VERSION as new_version assert_not_running_as_root() setup_path() os.environ["DJANGO_SETTINGS_MODULE"] = "zproject.settings" import django from django.db import connection from django.db.migrations.loader import MigrationLoader django.setup() loader = MigrationLoader(connection) missing = set(loader.applied_migrations) for key, migration in loader.disk_migrations.items(): missing.discard(key) missing.difference_update(migration.replaces) if not missing: sys.exit(0) current_version = parse_version_from(os.path.join(DEPLOYMENTS_DIR, "current")) logging.error( "This is not an upgrade -- the current deployment (version %s) " "contains %s database migrations which %s (version %s) does not.", current_version, len(missing), ZULIP_PATH, new_version, ) sys.exit(1)
Use faster password hasher in sqlite tests Fixed #18163
# This is an example test settings file for use with the Django test suite. # # The 'sqlite3' backend requires only the ENGINE setting (an in- # memory database will be used). All other backends will require a # NAME and potentially authentication information. See the # following section in the docs for more information: # # https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/ # # The different databases that Django supports behave differently in certain # situations, so it is recommended to run the test suite against as many # database backends as possible. You may want to create a separate settings # file for each of the backends you test against. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3' }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', } } SECRET_KEY = "django_tests_secret_key" # To speed up tests under SQLite we use the MD5 hasher as the default one. # This should not be needed under other databases, as the relative speedup # is only marginal there. PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', )
# This is an example test settings file for use with the Django test suite. # # The 'sqlite3' backend requires only the ENGINE setting (an in- # memory database will be used). All other backends will require a # NAME and potentially authentication information. See the # following section in the docs for more information: # # https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/ # # The different databases that Django supports behave differently in certain # situations, so it is recommended to run the test suite against as many # database backends as possible. You may want to create a separate settings # file for each of the backends you test against. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3' }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', } } SECRET_KEY = "django_tests_secret_key"
Add another optional=false for the description refset member.
package org.ihtsdo.otf.mapping.rf2.jpa; import org.hibernate.search.annotations.ContainedIn; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlIDREF; import org.hibernate.envers.Audited; import org.ihtsdo.otf.mapping.rf2.Description; import org.ihtsdo.otf.mapping.rf2.DescriptionRefSetMember; /** * Abstract implementation of {@link DescriptionRefSetMember}. */ @MappedSuperclass @Audited public abstract class AbstractDescriptionRefSetMember extends AbstractRefSetMember implements DescriptionRefSetMember { @ManyToOne(targetEntity=DescriptionJpa.class, optional=false) /* *//** The Description associated with this element *//* @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity=DescriptionJpa.class)*/ @JsonBackReference @ContainedIn private Description description; /** * {@inheritDoc} */ @Override @XmlIDREF @XmlAttribute public DescriptionJpa getDescription() { return (DescriptionJpa)this.description; } /** * {@inheritDoc} */ @Override public void setDescription(Description description) { this.description = description; } }
package org.ihtsdo.otf.mapping.rf2.jpa; import org.hibernate.search.annotations.ContainedIn; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlIDREF; import org.hibernate.envers.Audited; import org.ihtsdo.otf.mapping.rf2.Description; import org.ihtsdo.otf.mapping.rf2.DescriptionRefSetMember; /** * Abstract implementation of {@link DescriptionRefSetMember}. */ @MappedSuperclass @Audited public abstract class AbstractDescriptionRefSetMember extends AbstractRefSetMember implements DescriptionRefSetMember { @ManyToOne(targetEntity=DescriptionJpa.class) /* *//** The Description associated with this element *//* @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity=DescriptionJpa.class)*/ @JsonBackReference @ContainedIn private Description description; /** * {@inheritDoc} */ @Override @XmlIDREF @XmlAttribute public DescriptionJpa getDescription() { return (DescriptionJpa)this.description; } /** * {@inheritDoc} */ @Override public void setDescription(Description description) { this.description = description; } }