text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove f-string for pre-Python 3.6 support.
from .oauth import BaseOAuth2 class UniverseOAuth2(BaseOAuth2): """Universe Ticketing OAuth2 authentication backend""" name = 'universe' AUTHORIZATION_URL = 'https://www.universe.com/oauth/authorize' ACCESS_TOKEN_URL = 'https://www.universe.com/oauth/token' BASE_API_URL = 'https://www.universe.com/api' USER_INFO_URL = BASE_API_URL + '/v2/current_user' ACCESS_TOKEN_METHOD = 'POST' STATE_PARAMETER = True REDIRECT_STATE = True EXTRA_DATA = [ ('id', 'id'), ('slug', 'slug'), ('created_at', 'created_at'), ('updated_at', 'updated_at'), ] def get_user_id(self, details, response): return response['current_user'][self.ID_KEY] def get_user_details(self, response): """Return user details from a Universe account""" # Start with the user data as it was returned user_details = response['current_user'] user_details["username"] = user_details["email"] return user_details def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json(self.USER_INFO_URL, headers={'Authorization': 'Bearer {}'.format(access_token)})
from .oauth import BaseOAuth2 class UniverseOAuth2(BaseOAuth2): """Universe Ticketing OAuth2 authentication backend""" name = 'universe' AUTHORIZATION_URL = 'https://www.universe.com/oauth/authorize' ACCESS_TOKEN_URL = 'https://www.universe.com/oauth/token' BASE_API_URL = 'https://www.universe.com/api' USER_INFO_URL = BASE_API_URL + '/v2/current_user' ACCESS_TOKEN_METHOD = 'POST' STATE_PARAMETER = True REDIRECT_STATE = True EXTRA_DATA = [ ('id', 'id'), ('slug', 'slug'), ('created_at', 'created_at'), ('updated_at', 'updated_at'), ] def get_user_id(self, details, response): return response['current_user'][self.ID_KEY] def get_user_details(self, response): """Return user details from a Universe account""" # Start with the user data as it was returned user_details = response['current_user'] user_details["username"] = user_details["email"] return user_details def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json(self.USER_INFO_URL, headers={'Authorization': f'Bearer {access_token}'})
Fix test data plotting to use the changed interfaces
import zephyr.util from zephyr.collector import MeasurementCollector from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler from zephyr.message import MessagePayloadParser from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial from zephyr.protocol import Protocol, MessageFrameParser def main(): zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True collector = MeasurementCollector() rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event]) signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal] signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event]) payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet]) message_parser = MessageFrameParser(payload_parser.handle_message) ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat") protocol = Protocol(ser, [message_parser.parse_data]) try: protocol.run() except EOFError: pass visualize_measurements(collector) if __name__ == "__main__": main()
import zephyr.util from zephyr.collector import MeasurementCollector from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler from zephyr.message import MessagePayloadParser from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial from zephyr.protocol import Protocol def main(): zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True collector = MeasurementCollector() rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event]) signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal] signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event]) payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet]) ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat") protocol = Protocol(ser, payload_parser.handle_message) try: protocol.run() except EOFError: pass visualize_measurements(collector) if __name__ == "__main__": main()
Use find_packages helper to get everything except for tests. Add sphinx as an installation requirement.
import os from setuptools import setup, find_packages version_file = open(os.path.join(os.path.dirname(__file__), 'VERSION')) version = version_file.read().strip() README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() setup( name='canvas_python_sdk', version=version, description='A python sdk for the canvas LMS api', author='Harvard University', author_email='some_email_tbd@Harvard.edu', url='https://github.com/Harvard-University-iCommons/canvas_python_sdk', packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), long_description=README, classifiers=[ "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Software Development", ], keywords='canvas api sdk LMS', license='MIT', install_requires=[ 'requests>=2.3.0', 'sphinx>=1.2.0', ], test_suite='tests', tests_require=[ 'mock>=1.0.1', ], )
import os from setuptools import setup version_file = open(os.path.join(os.path.dirname(__file__), 'VERSION')) version = version_file.read().strip() README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() setup( name='canvas_python_sdk', version=version, description='A python sdk for the canvas LMS api', author='Harvard University', author_email='some_email_tbd@Harvard.edu', url='https://github.com/Harvard-University-iCommons/canvas_python_sdk', packages=['canvas_sdk'], long_description=README, classifiers=[ "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Software Development", ], keywords='canvas api sdk LMS', license='MIT', install_requires=[ 'requests>=2.3.0' ], test_suite='tests', tests_require=[ 'mock>=1.0.1', ], )
Fix missing import in contrib script added in [2630].
#!/usr/bin/env python # # This script completely migrates a <= 0.8.x Trac environment to use the new # default ticket model introduced in Trac 0.9. # # In particular, this means that the severity field is removed (or rather # disabled by removing all possible values), and the priority values are # changed to the more meaningful new defaults. # # Make sure to make a backup of the Trac environment before running this! import os import sys from trac.env import open_environment from trac.ticket.model import Priority, Severity priority_mapping = { 'highest': 'blocker', 'high': 'critical', 'normal': 'major', 'low': 'minor', 'lowest': 'trivial' } def main(): if len(sys.argv) < 2: print >> sys.stderr, 'usage: %s /path/to/projenv' \ % os.path.basename(sys.argv[0]) sys.exit(2) env = open_environment(sys.argv[1]) db = env.get_db_cnx() for oldprio, newprio in priority_mapping.items(): priority = Priority(env, oldprio, db) priority.name = newprio priority.update(db) for severity in list(Severity.select(env, db)): severity.delete(db) db.commit() if __name__ == '__main__': main()
#!/usr/bin/env python # # This script completely migrates a <= 0.8.x Trac environment to use the new # default ticket model introduced in Trac 0.9. # # In particular, this means that the severity field is removed (or rather # disabled by removing all possible values), and the priority values are # changed to the more meaningful new defaults. # # Make sure to make a backup of the Trac environment before running this! import sys from trac.env import open_environment from trac.ticket.model import Priority, Severity priority_mapping = { 'highest': 'blocker', 'high': 'critical', 'normal': 'major', 'low': 'minor', 'lowest': 'trivial' } def main(): if len(sys.argv) < 2: print >> sys.stderr, 'usage: %s /path/to/projenv' \ % os.path.basename(sys.argv[0]) sys.exit(2) env = open_environment(sys.argv[1]) db = env.get_db_cnx() for oldprio, newprio in priority_mapping.items(): priority = Priority(env, oldprio, db) priority.name = newprio priority.update(db) for severity in list(Severity.select(env, db)): severity.delete(db) db.commit() if __name__ == '__main__': main()
Make flute item work properly
package pokefenn.totemic.item.music; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import pokefenn.totemic.api.TotemicAPI; import pokefenn.totemic.init.ModContent; import pokefenn.totemic.init.ModItems; public class FluteItem extends Item { public FluteItem(Properties properties) { super(properties); } @Override public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) { if(!world.isClientSide) { if(player.isShiftKeyDown()) TotemicAPI.get().music().playSelector(player, ModContent.flute); else TotemicAPI.get().music().playMusic(player, ModContent.flute); } player.getCooldowns().addCooldown(ModItems.flute.get(), 20); player.getCooldowns().addCooldown(ModItems.infused_flute.get(), 20); player.awardStat(Stats.ITEM_USED.get(this)); return InteractionResultHolder.success(player.getItemInHand(hand)); } }
package pokefenn.totemic.item.music; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import pokefenn.totemic.api.TotemicAPI; import pokefenn.totemic.init.ModContent; import pokefenn.totemic.init.ModItems; public class FluteItem extends Item { public FluteItem(Properties properties) { super(properties); } @SuppressWarnings("null") @Override public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) { TotemicAPI.get().music().playMusic(player, ModContent.flute); player.getCooldowns().addCooldown(ModItems.flute.get(), 20); player.getCooldowns().addCooldown(ModItems.infused_flute.get(), 20); player.awardStat(Stats.ITEM_USED.get(this)); return InteractionResultHolder.success(player.getItemInHand(hand)); } }
Fix echo request identification and support all ISO-8583 versions
package com.github.kpavlov.jreactive8583.netty.pipeline; import com.github.kpavlov.jreactive8583.IsoMessageListener; import com.github.kpavlov.jreactive8583.iso.MessageClass; import com.github.kpavlov.jreactive8583.iso.MessageFactory; import com.solab.iso8583.IsoMessage; import io.netty.channel.ChannelHandlerContext; /** * */ public class EchoMessageListener<T extends IsoMessage> implements IsoMessageListener<T> { private final MessageFactory<T> isoMessageFactory; public EchoMessageListener(final MessageFactory<T> isoMessageFactory) { this.isoMessageFactory = isoMessageFactory; } @Override public boolean applies(final IsoMessage isoMessage) { return isoMessage != null && (isoMessage.getType() & MessageClass.NETWORK_MANAGEMENT.value()) != 0; } /** * Sends EchoResponse message. Always returns <code>false</code>. * * @param isoMessage a message to handle * @return <code>false</code> - message should not be handled by any other handler. */ @Override public boolean onMessage(final ChannelHandlerContext ctx, final T isoMessage) { final IsoMessage echoResponse = isoMessageFactory.createResponse(isoMessage); ctx.writeAndFlush(echoResponse); return false; } }
package com.github.kpavlov.jreactive8583.netty.pipeline; import com.github.kpavlov.jreactive8583.IsoMessageListener; import com.github.kpavlov.jreactive8583.iso.MessageFactory; import com.solab.iso8583.IsoMessage; import io.netty.channel.ChannelHandlerContext; /** * */ public class EchoMessageListener<T extends IsoMessage> implements IsoMessageListener<T> { private final MessageFactory<T> isoMessageFactory; public EchoMessageListener(final MessageFactory<T> isoMessageFactory) { this.isoMessageFactory = isoMessageFactory; } @Override public boolean applies(final IsoMessage isoMessage) { return isoMessage != null && isoMessage.getType() == 0x800; } /** * Sends EchoResponse message. Always returns <code>false</code>. * * @param isoMessage a message to handle * @return <code>false</code> - message should not be handled by any other handler. */ @Override public boolean onMessage(final ChannelHandlerContext ctx, final T isoMessage) { final IsoMessage echoResponse = isoMessageFactory.createResponse(isoMessage); ctx.writeAndFlush(echoResponse); return false; } }
Update 'add cordova platforms' to match latest command output
var selftest = require('../selftest.js'); var Sandbox = selftest.Sandbox; var files = require('../files.js'); // Add plugins to an app. Change the contents of the plugins and their // dependencies, make sure that the app still refreshes. selftest.define("add cordova platforms", function () { var s = new Sandbox(); var run; // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); s.set("METEOR_TEST_TMP", files.mkdtemp()); run = s.run("run", "android"); run.matchErr("Platform is not added"); run.match("meteor add-platform android"); run.expectExit(1); run = s.run("add-platform", "android"); run.match("Do you agree"); run.write("Y\n"); run.extraTime = 90; // Huge download run.match("added"); run = s.run("remove-platform", "foo"); run.match("foo is not"); run = s.run("remove-platform", "android"); run.match("removed"); run = s.run("run", "android"); run.matchErr("Platform is not added"); run.match("meteor add-platform android"); run.expectExit(1); });
var selftest = require('../selftest.js'); var Sandbox = selftest.Sandbox; var files = require('../files.js'); // Add plugins to an app. Change the contents of the plugins and their // dependencies, make sure that the app still refreshes. selftest.define("add cordova platforms", function () { var s = new Sandbox(); var run; // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); s.set("METEOR_TEST_TMP", files.mkdtemp()); run = s.run("run", "android"); run.matchErr("platform is not added"); run.matchErr("meteor add-platform android"); run.expectExit(1); run = s.run("add-platform", "android"); run.match("Do you agree"); run.write("Y\n"); run.extraTime = 90; // Huge download run.match("added"); run = s.run("remove-platform", "foo"); run.match("foo is not"); run = s.run("remove-platform", "android"); run.match("removed"); run = s.run("run", "android"); run.matchErr("platform is not added"); run.matchErr("meteor add-platform android"); run.expectExit(1); });
Mark instance variables private with leading _
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self._size = 0 self._head = None for value in values: self.push(value) def __len__(self): return self._size def head(self): if self._head is None: raise EmptyListException("Head is empty") def push(self, value): node = Node(value) if self._head is None: self._head = node self._size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): def __init__(self, message): self.message = message
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self.size = 0 for value in values: self.push(value) def __len__(self): return self.size def head(self): pass def push(self, value): node = Node(value) if self.head is None: self.head = node self.size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): pass
Switch to argparse for management command argument parsing
import logging from django.core.management import BaseCommand, CommandError from course_discovery.apps.courses.models import Course logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Refresh course data from external sources.' def add_arguments(self, parser): parser.add_argument( '--access_token', action='store', dest='access_token', default=None, help='OAuth2 access token used to authenticate API calls.' ) def handle(self, *args, **options): access_token = options.get('access_token') if not access_token: msg = 'Courses cannot be migrated if no access token is supplied.' logger.error(msg) raise CommandError(msg) Course.refresh_all(access_token=access_token)
import logging from optparse import make_option from django.core.management import BaseCommand, CommandError from course_discovery.apps.courses.models import Course logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Refresh course data from external sources.' option_list = BaseCommand.option_list + ( make_option('--access_token', action='store', dest='access_token', default=None, help='OAuth2 access token used to authenticate API calls.'), ) def handle(self, *args, **options): access_token = options.get('access_token') if not access_token: msg = 'Courses cannot be migrated if no access token is supplied.' logger.error(msg) raise CommandError(msg) Course.refresh_all(access_token=access_token)
Check primary keys for foreign key and one-to-one fields
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
Clarify since it's not a shallow clone hehe
import thunk from "redux-thunk"; import { combineReducers, createStore, applyMiddleware, compose } from "redux"; import _gluestick from "./reducers"; import promiseMiddleware from "../lib/promiseMiddleware"; export default function (client, customRequire, customMiddleware, hotCallback, devMode) { const reducer = combineReducers(Object.assign({}, {_gluestick}, customRequire())); let middleware = [ promiseMiddleware(client), thunk, ]; // Include middleware that will warn when you mutate the state object // but only include it in dev mode if (devMode) { middleware.push(require("redux-immutable-state-invariant")()); } // When `customMiddleware` is of type `function`, pass it current // array of `middlewares` and expect a new value in return. // Fallback to default behaviour. middleware = typeof customMiddleware === 'function' ? customMiddleware([...middleware]) : middleware.concat(customMiddleware); const composeArgs = [ applyMiddleware.apply(this, middleware), typeof window === "object" && typeof window.devToolsExtension !== "undefined" ? window.devToolsExtension() : f => f ]; const finalCreateStore = compose.apply(null, composeArgs)(createStore); const store = finalCreateStore(reducer, typeof window !== "undefined" ? window.__INITIAL_STATE__ : {}); if (hotCallback) { hotCallback(() => { const nextReducer = combineReducers(Object.assign({}, {_gluestick}, customRequire())); store.replaceReducer(nextReducer); }); } return store; }
import thunk from "redux-thunk"; import { combineReducers, createStore, applyMiddleware, compose } from "redux"; import _gluestick from "./reducers"; import promiseMiddleware from "../lib/promiseMiddleware"; export default function (client, customRequire, customMiddleware, hotCallback, devMode) { const reducer = combineReducers(Object.assign({}, {_gluestick}, customRequire())); let middleware = [ promiseMiddleware(client), thunk, ]; // Include middleware that will warn when you mutate the state object // but only include it in dev mode if (devMode) { middleware.push(require("redux-immutable-state-invariant")()); } // When `customMiddleware` is of type `function`, pass it a shallow // copy of the current array of `middlewares` and expect a new value // in return. Fallback to default behaviour. middleware = typeof customMiddleware === 'function' ? customMiddleware([...middleware]) : middleware.concat(customMiddleware); const composeArgs = [ applyMiddleware.apply(this, middleware), typeof window === "object" && typeof window.devToolsExtension !== "undefined" ? window.devToolsExtension() : f => f ]; const finalCreateStore = compose.apply(null, composeArgs)(createStore); const store = finalCreateStore(reducer, typeof window !== "undefined" ? window.__INITIAL_STATE__ : {}); if (hotCallback) { hotCallback(() => { const nextReducer = combineReducers(Object.assign({}, {_gluestick}, customRequire())); store.replaceReducer(nextReducer); }); } return store; }
Move process.nextTick() to run() method Hope this fixes the tests. Thanks @janmeier
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); return this; } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this return this } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
Use ScaleType.FIT_START to align graph and plot better.
package com.antonyt.coveredimageview.example; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView.ScaleType; import com.antonyt.coveredimageview.CoveredImageView; import com.antonyt.coveredimageview.R; /** * Example activity to demonstrate the {@link CoveredImageView}. Click on the * image to repeat the reveal animation. */ public class CoveredImageViewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final CoveredImageView image = (CoveredImageView) findViewById(R.id.image); image.setScaleType(ScaleType.FIT_START); image.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { image.reveal(2000); } }); } }
package com.antonyt.coveredimageview.example; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import com.antonyt.coveredimageview.CoveredImageView; import com.antonyt.coveredimageview.R; /** * Example activity to demonstrate the {@link CoveredImageView}. Click on the * image to repeat the reveal animation. */ public class CoveredImageViewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final CoveredImageView image = (CoveredImageView) findViewById(R.id.image); image.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { image.reveal(2000); } }); } }
Set name for not-found and access-denies pages This name will be shown in the page title and breadcrumbs instead of the component-key.
<?php class Kwc_Errors_Component extends Kwc_Abstract { public static function getSettings($param = null) { $ret = parent::getSettings($param); $ret['contentSender'] = 'Kwc_Errors_ContentSender'; $ret['generators']['accessDenied'] = array( 'class' => 'Kwf_Component_Generator_Page_Static', 'component' => 'Kwc_Errors_AccessDenied_Component', 'name' => trlKwfStatic('Access denied'), ); $ret['generators']['notFound'] = array( 'class' => 'Kwf_Component_Generator_Page_Static', 'component' => 'Kwc_Errors_NotFound_Component', 'name' => trlKwfStatic('Not found'), ); $ret['flags']['noIndex'] = true; $ret['flags']['skipFulltextRecursive'] = true; return $ret; } }
<?php class Kwc_Errors_Component extends Kwc_Abstract { public static function getSettings($param = null) { $ret = parent::getSettings($param); $ret['contentSender'] = 'Kwc_Errors_ContentSender'; $ret['generators']['accessDenied'] = array( 'class' => 'Kwf_Component_Generator_Page_Static', 'component' => 'Kwc_Errors_AccessDenied_Component' ); $ret['generators']['notFound'] = array( 'class' => 'Kwf_Component_Generator_Page_Static', 'component' => 'Kwc_Errors_NotFound_Component' ); $ret['flags']['noIndex'] = true; $ret['flags']['skipFulltextRecursive'] = true; return $ret; } }
Complete fiboncci_dp() by dynamic programming
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import absolute_import from __future__ import print_function from __future__ import division def fibonacci_recur(n): """Get nth number of Fibonacci series by recursion.""" if n <= 1: return n else: return fibonacci_recur(n - 1) + fibonacci_recur(n - 2) def fibonacci_dp(n): """Get nth number of Fibonacci series by dynamic programming. DP performs much faster than recursion. """ a, b = 0, 1 for _ in xrange(n): a, b = a+b, a return a def main(): import time n = 35 start_time = time.time() print('{}th number of Fibonacci series by recursion: {}' .format(n, fibonacci_recur(n))) print('Time: {}'.format(time.time() - start_time)) start_time = time.time() print('{}th number of Fibonacci series by recursion: {}' .format(n, fibonacci_dp(n))) print('Time: {}'.format(time.time() - start_time)) if __name__ == '__main__': main()
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import absolute_import from __future__ import print_function from __future__ import division def fibonacci_recur(n): """Get nth number of Fibonacci series by recursion.""" if n <= 1: return n else: return fibonacci_recur(n - 1) + fibonacci_recur(n - 2) def main(): import time n = 13 start_time = time.time() print('{}th number of Fibonacci series by recursion: {}' .format(n, fibonacci_recur(n))) print('Time: {}'.format(time.time() - start_time)) if __name__ == '__main__': main()
TEST - add test for value
""" Testing Siemens CSA header reader """ import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric data_path = pjoin(os.path.dirname(__file__), 'data') CSA2_B0 = open(pjoin(data_path, 'csa2_b0.bin')).read() CSA2_B1000 = open(pjoin(data_path, 'csa2_b1000.bin')).read() @parametric def test_csa(): csa_info = csa.read(CSA2_B0) yield assert_equal(csa_info['type'], 2) yield assert_equal(csa_info['n_tags'], 83) tags = csa_info['tags'] yield assert_equal(len(tags), 83) yield assert_equal(tags['NumberOfImagesInMosaic']['value'], '48')
""" Testing Siemens CSA header reader """ import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric data_path = pjoin(os.path.dirname(__file__), 'data') CSA2_B0 = open(pjoin(data_path, 'csa2_b0.bin')).read() CSA2_B1000 = open(pjoin(data_path, 'csa2_b1000.bin')).read() @parametric def test_csa(): csa_info = csa.read(CSA2_B0) yield assert_equal(csa_info['type'], 2) yield assert_equal(csa_info['n_tags'], 83) tags = csa_info['tags'] yield assert_equal(len(tags), 83) print csa_info
Replace LocalTime.MIDNIGHT with LocalTime.MIN as this is correct i.e. start of day to finish time, not end of day to finish time!
package uk.ac.ebi.quickgo.ontology; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.time.Duration; import java.time.LocalTime; /** * Holds values related to the operation of the Ontology REST service. * <p> * Created by Tony on 04-Apr-17. */ @Component @ConfigurationProperties(prefix = "ontology.cache.control.time") public class OntologyRestProperties { private static final int MINUTES = 0; private static final int DEFAULT_START_HOURS = 18; private static final int DEFAULT_END_HOURS = 17; private LocalTime startTime = LocalTime.of(DEFAULT_START_HOURS, MINUTES); private LocalTime endTime = LocalTime.of(DEFAULT_END_HOURS, MINUTES); private long midnightToEndCacheTime; public void setStart(int hours) { startTime = LocalTime.of(hours, MINUTES); } public void setEnd(int hours) { endTime = LocalTime.of(hours, MINUTES); this.midnightToEndCacheTime = Duration.between(LocalTime.MIN, endTime).getSeconds(); } public LocalTime getStartTime() { return startTime; } public LocalTime getEndTime() { return endTime; } public long midnightToEndCacheTime() { return midnightToEndCacheTime; } }
package uk.ac.ebi.quickgo.ontology; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.time.Duration; import java.time.LocalTime; /** * Holds values related to the operation of the Ontology REST service. * <p> * Created by Tony on 04-Apr-17. */ @Component @ConfigurationProperties(prefix = "ontology.cache.control.time") public class OntologyRestProperties { private static final int MINUTES = 0; private static final int DEFAULT_START_HOURS = 18; private static final int DEFAULT_END_HOURS = 17; private LocalTime startTime = LocalTime.of(DEFAULT_START_HOURS, MINUTES); private LocalTime endTime = LocalTime.of(DEFAULT_END_HOURS, MINUTES); private long midnightToEndCacheTime; public void setStart(int hours) { startTime = LocalTime.of(hours, MINUTES); } public void setEnd(int hours) { endTime = LocalTime.of(hours, MINUTES); this.midnightToEndCacheTime = Duration.between(LocalTime.MIDNIGHT, endTime).getSeconds(); } public LocalTime getStartTime() { return startTime; } public LocalTime getEndTime() { return endTime; } public long midnightToEndCacheTime() { return midnightToEndCacheTime; } }
Use ::class keyword when possible
<?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 Doctrine\Common\Annotations\AnnotationRegistry; use Symfony\Bridge\PhpUnit\DeprecationErrorHandler; // Detect if we need to serialize deprecations to a file. if ($file = getenv('SYMFONY_DEPRECATIONS_SERIALIZE')) { DeprecationErrorHandler::collectDeprecations($file); return; } // Detect if we're loaded by an actual run of phpunit if (!defined('PHPUNIT_COMPOSER_INSTALL') && !class_exists(\PHPUnit\TextUI\Command::class, false)) { return; } // Enforce a consistent locale setlocale(\LC_ALL, 'C'); if (!class_exists(AnnotationRegistry::class, false) && class_exists(AnnotationRegistry::class)) { if (method_exists(AnnotationRegistry::class, 'registerUniqueLoader')) { AnnotationRegistry::registerUniqueLoader('class_exists'); } else { AnnotationRegistry::registerLoader('class_exists'); } } if ('disabled' !== getenv('SYMFONY_DEPRECATIONS_HELPER')) { DeprecationErrorHandler::register(getenv('SYMFONY_DEPRECATIONS_HELPER')); }
<?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 Doctrine\Common\Annotations\AnnotationRegistry; use Symfony\Bridge\PhpUnit\DeprecationErrorHandler; // Detect if we need to serialize deprecations to a file. if ($file = getenv('SYMFONY_DEPRECATIONS_SERIALIZE')) { DeprecationErrorHandler::collectDeprecations($file); return; } // Detect if we're loaded by an actual run of phpunit if (!defined('PHPUNIT_COMPOSER_INSTALL') && !class_exists('PHPUnit\TextUI\Command', false)) { return; } // Enforce a consistent locale setlocale(\LC_ALL, 'C'); if (!class_exists('Doctrine\Common\Annotations\AnnotationRegistry', false) && class_exists('Doctrine\Common\Annotations\AnnotationRegistry')) { if (method_exists('Doctrine\Common\Annotations\AnnotationRegistry', 'registerUniqueLoader')) { AnnotationRegistry::registerUniqueLoader('class_exists'); } else { AnnotationRegistry::registerLoader('class_exists'); } } if ('disabled' !== getenv('SYMFONY_DEPRECATIONS_HELPER')) { DeprecationErrorHandler::register(getenv('SYMFONY_DEPRECATIONS_HELPER')); }
[DependencyInjection] Use ivory_ckeditor instead of ivory_ck_editor as alias
<?php /* * This file is part of the Ivory CKEditor package. * * (c) Eric GELOEN <geloen.eric@gmail.com> * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. */ namespace Ivory\CKEditorBundle\DependencyInjection; use Symfony\Component\Config\FileLocator, Symfony\Component\DependencyInjection\ContainerBuilder, Symfony\Component\DependencyInjection\Loader\XmlFileLoader, Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * Ivory CKEditor extension * * @author GeLo <geloen.eric@gmail.com> */ class IvoryCKEditorExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $container->setParameter('twig.form.resources', array_merge( $container->getParameter('twig.form.resources'), array('IvoryCKEditorBundle:Form:ckeditor_widget.html.twig') )); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } /** * {@inheritdoc} */ public function getAlias() { return 'ivory_ckeditor'; } }
<?php /* * This file is part of the Ivory CKEditor package. * * (c) Eric GELOEN <geloen.eric@gmail.com> * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. */ namespace Ivory\CKEditorBundle\DependencyInjection; use Symfony\Component\Config\FileLocator, Symfony\Component\DependencyInjection\ContainerBuilder, Symfony\Component\DependencyInjection\Loader\XmlFileLoader, Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * Ivory CKEditor extension * * @author GeLo <geloen.eric@gmail.com> */ class IvoryCKEditorExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $container->setParameter('twig.form.resources', array_merge( $container->getParameter('twig.form.resources'), array('IvoryCKEditorBundle:Form:ckeditor_widget.html.twig') )); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
Add back in missing auto config for galaxy integration tests.
package ca.corefacility.bioinformatics.irida.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.Tag; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import ca.corefacility.bioinformatics.irida.config.IridaApiGalaxyTestConfig; import ca.corefacility.bioinformatics.irida.config.data.IridaApiTestFilesystemConfig; import ca.corefacility.bioinformatics.irida.config.services.IridaApiServicesConfig; /** * Annotation that is to be specified on Galaxy integration tests. Simplifies the configuration of tests by * automatically adding a number of necessary annotations. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Inherited @Tag("IntegrationTest") @Tag("Galaxy") @ActiveProfiles("test") @SpringBootTest(classes = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, IridaApiTestFilesystemConfig.class, IridaApiServicesConfig.class, IridaApiGalaxyTestConfig.class }) public @interface GalaxyIntegrationTest { }
package ca.corefacility.bioinformatics.irida.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.Tag; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import ca.corefacility.bioinformatics.irida.config.IridaApiGalaxyTestConfig; import ca.corefacility.bioinformatics.irida.config.data.IridaApiTestFilesystemConfig; import ca.corefacility.bioinformatics.irida.config.services.IridaApiServicesConfig; /** * Annotation that is to be specified on Galaxy integration tests. Simplifies the configuration of tests by * automatically adding a number of necessary annotations. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Inherited @Tag("IntegrationTest") @Tag("Galaxy") @ActiveProfiles("test") @SpringBootTest(classes = { DataSourceAutoConfiguration.class, IridaApiTestFilesystemConfig.class, IridaApiServicesConfig.class, IridaApiGalaxyTestConfig.class }) public @interface GalaxyIntegrationTest { }
Remove outdated comment in FastFillStyle
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // @flow /** * Firefox has issues switching quickly between fill style colors, as the CSS color * is fully parsed each time it is set. As a mitigation, provide a class that only * switches the color when it's really needed. */ export class FastFillStyle { _ctx: CanvasRenderingContext2D; _previousFillColor: string; constructor(ctx: CanvasRenderingContext2D) { this._ctx = ctx; this._previousFillColor = ''; } set(fillStyle: string) { if (fillStyle !== this._previousFillColor) { this._ctx.fillStyle = fillStyle; this._previousFillColor = fillStyle; } } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // @flow /** * Firefox has issues switching quickly between fill style colors, as the CSS color * is fully parsed each time it is set. As a mitigation, provide a class that only * switches the color when it's really needed. */ export class FastFillStyle { _ctx: CanvasRenderingContext2D; _previousFillColor: string; constructor(ctx: CanvasRenderingContext2D) { this._ctx = ctx; this._previousFillColor = ''; } set(fillStyle: string) { if (fillStyle !== this._previousFillColor) { // This could throw if setCtx wasn't set before calling it. Don't provide an // extra check here since this code is so hot. this._ctx.fillStyle = fillStyle; this._previousFillColor = fillStyle; } } }
Refactor to be constructed without parameters
/* * DomainScope module * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-28 */ var Scope = require('./scope'); /** * DomainScope * @constructor */ function DomainScope() { "use strict"; Scope.call(this, null, Scope.DOMAIN_SCOPE_NAME, Scope.DOMAIN_TYPE, null); } DomainScope.prototype = Object.create(Scope.prototype); Object.defineProperty(DomainScope.prototype, 'constructor', { value: DomainScope }); /* start-public-data-members */ Object.defineProperties(DomainScope.prototype, { /** * Array of build-in objects * @type {Array} * @memberof DomainScope.prototype * @inheritdoc */ builtInObjects: { get: function () { "use strict"; /* manual */ return [ {name: "localStorage", def: "localStorage"} ]; } } }); /* end-public-data-members */ module.exports = DomainScope;
/* * DomainScope module * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-28 */ var Scope = require('./scope'); /** * DomainScope * @param {Object} cfg Graph of the domain scope * @constructor */ function DomainScope(cfg) { "use strict"; Scope.call(this, cfg, Scope.DOMAIN_SCOPE_NAME, Scope.DOMAIN_TYPE, null); } DomainScope.prototype = Object.create(Scope.prototype); Object.defineProperty(DomainScope.prototype, 'constructor', { value: DomainScope }); /* start-public-data-members */ Object.defineProperties(DomainScope.prototype, { /** * Array of build-in objects * @type {Array} * @memberof DomainScope.prototype * @inheritdoc */ builtInObjects: { get: function () { "use strict"; /* manual */ return [ {name: "localStorage", def: "localStorage"} ]; } } }); /* end-public-data-members */ module.exports = DomainScope;
Add my packages to featured list
import requests from . import packages from models import Package, Downloads from flask import jsonify from datetime import timedelta from app import cache from utils import cache_timeout @packages.route('/stats', methods=['GET']) @cache_timeout @cache.cached() def stats(): resp = dict() resp["count"] = Package.get_count() resp["day"] = Downloads.get_overall_downloads_count(timedelta(days=1)) resp["week"] = Downloads.get_overall_downloads_count(timedelta(days=7)) resp["month"] = Downloads.get_overall_downloads_count(timedelta(days=30)) return jsonify(resp) @packages.route('/featured', methods=['GET']) @cache_timeout @cache.cached() def featured(): package_list = requests.get("https://atom.io/api/packages/featured") theme_list = requests.get("https://atom.io/api/themes/featured") featured_list = package_list.json() + theme_list.json() # limit data to multiples of three length = ((len(featured_list) + 2) / 3) * 3 featured_list = featured_list[:(length - 2)] json_data = [] for item in featured_list: obj = Package.get_package(item['name']) if obj is not None: json_data.append(obj.get_json()) for item in ["docblockr", "git-log"]: obj = Package.get_package(item) json_data.append(obj.get_json()) return jsonify(results=json_data)
import requests from . import packages from models import Package, Downloads from flask import jsonify from datetime import timedelta from app import cache from utils import cache_timeout @packages.route('/stats', methods=['GET']) @cache_timeout @cache.cached() def stats(): resp = dict() resp["count"] = Package.get_count() resp["day"] = Downloads.get_overall_downloads_count(timedelta(days=1)) resp["week"] = Downloads.get_overall_downloads_count(timedelta(days=7)) resp["month"] = Downloads.get_overall_downloads_count(timedelta(days=30)) return jsonify(resp) @packages.route('/featured', methods=['GET']) @cache_timeout @cache.cached() def featured(): package_list = requests.get("https://atom.io/api/packages/featured") theme_list = requests.get("https://atom.io/api/themes/featured") featured_list = package_list.json() + theme_list.json() # limit data to multiples of three length = (len(featured_list) / 3) * 3 featured_list = featured_list[:length] json_data = [] for item in featured_list: obj = Package.get_package(item['name']) if obj is not None: json_data.append(obj.get_json()) return jsonify(results=json_data)
Support hyphens in string formatting
function get_cookie(name) { if(!document.cookie || document.cookie === '') return; var bits = document.cookie.split(';'); for(var i=0, l=bits.length; i < l; i++) { var m = bits[i].trim().match(/(\w+)=(.*)/); if(m !== undefined && m[1] == name) { return decodeURIComponent(m[2]) } } } /* resolve a string to an element, if it's not already */ function element(el) { return (typeof el == 'string') ? document.querySelector(el) : el; } /* Helpers for Fetch */ function check_status(response) { if(response.status >= 200 && response.status < 300) { return response; } var err = new Error(response.statusText); err.response = response; throw err; } function json (response) { return response.json(); } fetch.post = function (url, data) { return fetch(url, { method: 'post', body: data, credentials: 'same-origin', headers: { 'X-CSRFToken': get_cookie('csrftoken') } }); } fetch.get = function (url, data) { return fetch(url, { body: data, credentials: 'same-origin', }) } /* string helper */ String.prototype.format = function (args) { return this.replace(/{([\-\w]+)}/g, function(m, key) { return args[key]; }); }
function get_cookie(name) { if(!document.cookie || document.cookie === '') return; var bits = document.cookie.split(';'); for(var i=0, l=bits.length; i < l; i++) { var m = bits[i].trim().match(/(\w+)=(.*)/); if(m !== undefined && m[1] == name) { return decodeURIComponent(m[2]) } } } /* resolve a string to an element, if it's not already */ function element(el) { return (typeof el == 'string') ? document.querySelector(el) : el; } /* Helpers for Fetch */ function check_status(response) { if(response.status >= 200 && response.status < 300) { return response; } var err = new Error(response.statusText); err.response = response; throw err; } function json (response) { return response.json(); } fetch.post = function (url, data) { return fetch(url, { method: 'post', body: data, credentials: 'same-origin', headers: { 'X-CSRFToken': get_cookie('csrftoken') } }); } fetch.get = function (url, data) { return fetch(url, { body: data, credentials: 'same-origin', }) } /* string helper */ String.prototype.format = function (args) { return this.replace(/{(\w+)}/g, function(m, key) { return args[key]; }); }
Update extension to work with latest showdown version From showdown v1.0.0 and onward, the namespace changed from `Showdown` to `showdown`. This change reflect the new namespace, making it compatible with the latest version
/* * Showdown XSS Filter extension * https://github.com/VisionistInc/showdown-xss-filter * 2015, Visionist, Inc. * License: MIT */ (function() { // Server-side import if (typeof module !== 'undefined') { filterXSS = require('xss'); } // Filter out potential XSS attacks before rendering HTML var xssfilter = function (converter) { return [ { type: "lang", filter: function(text) { return filterXSS(text); } } ]; }; // Client-side export if (typeof window !== 'undefined' && window.showdown && window.showdown.extensions) { window.showdown.extensions.xssfilter = xssfilter; } // Server-side export if (typeof module !== 'undefined') { module.exports = xssfilter; } })();
/* * Showdown XSS Filter extension * https://github.com/VisionistInc/showdown-xss-filter * 2015, Visionist, Inc. * License: MIT */ (function() { // Server-side import if (typeof module !== 'undefined') { filterXSS = require('xss'); } // Filter out potential XSS attacks before rendering HTML var xssfilter = function (converter) { return [ { type: "lang", filter: function(text) { return filterXSS(text); } } ]; }; // Client-side export if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.xssfilter = xssfilter; } // Server-side export if (typeof module !== 'undefined') { module.exports = xssfilter; } })();
Remove fatal error in workers
package main import ( "fmt" "time" "sync" ) var wg sync.WaitGroup func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { if j == -1 { wg.Done() return } fmt.Println("worker", id, "processing job", j) time.Sleep(time.Second) results <- j * 2 } } func printer(results <-chan int) { for r := range results { fmt.Println(r) } } func main() { jobs := make(chan int, 100) results := make(chan int, 100) // This starts up 3 workers, initially blocked // because there are no jobs yet. for w := 1; w <= 3; w++ { wg.Add(1) go worker(w, jobs, results) } go printer(results) // Here we send 9 `jobs` and then `close` that // channel to indicate that's all the work we have. for j := 1; j <= 9; j++ { jobs <- j } for w := 1; w <= 3; w++ { jobs <- -1 } wg.Wait() }
package main import ( "fmt" "time" "sync" ) func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("worker", id, "processing job", j) time.Sleep(time.Second) results <- j * 2 } } func printer(results <-chan int) { for r := range results { fmt.Println(r) } } func main() { jobs := make(chan int, 100) results := make(chan int, 100) var wg sync.WaitGroup // This starts up 3 workers, initially blocked // because there are no jobs yet. for w := 1; w <= 3; w++ { wg.Add(1) go worker(w, jobs, results) } go printer(results) // Here we send 9 `jobs` and then `close` that // channel to indicate that's all the work we have. for j := 1; j <= 9; j++ { jobs <- j } wg.Wait() close(jobs) }
Add task for building docs
# coding=utf-8 """Useful task commands for development and maintenance.""" from invoke import run, task @task def clean(): """Clean the project directory of unwanted files and directories.""" run('rm -rf gmusicapi_scripts.egg-info') run('rm -rf .coverage') run('rm -rf .tox') run('rm -rf .cache') run('rm -rf build/') run('rm -rf dist/') run('rm -rf site/') run('find . -name *.pyc -delete') run('find . -name *.pyo -delete') run('find . -name __pycache__ -delete -depth') run('find . -name *~ -delete') @task(clean) def build(): """Build sdist and bdist_wheel distributions.""" run('python setup.py sdist bdist_wheel') @task(build) def deploy(): """Build and upload gmusicapi_scripts distributions.""" upload() @task def docs(test=False): """"Build the gmusicapi_scripts docs.""" if test: run('mkdocs serve') else: run('mkdocs gh-deploy --clean') @task def upload(): """Upload gmusicapi_scripts distributions using twine.""" run('twine upload dist/*')
# coding=utf-8 """Useful task commands for development and maintenance.""" from invoke import run, task @task def clean(): """Clean the project directory of unwanted files and directories.""" run('rm -rf gmusicapi_scripts.egg-info') run('rm -rf .coverage') run('rm -rf .tox') run('rm -rf .cache') run('rm -rf build/') run('rm -rf dist/') run('rm -rf site/') run('find . -name *.pyc -delete') run('find . -name *.pyo -delete') run('find . -name __pycache__ -delete -depth') run('find . -name *~ -delete') @task(clean) def build(): """Build sdist and bdist_wheel distributions.""" run('python setup.py sdist bdist_wheel') @task(build) def deploy(): """Build and upload gmusicapi_scripts distributions.""" upload() @task def upload(): """Upload gmusicapi_scripts distributions using twine.""" run('twine upload dist/*')
Update Laser Pistol for 1.7.10
package net.shadowfacts.zcraft.item.tool; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.shadowfacts.zcraft.entity.EntityLaserBolt; import net.shadowfacts.zcraft.item.ZItems; public class ItemLaserPistol extends Item { public ItemLaserPistol() { super(); this.setMaxStackSize(1); this.setMaxDamage(512); } @Override public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { itemStack.damageItem(1, player); world.playSoundAtEntity(player, "random.bow", 0.5f, 0.4f / (itemRand.nextFloat() * 0.4f + 0.8f)); if (!world.isRemote) { world.spawnEntityInWorld(new EntityLaserBolt(world, player)); } return itemStack; } }
package net.shadowfacts.zcraft.item.tool; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.shadowfacts.zcraft.entity.EntityLaserBolt; import net.shadowfacts.zcraft.item.ZItems; public class ItemLaserPistol extends Item { public ItemLaserPistol(int par1) { super(par1); this.setMaxStackSize(1); this.setMaxDamage(512); } @Override public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { itemStack.damageItem(1, player); world.playSoundAtEntity(player, "random.bow", 0.5f, 0.4f / (itemRand.nextFloat() * 0.4f + 0.8f)); if (!world.isRemote) { world.spawnEntityInWorld(new EntityLaserBolt(world, player)); } return itemStack; } }
Remove teacherConnect socket event for frontend handling
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage : function(io, req, res, next) { //var studentInformation = req.body.studentData var pollResponse = { responseId: 1, type: 'thumbs', datetime: new Date(), lessonId: 13, }; io.on('connection', function(student){ student.emit('studentStandby', studentInformation); student.on('newPoll', function(data) { student.emit(data); }); setTimeout(function(){ io.sockets.emit('responseFromStudent', pollResponse); }, 5000); }); res.status(200).send('Hello from the student side'); } };
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage : function(io, req, res, next) { //var studentInformation = req.body.studentData var pollResponse = { responseId: 1, type: 'thumbs', datetime: new Date(), lessonId: 13, }; io.on('connection', function(student){ student.emit('studentStandby', studentInformation); student.on('teacherConnect', function() { student.emit('teacherConnect'); }); student.on('newPoll', function(data) { student.emit(data); }); setTimeout(function(){ io.sockets.emit('responseFromStudent', pollResponse); }, 5000); }); res.status(200).send('Hello from the other side'); } };
JSCBC-409: Fix bug with cluster management on real buckets Motivation ---------- A bug was causing certain cluster management tests to fail to execute correctly during 'RealBucket' tests. Changes ------- Fixed incorrect use of bind rather than call. Change-Id: Ia60b3940b2aad09da63fd6000d26bbea57f1c794 Reviewed-on: http://review.couchbase.org/82480 Reviewed-by: Sergey Avseyev <87f6d5e4fd3644c3c20800cde7fd3ad1569370b3@gmail.com> Reviewed-by: Mike Goldsmith <c43a3c67d7a1203c37ce25b098df0254011e1ce6@gmail.com> Tested-by: Brett Lawson <c8c4369773d7d7226e031f0c4af62e3f38a08510@gmail.com>
'use strict'; var assert = require('assert'); var harness = require('./harness.js'); describe('#cluster management', function() { function allTests(H) { it('should be able to access a cluster manager', function () { var cluster = new H.lib.Cluster(H.connstr); var clusterMgr = cluster.manager(H.muser, H.mpass); assert(clusterMgr); }); it('should be able to list buckets', function () { var cluster = new H.lib.Cluster(H.connstr); var clusterMgr = cluster.manager(H.muser, H.mpass); clusterMgr.listBuckets(function (err, list) { assert(!err); assert(list); }); }); } describe('#RealBucket', function() { allTests.call(this, harness); it('should not be able to list buckets with wrong password', function (done) { var cluster = new harness.lib.Cluster(harness.connstr); var clusterMgr = cluster.manager(harness.muser, 'junk'); clusterMgr.listBuckets(function (err, list) { assert(err); assert.equal(err.message, 'operation failed (401)'); assert(!list); done(); }); }); }); describe('#MockBucket', allTests.bind(this, harness.mock)); });
'use strict'; var assert = require('assert'); var harness = require('./harness.js'); describe('#cluster management', function() { function allTests(H) { it('should be able to access a cluster manager', function () { var cluster = new H.lib.Cluster(H.connstr); var clusterMgr = cluster.manager(H.muser, H.mpass); assert(clusterMgr); }); it('should be able to list buckets', function () { var cluster = new H.lib.Cluster(H.connstr); var clusterMgr = cluster.manager(H.muser, H.mpass); clusterMgr.listBuckets(function (err, list) { assert(!err); assert(list); }); }); } describe('#RealBucket', function() { allTests.bind(this, harness); it('should not be able to list buckets with wrong password', function (done) { var cluster = new harness.lib.Cluster(harness.connstr); var clusterMgr = cluster.manager(harness.muser, 'junk'); clusterMgr.listBuckets(function (err, list) { assert(err); assert.equal(err.message, 'operation failed (401)'); assert(!list); done(); }); }); }); describe('#MockBucket', allTests.bind(this, harness.mock)); });
Enforce python3 on pep8 test (and remove print markers)
import os import sys from setuptools import setup, find_packages, Command class Doctest(Command): if sys.argv[-1] == 'test': print("Running docs make and make doctest") os.system("make doctest -C docs/") class Pep8Test(Command): if sys.argv[-1] == 'test': print("Running pep8 under source code folder") os.system("python3 setup.py pep8 --exclude '.eggs*'") setup(name='Kytos OpenFlow Parser library', version='0.1', description='Library to parse and generate OpenFlow messages', url='http://github.com/kytos/python-openflow', author='Kytos Team', author_email='of-ng-dev@ncc.unesp.br', license='MIT', test_suite='tests', packages=find_packages(exclude=["tests", "*v0x02*"]), setup_requires=['setuptools-pep8'], cmdclass={ 'doctests': Doctest }, zip_safe=False)
import os import sys from setuptools import setup, find_packages, Command SEP='<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>' class Doctest(Command): if sys.argv[-1] == 'test': print(SEP) print("Running docs make and make doctest") os.system("make doctest -C docs/") print(SEP) class Pep8Test(Command): if sys.argv[-1] == 'test': print("Running pep8 under source code folder") os.system("python setup.py pep8 --exclude '.eggs*'") print(SEP) setup(name='Kytos OpenFlow Parser library', version='0.1', description='Library to parse and generate OpenFlow messages', url='http://github.com/kytos/python-openflow', author='Kytos Team', author_email='of-ng-dev@ncc.unesp.br', license='MIT', test_suite='tests', packages=find_packages(exclude=["tests", "*v0x02*"]), setup_requires=['setuptools-pep8'], cmdclass={ 'doctests': Doctest }, zip_safe=False)
Upgrade requests to versions > 1.0.0
#!/usr/bin/env python import os import skosprovider_oe try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'skosprovider_oe', ] requires = [ 'skosprovider', 'requests>=1.0.0' ] setup( name='skosprovider_oe', version='0.1.0', description='A SKOS provider for OE vocabularies.', long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(), author='Koen Van Daele', author_email='koen_van_daele@telenet.be', url='http://github.com/koenedaele/skosprovider_oe', packages=packages, package_data={'': ['LICENSE']}, package_dir={'skosprovider': 'skosprovider'}, include_package_data=True, install_requires=requires, license=open('LICENSE').read(), zip_safe=False, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', ], )
#!/usr/bin/env python import os import skosprovider_oe try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'skosprovider_oe', ] requires = [ 'skosprovider', 'requests>0.14,<0.14.99' ] setup( name='skosprovider_oe', version='0.1.0', description='A SKOS provider for OE vocabularies.', long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(), author='Koen Van Daele', author_email='koen_van_daele@telenet.be', url='http://github.com/koenedaele/skosprovider_oe', packages=packages, package_data={'': ['LICENSE']}, package_dir={'skosprovider': 'skosprovider'}, include_package_data=True, install_requires=requires, license=open('LICENSE').read(), zip_safe=False, classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', ), )
Remove some unneeded sanity checks.
import React, { PropTypes } from 'react' import { matchContext as matchContextType } from './PropTypes' class MatchProvider extends React.Component { static propTypes = { match: PropTypes.any, children: PropTypes.node } static childContextTypes = { match: matchContextType.isRequired } constructor(props) { super(props) this.state = { parent: props.match, matches: [] } } addMatch = match => { const { matches } = this.state this.setState({ matches: matches.concat([match]) }) } removeMatch = match => { const { matches } = this.state this.setState({ matches: matches.splice(matches.indexOf(match), 1) }) } getChildContext() { return { match: { addMatch: this.addMatch, removeMatch: this.removeMatch, parent: this.state.parent, matches: this.state.matches, matchFound: this.state.matches.length > 0 } } } render() { return this.props.children } } export default MatchProvider
import React, { PropTypes } from 'react' import { matchContext as matchContextType } from './PropTypes' class MatchProvider extends React.Component { static propTypes = { match: PropTypes.any, children: PropTypes.node } static childContextTypes = { match: matchContextType.isRequired } constructor(props) { super(props) this.state = { parent: props.match, matches: [] } } addMatch = match => { const { matches } = this.state if (matches.indexOf(match) === -1 ) this.setState({ matches: matches.concat([match]) }) } removeMatch = match => { const { matches } = this.state const index = matches.indexOf(match) if (index > -1 ) this.setState({ matches: matches.splice(index, 1) }) } getChildContext() { return { match: { addMatch: this.addMatch, removeMatch: this.removeMatch, parent: this.state.parent, matches: this.state.matches, matchFound: this.state.matches.length > 0 } } } render() { return this.props.children } } export default MatchProvider
Install missing templatetags test package
from setuptools import setup setup( name='armstrong.base', version='0.1.3', description='Base functionality that needs to be shared widely', author='Texas Tribune', author_email='tech@texastribune.org', url='http://github.com/texastribune/armstrong.base/', packages=[ 'armstrong.base', 'armstrong.base.templatetags', 'armstrong.base.tests', 'armstrong.base.tests.templatetags', ], namespace_packages=[ "armstrong", ], install_requires=[ 'setuptools', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], )
from setuptools import setup setup( name='armstrong.base', version='0.1.2', description='Base functionality that needs to be shared widely', author='Texas Tribune', author_email='tech@texastribune.org', url='http://github.com/texastribune/armstrong.base/', packages=[ 'armstrong.base', 'armstrong.base.templatetags', 'armstrong.base.tests', ], namespace_packages=[ "armstrong", ], install_requires=[ 'setuptools', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], )
Update ui - favorite button
package com.alsash.reciper.logic.event; import com.alsash.reciper.logic.action.RecipeAction; public class RecipeEvent { public final RecipeAction action; public final String uuid; public RecipeEvent(RecipeAction action, String uuid) { this.action = action; this.uuid = uuid; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RecipeEvent)) return false; RecipeEvent event = (RecipeEvent) o; if (action != event.action) return false; return uuid != null ? uuid.equals(event.uuid) : event.uuid == null; } @Override public int hashCode() { int result = action != null ? action.hashCode() : 0; result = 31 * result + (uuid != null ? uuid.hashCode() : 0); return result; } }
package com.alsash.reciper.logic.event; import com.alsash.reciper.logic.action.RecipeAction; public class RecipeEvent { public final RecipeAction action; public final String uuid; public RecipeEvent(RecipeAction action, String uuid) { this.action = action; this.uuid = uuid; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RecipeEvent)) return false; RecipeEvent event = (RecipeEvent) o; if (action != event.action) return false; return uuid != null ? uuid.equals(event.uuid) : event.uuid == null; } @Override public int hashCode() { int result = action != null ? action.hashCode() : 0; result = 31 * result + (uuid != null ? uuid.hashCode() : 0); return result; } }
Sort line coverage info when reporting
#!/usr/bin/env python # coding: utf-8 import json import os import sys from coveralls import Coveralls, cli # Patch coveralls to get javascript coverage from mocha orig_get_coverage = Coveralls.get_coverage def get_coverage_with_js(self): report = orig_get_coverage(self) js_files = json.load(open('.coverage-js'))['files'] js_report = [] for f in js_files: source = '\n'.join(open(f['filename']).readlines()) name = os.path.relpath(f['filename']) coverage = [] # Create sorted coverage array from original dict for k, v in sorted(f['source'].items(), key=lambda x:int(x[0])): coverage.append(v['coverage'] if v['coverage'] != '' else None) js_report.append({ 'source': source, 'name': name, 'coverage': coverage} ) report += js_report return report Coveralls.get_coverage = get_coverage_with_js cli.main(sys.argv[1:])
#!/usr/bin/env python # coding: utf-8 import json import os import sys from coveralls import Coveralls, cli # Patch coveralls to get javascript coverage from mocha orig_get_coverage = Coveralls.get_coverage def get_coverage_with_js(self): report = orig_get_coverage(self) js_files = json.load(open('.coverage-js'))['files'] js_report = [] for f in js_files: source = '\n'.join(open(f['filename']).readlines()) name = os.path.relpath(f['filename']) coverage = [] for v in f['source'].values(): coverage.append(v['coverage'] if v['coverage'] != '' else None) js_report.append({ 'source': source, 'name': name, 'coverage': coverage} ) report += js_report return report Coveralls.get_coverage = get_coverage_with_js cli.main(sys.argv[1:])
Use slice to create a real array before trying to access a value by index.
import Model, { hasMany, belongsTo, attr } from '@ember-data/model'; import { htmlSafe } from '@ember/template'; import { use } from 'ember-could-get-used-to-this'; import ResolveAsyncValue from 'ilios-common/classes/resolve-async-value'; export default class SessionType extends Model { @attr('string') title; @attr('string') calendarColor; @attr('boolean') active; @attr('boolean') assessment; @belongsTo('assessment-option', { async: true }) assessmentOption; @belongsTo('school', { async: true }) school; @hasMany('aamc-method', { async: true }) aamcMethods; @hasMany('session', { async: true }) sessions; get safeCalendarColor() { const pattern = new RegExp('^#[a-fA-F0-9]{6}$'); if (pattern.test(this.calendarColor)) { return htmlSafe(this.calendarColor); } return ''; } get sessionCount() { return this.hasMany('sessions').ids().length; } @use _aamcMethods = new ResolveAsyncValue(() => [this.aamcMethods]); get firstAamcMethod() { if (!this._aamcMethods) { return undefined; } return this._aamcMethods.slice()[0]; } }
import Model, { hasMany, belongsTo, attr } from '@ember-data/model'; import { htmlSafe } from '@ember/template'; import { use } from 'ember-could-get-used-to-this'; import ResolveAsyncValue from 'ilios-common/classes/resolve-async-value'; export default class SessionType extends Model { @attr('string') title; @attr('string') calendarColor; @attr('boolean') active; @attr('boolean') assessment; @belongsTo('assessment-option', { async: true }) assessmentOption; @belongsTo('school', { async: true }) school; @hasMany('aamc-method', { async: true }) aamcMethods; @hasMany('session', { async: true }) sessions; get safeCalendarColor() { const pattern = new RegExp('^#[a-fA-F0-9]{6}$'); if (pattern.test(this.calendarColor)) { return htmlSafe(this.calendarColor); } return ''; } get sessionCount() { return this.hasMany('sessions').ids().length; } @use _aamcMethods = new ResolveAsyncValue(() => [this.aamcMethods]); get firstAamcMethod() { if (!this._aamcMethods) { return undefined; } return this._aamcMethods[0]; } }
Exclude mobile devices from v4 ramp for now
import { isWebView, getAgent, isDevice } from '../lib'; const SUPPORTED_AGENTS = { Chrome: 27, IE: 9, MSIE: 9, Firefox: 30, Safari: 5.1, Opera: 23 }; export function isUnsupportedIE() { return window.navigator.userAgent.match(/MSIE (5|6|7|8)\./i); } export function isOldIE() { return window.navigator.userAgent.match(/MSIE (5|6|7|8|9|10)\./i); } export function isEligible() { let currentAgent = getAgent(); if (typeof currentAgent === 'object' && currentAgent.length === 2) { if (parseFloat(currentAgent[1]) < SUPPORTED_AGENTS[currentAgent[0]]) { return false; } } return !(isWebView() || isUnsupportedIE() || isDevice()); }
import { isWebView, getAgent } from '../lib'; const SUPPORTED_AGENTS = { Chrome: 27, IE: 9, MSIE: 9, Firefox: 30, Safari: 5.1, Opera: 23 }; export function isUnsupportedIE() { return window.navigator.userAgent.match(/MSIE (5|6|7|8)\./i); } export function isOldIE() { return window.navigator.userAgent.match(/MSIE (5|6|7|8|9|10)\./i); } export function isEligible() { let currentAgent = getAgent(); if (typeof currentAgent === 'object' && currentAgent.length === 2) { if (parseFloat(currentAgent[1]) < SUPPORTED_AGENTS[currentAgent[0]]) { return false; } } return !(isWebView() || isUnsupportedIE()); }
Add rtrssmgr command entry point
""" RTRSS ----- RSS feeds for popular bittorrent tracker """ from setuptools import setup with open('reqs/production.txt') as f: _requirements = f.read().splitlines() setup( name='rtrss', version='0.3', author='notapresent', author_email='notapresent@gmail.com', url='https://github.com/notapresent/rtrss', description='RSS feeds for popular bittorrent tracker', long_description=__doc__, license='Apache 2.0', download_url='https://github.com/notapresent/rtrss/archive/master.zip', install_requires=_requirements, entry_points={ 'console_scripts': [ 'rtrssmgr = rtrss.worker:main', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Flask', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ] )
""" RTRSS ----- RSS feeds for popular bittorrent tracker """ from setuptools import setup with open('reqs/production.txt') as f: _requirements = f.read().splitlines() setup( name='rtrss', version='0.3', author='notapresent', author_email='notapresent@gmail.com', url='https://github.com/notapresent/rtrss', description='RSS feeds for popular bittorrent tracker', long_description=__doc__, license='Apache 2.0', download_url='https://github.com/notapresent/rtrss/archive/master.zip', install_requires=_requirements, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Flask', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ] )
Use num_leaves function in tests
from viridis import tree from six.moves import range import pytest @pytest.fixture def base_tree(): t = tree.Ultrametric(list(range(6))) t.merge(0, 1, 0.1) t.merge(6, 2, 0.2) t.merge(3, 4, 0.3) t.merge(8, 5, 0.4) t.merge(7, 8, 0.5) return t def test_split(base_tree): t = base_tree t.split(0, 2) assert t.node[9]['num_leaves'] == 3 t.split(0, 4) # nothing to do assert tree.num_leaves(t, 9) == 3 def test_children(base_tree): t = base_tree assert t.children(6) == [0, 1]
from viridis import tree from six.moves import range import pytest @pytest.fixture def base_tree(): t = tree.Ultrametric(list(range(6))) t.merge(0, 1, 0.1) t.merge(6, 2, 0.2) t.merge(3, 4, 0.3) t.merge(8, 5, 0.4) t.merge(7, 8, 0.5) return t def test_split(base_tree): t = base_tree t.split(0, 2) assert t.node[9]['num_leaves'] == 3 t.split(0, 4) # nothing to do assert t.node[9]['num_leaves'] == 3 def test_children(base_tree): t = base_tree assert t.children(6) == [0, 1]
testing: Add omitempty to id fields Otherwise adding a new customer (or any model) with a POST would include a zeroed ID field.
package model // Customer is a model in the "customers" table. type Customer struct { ID int `json:"id,omitempty"` Name *string `json:"name" gorm:"not null"` } // Order is a model in the "orders" table. type Order struct { ID int `json:"id,omitempty"` Subtotal float64 `json:"subtotal" gorm:"type:decimal(18,2)"` Customer Customer `json:"customer" gorm:"ForeignKey:CustomerID"` CustomerID int `json:"-"` Products []Product `json:"products" gorm:"many2many:order_products"` } // Product is a model in the "products" table. type Product struct { ID int `json:"id,omitempty"` Name *string `json:"name" gorm:"not null;unique"` Price float64 `json:"price" gorm:"type:decimal(18,2)"` }
package model // Customer is a model in the "customers" table. type Customer struct { ID int `json:"id"` Name *string `json:"name" gorm:"not null"` } // Order is a model in the "orders" table. type Order struct { ID int `json:"id"` Subtotal float64 `json:"subtotal" gorm:"type:decimal(18,2)"` Customer Customer `json:"customer" gorm:"ForeignKey:CustomerID"` CustomerID int `json:"-"` Products []Product `json:"products" gorm:"many2many:order_products"` } // Product is a model in the "products" table. type Product struct { ID int `json:"id"` Name *string `json:"name" gorm:"not null;unique"` Price float64 `json:"price" gorm:"type:decimal(18,2)"` }
Revert "Return timestamp from pre-purchase" This reverts commit 4e279ff4535dfa0636a3d6af5c92b8e9dcc4311a.
<?php namespace Omnipay\WeChat\Message; use Symfony\Component\HttpFoundation\ParameterBag; class WechatPurchaseRequest extends BaseAbstractRequest { public function initialize(array $parameters = array()) { if (null !== $this->response) { throw new \RuntimeException('Request cannot be modified after it has been sent!'); } $this->parameters = new ParameterBag; foreach ($parameters as $k => $v) { $this->parameters->set($k, $v); } return $this; } public function getData() { $this->validate('code_url'); $params['code_url'] = $this->parameters->get('code_url'); if (empty($params['code_url'])) { throw new \RuntimeException('The code_url that pre-purchase responded is empty, check your parameters!'); } return $params; } public function sendData($data) { return new WechatPurchaseResponse($this, $data); } }
<?php namespace Omnipay\WeChat\Message; use Symfony\Component\HttpFoundation\ParameterBag; class WechatPurchaseRequest extends BaseAbstractRequest { public function initialize(array $parameters = array()) { if (null !== $this->response) { throw new \RuntimeException('Request cannot be modified after it has been sent!'); } $this->parameters = new ParameterBag; foreach ($parameters as $k => $v) { $this->parameters->set($k, $v); } return $this; } public function getData() { $this->validate('code_url', 'timestamp'); $params['code_url'] = $this->parameters->get('code_url'); $params['timestamp'] = $this->parameters->get('timestamp'); if (empty($params['code_url'])) { throw new \RuntimeException('The code_url that pre-purchase responded is empty, check your parameters!'); } return $params; } public function sendData($data) { return new WechatPurchaseResponse($this, $data); } }
Make sure we pass the correct props to the overlay
import React from 'react'; import PropTypes from 'prop-types'; import DayPickerInput from 'react-day-picker/DayPickerInput'; import 'react-day-picker/lib/style.css'; function CustomOverlay({ classNames, selectedDay, children, ...props }) { return ( <div className={classNames.overlayWrapper} style={{ marginLeft: -100 }} {...props} > <div className={classNames.overlay}> <h3>Hello day picker!</h3> <button onClick={() => console.log('clicked!')}>button</button> <p> {selectedDay ? `You picked: ${selectedDay.toLocaleDateString()}` : 'Please pick a day'} </p> {children} </div> </div> ); } CustomOverlay.propTypes = { classNames: PropTypes.object.isRequired, selectedDay: PropTypes.instanceOf(Date), children: PropTypes.node.isRequired, }; export default function Example() { return ( <DayPickerInput overlayComponent={CustomOverlay} dayPickerProps={{ todayButton: 'Today', }} /> ); }
import React from 'react'; import PropTypes from 'prop-types'; import DayPickerInput from 'react-day-picker/DayPickerInput'; import 'react-day-picker/lib/style.css'; function CustomOverlay({ classNames, selectedDay, children }) { return ( <div className={classNames.overlayWrapper} style={{ marginLeft: -100 }}> <div className={classNames.overlay}> <h3>Hello day picker!</h3> <p> {selectedDay ? `You picked: ${selectedDay.toLocaleDateString()}` : 'Please pick a day'} </p> {children} </div> </div> ); } CustomOverlay.propTypes = { classNames: PropTypes.object.isRequired, selectedDay: PropTypes.oneOfType([Date]), children: PropTypes.number.isRequired, }; export default function Example() { return ( <DayPickerInput overlayComponent={CustomOverlay} dayPickerProps={{ todayButton: 'Today', }} /> ); }
Add a product page URI pattern
// ==UserScript== // @name Close ordered item page on Amazon.co.jp // @namespace curipha // @description Close ordered item page automatically // @include https://www.amazon.co.jp/dp/* // @include https://www.amazon.co.jp/*/dp/* // @include https://www.amazon.co.jp/gp/product/* // @exclude https://www.amazon.co.jp/ap/* // @exclude https://www.amazon.co.jp/mn/* // @exclude https://www.amazon.co.jp/clouddrive* // @version 0.0.1 // @grant none // @noframes // ==/UserScript== (function() { 'use strict'; if (document.getElementById('ebooksInstantOrderUpdate')) { window.open('about:blank', '_self').close(); } })();
// ==UserScript== // @name Close ordered item page on Amazon.co.jp // @namespace curipha // @description Close ordered item page automatically // @include https://www.amazon.co.jp/dp/* // @include https://www.amazon.co.jp/*/dp/* // @exclude https://www.amazon.co.jp/ap/* // @exclude https://www.amazon.co.jp/mn/* // @exclude https://www.amazon.co.jp/clouddrive* // @version 0.0.1 // @grant none // @noframes // ==/UserScript== (function() { 'use strict'; if (document.getElementById('ebooksInstantOrderUpdate')) { window.open('about:blank', '_self').close(); } })();
Fix mobile browser fade behavior
var scrollDown = function() { $("html, body").animate({ scrollTop: $(document).height()-$(window).height() }, "slow"); } var fadeTo = function(value) { $('#bottom').css("opacity", 0.6 * (1-value)); $('#fade').css("opacity", value * 0.8); $('#overlay').css("opacity", value); if (value > 0.5) { $("#overlay span").css("pointer-events", "all"); } else { $("#overlay span").css("pointer-events", "none"); } } var scrollValue = function() { return Math.max(($(window).scrollTop() / $(window).height())/0.6, 0.01); } var scrollCheck = function() { fadeTo(scrollValue()); } // $(function() { scrollCheck(); setInterval(scrollCheck, 39); $("#bottom").on('click', function(event) { scrollDown(); }); window.onunload = function() { scrollTo(0,0) }; });
var scrollDown = function() { $("html, body").animate({ scrollTop: $(document).height()-$(window).height() }, "slow"); } var fadeTo = function(value) { $('#bottom').css("opacity", 0.6 * (1-value)); $('#fade').css("opacity", value * 0.8); $('#overlay').css("opacity", value); if (value > 0.5) { $("#overlay span").css("pointer-events", "all"); } else { $("#overlay span").css("pointer-events", "none"); } } var scrollValue = function() { return ($(window).scrollTop() / $(window).height())/0.6; } // $(function() { fadeTo(scrollValue()); $("#bottom").on('click', function(event) { scrollDown(); }); $(window).on('scroll', function(event) { fadeTo(scrollValue()); }); window.onunload = function() { scrollTo(0,0) }; });
Send fqid on stage config creation
export default ['$scope', '$http', '$uibModalInstance', function($scope, $http, $uibModalInstance) { $http .get('/api/stage-types') .then(res => $scope.stages = res.data.data) $scope.ok = () => { let stage = $scope.stages.find(stage => { // $scope.stage_id is the user selected stage if (stage.id === $scope.stage_id) { return stage } }) let sort = $scope.$parent.$stages ? $scope.$parent.$stages.length + 1 : 0 $http .post('/api/stage/config', { pipeline_config_id: $scope.$parent.$id, type: stage.fqid, sort: sort, name: stage.name // options: {} }) .then(res => { console.log(res) }) .catch(err => { console.error(err) }) $uibModalInstance.close() } $scope.cancel = () => { $uibModalInstance.dismiss('cancel') } }]
export default ['$scope', '$http', '$uibModalInstance', function($scope, $http, $uibModalInstance) { // get stages in parent controller console.log('create-stage scope', $scope.$parent.$stages) $http .get('/api/stage-types') .then(res => $scope.stages = res.data.data) $scope.ok = () => { let sort = $scope.$parent.$stages ? $scope.$parent.$stages.length + 1 : 0 $http .post('/api/stage/config', { pipeline_config_id: $scope.$parent.$id, type: $scope.stage_id, sort: sort // options: {} }) .then(res => { console.log(res) }) .catch(err => { console.error(err) }) $uibModalInstance.close() } $scope.cancel = () => { $uibModalInstance.dismiss('cancel') } }]
Make corrections in task 3.3 again
package ru.job4j.maximum; /** * Max class. * @author Yury Chuksin (chuksin.yury@gmail.com) * @since 18.01.2017 */ public class Max { /** * maxFromTwo method compare two variables and takes maximum. * @param first first of two compared variables * @param second second of two compared variables */ public maxFromTwo(int first, int second) { int resultMax = 0; if (first > second) { resultMax = first; } else { resultMax = second; } return resultMax; } /** * maxFromTree method compare tree variables and takes maximum. * @param first first of tree compared variables * @param second second of tree compared variables * @param third of tree compared variables */ public maxFromThree(int first, int second, int third) { return maxFromTwo(maxFromTwo(first, second), third); } }
package ru.job4j.maximum; /** * Max class. * @author Yury Chuksin (chuksin.yury@gmail.com) * @since 18.01.2017 */ public class Max { /** * maxFromTwo method compare two variables and takes maximum. * @param first first of two compared variables * @param second second of two compared variables */ public maxFromTwo(int first, int second) { int resultMax = 0; if (first > second) { resultMax = first; } else { resultMax = second; } return resultMax; } /** * maxFromTree method compare tree variables and takes maximum. * @param first first of tree compared variables * @param second second of tree compared variables * @param third of tree compared variables */ public maxFromThree(int first, int second, int third) { int maxFthree = maxFromTwo(first, second); maxFthree = maxFromTwo(maxFthree, third); return maxFthree; } }
[Admin] Allow blank non-required e-mail fields.
const $ = require('jquery'); const Keys = require('keys/dist/client'); $(() => { $('body').on('click', '[type="submit"]', ev => { const $btn = $(ev.target); const $form = $btn.closest('form'); Keys.clearFieldErrors($form); $form.find('[required]').each((i, el) => { const $el = $(el); if (!$el.val()) { ev.preventDefault(); Keys.flagFieldError($el, 'Preenchimento obrigatório.'); } }); $form.find('[type="email"]').each((i, el) => { const $el = $(el); const val = $el.val(); const re = /^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z0-9_\-]+$/; if (val && !re.test(val)) { ev.preventDefault(); Keys.flagFieldError($el, 'E-mail inválido.'); } }); }); });
const $ = require('jquery'); const Keys = require('keys/dist/client'); $(() => { $('body').on('click', '[type="submit"]', ev => { const $btn = $(ev.target); const $form = $btn.closest('form'); Keys.clearFieldErrors($form); $form.find('[required]').each((i, el) => { const $el = $(el); if (!$el.val()) { ev.preventDefault(); Keys.flagFieldError($el, 'Preenchimento obrigatório.'); } }); $form.find('[type="email"]').each((i, el) => { const $el = $(el); const re = /^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z0-9_\-]+$/; if (!re.test($el.val())) { ev.preventDefault(); Keys.flagFieldError($el, 'E-mail inválido.'); } }); }); });
Use new Bottle debug API
#!/usr/bin/env python from glob import glob import os.path import re import bottle @bottle.route('/') @bottle.view('index') def index(): return dict(debug=bottle.request.GET.get('debug')) @bottle.route('/static/<path:re:.*>') def static(path): return bottle.static_file(path, root=os.path.join(os.path.dirname(__file__), 'static')) @bottle.route('/tests') @bottle.view('tests/index') def test_index(): tests = dict((re.match(r'\b(\w+)_test.html', os.path.basename(filename)).group(1), filename) for filename in glob(os.path.join(os.path.dirname(__file__), 'static', 'tests', '*_test.html'))) return dict(tests=tests) @bottle.route('/webglmaps') @bottle.view('webglmaps/index') def webglmaps_index(): return dict(debug=bottle.request.GET.get('debug')) if __name__ == '__main__': bottle.debug(True) bottle.run(reloader=True, server='tornado')
#!/usr/bin/env python from glob import glob import os.path import re import bottle @bottle.route('/') @bottle.view('index') def index(): return dict(debug=bottle.request.GET.get('debug')) @bottle.route('/static/<path:re:.*>') def static(path): return bottle.static_file(path, root=os.path.join(os.path.dirname(__file__), 'static')) @bottle.route('/tests') @bottle.view('tests/index') def test_index(): tests = dict((re.match(r'\b(\w+)_test.html', os.path.basename(filename)).group(1), filename) for filename in glob(os.path.join(os.path.dirname(__file__), 'static', 'tests', '*_test.html'))) return dict(tests=tests) @bottle.route('/webglmaps') @bottle.view('webglmaps/index') def webglmaps_index(): return dict(debug=bottle.request.GET.get('debug')) if __name__ == '__main__': bottle.DEBUG = True bottle.run(reloader=True, server='tornado')
Fix issue where idx test uses wrong bytes object Forgot to include the sizes of each dimension
from .. import idx import os def test__count_dimensions(): yield check__count_dimensions, 9, 0 yield check__count_dimensions, [1, 2], 1 yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2 yield check__count_dimensions, [[[1,2], [2]]], 3 def check__count_dimensions(lst, i): assert idx._count_dimensions(lst) == i # these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/ _somelist = [[1, 2], [3, 4]] def _get_somebytes(): header = b'\x00\x00\x0C\x02' dimensionsizes = b'\x00\x00\x00\x02' + b'\x00\x00\x00\x02' data = b'\x00\x00\x00\x01' + b'\x00\x00\x00\x02' data += b'\x00\x00\x00\x03' + b'\x00\x00\x00\x04' return header + dimensionsizes + data _somebytes = _get_somebytes() def test_list_to_idx(): data = idx.list_to_idx(_somelist, 'i') print(data, _somebytes) assert data == _somebytes def test_idx_to_list(): lst = idx.idx_to_list(_somebytes) assert lst == _somelist
from .. import idx import os def test__count_dimensions(): yield check__count_dimensions, 9, 0 yield check__count_dimensions, [1, 2], 1 yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2 yield check__count_dimensions, [[[1,2], [2]]], 3 def check__count_dimensions(lst, i): assert idx._count_dimensions(lst) == i # these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/ _somelist = [[1, 2], [3, 4]] _somebytes = b'\x00\x00\x0C\x02' + b'\x01\x02\x03\x04' def test_list_to_idx(): data = idx.list_to_idx(_somelist, 'i') assert data == _somebytes def test_idx_to_list(): lst = idx.idx_to_list(_somebytes) assert lst == _somelist
Allow wildcard star in filter list; "*.txt" instead of ".txt"
package com.samsung.sprc.fileselector; import java.io.File; /** * A set of tools for file operations */ public class FileUtils { /** Filter which accepts every file */ public static final String FILTER_ALLOW_ALL = "*.*"; /** * This method checks that the file is accepted by the filter * * @param file * - file that will be checked if there is a specific type * @param filter * - criterion - the file type(for example ".jpg") * @return true - if file meets the criterion - false otherwise. */ public static boolean accept(final File file, final String filter) { if (filter.compareTo(FILTER_ALLOW_ALL) == 0) { return true; } if (file.isDirectory()) { return true; } int lastIndexOfPoint = file.getName().lastIndexOf('.'); if (lastIndexOfPoint == -1) { return false; } String fileType = "*" + file.getName().substring(lastIndexOfPoint).toLowerCase(); return fileType.compareTo(filter) == 0; } }
package com.samsung.sprc.fileselector; import java.io.File; /** * A set of tools for file operations */ public class FileUtils { /** Filter which accepts every file */ public static final String FILTER_ALLOW_ALL = "*.*"; /** * This method checks that the file is accepted by the filter * * @param file * - file that will be checked if there is a specific type * @param filter * - criterion - the file type(for example ".jpg") * @return true - if file meets the criterion - false otherwise. */ public static boolean accept(final File file, final String filter) { if (filter.compareTo(FILTER_ALLOW_ALL) == 0) { return true; } if (file.isDirectory()) { return true; } int lastIndexOfPoint = file.getName().lastIndexOf('.'); if (lastIndexOfPoint == -1) { return false; } String fileType = file.getName().substring(lastIndexOfPoint).toLowerCase(); return fileType.compareTo(filter) == 0; } }
Revert "changed iteration generator for redis to have only positive counters" This reverts commit 010788a
/* * Copyright 2014 Aurélien Broszniowski * * 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 io.rainfall.generator; import io.rainfall.SequenceGenerator; import java.util.concurrent.atomic.AtomicLong; /** * @author Aurelien Broszniowski */ public class IterationSequenceGenerator implements SequenceGenerator { private final AtomicLong next; public IterationSequenceGenerator() { this.next = new AtomicLong(1); } /** * Constructor taking the first value to be returned by {@link #next()} in parameter * * @param firstValue first value to be returned */ public IterationSequenceGenerator(long firstValue) { this.next = new AtomicLong(firstValue); } @Override public long next() { return next.getAndIncrement(); } @Override public String getDescription() { return "Iterative sequence"; } }
/* * Copyright 2014 Aurélien Broszniowski * * 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 io.rainfall.generator; import io.rainfall.SequenceGenerator; import java.util.concurrent.atomic.AtomicLong; /** * @author Aurelien Broszniowski * */ public class IterationSequenceGenerator implements SequenceGenerator { private final AtomicLong next; public IterationSequenceGenerator() { this.next = new AtomicLong(1); } /** * Constructor taking the first value to be returned by {@link #next()} in parameter * * @param firstValue first value to be returned */ public IterationSequenceGenerator(long firstValue) { this.next = new AtomicLong(firstValue); } @Override public long next() { return next.getAndIncrement(); } @Override public String getDescription() { return "Iterative sequence"; } }
Change pyodbc requirement to >= version
# coding=utf-8 from __future__ import absolute_import, division, print_function import sys from setuptools import setup VERSION='0.1.0' ANTLR4 = 'antlr4-python{}-runtime'.format(sys.version_info.major) setup( name='vfp2py', version=VERSION, description='Convert foxpro code to python', author='Michael Wisslead', author_email='michael.wisslead@gmail.com', url='https://github.com/mwisslead', packages=['vfp2py'], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Foxpro", "Topic :: Software Development :: Libraries :: Python Modules", ], install_requires=[ANTLR4 + '==4.8', 'dbf==0.97.2', 'autopep8==1.2.4', 'isort==4.3.4', 'python-dateutil==2.7.2', 'pyodbc>=4.0.23'], test_suite='nose.collector', tests_require=['nose', 'Faker<=0.9.0'], entry_points = { 'console_scripts': ['vfp2py=vfp2py.__main__:main'], } )
# coding=utf-8 from __future__ import absolute_import, division, print_function import sys from setuptools import setup VERSION='0.1.0' ANTLR4 = 'antlr4-python{}-runtime'.format(sys.version_info.major) setup( name='vfp2py', version=VERSION, description='Convert foxpro code to python', author='Michael Wisslead', author_email='michael.wisslead@gmail.com', url='https://github.com/mwisslead', packages=['vfp2py'], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Foxpro", "Topic :: Software Development :: Libraries :: Python Modules", ], install_requires=[ANTLR4 + '==4.8', 'dbf==0.97.2', 'autopep8==1.2.4', 'isort==4.3.4', 'python-dateutil==2.7.2', 'pyodbc==4.0.23'], test_suite='nose.collector', tests_require=['nose', 'Faker<=0.9.0'], entry_points = { 'console_scripts': ['vfp2py=vfp2py.__main__:main'], } )
Bump version number for Python 3.2-matching release
#!/usr/bin/env python from distutils.core import setup setup(name='futures', version='2.0', description='Java-style futures implementation in Python 2.x', author='Brian Quinlan', author_email='brian@sweetapp.com', url='http://code.google.com/p/pythonfutures', download_url='http://pypi.python.org/pypi/futures3/', packages=['futures'], license='BSD', classifiers=['License :: OSI Approved :: BSD License', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2'] )
#!/usr/bin/env python from distutils.core import setup setup(name='futures', version='1.0', description='Java-style futures implementation in Python 2.x', author='Brian Quinlan', author_email='brian@sweetapp.com', url='http://code.google.com/p/pythonfutures', download_url='http://pypi.python.org/pypi/futures3/', packages=['futures'], license='BSD', classifiers=['License :: OSI Approved :: BSD License', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2'] )
Remove unneeded call to toString()
import React, { PropTypes } from 'react' import { connect } from 'react-redux' import { incrementCounter, decrementCounter } from '../../actions/counter' import {} from './app.css' let Counter = ({ counter, onIncrementCounter, onDecrementCounter }) => ( <div className="counter"> <h2 className="counter__number">{counter}</h2> <button onClick={onIncrementCounter} className="counter__button">+</button> <button onClick={onDecrementCounter} className="counter__button">-</button> </div> ) Counter.propTypes = { counter: PropTypes.number.isRequired, onIncrementCounter: PropTypes.func.isRequired, onDecrementCounter: PropTypes.func.isRequired } const mapStateToProps = (state) => { return { counter: state.counter } } const mapDispatchToProps = (dispatch) => { return { onIncrementCounter () { dispatch(incrementCounter()) }, onDecrementCounter () { dispatch(decrementCounter()) } } } export default connect( mapStateToProps, mapDispatchToProps )(Counter)
import React, { PropTypes } from 'react' import { connect } from 'react-redux' import { incrementCounter, decrementCounter } from '../../actions/counter' import {} from './app.css' let Counter = ({ counter, onIncrementCounter, onDecrementCounter }) => ( <div className="counter"> <h2 className="counter__number">{counter.toString()}</h2> <button onClick={onIncrementCounter} className="counter__button">+</button> <button onClick={onDecrementCounter} className="counter__button">-</button> </div> ) Counter.propTypes = { counter: PropTypes.number.isRequired, onIncrementCounter: PropTypes.func.isRequired, onDecrementCounter: PropTypes.func.isRequired } const mapStateToProps = (state) => { return { counter: state.counter } } const mapDispatchToProps = (dispatch) => { return { onIncrementCounter () { dispatch(incrementCounter()) }, onDecrementCounter () { dispatch(decrementCounter()) } } } export default connect( mapStateToProps, mapDispatchToProps )(Counter)
Update test according to data from CLDR 28
define([ "src/core", "src/bundle/parent_lookup", "json!cldr-data/supplemental/parentLocales.json" ], function( Cldr, parentLookup, parentLocalesJson ) { describe( "Bundle Parent Lookup", function() { before(function() { Cldr.load( parentLocalesJson ); }); it( "should truncate locale", function() { expect( parentLookup( Cldr, [ "pt", "BR" ].join( Cldr.localeSep ) ) ).to.equal( "pt" ); }); it( "should end with root", function() { expect( parentLookup( Cldr, "en" ) ).to.equal( "root" ); }); it( "should use supplemental resource", function() { expect( parentLookup( Cldr, [ "en", "IN" ].join( Cldr.localeSep ) )).to.equal( [ "en", "001" ].join( Cldr.localeSep ) ); }); }); });
define([ "src/core", "src/bundle/parent_lookup", "json!cldr-data/supplemental/parentLocales.json" ], function( Cldr, parentLookup, parentLocalesJson ) { describe( "Bundle Parent Lookup", function() { before(function() { Cldr.load( parentLocalesJson ); }); it( "should truncate locale", function() { expect( parentLookup( Cldr, [ "pt", "BR" ].join( Cldr.localeSep ) ) ).to.equal( "pt" ); }); it( "should end with root", function() { expect( parentLookup( Cldr, "en" ) ).to.equal( "root" ); }); it( "should use supplemental resource", function() { expect( parentLookup( Cldr, [ "en", "IN" ].join( Cldr.localeSep ) ) ).to.equal( [ "en", "GB" ].join( Cldr.localeSep ) ); }); }); });
Fix typo in Config name
package com.inmobi.messaging.consumer.databus; import com.inmobi.databus.FSCheckpointProvider; /** * Configuration properties and their default values for {@link DatabusConsumer} */ public interface DatabusConsumerConfig { public static final String queueSizeConfig = "databus.consumer.buffer.size"; public static final int DEFAULT_QUEUE_SIZE = 5000; public static final String waitTimeForFlushConfig = "databus.consumer.waittime.forcollectorflush"; public static final long DEFAULT_WAIT_TIME_FOR_FLUSH = 1000; // 1 second public static final String databusConfigFileKey = "databus.conf"; public static final String DEFAULT_DATABUS_CONFIG_FILE = "databus.xml"; public static final String databusClustersConfig = "databus.consumer.clusters"; public static final String databusChkProviderConfig = "databus.consumer.chkpoint.provider.classname"; public static final String DEFAULT_CHK_PROVIDER = FSCheckpointProvider.class .getName(); public static final String checkpointDirConfig = "databus.consumer.checkpoint.dir"; public static final String DEFAULT_CHECKPOINT_DIR = "."; public static final String databusConsumerPrincipal = "databus.consumer.principal.name"; public static final String databusConsumerKeytab = "databus.consumer.keytab.path"; }
package com.inmobi.messaging.consumer.databus; import com.inmobi.databus.FSCheckpointProvider; /** * Configuration properties and their default values for {@link DatabusConsumer} */ public interface DatabusConsumerConfig { public static final String queueSizeConfig = "databus.consumer.buffer.size"; public static final int DEFAULT_QUEUE_SIZE = 5000; public static final String waitTimeForFlushConfig = "databus.consumer.waittime.forcollectorflush"; public static final long DEFAULT_WAIT_TIME_FOR_FLUSH = 1000; // 1 second public static final String databusConfigFileKey = "databus.conf"; public static final String DEFAULT_DATABUS_CONFIG_FILE = "databus.xml"; public static final String databusClustersConfig = "databus.consumer.clusters"; public static final String databusChkProviderConfig = "databus.consumer.chkpoint.provider.classname"; public static final String DEFAULT_CHK_PROVIDER = FSCheckpointProvider.class .getName(); public static final String checkpointDirConfig = "databus.consumer.checkpoint.dir"; public static final String DEFAULT_CHECKPOINT_DIR = "."; }
Fix code style issues with Black
# -*- coding: utf-8 -*- import os from scout.demo import coverage_qc_report from scout.commands import cli def test_load_coverage_qc_report(mock_app, case_obj): """Testing the load delivery report cli command""" # Make sure the path to delivery report is a valid path assert os.path.isfile(coverage_qc_report_path) runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "coverage-qc-report", case_obj["_id"], coverage_qc_report_path, "-u"], ) assert "saved report to case!" in result.output assert result.exit_code == 0 def test_invalid_path_load_coverage_qc_report(mock_app, case_obj): """Testing the load delivery report cli command""" runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "coverage-qc-report", case_obj["_id"], "invalid-path", "-u"], ) assert "does not exist" in result.output assert result.exit_code == 2
# -*- coding: utf-8 -*- import os from scout.demo import coverage_qc_report from scout.commands import cli def test_load_coverage_qc_report(mock_app, case_obj): """Testing the load delivery report cli command""" # Make sure the path to delivery report is a valid path assert os.path.isfile(coverage_qc_report_path) runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "coverage-qc-report", case_obj["_id"], coverage_qc_report_path, "-u"], ) assert "saved report to case!" in result.output assert result.exit_code == 0 def test_invalid_path_load_coverage_qc_report(mock_app, case_obj): """Testing the load delivery report cli command""" runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "coverage-qc-report", case_obj["_id"], "invalid-path", "-u"], ) assert "does not exist" in result.output assert result.exit_code == 2
Update minimum python versioning checks
#!/usr/bin/env python from setuptools import setup, find_packages from os import path import sys min_py_version = (3, 4) if sys.version_info < min_py_version: sys.exit('DataJoint is only supported on Python {}.{} or higher'.format(*min_py_version)) here = path.abspath(path.dirname(__file__)) long_description = "A relational data framework for scientific data pipelines with MySQL backend." # read in version number with open(path.join(here, 'datajoint', 'version.py')) as f: exec(f.read()) with open(path.join(here, 'requirements.txt')) as f: requirements = f.read().split() setup( name='datajoint', version=__version__, description="A relational data pipeline framework.", long_description=long_description, author='Dimitri Yatsenko', author_email='info@datajoint.io', license="GNU LGPL", url='https://datajoint.io', keywords='database organization', packages=find_packages(exclude=['contrib', 'docs', 'tests*']), install_requires=requirements, python_requires='~={}.{}'.format(*min_py_version) )
#!/usr/bin/env python from setuptools import setup, find_packages from os import path import sys if sys.version_info < (3, 4): sys.exit('DataJoint is only supported on Python 3.4 or higher') here = path.abspath(path.dirname(__file__)) long_description = "A relational data framework for scientific data pipelines with MySQL backend." # read in version number with open(path.join(here, 'datajoint', 'version.py')) as f: exec(f.read()) with open(path.join(here, 'requirements.txt')) as f: requirements = f.read().split() setup( name='datajoint', version=__version__, description="A relational data pipeline framework.", long_description=long_description, author='Dimitri Yatsenko', author_email='info@datajoint.io', license="GNU LGPL", url='https://datajoint.io', keywords='database organization', packages=find_packages(exclude=['contrib', 'docs', 'tests*']), install_requires=requirements, )
Add ignored stories that come from Apps Manager tracker Signed-off-by: Steven Locke <baaff752d2ae0b1c8049cab727257de91dfbb71f@pivotal.io>
import axios from 'axios'; const ignoredStories = ['151262175', '148077489', '151620080', '150190185', '153578787']; function url(storyNumber) { return `https://www.pivotaltracker.com/services/v5/projects/1126018/stories/${storyNumber}`; } const privates = new WeakMap(); export default class TrackerHelper { constructor(trackerToken) { privates.set(this, {trackerToken}); } async getStories(storyNumbers) { const {trackerToken} = privates.get(this); const stories = {}; await Promise.all(storyNumbers .filter(storyNumber => ignoredStories.indexOf(storyNumber) === -1) .map(storyNumber => axios.get(url(storyNumber), {headers: {'X-TrackerToken': trackerToken}}) .then(({data, data: {id}}) => stories[id] = data) .catch(console.error))); return stories; } };
import axios from 'axios'; const ignoredStories = ['151262175', '148077489', '151620080']; function url(storyNumber) { return `https://www.pivotaltracker.com/services/v5/projects/1126018/stories/${storyNumber}`; } const privates = new WeakMap(); export default class TrackerHelper { constructor(trackerToken) { privates.set(this, {trackerToken}); } async getStories(storyNumbers) { const {trackerToken} = privates.get(this); const stories = {}; await Promise.all(storyNumbers .filter(storyNumber => ignoredStories.indexOf(storyNumber) === -1) .map(storyNumber => axios.get(url(storyNumber), {headers: {'X-TrackerToken': trackerToken}}) .then(({data, data: {id}}) => stories[id] = data) .catch(console.error))); return stories; } };
Fix typo in session item controller
<?php //used to control access to item stored in the session //used when trying to save and item with errors and need to preload form //or when saving and adding another /** * */ class SessionItemController{ const SESSION_ITEM_KEY = 'item'; //stores given item in session static function setItem(array $item){ $_SESSION[self::SESSION_ITEM_KEY] = $item; } //returns item and deletes from session //so it does not persist between pages static function getItem(): array{ if(self::isItemStored()){ $item = $_SESSION[self::SESSION_ITEM_KEY]; self::deleteItem(); return $item; } return []; } //used to check if item is saved in session static function isItemStored(): bool{ return isset($_SESSION[self::SESSION_ITEM_KEY]) && !empty($_SESSION[self::SESSION_ITEM_KEY]); } //deletes item from session static function deleteItem(){ unset($_SESSION[self::SESSION_ITEM_KEY]); } }
<?php //used to control access to item stored in the session //used when trying to save and item with errors and need to preload form //or when saving and adding another /** * */ class SessionItemController{ const SESSION_ITEM_KEY = 'item'; //stores given item in session static function setItem(array $item){ $_SESSION[self::SESSION_ITEM_KEY] = $item; } //returns item and deletes from session //so it does not persist between pages static function getItem(): array{ if(self::isItemStored()){ $item = $_SESSION[self::SESSION_ITEM_KEY]; self::deleteItem(); return $item; } return []; } //used to check if item is saved in session static function isItemStored(): bool{ return isset($_SESSION[self::SESSION_ITEM_KEY] && !empty($_SESSION[self::SESSION_ITEM_KEY])); } //deletes item from session static function deleteItem(){ unset($_SESSION[self::SESSION_ITEM_KEY]); } }
Fix issue where the presenter bombs if the entry is not set / exists.
<?php namespace Anomaly\PagesModule\Page; use Anomaly\PagesModule\Page\Contract\PageInterface; use Anomaly\Streams\Platform\Entry\EntryPresenter; use Anomaly\Streams\Platform\Support\Decorator; /** * Class PagePresenter * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> * @package Anomaly\PagesModule\Page */ class PagePresenter extends EntryPresenter { /** * The decorated object. * This is for IDE hinting. * * @var PageInterface */ protected $object; /** * Create a new PagePresenter instance. * * @param mixed $object */ public function __construct($object) { $this->object = $object; } /** * Catch calls to fields on * the page's related entry. * * @param string $key * @return mixed */ public function __get($key) { $entry = $this->object->getEntry(); if ($entry && $entry->hasField($key)) { return (New Decorator())->decorate($entry)->{$key}; } return parent::__get($key); } }
<?php namespace Anomaly\PagesModule\Page; use Anomaly\PagesModule\Page\Contract\PageInterface; use Anomaly\Streams\Platform\Entry\EntryPresenter; use Anomaly\Streams\Platform\Support\Decorator; /** * Class PagePresenter * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> * @package Anomaly\PagesModule\Page */ class PagePresenter extends EntryPresenter { /** * The decorated object. * This is for IDE hinting. * * @var PageInterface */ protected $object; /** * Create a new PagePresenter instance. * * @param mixed $object */ public function __construct($object) { $this->object = $object; } /** * Catch calls to fields on * the page's related entry. * * @param string $key * @return mixed */ public function __get($key) { $entry = $this->object->getEntry(); if ($entry->hasField($key)) { return (New Decorator())->decorate($entry)->{$key}; } return parent::__get($key); } }
fix: Change the label UID to ID.
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; const AssessmentEntryColHeaderView = ({ questions }) => { const values = Object.keys(questions); return ( <tr className="bg-info"> <td>ID</td> <td colSpan="2">Boundary Name</td> <td>Name</td> <td>Date of Visit</td> {values.map((id, i) => { return ( <td key={id} title={questions[id].question_text}> {i + 1} </td> ); })} <td>Save</td> </tr> ); }; AssessmentEntryColHeaderView.propTypes = { questions: PropTypes.object, }; const mapStateToProps = (state) => { return { questions: state.questions.questions, }; }; const AssessmentEntryColHeader = connect(mapStateToProps)(AssessmentEntryColHeaderView); export { AssessmentEntryColHeader };
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; const AssessmentEntryColHeaderView = ({ questions }) => { const values = Object.keys(questions); return ( <tr className="bg-info"> <td>UID</td> <td colSpan="2">Boundary Name</td> <td>Name</td> <td>Date of Visit</td> {values.map((id, i) => { return ( <td key={id} title={questions[id].question_text}> {i + 1} </td> ); })} <td>Save</td> </tr> ); }; AssessmentEntryColHeaderView.propTypes = { questions: PropTypes.object, }; const mapStateToProps = (state) => { return { questions: state.questions.questions, }; }; const AssessmentEntryColHeader = connect(mapStateToProps)(AssessmentEntryColHeaderView); export { AssessmentEntryColHeader };
Add a link to the day
<a href="<?php echo $context->getURL(); ?>"><?php echo $context->getDateTime()->format('j')?></a> <ul class="month-day-listing"> <?php foreach ($context as $e) { //Start building an array of row classes $classes = array('event'); if ($e->isAllDay()) { $classes[] = 'all-day'; } if ($e->isInProgress()) { $classes[] = 'in-progress'; } if ($e->isOnGoing()) { $classes[] = 'ongoing'; } ?> <li class="<?php echo implode(' ', $classes); ?>"> <?php echo $savvy->render($e, 'EventInstance/Date.tpl.php') ?> <span class="date-title-separator">:</span> <a href="<?php echo $e->getURL(); ?>"><?php echo $savvy->dbStringtoHtml($e->event->title)?></a> </li> <?php } ?> </ul>
<ul class="month-day-listing"> <?php foreach ($context as $e) { //Start building an array of row classes $classes = array('event'); if ($e->isAllDay()) { $classes[] = 'all-day'; } if ($e->isInProgress()) { $classes[] = 'in-progress'; } if ($e->isOnGoing()) { $classes[] = 'ongoing'; } ?> <li class="<?php echo implode(' ', $classes); ?>"> <?php echo $savvy->render($e, 'EventInstance/Date.tpl.php') ?> <span class="date-title-separator">:</span> <a href="<?php echo $e->getURL(); ?>"><?php echo $savvy->dbStringtoHtml($e->event->title)?></a> </li> <?php } ?> </ul>
Use getattr for expando props
from django import forms class EditUserForm(forms.Form): about_me = forms.CharField(widget=forms.Textarea, required=False) url = forms.CharField(max_length=255, required=False) facebook_url = forms.CharField(max_length=255, required=False) email = forms.EmailField(max_length=255) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(EditUserForm, self).__init__(*args, **kwargs) if user: self.fields['about_me'].initial=getattr(user, 'about_me', None) self.fields['url'].initial=getattr(user, 'url', None) self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None) self.fields['email'].initial=user.email
from django import forms class EditUserForm(forms.Form): about_me = forms.CharField(widget=forms.Textarea, required=False) url = forms.CharField(max_length=255, required=False) facebook_url = forms.CharField(max_length=255, required=False) email = forms.EmailField(max_length=255) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(EditUserForm, self).__init__(*args, **kwargs) if user: self.fields['about_me'].initial=user.about_me self.fields['url'].initial=user.url self.fields['facebook_url'].initial=user.facebook_url self.fields['email'].initial=user.email
Correct version for deploy to GAE
package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test server started on 8080 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":80", nil) } */ //goapp serve app.yaml //goapp deploy -application golangnode0 -version 0
// +build !appengine package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test server started on 8080 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":80", nil) } */ //goapp serve app.yaml //goapp deploy -application golangnode0 -version 0
Fix one more type hint
<?php declare(strict_types=1); namespace Josegonzalez\Upload\File\Path; use Cake\Datasource\EntityInterface; use Cake\ORM\Table; interface ProcessorInterface { /** * Constructor * * @param \Cake\ORM\Table $table the instance managing the entity * @param \Cake\Datasource\EntityInterface $entity the entity to construct a path for. * @param \Psr\Http\Message\UploadedFileInterface|string $data the data being submitted for a save or filename stored in db * @param string $field the field for which data will be saved * @param array $settings the settings for the current field */ public function __construct(Table $table, EntityInterface $entity, $data, string $field, array $settings); /** * Returns the basepath for the current field/data combination * * @return string */ public function basepath(): string; /** * Returns the filename for the current field/data combination * * @return string */ public function filename(): string; }
<?php declare(strict_types=1); namespace Josegonzalez\Upload\File\Path; use Cake\Datasource\EntityInterface; use Cake\ORM\Table; use Psr\Http\Message\UploadedFileInterface; interface ProcessorInterface { /** * Constructor * * @param \Cake\ORM\Table $table the instance managing the entity * @param \Cake\Datasource\EntityInterface $entity the entity to construct a path for. * @param \Psr\Http\Message\UploadedFileInterface $data the data being submitted for a save or filename stored in db * @param string $field the field for which data will be saved * @param array $settings the settings for the current field */ public function __construct(Table $table, EntityInterface $entity, UploadedFileInterface $data, string $field, array $settings); /** * Returns the basepath for the current field/data combination * * @return string */ public function basepath(): string; /** * Returns the filename for the current field/data combination * * @return string */ public function filename(): string; }
Add a commented-out section for impersonation
import { Accounts } from 'meteor/accounts-base'; import { Bans } from './collection.js'; import { ForwardedWhitelist } from '../../modules/forwarded_whitelist.js'; // Check during login whether the user currently has their login disabled // User ban callback Accounts.validateLoginAttempt((attempt) => { if (!attempt.allowed) { return false; } if (attempt.user && attempt.user.banned && new Date(attempt.user.banned) > new Date()) { throw new Meteor.Error('user-banned', 'This account is banned until ' + new Date(attempt.user.banned)); } else { return true; } }) Accounts.validateLoginAttempt((attempt) => { if (!attempt.allowed) { return false; } const ban = Bans.findOne({ip: attempt.connection && ForwardedWhitelist.getClientIP(attempt.connection)}); if (ban && new Date(ban.expirationDate) > new Date()) { // eslint-disable-next-line no-console console.warn("IP address is banned: ", attempt, attempt.connection, ban) return true; } else { return true; } }) /* Uncomment this section to allow for user-impersonation, by using the following console commands: Accounts.callLoginMethod({ methodArguments: [{userId: <userId>}], userCallback: (err) => {console.log(err)} }); DO NOT ACTIVATE THIS IN PRODUCTION. ONLY USE THIS IN A DEVELOPMENT CONTEXT. */ // Accounts.registerLoginHandler('admin', function(loginRequest) { // return { userId : loginRequest.userId }; // });
import { Accounts } from 'meteor/accounts-base'; import { Bans } from './collection.js'; import { ForwardedWhitelist } from '../../modules/forwarded_whitelist.js'; // Check during login whether the user currently has their login disabled // User ban callback Accounts.validateLoginAttempt((attempt) => { if (!attempt.allowed) { return false; } if (attempt.user && attempt.user.banned && new Date(attempt.user.banned) > new Date()) { throw new Meteor.Error('user-banned', 'This account is banned until ' + new Date(attempt.user.banned)); } else { return true; } }) Accounts.validateLoginAttempt((attempt) => { if (!attempt.allowed) { return false; } const ban = Bans.findOne({ip: attempt.connection && ForwardedWhitelist.getClientIP(attempt.connection)}); if (ban && new Date(ban.expirationDate) > new Date()) { // eslint-disable-next-line no-console console.warn("IP address is banned: ", attempt, attempt.connection, ban) return true; } else { return true; } })
Update Checking List for internal purposes
[1,"Before data cleaning: Importing the data"], [2,"Check for importing issues such as broken lines when importing .csv files"], [2,"Make sure you have unique IDs"], [2,"De-identify all data and save in a new .dta file"], [2,"Never make any changes to the raw data"], [1,"Important steps for data cleaning"], [2,"Label variables, don’t use special characters"], [2,"Recode and label missing values: your data set should not have observations with -777, -88 or -9 values, for example"], [2,"Encode variables: all categorical variables should be saved as labeled numeric variables, no strings"], [2,"Don’t change variable names from questionnaire, except for nested repeat groups and reshaped roster data"], [2,"Check sample representativeness of age, gender, urban/rural, region and religion"], [2,"Check administrative data such as date, time, interviewer variables included"], [2,"Test variables consistency"], [2,"Identify and document outliers"], [2,"Compress dataset so it is saved in the most efficient format"], [2,"Save cleaned data set with an informative name. Avoid saving in a very recent Stata version"], [1,"Optional steps in data cleaning"], [2,"Order variables – unique ID always first, then same order as questionnaire"], [2,"Drop variables that only make sense for questionnaire review (duration, notes, calculates)"], [2,"Rename roster variables"], [2,"Categorize variables listed as “others”"], [2,"Add metadata as notes: original survey question, relevance, constraints, etc"]
[1,"Before data cleaning: Importing the data"], [2,"Check for importing issues such as broken lines when importing .csv files"], [2,"Make sure you have unique IDs"], [2,"De-identify all data and save in a new .dta file"], [2,"Never make any changes to the raw data"], [1,"Important steps for data cleaning"], [2,"Label variables, don’t use special characters"], [2,"Recode and label missing values: your data set should not have observations with -777, -88 or -9 values, for example"], [2,"Encode variables: all categorical variables should be saved as labeled numeric variables, no strings"], [2,"Don’t change variable names from questionnaire, except for nested repeat groups and reshaped roster data"], [2,"Test variables consistency"], [2,"Identify and document outliers"], [2,"Compress dataset so it is saved in the most efficient format"], [2,"Save cleaned data set with an informative name. Avoid saving in a very recent Stata version"], [1,"Optional steps in data cleaning"], [2,"Order variables – unique ID always first, then same order as questionnaire"], [2,"Drop variables that only make sense for questionnaire review (duration, notes, calculates)"], [2,"Rename roster variables"], [2,"Categorize variables listed as “others”"], [2,"Add metadata as notes: original survey question, relevance, constraints, etc"]
Fix re to match newlines as well
import re from setuptools import setup init_py = open('textlines/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""((.|\n)*)"""', init_py)[0] setup( name='textlines', version=metadata['version'], description=metadata['doc'], author=metadata['author'], author_email=metadata['email'], url=metadata['url'], packages=['textlines'], include_package_data=True, install_requires=[ 'docopt < 1.0.0' ], entry_points={ 'console_scripts': [ 'textlines = textlines.cli:main', ], }, test_suite='nose.collector', license=open('LICENSE').read(), )
import re from setuptools import setup init_py = open('textlines/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='textlines', version=metadata['version'], description=metadata['doc'], author=metadata['author'], author_email=metadata['email'], url=metadata['url'], packages=['textlines'], include_package_data=True, install_requires=[ 'docopt < 1.0.0' ], entry_points={ 'console_scripts': [ 'textlines = textlines.cli:main', ], }, test_suite='nose.collector', license=open('LICENSE').read(), )
Remove extra slash from group password form
<style type='text/css'> #message { width: 30%; margin: 200px auto 0; } #message h1 { font-weight:bold; font-size:1.3em; } #authBox { background: #000; text-align:center; padding:20px; } #passError { background: none repeat scroll 0 0 #910E0E; margin-bottom: 15px; padding: 4px; } </style> <div id="message"> <div class="box"> <div class="box-header">Authentication Required</div> <div class="box-content"> <p style='font-weight:bold'> In order to continue, please enter your group's password below.</p> <p> This password should have been provided by your group in a bulletin, mail, etc.</p> <?php if( $wrongPass == true ): ?> <p id="passError">You have entered an incorrect password!</p> <?php endif; ?> <form action='<?php echo URL::base(TRUE, TRUE);?>access/group_password' method='POST' class="center-text"> <input type='password' name='group_password' /><br /><br /> <input type='submit' value='Submit' style="padding:10px" /> </form> </div> </div> </div>
<style type='text/css'> #message { width: 30%; margin: 200px auto 0; } #message h1 { font-weight:bold; font-size:1.3em; } #authBox { background: #000; text-align:center; padding:20px; } #passError { background: none repeat scroll 0 0 #910E0E; margin-bottom: 15px; padding: 4px; } </style> <div id="message"> <div class="box"> <div class="box-header">Authentication Required</div> <div class="box-content"> <p style='font-weight:bold'> In order to continue, please enter your group's password below.</p> <p> This password should have been provided by your group in a bulletin, mail, etc.</p> <?php if( $wrongPass == true ): ?> <p id="passError">You have entered an incorrect password!</p> <?php endif; ?> <form action='<?php echo URL::base(TRUE, TRUE);?>/access/group_password' method='POST' class="center-text"> <input type='password' name='group_password' /><br /><br /> <input type='submit' value='Submit' style="padding:10px" /> </form> </div> </div> </div>
Remove a bunch of text. This referred to an earlier (never checked in) implementation.
/* * Copyright 2015 the Mimu Authors (Dan Bornstein et alia). * Licensed AS IS and WITHOUT WARRANTY under the Apache License, * Version 2.0. Details: <http://www.apache.org/licenses/LICENSE-2.0> */ "use strict"; // The `DOMImplementation` instance to use. Relies on there being a global // `document` to poke at. var domImpl = document.implementation; // Utilities for interacting with styles. class StyleUtil { // Clones the computed style of the given node. The result can be modified // freely without affecting the original. static cloneComputedStyle(orig) { // We make a fresh element in a fresh document, apply the original's // style to it by using the text representation (which seems to be the // simplest way to achieve that), and then return the style object. var doc = domImpl.createHTMLDocument(); var node = doc.createElement("span"); node.style.cssText = orig.ownerDocument.defaultView.getComputedStyle(orig).cssText; return node.style; } }
/* * Copyright 2015 the Mimu Authors (Dan Bornstein et alia). * Licensed AS IS and WITHOUT WARRANTY under the Apache License, * Version 2.0. Details: <http://www.apache.org/licenses/LICENSE-2.0> */ "use strict"; // The `DOMImplementation` instance to use. Relies on there being a global // `document` to poke at. var domImpl = document.implementation; // Utilities for interacting with styles. Instances are constructed with // a node from which to get the "original" CSS style. From there, you can // modify properties of the instance and then extract the modified properties, // including computed properties. class StyleUtil { // Clones the computed style of the given node. The result can be modified // freely without affecting the original. static cloneComputedStyle(orig) { // We make a fresh element in a fresh document, apply the original's // style to it by using the text representation (which seems to be the // simplest way to achieve that), and then return the style object. var doc = domImpl.createHTMLDocument(); var node = doc.createElement("span"); node.style.cssText = orig.ownerDocument.defaultView.getComputedStyle(orig).cssText; return node.style; } }
Update User class to match Telegram API
from collections import namedtuple class User: def __init__(self, id_, first_name, last_name='', username='', language_code=''): self.id = id_ self.first_name = first_name self.last_name = last_name self.username = username @classmethod def from_database(cls, user): return cls(*user) @classmethod def from_telegram(cls, user): copy = user.copy() copy['id_'] = copy['id'] del copy['id'] return cls(**copy) class Quote: def __init__(self, id_, chat_id, message_id, sent_at, sent_by, content, quoted_by=None): self.id = id_ self.chat_id = chat_id self.message_id = message_id self.sent_at = sent_at self.sent_by = sent_by self.content = content self.quoted_by = quoted_by @classmethod def from_database(cls, quote): return cls(*quote) Result = namedtuple('Result', ['quote', 'user'])
from collections import namedtuple class User: def __init__(self, id_, first_name, last_name='', username=''): self.id = id_ self.first_name = first_name self.last_name = last_name self.username = username @classmethod def from_database(cls, user): return cls(*user) @classmethod def from_telegram(cls, user): copy = user.copy() copy['id_'] = copy['id'] del copy['id'] return cls(**copy) class Quote: def __init__(self, id_, chat_id, message_id, sent_at, sent_by, content, quoted_by=None): self.id = id_ self.chat_id = chat_id self.message_id = message_id self.sent_at = sent_at self.sent_by = sent_by self.content = content self.quoted_by = quoted_by @classmethod def from_database(cls, quote): return cls(*quote) Result = namedtuple('Result', ['quote', 'user'])
Add day of the week to time.
module.exports = function crawler(callback) { const request = require('request'); const cheerio = require('cheerio'); const URL = 'http://sarc.pucrs.br/Default/'; var data = {}; let requestHandler = (err, response, html) => { if(err) return callback(err); let $ = cheerio.load(html)('#ctl00_cphTitulo_UpdatePanel2 > div > table'); for (let i = 0, l = $.length; i < l; i++) { let content = cheerio.load($.eq(i).html()); let time = content('span').html(); let table_data = content('.ms-btoolbar').children(); let details = []; for (let j = 0, l = table_data.length; j < l; j+=3) { let detail = { 'resource' : table_data.eq(j).text().trim(), 'course' : table_data.eq(j+1).text().trim(), 'owner' : table_data.eq(j+2).text().trim() }; details.push(detail); } time = formatTime(time); data[time] = details; } callback(null, data); } request(URL, requestHandler); } function formatTime(time) { var weekday = new Date().getDay() + 1 return weekday + time }
module.exports = function crawler(callback) { const request = require('request'); const cheerio = require('cheerio'); const URL = 'http://sarc.pucrs.br/Default/'; var data = {}; let requestHandler = (err, response, html) => { if(err) return callback(err); let $ = cheerio.load(html)('#ctl00_cphTitulo_UpdatePanel2 > div > table'); for (let i = 0, l = $.length; i < l; i++) { let content = cheerio.load($.eq(i).html()); let horario = content('span').html(); let table_data = content('.ms-btoolbar').children(); let details = []; for (let j = 0, l = table_data.length; j < l; j+=3) { let detail = { 'resource' : table_data.eq(j).text().trim(), 'course' : table_data.eq(j+1).text().trim(), 'owner' : table_data.eq(j+2).text().trim() }; details.push(detail); } data[horario] = details; } callback(null, data); } request(URL, requestHandler); }
Fix demo users to name uppercase USERNAMEs
exports.users = [ {username:'ROOT', active: true, password:'root', role:'root', name:'root', emails:['root@fake-meku.fi'] }, {username:'KAVI', active: true, password:'kavi', role:'kavi', name:'kavi', emails:['kavi@fake-meku.fi'] }, {username:'USER', active: true, password:'user', role:'user', name:'user', emails:['user@fake-meku.fi'] } ] exports.accounts = [ {name: "DEMO tilaaja 1", roles: ['Subscriber'], emailAddresses: [], users: ['ROOT', 'KAVI', 'USER'], yTunnus: 'DEMO1' }, {name: "DEMO tilaaja 2", roles: ['Subscriber'], emailAddresses: [], users: ['ROOT', 'KAVI', 'USER'], yTunnus: 'DEMO2' }, {name: "DEMO tilaaja 3", roles: ['Subscriber', 'Classifier'], emailAddresses: [], users: ['ROOT', 'KAVI', 'USER'], yTunnus: 'DEMO3' } ]
exports.users = [ {username:'root', active: true, password:'root', role:'root', name:'root', emails:['root@fake-meku.fi'] }, {username:'kavi', active: true, password:'kavi', role:'kavi', name:'kavi', emails:['kavi@fake-meku.fi'] }, {username:'user', active: true, password:'user', role:'user', name:'user', emails:['user@fake-meku.fi'] } ] exports.accounts = [ {name: "DEMO tilaaja 1", roles: ['Subscriber'], emailAddresses: [], users: ['root', 'kavi', 'user'], yTunnus: 'DEMO1' }, {name: "DEMO tilaaja 2", roles: ['Subscriber'], emailAddresses: [], users: ['root', 'kavi', 'user'], yTunnus: 'DEMO2' }, {name: "DEMO tilaaja 3", roles: ['Subscriber', 'Classifier'], emailAddresses: [], users: ['root', 'kavi', 'user'], yTunnus: 'DEMO3' } ]
Reorder methods to match the order TlsProtocolHandler will call them during handshake
package org.bouncycastle.crypto.tls; import java.io.IOException; import java.io.InputStream; /** * A generic class for ciphersuites in TLS 1.0. */ abstract class TlsCipherSuite { protected static final short KE_RSA = 1; protected static final short KE_RSA_EXPORT = 2; protected static final short KE_DHE_DSS = 3; protected static final short KE_DHE_DSS_EXPORT = 4; protected static final short KE_DHE_RSA = 5; protected static final short KE_DHE_RSA_EXPORT = 6; protected static final short KE_DH_DSS = 7; protected static final short KE_DH_RSA = 8; protected static final short KE_DH_anon = 9; protected static final short KE_SRP = 10; protected static final short KE_SRP_RSA = 11; protected static final short KE_SRP_DSS = 12; protected abstract void skipServerCertificate() throws IOException; protected abstract void processServerCertificate(Certificate serverCertificate, CertificateVerifyer verifyer) throws IOException; protected abstract void skipServerKeyExchange() throws IOException; protected abstract void processServerKeyExchange(InputStream is, byte[] cr, byte[] sr) throws IOException; protected abstract byte[] generateClientKeyExchange() throws IOException; protected abstract byte[] getPremasterSecret(); protected abstract TlsCipher createCipher(byte[] ms, byte[] cr, byte[] sr); }
package org.bouncycastle.crypto.tls; import java.io.IOException; import java.io.InputStream; /** * A generic class for ciphersuites in TLS 1.0. */ abstract class TlsCipherSuite { protected static final short KE_RSA = 1; protected static final short KE_RSA_EXPORT = 2; protected static final short KE_DHE_DSS = 3; protected static final short KE_DHE_DSS_EXPORT = 4; protected static final short KE_DHE_RSA = 5; protected static final short KE_DHE_RSA_EXPORT = 6; protected static final short KE_DH_DSS = 7; protected static final short KE_DH_RSA = 8; protected static final short KE_DH_anon = 9; protected static final short KE_SRP = 10; protected static final short KE_SRP_RSA = 11; protected static final short KE_SRP_DSS = 12; protected abstract TlsCipher createCipher(byte[] ms, byte[] cr, byte[] sr); protected abstract void skipServerCertificate() throws IOException; protected abstract void processServerCertificate(Certificate serverCertificate, CertificateVerifyer verifyer) throws IOException; protected abstract void processServerKeyExchange(InputStream is, byte[] cr, byte[] sr) throws IOException; protected abstract void skipServerKeyExchange() throws IOException; protected abstract byte[] generateClientKeyExchange() throws IOException; protected abstract byte[] getPremasterSecret(); }
Send events for dirs to...
package dirscanner import ( "fmt" "io/ioutil" "path" ) func ScanDir(a_path string, a_fileMsgs chan FileMsg, a_events chan Event) { if files, err := ioutil.ReadDir(a_path); err == nil { for _, file := range files { if file.IsDir() { a_fileMsgs <- FileMsg{a_path, file.Name(), CREATED} a_events <- Event{DEBUG, fmt.Sprintf("Found dir %s", path.Join(a_path, file.Name())), nil} ScanDir(path.Join(a_path, file.Name()), a_fileMsgs, a_events) } else { a_fileMsgs <- FileMsg{a_path, file.Name(), CREATED} a_events <- Event{DEBUG, fmt.Sprintf("Found file %s", path.Join(a_path, file.Name())), nil} } } } else { a_events <- Event{ERROR, fmt.Sprintf("Failed to scan path %s", a_path), err} } }
package dirscanner import ( "fmt" "io/ioutil" "path" ) func ScanDir(a_path string, a_fileMsgs chan FileMsg, a_events chan Event) { if files, err := ioutil.ReadDir(a_path); err == nil { for _, file := range files { if file.IsDir() { ScanDir(path.Join(a_path, file.Name()), a_fileMsgs, a_events) } else { a_fileMsgs <- FileMsg{a_path, file.Name(), CREATED} a_events <- Event{DEBUG, fmt.Sprintf("Found file %s", path.Join(a_path, file.Name())), nil} } } } else { a_events <- Event{ERROR, fmt.Sprintf("Failed to scan path %s", a_path), err} } }
Add metadata of WooCommerce compatibility
<?php /** * WooRule - Rule integration for WooCommerce. * * @wordpress-plugin * @woocommerce-plugin * * Plugin Name: WooRule * Plugin URI: http://github.com/rulecom/woorule * Description: Rule integration for WooCommerce * Version: 2.7.5 * Author: Rule * Author URI: http://rule.se * * Text Domain: woorule * Domain Path: /languages * WC requires at least: 3.0.0 * WC tested up to: 6.5.1 * * @package WooRule */ define( 'WOORULE_VERSION', '2.7.5' ); define( 'WOORULE_PATH', plugin_dir_path( __FILE__ ) ); define( 'WOORULE_URL', plugin_dir_url( __FILE__ ) ); require_once WOORULE_PATH . 'inc/class-woorule.php'; $woorule = new Woorule();
<?php /** * WooRule - Rule integration for WooCommerce. * * @wordpress-plugin * @woocommerce-plugin * * Plugin Name: WooRule * Plugin URI: http://github.com/rulecom/woorule * Description: Rule integration for WooCommerce * Version: 2.7.5 * Author: Rule * Author URI: http://rule.se * * Text Domain: woorule * Domain Path: /languages * * @package WooRule */ define( 'WOORULE_VERSION', '2.7.5' ); define( 'WOORULE_PATH', plugin_dir_path( __FILE__ ) ); define( 'WOORULE_URL', plugin_dir_url( __FILE__ ) ); require_once WOORULE_PATH . 'inc/class-woorule.php'; $woorule = new Woorule();
Delete the intro after confirming it ;-)
<?php namespace Friendica\Module; use Friendica\BaseModule; use Friendica\DI; use Friendica\Model\Contact; /** * Process follow request confirmations */ class FollowConfirm extends BaseModule { public static function post(array $parameters = []) { $uid = local_user(); if (!$uid) { notice(DI::l10n()->t('Permission denied.')); return; } $intro_id = intval($_POST['intro_id'] ?? 0); $duplex = intval($_POST['duplex'] ?? 0); $hidden = intval($_POST['hidden'] ?? 0); $intro = DI::intro()->selectOneById($intro_id, local_user()); Contact\Introduction::confirm($intro, $duplex, $hidden); DI::intro()->delete($intro); DI::baseUrl()->redirect('contact/' . $intro->cid); } }
<?php namespace Friendica\Module; use Friendica\BaseModule; use Friendica\DI; use Friendica\Model\Contact; /** * Process follow request confirmations */ class FollowConfirm extends BaseModule { public static function post(array $parameters = []) { $uid = local_user(); if (!$uid) { notice(DI::l10n()->t('Permission denied.')); return; } $intro_id = intval($_POST['intro_id'] ?? 0); $duplex = intval($_POST['duplex'] ?? 0); $hidden = intval($_POST['hidden'] ?? 0); $intro = DI::intro()->selectOneById($intro_id, local_user()); Contact\Introduction::confirm($intro, $duplex, $hidden); DI::baseUrl()->redirect('contact/' . $intro->cid); } }
Allow root access for mock jdk in introduce variable test
package org.jetbrains.plugins.scala.refactoring.introduceVariable; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess; import junit.framework.Test; import org.jetbrains.annotations.NonNls; import org.jetbrains.plugins.scala.base.ScalaLibraryLoader; import org.jetbrains.plugins.scala.util.TestUtils; import scala.Option$; /** * @author Alexander Podkhalyuzin */ public class IntroduceVariableTest extends AbstractIntroduceVariableTestBase { @NonNls private static final String DATA_PATH = "/introduceVariable/data"; public IntroduceVariableTest() { super(TestUtils.getTestDataPath() + DATA_PATH); } public static Test suite() { return new IntroduceVariableTest(); } @Override protected void setUp(Project project) { super.setUp(project); Module[] modules = ModuleManager.getInstance(project).getModules(); String mockJdk = TestUtils.getMockJdk(); VfsRootAccess.allowRootAccess(mockJdk); Sdk sdk = JavaSdk.getInstance().createJdk("java sdk", mockJdk, false); ScalaLibraryLoader loader = new ScalaLibraryLoader(project, modules[0], null, false, false, Option$.MODULE$.apply(sdk)); loader.loadLibrary(TestUtils.DEFAULT_SCALA_SDK_VERSION); } }
package org.jetbrains.plugins.scala.refactoring.introduceVariable; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.Sdk; import junit.framework.Test; import org.jetbrains.annotations.NonNls; import org.jetbrains.plugins.scala.base.ScalaLibraryLoader; import org.jetbrains.plugins.scala.util.TestUtils; import scala.Option$; /** * @author Alexander Podkhalyuzin */ public class IntroduceVariableTest extends AbstractIntroduceVariableTestBase { @NonNls private static final String DATA_PATH = "/introduceVariable/data"; public IntroduceVariableTest() { super(TestUtils.getTestDataPath() + DATA_PATH); } public static Test suite() { return new IntroduceVariableTest(); } @Override protected void setUp(Project project) { super.setUp(project); Module[] modules = ModuleManager.getInstance(project).getModules(); Sdk sdk = JavaSdk.getInstance().createJdk("java sdk", TestUtils.getMockJdk(), false); ScalaLibraryLoader loader = new ScalaLibraryLoader(project, modules[0], null, false, false, Option$.MODULE$.apply(sdk)); loader.loadLibrary(TestUtils.DEFAULT_SCALA_SDK_VERSION); } }
Make Clear Inbox keyword more robust.
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) if not os.path.isdir(maildir): return for fname in os.listdir(maildir): os.remove(os.path.join(maildir, fname)) def inbox_should_contain_num_mails(maildir, count): print('Testing if inbox at {} has {} items.'.format(maildir, count)) count = int(count) nmails = len(os.listdir(maildir)) if nmails != count: raise AssertionError( 'Inbox should contain {} messages, but has {}.'.format( count, nmails) ) def mail_should_contain_text(maildir, num, text): print('Testing if mail {} in {} contains text {}.'.format( num, maildir, text)) mails = os.listdir(maildir) num = int(num) if len(mails) < num: raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails))) fname = mails[num - 1] with open(os.path.join(maildir, fname)) as f: content = f.read() if not text in content: raise AssertionError('Mail does not contain text.')
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) for fname in os.listdir(maildir): os.remove(os.path.join(maildir, fname)) def inbox_should_contain_num_mails(maildir, count): print('Testing if inbox at {} has {} items.'.format(maildir, count)) count = int(count) nmails = len(os.listdir(maildir)) if nmails != count: raise AssertionError( 'Inbox should contain {} messages, but has {}.'.format( count, nmails) ) def mail_should_contain_text(maildir, num, text): print('Testing if mail {} in {} contains text {}.'.format( num, maildir, text)) mails = os.listdir(maildir) num = int(num) if len(mails) < num: raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails))) fname = mails[num - 1] with open(os.path.join(maildir, fname)) as f: content = f.read() if not text in content: raise AssertionError('Mail does not contain text.')
Use `var` in source code because Helmet supports Node 0.10
var DEFAULT_PERMITTED_POLICIES = 'none' var ALLOWED_POLICIES = [ 'none', 'master-only', 'by-content-type', 'all' ] module.exports = function crossdomain (options) { options = options || {} var permittedPolicies if ('permittedPolicies' in options) { permittedPolicies = options.permittedPolicies } else { permittedPolicies = DEFAULT_PERMITTED_POLICIES } if (ALLOWED_POLICIES.indexOf(permittedPolicies) === -1) { throw new Error('"' + permittedPolicies + '" is not a valid permitted policy. Allowed values: ' + ALLOWED_POLICIES.join(', ') + '.') } return function crossdomain (req, res, next) { res.setHeader('X-Permitted-Cross-Domain-Policies', permittedPolicies) next() } }
const DEFAULT_PERMITTED_POLICIES = 'none' const ALLOWED_POLICIES = [ 'none', 'master-only', 'by-content-type', 'all' ] module.exports = function crossdomain (options) { options = options || {} let permittedPolicies if ('permittedPolicies' in options) { permittedPolicies = options.permittedPolicies } else { permittedPolicies = DEFAULT_PERMITTED_POLICIES } if (ALLOWED_POLICIES.indexOf(permittedPolicies) === -1) { throw new Error('"' + permittedPolicies + '" is not a valid permitted policy. Allowed values: ' + ALLOWED_POLICIES.join(', ') + '.') } return function crossdomain (req, res, next) { res.setHeader('X-Permitted-Cross-Domain-Policies', permittedPolicies) next() } }
Work with broken Koschei rules Messages sent in the morning of 2015-09-25 were missing the groups field. Deal with that not existing. Example messages: - 2015-eebf137e-cc22-48c2-87f0-7d736950f76b - 2015-2a5361ec-9c36-438a-8233-709e9f006003 Signed-off-by: Patrick Uiterwijk <bd6d5394796bee9cca2245486eb583fd64b70226@redhat.com>
from fmn.lib.hinting import hint, prefixed as _ @hint(topics=[_('koschei.package.state.change')]) def koschei_package_state_change(config, message): """ Continuous integration state changes for a package (koschei) `Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes this message when package's build or resolution state changes. """ return message['topic'].endswith('koschei.package.state.change') @hint(categories=['koschei'], invertible=False) def koschei_group(config, message, group=None): """ Particular Koschei package groups This rule limits message to particular `Koschei <https://apps.fedoraproject.org/koschei/>`_ groups. You can specify more groups separated by commas. """ if not group or 'koschei' not in message['topic']: return False groups = set([item.strip() for item in group.split(',')]) return bool(groups.intersection(message['msg'].get('groups', [])))
from fmn.lib.hinting import hint, prefixed as _ @hint(topics=[_('koschei.package.state.change')]) def koschei_package_state_change(config, message): """ Continuous integration state changes for a package (koschei) `Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes this message when package's build or resolution state changes. """ return message['topic'].endswith('koschei.package.state.change') @hint(categories=['koschei'], invertible=False) def koschei_group(config, message, group=None): """ Particular Koschei package groups This rule limits message to particular `Koschei <https://apps.fedoraproject.org/koschei/>`_ groups. You can specify more groups separated by commas. """ if not group or 'koschei' not in message['topic']: return False groups = set([item.strip() for item in group.split(',')]) return bool(groups.intersection(message['msg'].get('groups')))
Document that CurrentDoc is not callable on invalid ops.
package ops import ( "bsearch/index" ) type HeaderCollector interface { Add(key, value string) } // QueryOp is the interface for search queries implemented by everything // that will return documents. Each QueryOp is assumed to define access // to a sorted set of documents sorted on IbDoc.order. type QueryOp interface { // CurrentDoc returns the last document returned by NextDoc // or the first document from this query if NextDoc hasn't been // called yet. // Can't be called on invalid or exhausted QueryOp. CurrentDoc() *index.IbDoc // NextDoc returns the document equal to `search` or next higher. NextDoc(search *index.IbDoc) *index.IbDoc // Recursively adds any headers this might need to return. ProcessHeaders(hc HeaderCollector) } // QueryContainer is an interface for ops that not only implement sets of // documents like QueryOp, but are also containers for other queries. // This applies to intersections and unions. type QueryContainer interface { QueryOp // Add adds one or more QueryOp to the container. Add(...QueryOp) }
package ops import ( "bsearch/index" ) type HeaderCollector interface { Add(key, value string) } // QueryOp is the interface for search queries implemented by everything // that will return documents. Each QueryOp is assumed to define access // to a sorted set of documents sorted on IbDoc.order. type QueryOp interface { // CurrentDoc returns the last document returned by NextDoc // or the first document from this query if NextDoc hasn't been // called yet. CurrentDoc() *index.IbDoc // NextDoc returns the document equal to `search` or next higher. NextDoc(search *index.IbDoc) *index.IbDoc // Recursively adds any headers this might need to return. ProcessHeaders(hc HeaderCollector) } // QueryContainer is an interface for ops that not only implement sets of // documents like QueryOp, but are also containers for other queries. // This applies to intersections and unions. type QueryContainer interface { QueryOp // Add adds one or more QueryOp to the container. Add(...QueryOp) }
Fix waila rooty dirt life calculation
package com.ferreusveritas.dynamictrees.compat; import java.util.List; import com.ferreusveritas.dynamictrees.blocks.BlockRooty; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.util.math.MathHelper; public class WailaRootyHandler implements IWailaDataProvider { @Override public List<String> getWailaBody(ItemStack itemStack, List<String> tooltip, IWailaDataAccessor accessor, IWailaConfigHandler config) { IBlockState state = accessor.getWorld().getBlockState(accessor.getPosition()); if(state.getBlock() instanceof BlockRooty) { BlockRooty rooty = (BlockRooty) state.getBlock(); int life = rooty.getSoilLife(state, accessor.getWorld(), accessor.getPosition()); tooltip.add("Soil Life: " + MathHelper.floor(life * 6.25f) + "%"); } return tooltip; } }
package com.ferreusveritas.dynamictrees.compat; import java.util.List; import com.ferreusveritas.dynamictrees.blocks.BlockRooty; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.util.math.MathHelper; public class WailaRootyHandler implements IWailaDataProvider { @Override public List<String> getWailaBody(ItemStack itemStack, List<String> tooltip, IWailaDataAccessor accessor, IWailaConfigHandler config) { IBlockState state = accessor.getWorld().getBlockState(accessor.getPosition()); if(state.getBlock() instanceof BlockRooty) { BlockRooty rooty = (BlockRooty) state.getBlock(); int life = rooty.getSoilLife(state, accessor.getWorld(), accessor.getPosition()); tooltip.add("Soil Life: " + MathHelper.floor(life / 16.0) + "%"); } return tooltip; } }
Correct the formating of the period in tostring
/** * Copyright (c) 2011 RedEngine Ltd, http://www.RedEngine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.scheduled; import java.util.concurrent.TimeUnit; public class PeriodicSchedule implements Schedule { private final long period; private final TimeUnit periodUnit; public PeriodicSchedule(long period, TimeUnit periodUnit) { this.period = period; this.periodUnit = periodUnit; } @Override public long getInitialDelay() { return 0; } @Override public long getPeriod() { return period; } @Override public TimeUnit getUnits() { return periodUnit; } @Override public String toString() { return String.format("with period %d %s", period, periodUnit.toString().toLowerCase()); } }
/** * Copyright (c) 2011 RedEngine Ltd, http://www.RedEngine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.scheduled; import java.util.concurrent.TimeUnit; public class PeriodicSchedule implements Schedule { private final long period; private final TimeUnit periodUnit; public PeriodicSchedule(long period, TimeUnit periodUnit) { this.period = period; this.periodUnit = periodUnit; } @Override public long getInitialDelay() { return 0; } @Override public long getPeriod() { return period; } @Override public TimeUnit getUnits() { return periodUnit; } @Override public String toString() { return String.format("with period %i%s", period, periodUnit.toString().toLowerCase()); } }
Add note for user about count of metadata differences the note tells the user that although metadata differences are displayed, they are not counted in the final difference count and don't affect any test report results
package de.retest.recheck.printer; import java.util.stream.Collectors; import de.retest.recheck.ui.diff.meta.MetadataDifference; import de.retest.recheck.ui.diff.meta.MetadataElementDifference; public class MetadataDifferencePrinter implements Printer<MetadataDifference> { private static final String KEY_EXPECTED_ACTUAL_FORMAT = "%s: expected=\"%s\", actual=\"%s\""; @Override public String toString( final MetadataDifference difference, final String indent ) { final String prefix = "Metadata Differences:"; final String note = "\n\t Please note that these differences do not affect the result and are not included in the difference count."; return indent + prefix + note + printDifferences( difference, indent + "\t" ); } private String printDifferences( final MetadataDifference difference, final String indent ) { return difference.getDifferences().stream() // .map( this::print ) // .collect( Collectors.joining( "\n" + indent, "\n" + indent, "" ) ); } private String print( final MetadataElementDifference difference ) { return String.format( KEY_EXPECTED_ACTUAL_FORMAT, difference.getKey(), difference.getExpected(), difference.getActual() ); } }
package de.retest.recheck.printer; import java.util.stream.Collectors; import de.retest.recheck.ui.diff.meta.MetadataDifference; import de.retest.recheck.ui.diff.meta.MetadataElementDifference; public class MetadataDifferencePrinter implements Printer<MetadataDifference> { private static final String KEY_EXPECTED_ACTUAL_FORMAT = "%s: expected=\"%s\", actual=\"%s\""; @Override public String toString( final MetadataDifference difference, final String indent ) { final String prefix = "Metadata Differences:"; return indent + prefix + printDifferences( difference, indent + "\t" ); } private String printDifferences( final MetadataDifference difference, final String indent ) { return difference.getDifferences().stream() // .map( this::print ) // .collect( Collectors.joining( "\n" + indent, "\n" + indent, "" ) ); } private String print( final MetadataElementDifference difference ) { return String.format( KEY_EXPECTED_ACTUAL_FORMAT, difference.getKey(), difference.getExpected(), difference.getActual() ); } }
Make border of imagery graphics transparent
import SimpleFillSymbol from 'esri/symbols/SimpleFillSymbol'; import SimpleLineSymbol from 'esri/symbols/SimpleLineSymbol'; import Color from 'esri/Color'; let customSymbol; let imagerySymbol; export default { getCustomSymbol: () => { if (customSymbol) { return customSymbol; } customSymbol = new SimpleFillSymbol( SimpleLineSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([3, 188, 255]), 3), new Color([210, 210, 210, 0.0]) ); return customSymbol; }, getImagerySymbol: () => { if (imagerySymbol) { return imagerySymbol; } imagerySymbol = new SimpleFillSymbol( SimpleLineSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([210, 210, 210, 0]), 1), new Color([210, 210, 210, 0.0]) ); return imagerySymbol; } };
import SimpleFillSymbol from 'esri/symbols/SimpleFillSymbol'; import SimpleLineSymbol from 'esri/symbols/SimpleLineSymbol'; import Color from 'esri/Color'; let customSymbol; let imagerySymbol; export default { getCustomSymbol: () => { if (customSymbol) { return customSymbol; } customSymbol = new SimpleFillSymbol( SimpleLineSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([3, 188, 255]), 3), new Color([210, 210, 210, 0.0]) ); return customSymbol; }, getImagerySymbol: () => { if (imagerySymbol) { return imagerySymbol; } imagerySymbol = new SimpleFillSymbol( SimpleLineSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([210, 210, 210, 1]), 1), new Color([210, 210, 210, 0.0]) ); return imagerySymbol; } };
Fix map issues with Python3 Partially implements: blueprint python-3 Change-Id: Ia7dfc2a28c311a378ca5ada477d18a5b741782b2
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))), )
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=map(six.text_type.strip, headers['X-Roles'].split(',')), )
Fix the 'Improve logging' improvement
package pl.mkrystek.mkbot; import static org.springframework.boot.Banner.Mode.OFF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; public class Main { private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { ConfigurableApplicationContext ctx = new SpringApplicationBuilder().bannerMode(OFF).web(true).logStartupInfo(false) .sources(BotApplicationConfiguration.class).headless(false).run(args); LOGGER.debug("Starting application"); BotApplication application = ctx.getBean(BotApplication.class); try { application.init(); application.startApplication(); } catch (Exception e) { LOGGER.error("Error : ", e); } finally { LOGGER.debug("Shutting down application"); if (application != null) application.shutdown(); } } }
package pl.mkrystek.mkbot; import static org.springframework.boot.Banner.Mode.OFF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; public class Main { private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { ConfigurableApplicationContext ctx = new SpringApplicationBuilder().bannerMode(OFF).web(true).logStartupInfo(false) .sources(BotApplicationConfiguration.class).headless(false).run(args); LOGGER.debug("Starting application"); BotApplication application = ctx.getBean(BotApplication.class); try { application.init(); application.startApplication(); LOGGER.debug("Application started!"); } catch (Exception e) { LOGGER.error("Error : ", e); } finally { LOGGER.debug("Shutting down application"); if (application != null) application.shutdown(); } } }
Revert to previous way of calculating load avg %
<?php function seconds_to_time($seconds) { $dtF = new DateTime("@0"); $dtT = new DateTime("@$seconds"); return $dtF->diff($dtT)->format('%ad %hh %im'); } function pretty_baud($baud) { $baud = intval($baud); $ret = "unknown"; if ($baud > 1000000){ $baud = $baud/1000000; $ret = "$baud Mb/s"; } else if ($baud > 1000){ $baud = $baud/1000; $ret = "$baud Kb/s"; } else{ $ret = "$baud b/s"; } return $ret; } function pretty_load_average($load_average){ $load_average = substr($load_average, 0, -1); $avg_percent = ($load_average) * 100; return "{$avg_percent}% Utilized ($load_average)"; }
<?php function seconds_to_time($seconds) { $dtF = new DateTime("@0"); $dtT = new DateTime("@$seconds"); return $dtF->diff($dtT)->format('%ad %hh %im'); } function pretty_baud($baud) { $baud = intval($baud); $ret = "unknown"; if ($baud > 1000000){ $baud = $baud/1000000; $ret = "$baud Mb/s"; } else if ($baud > 1000){ $baud = $baud/1000; $ret = "$baud Kb/s"; } else{ $ret = "$baud b/s"; } return $ret; } // See https://en.wikipedia.org/wiki/Load_(computing)#Unix-style_load_calculation // for more info on load average % calculation function pretty_load_average($load_average){ $load_average = substr($load_average, 0, -1); if ($load_average < 1.0) { $avg_percent = (($load_average-1) * -1) * 100; // * -1 to get a positive percentage return "{$avg_percent}% Idling ($load_average)"; } else { $avg_percent = ($load_average-1) * 100; return "{$avg_percent}% Overloaded ($load_average)"; } }
Fix translation issue in the social login
'use strict'; angular.module('<%=angularAppName%>') .directive('jhSocial', function(<% if (enableTranslation){ %>$translatePartialLoader, $translate, <% } %>$filter, SocialService) { return { restrict: 'E', scope: { provider: "@ngProvider" }, templateUrl: 'scripts/app/account/social/directive/social.html', link: function(scope, element, attrs) {<% if (enableTranslation){ %> $translatePartialLoader.addPart('social'); $translate.refresh(); <% } %> scope.label = $filter('capitalize')(scope.provider); scope.providerSetting = SocialService.getProviderSetting(scope.provider); scope.providerURL = SocialService.getProviderURL(scope.provider); scope.csrf = SocialService.getCSRF(); } } });
'use strict'; angular.module('<%=angularAppName%>') .directive('jhSocial', function($translatePartialLoader, $translate, $filter, SocialService) { return { restrict: 'E', scope: { provider: "@ngProvider" }, templateUrl: 'scripts/app/account/social/directive/social.html', link: function(scope, element, attrs) { $translatePartialLoader.addPart('social'); $translate.refresh(); scope.label = $filter('capitalize')(scope.provider); scope.providerSetting = SocialService.getProviderSetting(scope.provider); scope.providerURL = SocialService.getProviderURL(scope.provider); scope.csrf = SocialService.getCSRF(); } } });
Handle having a single role in the SAML assertion
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: if isinstance(attribute[attribute_value_key], list): for value in attribute[attribute_value_key]: roles.append(value['#text']) else: value = attribute[attribute_value_key] roles.append(value['#text']) return roles
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: for value in attribute[attribute_value_key]: roles.append(value['#text']) return roles
Mark this project as using the MIT License.
try: from setuptools import setup except ImportError: from distutils.core import setup Version = "0.01" setup(name = "coverage-reporter", version = Version, description = "Coverage reporting tool", long_description="Allows more complicated reporting of information from figleaf and other coverage tools", author = "David Christian", author_email = "david.chrsitian@gmail.com", url = "http://github.org/dugan/coverage-reporter/", packages = [ 'coverage_reporter', 'coverage_reporter.filters', 'coverage_reporter.collectors', 'coverage_reporter.reports' ], license = 'MIT', scripts = ['scripts/coverage-reporter'], platforms = 'Posix; MacOS X; Windows', classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], )
try: from setuptools import setup except ImportError: from distutils.core import setup Version = "0.01" setup(name = "coverage-reporter", version = Version, description = "Coverage reporting tool", long_description="Allows more complicated reporting of information from figleaf and other coverage tools", author = "David Christian", author_email = "david.chrsitian@gmail.com", url = "http://github.org/dugan/coverage-reporter/", packages = [ 'coverage_reporter', 'coverage_reporter.filters', 'coverage_reporter.collectors', 'coverage_reporter.reports' ], license = 'BSD', scripts = ['scripts/coverage-reporter'], platforms = 'Posix; MacOS X; Windows', classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Development', ], )
Use find_packages to ensure management command is included in installs
import os import codecs from setuptools import setup, find_packages PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) def read(*path): full_path = os.path.join(PROJECT_ROOT, *path) with codecs.open(full_path, 'r', encoding='utf-8') as f: return f.read() setup( name='whitenoise', version='0.12', author='David Evans', author_email='d@evans.io', url='http://whitenoise.evans.io', packages=find_packages(exclude=['tests*']), license='MIT', description="Serve static files direct from WSGI application", long_description=read('README.rst'), classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', ], )
import os import codecs from setuptools import setup PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) def read(*path): full_path = os.path.join(PROJECT_ROOT, *path) with codecs.open(full_path, 'r', encoding='utf-8') as f: return f.read() setup( name='whitenoise', version='0.12', author='David Evans', author_email='d@evans.io', url='http://whitenoise.evans.io', packages=['whitenoise'], license='MIT', description="Serve static files direct from WSGI application", long_description=read('README.rst'), classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', ], )
Refactor KeyEvent generation for unit tests.
import java.awt.Component; import java.awt.Container; import java.awt.event.KeyEvent; import static org.junit.Assert.*; import org.junit.Test; import org.junit.Before; public class TestInputResponder implements InputResponder { private static final Component testKeyEventSource = new Container(); private InputResponder inputResponder; private KeyEvent currentKeyEvent = null; private static final char testKey = 'x'; private static KeyEvent generateKeyEvent(int id, char key) { return new KeyEvent(testKeyEventSource, id, System.currentTimeMillis(), 0, (int)key, key); } public static KeyEvent generateKeyDownEvent(char key) { return generateKeyEvent(KeyEvent.KEY_PRESSED, key); } public static KeyEvent generateKeyUpEvent(char key) { return generateKeyEvent(KeyEvent.KEY_RELEASED, key); } public void keyDownResponse(KeyEvent e) { currentKeyEvent = e; } public void keyUpResponse(KeyEvent e) { if ((currentKeyEvent == null) || (e.getKeyCode() != currentKeyEvent.getKeyCode())) throw new RuntimeException("keyUp is triggered before keyDown!"); else currentKeyEvent = null; } @Before public void instantiate() { inputResponder = new TestInputResponder(); } @Test public void testKeyDownUpResponse() { inputResponder.keyDownResponse(generateKeyDownEvent(testKey)); inputResponder.keyUpResponse(generateKeyUpEvent(testKey)); } }
import java.awt.Component; import java.awt.Container; import java.awt.event.KeyEvent; import static org.junit.Assert.*; import org.junit.Test; import org.junit.Before; public class TestInputResponder implements InputResponder { private InputResponder inputResponder; private KeyEvent currentKeyEvent = null; private static final char testKey = 'x'; public void keyDownResponse(KeyEvent e) { currentKeyEvent = e; } public void keyUpResponse(KeyEvent e) { if ((currentKeyEvent == null) || (e.getKeyCode() != currentKeyEvent.getKeyCode())) throw new RuntimeException("keyUp is triggered before keyDown!"); else currentKeyEvent = null; } @Before public void instantiate() { inputResponder = new TestInputResponder(); } @Test public void testKeyDownUpResponse() { Component source = new Container(); KeyEvent key = new KeyEvent(source, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, (int)testKey, testKey); inputResponder.keyDownResponse(key); key = new KeyEvent(source, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), 0, (int)testKey, testKey); inputResponder.keyUpResponse(key); } }
:art: Set a default count value of Bottom Tab
'use strict'; class BottomTab extends HTMLElement{ prepare(name) { this.name = name this.attached = false this.active = false this.classList.add('linter-tab') this.countSpan = document.createElement('span') this.countSpan.classList.add('count') this.countSpan.textContent = '0' this.innerHTML = this.name + ' ' this.appendChild(this.countSpan) this.count = 0 return this } attachedCallback() { this.attached = true } detachedCallback() { this.attached = false } get active() { return this._active } set active(value) { this._active = value if (value) { this.classList.add('active') } else { this.classList.remove('active') } } get count(){ return this._count } set count(value) { this._count = value this.countSpan.textContent = value } } module.exports = BottomTab = document .registerElement( 'linter-bottom-tab', {prototype: BottomTab.prototype} )
'use strict'; class BottomTab extends HTMLElement{ prepare(name) { this.name = name this.attached = false this.active = false this.classList.add('linter-tab') this.countSpan = document.createElement('span') this.countSpan.classList.add('count') this.countSpan.textContent = '0' this.innerHTML = this.name + ' ' this.appendChild(this.countSpan) return this } attachedCallback() { this.attached = true } detachedCallback() { this.attached = false } get active() { return this._active } set active(value) { this._active = value if (value) { this.classList.add('active') } else { this.classList.remove('active') } } get count(){ return this._count } set count(value) { this._count = value this.countSpan.textContent = value } } module.exports = BottomTab = document .registerElement( 'linter-bottom-tab', {prototype: BottomTab.prototype} )
Enable Q's long stack support by default Since the response builder handler is often one of the first things created in our APIs, it provides a convenient place to enable the long stack support in Q.
'use strict'; var ResponseBuilder = require('./ResponseBuilder'); /** * In our APIs, we often have errors that are several promises deep, and without this, * it's hard to tell where the error actually originated (especially with AWS calls, etc). * This will generally make error stack traces much more helpful to us, so we are making * it a default. */ require('q').longStackSupport = true; module.exports = function(promiseReturningHandlerFn, request, cb, CustomRespBuilderClass) { promiseReturningHandlerFn() .then(function(respBuilder) { // eslint-disable-next-line no-console console.log('completed with %s millis left', request.getContext().getRemainingTimeInMillis()); cb(undefined, respBuilder.toResponse(request)); }) .catch(function(err) { var RB = CustomRespBuilderClass || ResponseBuilder, respBuilder = new RB().serverError().rb(); // eslint-disable-next-line no-console console.log('ERROR:', err, err.stack); cb(undefined, respBuilder.toResponse(request)); }) .done(); };
'use strict'; var ResponseBuilder = require('./ResponseBuilder'); module.exports = function(promiseReturningHandlerFn, request, cb, CustomRespBuilderClass) { promiseReturningHandlerFn() .then(function(respBuilder) { // eslint-disable-next-line no-console console.log('completed with %s millis left', request.getContext().getRemainingTimeInMillis()); cb(undefined, respBuilder.toResponse(request)); }) .catch(function(err) { var RB = CustomRespBuilderClass || ResponseBuilder, respBuilder = new RB().serverError().rb(); // eslint-disable-next-line no-console console.log('ERROR:', err, err.stack); cb(undefined, respBuilder.toResponse(request)); }) .done(); };
Add new test called pingPongType
describe('pingPong', function() { it("is false for a number that is not divisible by 3 or 5", function() { expect(pingPong(7)).to.equal(false); }); it("will run pingPongType if isPingPong is true", function() { expect(pingPong(6)).to.equal("ping"); }); }); describe('pingPongType', function() { it("returns ping for a number that is divisible by 3", function() { expect(pingPongType(6)).to.equal("ping"); }); it("returns pong for a number that is divisible by 5", function() { expect(pingPongType(10)).to.equal("pong"); }); it("returns pingpong for a number that is divisible by 3 and 5", function() { expect(pingPongType(30)).to.equal("pingpong") }); }); describe('isPingPong', function() { it("returns true for a number divisible by 3, 5, or 15", function() { expect(isPingPong(6)).to.equal(true); }); it("returns false for a number not divisible by 3, 5, or 15", function() { expect(isPingPong(7)).to.equal(false); }); });
describe('pingPong', function() { it("returns ping for a number that is divisible by 3", function() { expect(pingPong(6)).to.equal("ping"); }); it("returns pong for a number that is divisible by 5", function() { expect(pingPong(10)).to.equal("pong"); }); it("returns pingpong for a number that is divisible by 3 and 5", function() { expect(pingPong(30)).to.equal("pingpong") }); it("is false for a number that is not divisible by 3 or 5", function() { expect(!pingPong).to.equal(false); }); }); describe('isPingPong', function() { it("returns true for a number divisible by 3, 5, or 15", function() { expect(isPingPong(6)).to.equal(true); }); it("returns false for a number not divisible by 3, 5, or 15", function() { expect(isPingPong(7)).to.equal(false); }); });
Update to latest Google Play Services APIs
/* * Copyright 2014 Kevin Quan (kevin.quan@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kevinquan.google.activityrecoginition; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; public abstract class AbstractActivityRecognitionCallback implements ConnectionCallbacks { @SuppressWarnings("unused") private static final String TAG = AbstractActivityRecognitionCallback.class.getSimpleName(); protected GoogleApiClient mClient; @Override public void onConnectionSuspended(int reason) {} public AbstractActivityRecognitionCallback setClient(GoogleApiClient client) { mClient = client; return this; } }
/* * Copyright 2014 Kevin Quan (kevin.quan@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kevinquan.google.activityrecoginition; import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks; import com.google.android.gms.location.ActivityRecognitionClient; public abstract class AbstractActivityRecognitionCallback implements ConnectionCallbacks { @SuppressWarnings("unused") private static final String TAG = AbstractActivityRecognitionCallback.class.getSimpleName(); protected ActivityRecognitionClient mClient; public AbstractActivityRecognitionCallback setClient(ActivityRecognitionClient client) { mClient = client; return this; } @Override public void onDisconnected() {} }