text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Disable stream synchronization task in Mainteance::common()
<?php class CM_Maintenance_Cli extends CM_Cli_Runnable_Abstract { /** * @synchronized */ public function common() { CM_Model_User::offlineOld(); CM_ModelAsset_User_Roles::deleteOld(); CM_Paging_Useragent_Abstract::deleteOlder(100 * 86400); CM_File_UserContent_Temp::deleteOlder(86400); CM_SVM::deleteOldTrainings(3000); CM_SVM::trainChanged(); CM_Paging_Ip_Blocked::deleteOlder(7 * 86400); CM_Captcha::deleteOlder(3600); CM_ModelAsset_User_Roles::deleteOld(); CM_Session::deleteExpired(); CM_Stream_Video::getInstance()->synchronize(); CM_Stream_Video::getInstance()->checkStreams(); CM_KissTracking::getInstance()->exportEvents(); // CM_Stream_Message::getInstance()->synchronize(); } /** * @synchronized */ public function heavy() { CM_Mail::processQueue(500); CM_Action_Abstract::aggregate(); } public static function getPackageName() { return 'maintenance'; } }
<?php class CM_Maintenance_Cli extends CM_Cli_Runnable_Abstract { /** * @synchronized */ public function common() { CM_Model_User::offlineOld(); CM_ModelAsset_User_Roles::deleteOld(); CM_Paging_Useragent_Abstract::deleteOlder(100 * 86400); CM_File_UserContent_Temp::deleteOlder(86400); CM_SVM::deleteOldTrainings(3000); CM_SVM::trainChanged(); CM_Paging_Ip_Blocked::deleteOlder(7 * 86400); CM_Captcha::deleteOlder(3600); CM_ModelAsset_User_Roles::deleteOld(); CM_Session::deleteExpired(); CM_Stream_Video::getInstance()->synchronize(); CM_Stream_Video::getInstance()->checkStreams(); CM_KissTracking::getInstance()->exportEvents(); CM_Stream_Message::getInstance()->synchronize(); } /** * @synchronized */ public function heavy() { CM_Mail::processQueue(500); CM_Action_Abstract::aggregate(); } public static function getPackageName() { return 'maintenance'; } }
Adjust ember try config to make travis pass
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release', 'ember-data': 'components/ember-data#canary' }, resolutions: { 'ember': 'release', 'ember-data': 'canary' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta', 'ember-data': 'components/ember-data#canary' }, resolutions: { 'ember': 'beta', 'ember-data': 'canary' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary', 'ember-data': 'components/ember-data#canary' }, resolutions: { 'ember': 'canary', 'ember-data': 'canary' } } ] };
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } } ] };
Abort pending requests when there is a new event
var pendingRequest = undefined; var timeouts = []; function updateResults(e) { if (e.which === 0) { return; } var query = $("#query").val(); if (pendingRequest) { pendingRequest.abort(); } for (var x=0; x<timeouts.length; x++) { clearTimeout(timeouts[x]); } pendingRequest = $.getJSON( "/search", {query: query}, function processQueryResult(data) { $("#results").html(""); for (var x=0; x<data.length; x++) { var postId = 'post' + x; var post = '<div id="' + postId + '" class="result">'; post += '<h2><a href="' + data[x].url + '">' + data[x].title + '</a></h2>'; post += '</div>'; var timeout = showImage(x, postId, data[x].image); timeouts.push(timeout); $("#results").append(post); } } ); } function showImage(x, postId, image) { var timeout = setTimeout(function() { var img = '<img src="' + image + '" class="result-img"/>'; $("#" + postId).append(img); }, 500 * x); return timeout; } $("#query").keypress(updateResults);
var timeouts = []; function updateResults(e) { if (e.which === 0) { return; } var query = $("#query").val(); for (var x=0; x<timeouts.length; x++) { clearTimeout(timeouts[x]); } $.getJSON( "/search", {query: query}, function processQueryResult(data) { $("#results").html(""); for (var x=0; x<data.length; x++) { var postId = 'post' + x; var post = '<div id="' + postId + '" class="result">'; post += '<h2><a href="' + data[x].url + '">' + data[x].title + '</a></h2>'; post += '</div>'; var timeout = showImage(x, postId, data[x].image); timeouts.push(timeout); $("#results").append(post); } } ); } function showImage(x, postId, image) { var timeout = setTimeout(function() { var img = '<img src="' + image + '" class="result-img"/>'; $("#" + postId).append(img); }, 500 * x); return timeout; } $("#query").keypress(updateResults);
Stop Sopel from relying rudely to the bot's owner.
# coding=utf8 """ ping.py - Sopel Ping Module Author: Sean B. Palmer, inamidst.com About: http://sopel.chat """ from __future__ import unicode_literals import random from sopel.module import rule, priority, thread @rule(r'(?i)(hi|hello|hey),? $nickname[ \t]*$') def hello(bot, trigger): greeting = random.choice(('Hi', 'Hey', 'Hello')) punctuation = random.choice(('', '!')) bot.say(greeting + ' ' + trigger.nick + punctuation) @rule(r'(?i)(Fuck|Screw) you,? $nickname[ \t]*$') def rude(bot, trigger): bot.say('Watch your mouth, ' + trigger.nick + ', or I\'ll tell your mother!') @rule('$nickname!') @priority('high') @thread(False) def interjection(bot, trigger): bot.say(trigger.nick + '!')
# coding=utf8 """ ping.py - Sopel Ping Module Author: Sean B. Palmer, inamidst.com About: http://sopel.chat """ from __future__ import unicode_literals import random from sopel.module import rule, priority, thread @rule(r'(?i)(hi|hello|hey),? $nickname[ \t]*$') def hello(bot, trigger): if trigger.owner: greeting = random.choice(('Fuck off,', 'Screw you,', 'Go away')) else: greeting = random.choice(('Hi', 'Hey', 'Hello')) punctuation = random.choice(('', '!')) bot.say(greeting + ' ' + trigger.nick + punctuation) @rule(r'(?i)(Fuck|Screw) you,? $nickname[ \t]*$') def rude(bot, trigger): bot.say('Watch your mouth, ' + trigger.nick + ', or I\'ll tell your mother!') @rule('$nickname!') @priority('high') @thread(False) def interjection(bot, trigger): bot.say(trigger.nick + '!')
Remove no longer valid test
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
[SMALLFIX] Replace anonymous type with lambda Java 8 Improvement: replace anonymous type with lambda in alluxio/core/common/src/main/java/alluxio/util/ExtensionUtils.java#listExtensions pr-link: Alluxio/alluxio#8651 change-id: cid-c2f89e9233c853cdf9b027254a33aa93f9297217
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.util; import alluxio.Constants; import java.io.File; import javax.annotation.concurrent.ThreadSafe; /** * Utility functions for working with extensions. */ @ThreadSafe public final class ExtensionUtils { private static final File[] EMPTY_EXTENSIONS_LIST = new File[0]; /** * List extension jars from the configured extensions directory. * * @param extensionDir the directory containing extensions * @return an array of files (one file per jar) */ public static File[] listExtensions(String extensionDir) { File[] extensions = new File(extensionDir) .listFiles(file -> file.getPath().toLowerCase().endsWith(Constants.EXTENSION_JAR)); if (extensions == null) { // Directory does not exist return EMPTY_EXTENSIONS_LIST; } return extensions; } private ExtensionUtils() {} // prevent instantiation }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.util; import alluxio.Constants; import java.io.File; import java.io.FileFilter; import javax.annotation.concurrent.ThreadSafe; /** * Utility functions for working with extensions. */ @ThreadSafe public final class ExtensionUtils { private static final File[] EMPTY_EXTENSIONS_LIST = new File[0]; /** * List extension jars from the configured extensions directory. * * @param extensionDir the directory containing extensions * @return an array of files (one file per jar) */ public static File[] listExtensions(String extensionDir) { File[] extensions = new File(extensionDir).listFiles(new FileFilter() { public boolean accept(File file) { return file.getPath().toLowerCase().endsWith(Constants.EXTENSION_JAR); } }); if (extensions == null) { // Directory does not exist return EMPTY_EXTENSIONS_LIST; } return extensions; } private ExtensionUtils() {} // prevent instantiation }
Use streams to make the toArray method nicer
package info.u_team.u_team_core.intern.init; import info.u_team.u_team_core.UCoreMain; import info.u_team.u_team_core.api.dye.*; import net.minecraft.item.Item; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ColorHandlerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; @EventBusSubscriber(modid = UCoreMain.MODID, bus = Bus.MOD, value = Dist.CLIENT) public class UCoreColors { @SubscribeEvent public static void register(ColorHandlerEvent.Item event) { event.getItemColors().register((itemstack, index) -> { final Item item = itemstack.getItem(); if (item instanceof IDyeableItem) { return ((IDyeableItem) item).getColor(itemstack); } return 0; }, DyeableItemsRegistry.getDyeableItems().stream().toArray(Item[]::new)); } }
package info.u_team.u_team_core.intern.init; import info.u_team.u_team_core.UCoreMain; import info.u_team.u_team_core.api.dye.*; import net.minecraft.item.Item; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ColorHandlerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; @EventBusSubscriber(modid = UCoreMain.MODID, bus = Bus.MOD, value = Dist.CLIENT) public class UCoreColors { @SubscribeEvent public static void register(ColorHandlerEvent.Item event) { event.getItemColors().register((itemstack, index) -> { final Item item = itemstack.getItem(); if (item instanceof IDyeableItem) { return ((IDyeableItem) item).getColor(itemstack); } return 0; }, DyeableItemsRegistry.getDyeableItems().toArray(new Item[DyeableItemsRegistry.getDyeableItems().size()])); } }
TASK: Adjust test assertions to PHPUnit 8
<?php namespace Neos\Flow\Tests\Unit\Http\Helper; use GuzzleHttp\Psr7\ServerRequest; use Neos\Flow\Http\Helper\RequestInformationHelper; use Neos\Flow\Tests\UnitTestCase; /** * Tests for the RequestInformationHelper */ class RequestInformationHelperTest extends UnitTestCase { /** * @test */ public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials() { $request = ServerRequest::fromGlobals() ->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword') ->withAddedHeader('Authorization', 'Bearer SomeToken'); $renderedHeaders = RequestInformationHelper::renderRequestHeaders($request); self::assertStringContainsString('SomePassword', $renderedHeaders); self::assertStringContainsString('SomeToken', $renderedHeaders); } }
<?php namespace Neos\Flow\Tests\Unit\Http\Helper; use GuzzleHttp\Psr7\ServerRequest; use Neos\Flow\Http\Helper\RequestInformationHelper; use Neos\Flow\Tests\UnitTestCase; /** * Tests for the RequestInformationHelper */ class RequestInformationHelperTest extends UnitTestCase { /** * @test */ public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials() { $request = ServerRequest::fromGlobals() ->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword') ->withAddedHeader('Authorization', 'Bearer SomeToken'); $renderedHeaders = RequestInformationHelper::renderRequestHeaders($request); self::assertNotContains('SomePassword', $renderedHeaders); self::assertNotContains('SomeToken', $renderedHeaders); } }
Edit author field. Use full name
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup( name='top40', version='0.1', py_modules=['top40'], author = "Kevin Ndung'u", author_email = 'kevgathuku@gmail.com', description = ("Print and optionally download songs in the " "UK Top 40 Charts"), url='https://github.com/kevgathuku/top40', license = "MIT", install_requires=[ 'Click>=3.3', 'requests', 'requests-cache', 'google-api-python-client', ], entry_points=''' [console_scripts] top40=top40:cli ''', )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup( name='top40', version='0.1', py_modules=['top40'], author = 'kevgathuku', author_email = 'kevgathuku@gmail.com', description = ("Print and optionally download songs in the " "UK Top 40 Charts"), url='https://github.com/kevgathuku/top40', license = "MIT", install_requires=[ 'Click>=3.3', 'requests', 'requests-cache', 'google-api-python-client', ], entry_points=''' [console_scripts] top40=top40:cli ''', )
Disable Parallax3D on navigation page
import NavigationBase from '../navigation/anim-base'; export default class AboutNavigationAnimation extends NavigationBase { constructor() { super(); this.hash = 'about'; // Add objects to this.elem Object.assign(this.elem, { wrapper: document.getElementById('about-wrapper'), container: document.querySelector('#about-wrapper .container'), monogram: document.querySelector('#about-wrapper .monogram'), content: document.querySelector('#about-wrapper .content'), }); this.fontSize = { content: 'calc(13px + .75vw)', monogram: '4vw', }; } putInLaptop() { super.putInLaptop(); // Calculate appropriate font size scale this.scaleX = this.elem.container.getBoundingClientRect().width / window.innerWidth; // Scale font sizes using CSS `calc` Object.entries(this.fontSize).forEach((pair) => { const [key, value] = pair; this.elem[key].style.fontSize = `calc(${value} * ${this.scaleX})`; }); // Turn off parallax effect window.parallax.disable(); } removeFromLaptop() { super.removeFromLaptop(); // Remove adjusted font sizes Array.from(Object.keys(this.fontSize)).forEach((n) => { this.elem[n].style.fontSize = ''; }); // Re-enable parallax effect window.parallax.enable(); } }
import NavigationBase from '../navigation/anim-base'; export default class AboutNavigationAnimation extends NavigationBase { constructor() { super(); this.hash = 'about'; // Add objects to this.elem Object.assign(this.elem, { wrapper: document.getElementById('about-wrapper'), container: document.querySelector('#about-wrapper .container'), monogram: document.querySelector('#about-wrapper .monogram'), content: document.querySelector('#about-wrapper .content'), }); this.fontSize = { content: 'calc(13px + .75vw)', monogram: '4vw', }; } putInLaptop() { super.putInLaptop(); // Calculate appropriate font size scale this.scaleX = this.elem.container.getBoundingClientRect().width / window.innerWidth; // Scale font sizes using CSS `calc` Object.entries(this.fontSize).forEach((pair) => { const [key, value] = pair; this.elem[key].style.fontSize = `calc(${value} * ${this.scaleX})`; }); } removeFromLaptop() { super.removeFromLaptop(); // Remove adjusted font sizes Array.from(Object.keys(this.fontSize)).forEach((n) => { this.elem[n].style.fontSize = ''; }); } }
Declare required version of zeit.cms
from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>=1.53.0.dev', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], )
from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>1.40.3', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], )
Add better instructions to the Gitter example
# -*- coding: utf-8 -*- from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from settings import GITTER # Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) ''' To use this example, create a new file called settings.py. In settings.py define the following: GITTER = { "API_TOKEN": "my-api-token", "ROOM": "example_project/test_room" } ''' chatbot = ChatBot( 'GitterBot', gitter_room=GITTER['ROOM'], gitter_api_token=GITTER['API_TOKEN'], gitter_only_respond_to_mentions=False, input_adapter='chatterbot.input.Gitter', output_adapter='chatterbot.output.Gitter' ) trainer = ChatterBotCorpusTrainer(chatbot) trainer.train('chatterbot.corpus.english') # The following loop will execute each time the user enters input while True: try: response = chatbot.get_response(None) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
# -*- coding: utf-8 -*- from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from settings import GITTER # Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) chatbot = ChatBot( 'GitterBot', gitter_room=GITTER['ROOM'], gitter_api_token=GITTER['API_TOKEN'], gitter_only_respond_to_mentions=False, input_adapter='chatterbot.input.Gitter', output_adapter='chatterbot.output.Gitter' ) trainer = ChatterBotCorpusTrainer(chatbot) trainer.train('chatterbot.corpus.english') # The following loop will execute each time the user enters input while True: try: response = chatbot.get_response(None) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
Change Beat's instance property 'freq' to 'frequency' for more natural get/setting
(function() { var Beat = function ( dance, frequency, threshold, decay, onBeat, offBeat ) { this.dance = dance; this.frequency = frequency; this.threshold = threshold; this.decay = decay; this.onBeat = onBeat; this.offBeat = offBeat; this.isOn = false; this.currentThreshold = threshold; var _this = this; this.dance.bind( 'update', function() { if ( !_this.isOn ) { return; } var magnitude = _this.dance.spectrum()[ _this.frequency ]; if ( magnitude >= _this.currentThreshold && magnitude >= _this.threshold ) { _this.currentThreshold = magnitude; onBeat.call( _this.dance, magnitude ); } else { offBeat.call( _this.dance, magnitude ); _this.currentThreshold -= _this.decay; } }); }; Beat.prototype = { on : function () { this.isOn = true; }, off : function () { this.isOn = false; } }; window.Dance.Beat = Beat; })();
(function() { var Beat = function ( dance, freq, threshold, decay, onBeat, offBeat ) { this.dance = dance; this.freq = freq; this.threshold = threshold; this.decay = decay; this.onBeat = onBeat; this.offBeat = offBeat; this.isOn = false; this.currentThreshold = threshold; var _this = this; this.dance.bind( 'update', function() { if ( !_this.isOn ) { return; } var magnitude = _this.dance.spectrum()[ _this.freq ]; if ( magnitude >= _this.currentThreshold && magnitude >= _this.threshold ) { _this.currentThreshold = magnitude; onBeat.call( _this.dance, magnitude ); } else { offBeat.call( _this.dance, magnitude ); _this.currentThreshold -= _this.decay; } }); }; Beat.prototype = { on : function () { this.isOn = true; }, off : function () { this.isOn = false; } }; window.Dance.Beat = Beat; })();
Add source maps to webpack
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { app: ["babel-polyfill", "./js/game.js"], vendor: ['protobufjs'] }, output: { filename: "[name].js" }, module: { loaders: [ { test: /\.json$/, loader: 'json' }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: path.resolve(__dirname, 'node_modules', 'pixi.js'), loader: 'ify' } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js") ], postLoaders: [ { test: /\.js$/, include: path.resolve(__dirname, 'node_modules/pixi.js'), loader: 'transform/cacheable?brfs' } ], // TODO: configure production build debug: true, devtool: 'eval-source-map' };
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { app: ["babel-polyfill", "./js/game.js"], vendor: ['protobufjs'] }, output: { filename: "[name].js" }, module: { loaders: [ { test: /\.json$/, loader: 'json' }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: path.resolve(__dirname, 'node_modules', 'pixi.js'), loader: 'ify' } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js") ], postLoaders: [ { test: /\.js$/, include: path.resolve(__dirname, 'node_modules/pixi.js'), loader: 'transform/cacheable?brfs' } ] };
Use log package instead of println Signed-off-by: Wincent Colaiuta <c76ac2e9cd86441713c7dfae92c451f3e6d17fdc@wincent.com>
package main import( "log" "net" ) const( RECV_BUF_LEN = 1024 ) func main() { log.Print("Starting the server") listener, err := net.Listen("tcp", "127.0.0.1:8377") if err != nil { log.Fatal("Listen: ", err.Error()) } for { conn, err := listener.Accept() if err != nil { log.Print("Accept: ", err.Error()) return } go HandleConnection(conn) } } func HandleConnection(conn net.Conn) { buf := make([]byte, RECV_BUF_LEN) n, err := conn.Read(buf) if err != nil { log.Print("Read: ", err.Error()) return } log.Print("Received ", n, " bytes of data") _, err = conn.Write(buf) if err != nil { log.Print("Write: ", err.Error()) return } else { log.Print("Reply echoed") conn.Close() } }
package main import( "net" "os" ) const( RECV_BUF_LEN = 1024 ) func main() { println("Starting the server") listener, err := net.Listen("tcp", "127.0.0.1:8377") if err != nil { println("error Listen: ", err.Error()) os.Exit(1) } for { conn, err := listener.Accept() if err != nil { println("error Accept: ", err.Error()) return } go HandleConnection(conn) } } func HandleConnection(conn net.Conn) { buf := make([]byte, RECV_BUF_LEN) n, err := conn.Read(buf) if err != nil { println("error Read: ", err.Error()) return } println("Received ", n, " bytes of data: ", string(buf)) _, err = conn.Write(buf) if err != nil { println("error Write: ", err.Error()) return } else { println("Reply echoed") } }
Prepare for next dev cycle
#!/usr/bin/env python # coding: utf-8 from setuptools import setup, find_packages setup( name="bentoo", description="Benchmarking tools", version="0.20.0_dev", packages=find_packages(), scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py", "scripts/bentoo-collector.py", "scripts/bentoo-analyser.py", "scripts/bentoo-aggregator.py", "scripts/bentoo-metric.py", "scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py", "scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py", "scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py", "scripts/bentoo-confreader.py"], package_data={ '': ['*.adoc', '*.rst', '*.md'] }, author="Zhang YANG", author_email="zyangmath@gmail.com", license="PSF", keywords="Benchmark;Performance Analysis", url="http://github.com/ProgramFan/bentoo")
#!/usr/bin/env python # coding: utf-8 from setuptools import setup, find_packages setup( name="bentoo", description="Benchmarking tools", version="0.19.0", packages=find_packages(), scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py", "scripts/bentoo-collector.py", "scripts/bentoo-analyser.py", "scripts/bentoo-aggregator.py", "scripts/bentoo-metric.py", "scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py", "scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py", "scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py", "scripts/bentoo-confreader.py"], package_data={ '': ['*.adoc', '*.rst', '*.md'] }, author="Zhang YANG", author_email="zyangmath@gmail.com", license="PSF", keywords="Benchmark;Performance Analysis", url="http://github.com/ProgramFan/bentoo")
Allow CancelTaskHandler to be called when nsync CancelTaskRoute is hit. - Register the handler with Rata [#111473134] Signed-off-by: Frank Kotsianas <7292b1604e9876e8e1934a101736830424483797@pivotal.io>
package handlers import ( "net/http" "github.com/cloudfoundry-incubator/bbs" "github.com/cloudfoundry-incubator/nsync" "github.com/cloudfoundry-incubator/nsync/recipebuilder" "github.com/pivotal-golang/lager" "github.com/tedsuo/rata" ) func New(logger lager.Logger, bbsClient bbs.Client, recipebuilders map[string]recipebuilder.RecipeBuilder) http.Handler { desireAppHandler := NewDesireAppHandler(logger, bbsClient, recipebuilders) stopAppHandler := NewStopAppHandler(logger, bbsClient) killIndexHandler := NewKillIndexHandler(logger, bbsClient) taskHandler := NewTaskHandler(logger, bbsClient, recipebuilders) cancelTaskHandler := NewCancelTaskHandler(logger, bbsClient) actions := rata.Handlers{ nsync.DesireAppRoute: http.HandlerFunc(desireAppHandler.DesireApp), nsync.StopAppRoute: http.HandlerFunc(stopAppHandler.StopApp), nsync.KillIndexRoute: http.HandlerFunc(killIndexHandler.KillIndex), nsync.TasksRoute: http.HandlerFunc(taskHandler.DesireTask), nsync.CancelTaskRoute: http.HandlerFunc(cancelTaskHandler.CancelTask), } handler, err := rata.NewRouter(nsync.Routes, actions) if err != nil { panic("unable to create router: " + err.Error()) } return handler }
package handlers import ( "net/http" "github.com/cloudfoundry-incubator/bbs" "github.com/cloudfoundry-incubator/nsync" "github.com/cloudfoundry-incubator/nsync/recipebuilder" "github.com/pivotal-golang/lager" "github.com/tedsuo/rata" ) func New(logger lager.Logger, bbsClient bbs.Client, recipebuilders map[string]recipebuilder.RecipeBuilder) http.Handler { desireAppHandler := NewDesireAppHandler(logger, bbsClient, recipebuilders) stopAppHandler := NewStopAppHandler(logger, bbsClient) killIndexHandler := NewKillIndexHandler(logger, bbsClient) taskHandler := NewTaskHandler(logger, bbsClient, recipebuilders) actions := rata.Handlers{ nsync.DesireAppRoute: http.HandlerFunc(desireAppHandler.DesireApp), nsync.StopAppRoute: http.HandlerFunc(stopAppHandler.StopApp), nsync.KillIndexRoute: http.HandlerFunc(killIndexHandler.KillIndex), nsync.TasksRoute: http.HandlerFunc(taskHandler.DesireTask), } handler, err := rata.NewRouter(nsync.Routes, actions) if err != nil { panic("unable to create router: " + err.Error()) } return handler }
Fix up package naming confusion for the moment.
import os import setuptools setuptools.setup( name='lmj.sim', version='0.0.2', packages=setuptools.find_packages(), author='Leif Johnson', author_email='leif@leifjohnson.net', description='yet another OpenGL-with-physics simulation framework', long_description=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.md')).read(), license='MIT', url='http://github.com/lmjohns3/py-sim/', keywords=('simulation ' 'physics ' 'ode ' 'visualization ' ), install_requires=['climate', 'numpy', 'pyglet', 'Open-Dynamics-Engine'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Scientific/Engineering :: Physics', 'Topic :: Scientific/Engineering :: Visualization', ], )
import os import setuptools setuptools.setup( name='gymnasium', version='0.0.2', packages=setuptools.find_packages(), author='Leif Johnson', author_email='leif@leifjohnson.net', description='yet another OpenGL-with-physics simulation framework', long_description=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.md')).read(), license='MIT', url='http://github.com/lmjohns3/py-sim/', keywords=('simulation ' 'physics ' 'ode ' 'visualization ' ), install_requires=['climate', 'numpy', 'pyglet', 'Open-Dynamics-Engine'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Scientific/Engineering :: Physics', 'Topic :: Scientific/Engineering :: Visualization', ], )
Fix event source for S3 put events
import logging import urllib import sentry_sdk from cloudpathlib import AnyPath from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration from .config import Config from .main import get_all_unsubmitted_roots, process_file, setup_logging config = Config() setup_logging(config) sentry_sdk.init( dsn=config.reward_root_submitter_sentry_dsn, integrations=[ AwsLambdaIntegration(), ], environment=config.environment, traces_sample_rate=1.0, ) def handler(event, _context): if event.get("source") == "aws.events": logging.info("Cron event triggered") unsubmitted_roots = get_all_unsubmitted_roots(config) for index, row in unsubmitted_roots.iterrows(): process_file(row["file"], config) elif event["Records"][0]["eventSource"] == "aws:s3": bucket = event["Records"][0]["s3"]["bucket"]["name"] key = urllib.parse.unquote_plus( event["Records"][0]["s3"]["object"]["key"], encoding="utf-8" ) process_file(AnyPath(f"s3://{bucket}/{key}"), Config())
import logging import urllib import sentry_sdk from cloudpathlib import AnyPath from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration from .config import Config from .main import get_all_unsubmitted_roots, process_file, setup_logging config = Config() setup_logging(config) sentry_sdk.init( dsn=config.reward_root_submitter_sentry_dsn, integrations=[ AwsLambdaIntegration(), ], environment=config.environment, traces_sample_rate=1.0, ) def handler(event, _context): if event.get("source") == "aws.events": logging.info("Cron event triggered") unsubmitted_roots = get_all_unsubmitted_roots(config) for index, row in unsubmitted_roots.iterrows(): process_file(row["file"], config) elif event["Records"][0]["eventSource"] == "aws.s3": bucket = event["Records"][0]["s3"]["bucket"]["name"] key = urllib.parse.unquote_plus( event["Records"][0]["s3"]["object"]["key"], encoding="utf-8" ) process_file(AnyPath(f"s3://{bucket}/{key}"), Config())
Fix a typo in the test.
var vows = require('vows'), assert = require('assert'), events = require('events'), load = require('./load'), suite = vows.describe('brushModes'); function d3Parcoords() { var promise = new(events.EventEmitter); load(function(d3) { promise.emit('success', d3.parcoords()); }); return promise; } suite.addBatch({ 'd3.parcoords': { 'has by default': { topic: d3Parcoords(), 'three brush modes': function(pc) { assert.strictEqual(pc.brushModes().length, 3); }, 'the brush mode "None"': function(pc) { assert.notStrictEqual(pc.brushModes().indexOf("None"), -1); }, 'the brush mode "1D-axes"': function(pc) { assert.notStrictEqual(pc.brushModes().indexOf("1D-axes"), -1); }, 'the brush mode "2D-strums"': function(pc) { assert.notStrictEqual(pc.brushModes().indexOf("2D-strums"), -1); } }, } }); suite.export(module);
var vows = require('vows'), assert = require('assert'), events = require('events'), load = require('./load'), suite = vows.describe('brushModes'); function d3Parcoords() { var promise = new(events.EventEmitter); load(function(d3) { promise.emit('success', d3.parcoords()); }); return promise; } suite.addBatch({ 'd3.parcoords': { 'has by default': { topic: d3Parcoords(), 'three brush modes': function(pc) { assert.strictEqual(pc.brushModes().length, 3); }, 'the brush mode "None"': function(pc) { assert.notStrictEqual(pc.brushModes().indexOf("None"), -1); }, 'the brush mode "1D-Axes"': function(pc) { assert.notStrictEqual(pc.brushModes().indexOf("1D-Axis"), -1); }, 'the brush mode "2D-strums"': function(pc) { assert.notStrictEqual(pc.brushModes().indexOf("2D-strums"), -1); } }, } }); suite.export(module);
Change default server port from 8000 to 8888 (as suggested in tornado's documentation)
# coding: utf-8 import tornado.ioloop from forecast.manager import BaseCommand, Argument class RunserverCommand(BaseCommand): help_text = "Start a server" parameters = ( Argument("--port", "-p", action="store", default=8888, type=int), ) def run(self, project, args, unknown_args): print "Development server is running at http://127.0.0.1:%s/" % (args.port,) print "Quit the server with CONTROL-C." tornado_application = project.get_tornado_application() tornado_application.listen(args.port) try: tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: print "\nInterrupted!"
# coding: utf-8 import tornado.ioloop from forecast.manager import BaseCommand, Argument class RunserverCommand(BaseCommand): help_text = "Start a server" parameters = ( Argument("--port", "-p", action="store", default=8000, type=int), ) def run(self, project, args, unknown_args): print "Development server is running at http://127.0.0.1:%s/" % (args.port,) print "Quit the server with CONTROL-C." tornado_application = project.get_tornado_application() tornado_application.listen(args.port) try: tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: print "\nInterrupted!"
Revert "flake8: Ignore geoid.py issues" This reverts commit a70cea27c37c1ced21d51b950f49d4987f501385.
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.')
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] FLAKE8_EXCLUDES = [ 'geoid.py' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder, '--exclude=' + ','.join(FLAKE8_EXCLUDES)]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.')
Troubleshoot failing tests on Travis
const dotenv = require('dotenv'); dotenv.config(); module.exports = { development: { username: 'Newman', password: 'andela2017', database: 'postit-db-dev', host: '127.0.0.1', port: 5432, secret_key: process.env.SECRET_KEY, dialect: 'postgres' }, test: { // username: 'Newman', // password: 'andela2017', // database: 'postit-db-test', username: 'postgres', password: '', database: 'postit_db_test', host: '127.0.0.1', port: 5432, secret_key: process.env.SECRET_KEY, dialect: 'postgres' }, production: { use_env_variable: 'PROD_DB_URL', username: '?', password: '?', database: '?', host: '?', dialect: '?' } };
const dotenv = require('dotenv'); dotenv.config(); module.exports = { development: { username: 'Newman', password: 'andela2017', database: 'postit-db-dev', host: '127.0.0.1', port: 5432, secret_key: process.env.SECRET_KEY, dialect: 'postgres' }, test: { username: 'Newman', password: 'andela2017', database: 'postit-db-test', // username: 'postgres', // password: '', // database: 'postit_db_test', host: '127.0.0.1', port: 5432, secret_key: process.env.SECRET_KEY, dialect: 'postgres' }, production: { use_env_variable: 'PROD_DB_URL', username: '?', password: '?', database: '?', host: '?', dialect: '?' } };
Fix typo in JS Hello Client
// JS Hello Client Example /* jshint node: true */ "use strict"; var process = require("process"); var hello = require("hello").hello; // "http://hello.datawire.io/" is the URL of the simple "Hello" cloud // microservice run by Datawire, Inc. to serve as a simple first test. // // You can test completely locally, too: // - comment out the http://hello.datawire.io line // - uncomment the http://127.0.0.1:8910/hello line // - fire up the local version of the server by following the instructions // in the README.md. // var client = new hello.HelloClient("http://hello.datawire.io/"); // var client = new hello.HelloClient("http://localhost:8910/hello"); var request = new hello.Request(); if (process.argv[2]) { request.text = process.argv[2]; } else { request.text = "Hello from JavaScript!"; } console.log("Request says", request.text); var response = client.hello(request); function FutureListener(cb) { this.onFuture = cb; } response.onFinished( new FutureListener( // XXX: if this can become magic then the quark-js API can be idiomatic function(response) { if (response.getError() != null) { console.log("Response failed with", response.getError()); } else { console.log("Response says", response.result); } }));
// JS Hello Client Example /* jshint node: true */ "use strict"; var process = require("process"); var hello = require("hello").hello; // "http://hello.datawire.io/" is the URL of the simple "Hello" cloud // microservice run by Datawire, Inc. to serve as a simple first test. // // You can test completely locally, too: // - comment out the http://hello.datawire.io line // - uncomment the http://127.0.0.1:8910/hello line // - fire up the local version of the server by following the instructions // in the README.md. // var client = new hello.HelloClient("http://hello.datawire.io/"); // var client = new hello.HelloClient("http://localhost:8910/hello"); var request = new hello.Request(); if (process.argv[2]) { request.text = process.argv[2]; } else { request.test = "Hello from JavaScript!"; } console.log("Request says", request.text); var response = client.hello(request); function FutureListener(cb) { this.onFuture = cb; } response.onFinished( new FutureListener( // XXX: if this can become magic then the quark-js API can be idiomatic function(response) { if (response.getError() != null) { console.log("Response failed with", response.getError()); } else { console.log("Response says", response.result); } }));
Revert to v0.10 method of signature generation
package utility import ( "encoding/json" "github.com/bitspill/bitsig-go" "github.com/btcsuite/btcutil" ) var utilIsTestnet bool = false func SetTestnet(testnet bool) { utilIsTestnet = testnet } func Testnet() bool { return utilIsTestnet } func CheckAddress(address string) bool { var err error if utilIsTestnet { _, err = btcutil.DecodeAddress(address, &FloTestnetParams) } else { _, err = btcutil.DecodeAddress(address, &FloParams) } if err != nil { return false } return true } func CheckSignature(address string, signature string, message string) (bool, error) { if utilIsTestnet { return bitsig_go.CheckSignature(address, signature, message, "Florincoin", &FloTestnetParams) } return bitsig_go.CheckSignature(address, signature, message, "Florincoin", &FloParams) } // reference: Cory LaNou, Mar 2 '14 at 15:21, http://stackoverflow.com/a/22129435/2576956 func IsJSON(s string) bool { var js map[string]interface{} return json.Unmarshal([]byte(s), &js) == nil }
package utility import ( "encoding/json" "github.com/bitspill/bitsig-go" "github.com/btcsuite/btcutil" ) var utilIsTestnet bool = false func SetTestnet(testnet bool) { utilIsTestnet = testnet } func Testnet() bool { return utilIsTestnet } func CheckAddress(address string) bool { var err error if utilIsTestnet { _, err = btcutil.DecodeAddress(address, &FloTestnetParams) } else { _, err = btcutil.DecodeAddress(address, &FloParams) } if err != nil { return false } return true } func CheckSignature(address string, signature string, message string) (bool, error) { if utilIsTestnet { return bitsig_go.CheckSignature(address, signature, message, "FLO", &FloTestnetParams) } return bitsig_go.CheckSignature(address, signature, message, "FLO", &FloParams) } // reference: Cory LaNou, Mar 2 '14 at 15:21, http://stackoverflow.com/a/22129435/2576956 func IsJSON(s string) bool { var js map[string]interface{} return json.Unmarshal([]byte(s), &js) == nil }
Fix logout state name in actions
import { LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_SUCCESS, LOGOUT_FAILURE } from '../constants/actions/Auth'; const fakeUser = { username: 'demo', token: 'ojn2jr3wrefj' }; export function login(username, password) { return async (dispatch) => { try { if (username !== 'demo' && password !== 'demo') { throw new Error('Bad credentials'); } dispatch({ type: LOGIN_SUCCESS, result: fakeUser }); } catch (error) { dispatch({ type: LOGIN_FAILURE, error: error.message }); } }; } export function logout() { return async (dispatch) => { try { dispatch({ type: LOGOUT_SUCCESS }); } catch (error) { dispatch({ type: LOGOUT_FAILURE, error: error.message }); } }; }
import { LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_SUCCESS, LOGOUT_FAILURE } from '../constants/actions/Auth'; const fakeUser = { username: 'demo', token: 'ojn2jr3wrefj' }; export function login(username, password) { return async (dispatch) => { try { if (username !== 'demo' && password !== 'demo') { throw new Error('Bad credentials'); } dispatch({ type: LOGIN_SUCCESS, result: fakeUser }); } catch (error) { dispatch({ type: LOGIN_FAILURE, error: error.message }); } }; } export function logout() { return async (dispatch) => { try { dispatch({ type: LOGIN_SUCCESS }); } catch (error) { dispatch({ type: LOGOUT_FAILURE, error: error.message }); } }; }
Set max players to total amount of members in server
const Core = require('./core'); class Discord extends Core { constructor() { super(); this.dnsResolver = { resolve: function(address) {return {address: address} } }; } async run(state) { this.usedTcp = true; const raw = await this.request({ uri: 'https://discordapp.com/api/guilds/' + this.options.address + '/widget.json', }); const json = JSON.parse(raw); state.name = json.name; if (json.instant_invite) { state.connect = json.instant_invite; } else { state.connect = 'https://discordapp.com/channels/' + this.options.address } state.players = json.members.map(v => { return { name: v.username + '#' + v.discriminator, username: v.username, discriminator: v.discriminator, team: v.status } }); state.maxplayers = json.presence_count; state.raw = json; } } module.exports = Discord;
const Core = require('./core'); class Discord extends Core { constructor() { super(); this.dnsResolver = { resolve: function(address) {return {address: address} } }; } async run(state) { this.usedTcp = true; const raw = await this.request({ uri: 'https://discordapp.com/api/guilds/' + this.options.address + '/widget.json', }); const json = JSON.parse(raw); state.name = json.name; if (json.instant_invite) { state.connect = json.instant_invite; } else { state.connect = 'https://discordapp.com/channels/' + this.options.address } state.players = json.members.map(v => { return { name: v.username + '#' + v.discriminator, username: v.username, discriminator: v.discriminator, team: v.status } }); state.raw = json; } } module.exports = Discord;
Fix message with 462 numeric
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
Add a comment to py3 byte string decode.
from django.contrib import auth from django.contrib.auth.middleware import AuthenticationMiddleware import base64 class AutologinAuthenticationMiddleware(AuthenticationMiddleware): def process_request(self, request): if 'autologin' not in request.COOKIES: return if request.COOKIES['autologin'] == '': auth.logout(request) return autologin_cookie_value = base64.b64decode(request.COOKIES['autologin']) # Py3 uses a bytes string here, so we need to decode to utf-8 autologin_cookie_value = autologin_cookie_value.decode('utf-8') username = autologin_cookie_value.split(':')[0] password = autologin_cookie_value.split(':')[1] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user)
from django.contrib import auth from django.contrib.auth.middleware import AuthenticationMiddleware import base64 class AutologinAuthenticationMiddleware(AuthenticationMiddleware): def process_request(self, request): if 'autologin' not in request.COOKIES: return if request.COOKIES['autologin'] == '': auth.logout(request) return autologin_cookie_value = base64.b64decode(request.COOKIES['autologin']) autologin_cookie_value = autologin_cookie_value.decode('utf8') username = autologin_cookie_value.split(':')[0] password = autologin_cookie_value.split(':')[1] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user)
Use the URL to get the stream, not the class loader. Should not have made a different, but it does.
/* * Copyright 2015, Imtech Traffic & Infra * Copyright 2015, aVineas IT Consulting * * 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 osgi.extender.resource.impl; import java.io.InputStream; import java.net.URL; import org.osgi.framework.Bundle; import osgi.extender.resource.BundleResource; /** * Our own implementation of a bundle resource. Simple wrapping. */ class OurBundleResource implements BundleResource { private Bundle bundle; private String path; OurBundleResource(Bundle bundle, String path) { this.bundle = bundle; this.path = path; } @Override public URL getURL() { return bundle.getEntry(path); } @Override public InputStream getInputStream() { try { return getURL().openStream(); } catch (Exception exc) { exc.printStackTrace(); } return null; } }
/* * Copyright 2015, Imtech Traffic & Infra * Copyright 2015, aVineas IT Consulting * * 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 osgi.extender.resource.impl; import java.io.InputStream; import java.net.URL; import org.osgi.framework.Bundle; import org.osgi.framework.wiring.BundleWiring; import osgi.extender.resource.BundleResource; /** * Our own implementation of a bundle resource. Simple wrapping. */ class OurBundleResource implements BundleResource { private Bundle bundle; private String path; OurBundleResource(Bundle bundle, String path) { this.bundle = bundle; this.path = path; } @Override public URL getURL() { return bundle.getEntry(path); } @Override public InputStream getInputStream() { return bundle.adapt(BundleWiring.class).getClassLoader().getResourceAsStream(path); } }
Fix cannot add a column with non-constant default With newer versions of sqlite tests are failing on sqlite3.OperationalError : Cannot add a column with non-constant default. In SQL queries is boolean without apostrophes which causes sqlite3 error. This fix is solving this issue by replacing text('false') to expression.false() from sqlalchemy.sql which is working correct. Change-Id: Ia96255a2a61994a18b21acc235931ad03a8501ea Closes-Bug: #1773123
# Copyright (c) 2016 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Boolean, Column, MetaData, String, Table from sqlalchemy.sql import expression def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, server_default=expression.false()) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id)
# Copyright (c) 2016 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Boolean, Column, MetaData, String, Table, text def upgrade(migrate_engine): """Add replication info to clusters table.""" meta = MetaData() meta.bind = migrate_engine clusters = Table('clusters', meta, autoload=True) replication_status = Column('replication_status', String(length=36), default="not-capable") active_backend_id = Column('active_backend_id', String(length=255)) frozen = Column('frozen', Boolean, nullable=False, default=False, server_default=text('false')) clusters.create_column(replication_status) clusters.create_column(frozen) clusters.create_column(active_backend_id)
Remove extra setup() from rebase.
#!/usr/bin/env python import os import sys import six if six.PY2: import unittest2 as unittest else: import unittest def main(): # Configure python path parent = os.path.dirname(os.path.abspath(__file__)) if not parent in sys.path: sys.path.insert(0, parent) # Discover tests os.environ['DJANGO_SETTINGS_MODULE'] = 'djedi.tests.settings' unittest.defaultTestLoader.discover('djedi') # Run tests import django if hasattr(django, 'setup'): django.setup() if django.VERSION < (1,7): from django.test.simple import DjangoTestSuiteRunner as TestRunner else: from django.test.runner import DiscoverRunner as TestRunner runner = TestRunner(verbosity=1, interactive=True, failfast=False) exit_code = runner.run_tests(['djedi']) sys.exit(exit_code) if __name__ == '__main__': main()
#!/usr/bin/env python import os import sys import six if six.PY2: import unittest2 as unittest else: import unittest def main(): # Configure python path parent = os.path.dirname(os.path.abspath(__file__)) if not parent in sys.path: sys.path.insert(0, parent) # Discover tests os.environ['DJANGO_SETTINGS_MODULE'] = 'djedi.tests.settings' unittest.defaultTestLoader.discover('djedi') import django if hasattr(django, "setup"): django.setup() # Run tests import django if hasattr(django, 'setup'): django.setup() if django.VERSION < (1,7): from django.test.simple import DjangoTestSuiteRunner as TestRunner else: from django.test.runner import DiscoverRunner as TestRunner runner = TestRunner(verbosity=1, interactive=True, failfast=False) exit_code = runner.run_tests(['djedi']) sys.exit(exit_code) if __name__ == '__main__': main()
Add the announced global schema
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Superhero Schema */ 'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Superhero Schema */ var SuperheroSchema = new Schema({ name: { type: String, default: '', required: 'Please fill in the applicant&rsquo;s name', trim: true }, gpa: { type: Number, default: -1 }, fe: { type: Number, default: -1 }, gmat: { type: Number, default: -1 }, gre: { type: Number, default: -1 }, ielts: { type: Number, default: -1 }, melab: { type: Number, default: -1 }, toefl: { type: Number, default: -1 }, tse: { type: Number, default: -1 }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Superhero', SuperheroSchema);
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Superhero Schema */ var SuperheroSchema = new Schema({ name: { type: String, default: '', required: 'Please fill in the applicant&rsquo;s name', trim: true }, gpa: { type: Number, default: -1 }, fe: { type: Number, default: -1 }, gmat: { type: Number, default: -1 }, gre: { type: Number, default: -1 }, ielts: { type: Number, default: -1 }, melab: { type: Number, default: -1 }, toefl: { type: Number, default: -1 }, tse: { type: Number, default: -1 }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Superhero', SuperheroSchema);
Remove UTC from time util<Manohar/Shruthi>
package org.motechproject.server.pillreminder.util; import org.joda.time.DateTime; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Util { public static DateTime currentDateTime() { return new DateTime(); } public static Date newDate(int year, int month, int day) { Calendar cal = Calendar.getInstance(); cal.set(year, month, day); return cal.getTime(); } public static boolean areDatesSame(Date date1, Date date2) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd"); return dateFormat.format(date1).equals(dateFormat.format(date2)); } public static Date getDateAfter(Date date, int numOfMonth) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, numOfMonth); return cal.getTime(); } }
package org.motechproject.server.pillreminder.util; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Util { public static DateTime currentDateTime() { return new DateTime(DateTimeZone.UTC); } public static Date newDate(int year, int month, int day) { Calendar cal = Calendar.getInstance(); cal.set(year, month, day); return cal.getTime(); } public static boolean areDatesSame(Date date1, Date date2) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd"); return dateFormat.format(date1).equals(dateFormat.format(date2)); } public static Date getDateAfter(Date date, int numOfMonth) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, numOfMonth); return cal.getTime(); } }
Fix direct exporting of imports
export { default as Store } from './store'; //Export types export { default as union } from './types/union'; export { default as Any } from './types/any'; export { default as Nil } from './types/nil'; export { default as reference } from './types/reference'; export { default as ObjectId } from './types/object-id'; export { default as collection } from './types/collection'; export { default as collections } from './types/collections'; export { default as model } from './types/model'; //Export modifiers export { default as optional } from './modifiers/optional'; export { default as validate } from './modifiers/validate'; export { default as bare } from './modifiers/bare'; export { default as reducer } from './modifiers/reducer'; export { default as autoResolve } from './modifiers/auto-resolve'; export { default as dog } from './modifiers/optional'; //Export generic type parser export { default as type } from './parse/type';
import _Store from './store'; export const Store = _Store; //Export types import _union from './types/union'; import _Any from './types/any'; import _Nil from './types/nil'; import _reference from './types/reference'; import _ObjectId from './types/object-id'; import _collection from './types/collection'; import _collections from './types/collections'; import _model from './types/model'; export const union = _union; export const Any = _Any; export const Nil = _Nil; export const reference = _reference; export const ObjectId = _ObjectId; export const collection = _collection; export const collections = _collections; export const model = _model; //Export modifiers import _optional from './modifiers/optional'; import _validate from './modifiers/validate'; import _bare from './modifiers/bare'; import _reducer from './modifiers/reducer'; import _autoResolve from './modifiers/auto-resolve'; export const optional = _optional; export const validate = _validate; export const bare = _bare; export const reducer = _reducer; export const autoResolve = _autoResolve; //Export generic type parser import _type from './parse/type'; export const type = _type;
Remove the only remaining reference to `u'` string prefix
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.abspath(os.getcwd())) extensions = ['powerline_autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] source_suffix = '.rst' master_doc = 'index' project = 'Powerline' version = 'beta' release = 'beta' exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = 'default' html_static_path = ['_static'] html_show_copyright = False on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except ImportError: pass
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.abspath(os.getcwd())) extensions = ['powerline_autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] source_suffix = '.rst' master_doc = 'index' project = u'Powerline' version = 'beta' release = 'beta' exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = 'default' html_static_path = ['_static'] html_show_copyright = False on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except ImportError: pass
Handle businessUnitId parameter in webhook
module.exports = (slackapp) => { slackapp.webserver.post('/incoming-webhooks/:teamId', (req, res) => { const events = req.body.events; if (!events) { slackapp.log('Bad incoming webhook request', req); res.sendStatus(400); } else { const { params: { teamId }, query: { businessUnitId } } = req; events.filter((e) => { return e.eventName === 'service-review-created'; }).forEach((e) => { e.eventData.consumer.displayName = e.eventData.consumer.name; // Massaging into expected format slackapp.log(`Posting new review for team ${teamId}, business unit ${businessUnitId}`); slackapp.trigger('trustpilot_review_received', [e.eventData, teamId, businessUnitId]); }); res.sendStatus(200); } }); };
module.exports = (slackapp) => { slackapp.webserver.post('/incoming-webhooks/:teamId', (req, res) => { const events = req.body.events; if (!events) { slackapp.log('Bad incoming webhook request', req); res.sendStatus(400); } else { events.filter((e) => { return e.eventName === 'service-review-created'; }).forEach((e) => { e.eventData.consumer.displayName = e.eventData.consumer.name; // Massaging into expected format slackapp.log('Posting new review for team', req.params.teamId); slackapp.trigger('trustpilot_review_received', [e.eventData, req.params.teamId]); }); res.sendStatus(200); } }); };
Use historical model in migration, not directly imported model
# Generated by Django 2.2.24 on 2021-06-10 09:13 from django.db import migrations from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor): SQLTurnWhatsAppBackend = apps.get_model('sms', 'SQLTurnWhatsAppBackend') for backend in SQLTurnWhatsAppBackend.objects.all(): # Check for backend.deleted to account for active_objects if not backend.deleted: domain = backend.domain TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN) def noop(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('sms', '0048_delete_sqlicdsbackend'), ] operations = [ migrations.RunPython(auto_enable_turnio_ff_for_certain_domains, reverse_code=noop), ]
# Generated by Django 2.2.24 on 2021-06-10 09:13 from django.db import migrations from corehq.messaging.smsbackends.turn.models import SQLTurnWhatsAppBackend from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor): for backend in SQLTurnWhatsAppBackend.active_objects.all(): domain = backend.domain TURN_IO_BACKEND.set(item=domain, enabled=True, namespace=NAMESPACE_DOMAIN) def noop(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('sms', '0048_delete_sqlicdsbackend'), ] operations = [ migrations.RunPython(auto_enable_turnio_ff_for_certain_domains, reverse_code=noop), ]
Fix Mbean interface must be public, fails validation on JDK8
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.sar.injection.pojos; /** * @author <a href="mailto:opalka.richard@gmail.com">Richard Opalka</a> */ public interface AMBean { int getCount(); boolean getStartCalled(); boolean getCreateCalled(); }
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.sar.injection.pojos; /** * @author <a href="mailto:opalka.richard@gmail.com">Richard Opalka</a> */ interface AMBean { int getCount(); boolean getStartCalled(); boolean getCreateCalled(); }
Use inline flags with local scope.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker'] master_doc = "index" link_files = { '../CHANGES.rst': dict( using=dict(GH='https://github.com'), replace=[ dict( pattern=r'(Issue #|\B#)(?P<issue>\d+)', url='{package_url}/issues/{issue}', ), dict( pattern=r'(?m:^((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n)', with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n', ), dict( pattern=r'PEP[- ](?P<pep_number>\d+)', url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/', ), ], ) }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker'] master_doc = "index" link_files = { '../CHANGES.rst': dict( using=dict(GH='https://github.com'), replace=[ dict( pattern=r'(Issue #|\B#)(?P<issue>\d+)', url='{package_url}/issues/{issue}', ), dict( pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n', with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n', ), dict( pattern=r'PEP[- ](?P<pep_number>\d+)', url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/', ), ], ) }
FIX Rename board hit /api
import { CLEAN_STATE, GET_ALL_LISTS_IN_BOARD, GET_ONE_BOARD, SAVE_BOARD_TITLE } from './constants' export const cleanState = () => (dispatch) => { dispatch({ type: CLEAN_STATE, }) } export const getAllListsInBoard = boardId => (dispatch) => { dispatch({ type: GET_ALL_LISTS_IN_BOARD, payload: { request: { method: 'GET', url: `/api/boards/${boardId}/lists`, }, }, }) } export const getOneBoard = boardId => (dispatch) => { dispatch({ type: GET_ONE_BOARD, payload: { request: { method: 'GET', url: `/api/boards/${boardId}`, }, }, }) } export const saveBoardTitle = (boardId, boardTitle) => (dispatch) => { dispatch({ type: SAVE_BOARD_TITLE, payload: { request: { method: 'PUT', url: `/api/boards/${boardId}`, data: { title: boardTitle, }, }, }, }) }
import { CLEAN_STATE, GET_ALL_LISTS_IN_BOARD, GET_ONE_BOARD, SAVE_BOARD_TITLE } from './constants' export const cleanState = () => (dispatch) => { dispatch({ type: CLEAN_STATE, }) } export const getAllListsInBoard = boardId => (dispatch) => { dispatch({ type: GET_ALL_LISTS_IN_BOARD, payload: { request: { method: 'GET', url: `/api/boards/${boardId}/lists`, }, }, }) } export const getOneBoard = boardId => (dispatch) => { dispatch({ type: GET_ONE_BOARD, payload: { request: { method: 'GET', url: `/api/boards/${boardId}`, }, }, }) } export const saveBoardTitle = (boardId, boardTitle) => (dispatch) => { dispatch({ type: SAVE_BOARD_TITLE, payload: { request: { method: 'PUT', url: `/boards/${boardId}`, data: { title: boardTitle, }, }, }, }) }
Add missing checking rules of activity time
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SettingController extends Controller { /** * @return \Illuminate\Http\Response */ public function edit() { return view('setting.edit'); } /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function update(Request $request) { $this->validate($request, [ 'start_at' => 'required|date|before:end_at', 'end_at' => 'required|date|after:start_at', 'target' => 'required|integer|min:0', ]); \Setting::set('start_at', $request->get('start_at')); \Setting::set('end_at', $request->get('end_at')); \Setting::set('target', $request->get('target')); \Setting::save(); return redirect()->route('setting.edit')->with('global', '設定已更新'); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SettingController extends Controller { /** * @return \Illuminate\Http\Response */ public function edit() { return view('setting.edit'); } /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function update(Request $request) { $this->validate($request, [ 'start_at' => 'required|date', 'end_at' => 'required|date', 'target' => 'required|integer|min:0', ]); \Setting::set('start_at', $request->get('start_at')); \Setting::set('end_at', $request->get('end_at')); \Setting::set('target', $request->get('target')); \Setting::save(); return redirect()->route('setting.edit')->with('global', '設定已更新'); } }
Add integration tests to standard `grunt test`
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), nodeunit: { unit: ['test/unit/test*.js'], integration: ['test/integration/test*.js'] }, release: { options: { file: 'package.json', tagName: '<%= version %>', //default: '<%= version %>' commitMessage: 'Release <%= version %>', //default: 'release <%= version %>' tagMessage: 'Tag version <%= version %>' //default: 'Version <%= version %>' } } }); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-release-steps'); grunt.registerTask('-to-npm', ['release:npm']); grunt.registerTask('-to-git', ['release:add:commit:push']); grunt.registerTask('-tag', ['release:tag:pushTags']); 'patch minor major'.split(' ').forEach(function (type) { grunt.registerTask(type, ['test', 'release:bump:' + type, '-tag', '-to-git', '-to-npm']); }); grunt.registerTask('default', ['patch']); grunt.registerTask('test', ['nodeunit:unit', 'nodeunit:integration']); };
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), nodeunit: { unit: ['test/unit/test*.js'], integration: ['test/integration/test*.js'] }, release: { options: { file: 'package.json', tagName: '<%= version %>', //default: '<%= version %>' commitMessage: 'Release <%= version %>', //default: 'release <%= version %>' tagMessage: 'Tag version <%= version %>' //default: 'Version <%= version %>' } } }); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-release-steps'); grunt.registerTask('-to-npm', ['release:npm']); grunt.registerTask('-to-git', ['release:add:commit:push']); grunt.registerTask('-tag', ['release:tag:pushTags']); 'patch minor major'.split(' ').forEach(function (type) { grunt.registerTask(type, ['test', 'release:bump:' + type, '-tag', '-to-git', '-to-npm']); }); grunt.registerTask('default', ['patch']); grunt.registerTask('test', ['nodeunit:unit']); };
Adjust nav to new recommended layout. This removes "Intro", which is actually no longer the recommended get-started place (Learn takes that spot). Additionally, there is now a separator between the high level business value stuff, and the low level developer stuff.
export default [ { text: 'Overview', url: '/', type: 'inbound' }, { text: 'Use Cases', submenu: [ { text: 'Service Discovery', url: '/discovery' }, { text: 'Service Mesh', url: '/mesh' }, ], }, { text: 'Enterprise', url: 'https://www.hashicorp.com/products/consul/?utm_source=oss&utm_medium=header-nav&utm_campaign=consul', type: 'outbound', }, 'divider', { text: 'Learn', url: 'https://learn.hashicorp.com/consul', type: 'outbound', }, { text: 'Docs', url: '/docs', type: 'inbound', }, { text: 'API', url: '/api-docs', type: 'inbound', }, { text: 'Community', url: '/community', type: 'inbound', }, ]
export default [ { text: 'Use Cases', submenu: [ { text: 'Service Discovery', url: '/discovery' }, { text: 'Service Mesh', url: '/mesh' }, ], }, { text: 'Intro', url: '/intro', type: 'inbound', }, { text: 'Learn', url: 'https://learn.hashicorp.com/consul', type: 'outbound', }, { text: 'Docs', url: '/docs', type: 'inbound', }, { text: 'API', url: '/api-docs', type: 'inbound', }, { text: 'Community', url: '/community', type: 'inbound', }, { text: 'Enterprise', url: 'https://www.hashicorp.com/products/consul/?utm_source=oss&utm_medium=header-nav&utm_campaign=consul', type: 'outbound', }, ]
Use `defineConstants` in webpack2 e2e test like in the webpack 1.x one
const webpack2 = require('../../index') // Need to write it like this instead of destructuring so it runs on Node 4.x w/o transpiling const createConfig = webpack2.createConfig const defineConstants = webpack2.defineConstants const entryPoint = webpack2.entryPoint const performance = webpack2.performance const setOutput = webpack2.setOutput const babel = require('@webpack-blocks/babel6') const postcss = require('@webpack-blocks/postcss') const extractText = require('@webpack-blocks/extract-text2') const path = require('path') const precss = require('precss') module.exports = createConfig([ entryPoint( path.join(__dirname, 'app.js') ), setOutput( path.join(__dirname, 'build/bundle.js') ), babel(), postcss([ precss ]), extractText( path.join('styles.css') ), performance({ maxAssetSize: 100000, maxEntrypointSize: 500000, hints: 'error' }), defineConstants({ 'process.env.TEST': 'This is the injected process.env.TEST!' }) ])
const webpack2 = require('../../index') // Need to write it like this instead of destructuring so it runs on Node 4.x w/o transpiling const addPlugins = webpack2.addPlugins const createConfig = webpack2.createConfig const entryPoint = webpack2.entryPoint const performance = webpack2.performance const setOutput = webpack2.setOutput const webpack = webpack2.webpack const babel = require('@webpack-blocks/babel6') const postcss = require('@webpack-blocks/postcss') const extractText = require('@webpack-blocks/extract-text2') const path = require('path') const precss = require('precss') module.exports = createConfig([ entryPoint( path.join(__dirname, 'app.js') ), setOutput( path.join(__dirname, 'build/bundle.js') ), babel(), postcss([ precss ]), extractText( path.join('styles.css') ), performance({ maxAssetSize: 100000, maxEntrypointSize: 500000, hints: 'error' }), addPlugins([ new webpack.DefinePlugin({ 'process.env': { TEST: '"This is the injected process.env.TEST!"' } }) ]) ])
Return the agent id and the skill id
'use strict'; /** * * @param data the result that came out from the history api getting recently (last 10) consumers conversations */ function getAgentDataForBestConversationMCS (data) { let conversations = data.conversationHistoryRecords; let mcsArr = []; conversations.forEach((conversation) => { if (conversation && conversation.info && conversation.info.mcs) { mcsArr.push( { 'mcs': conversation.info.mcs, 'agentId': conversation.info.latestAgentId, 'skillId': conversation.info.latestSkillId }); } }); mcsArr.sort((a, b) => a.mcs - b.mcs); return mcsArr && mcsArr.length > 0 && mcsArr.pop(); } module.exports = { getAgentDataForBestConversationMCS };
'use strict'; /** * * @param data the result that came out from the history api getting recently (last 10) consumers conversations */ function getAgentIdForBestConversationMCS (data) { let conversations = data.conversationHistoryRecords; let mcsArr = []; conversations.forEach((conversation) => { if (conversation && conversation.info && conversation.info.mcs) { mcsArr.push( { "mcs": conversation.info.mcs, "agentId": conversation.info.latestAgentId }); } }); mcsArr.sort((a, b) => a.mcs - b.mcs); return mcsArr && mcsArr.length > 0 && mcsArr.pop().agentId; } module.exports = { getAgentIdForBestConversationMCS };
Use .string so we keep within BS parse tree
import markgen from bs4 import BeautifulSoup TAGS = { 'p': 'paragraph', 'div': 'paragraph', 'a': 'link', 'strong': 'emphasis', 'em': 'emphasis', 'b': 'emphasis', 'i': 'emphasis', 'u': 'emphasis', 'img': 'image', 'image': 'image', 'blockquote': 'quote', 'pre': 'pre', 'code': 'pre', 'h1': 'header', 'h2': 'header', 'h3': 'header', 'h4': 'header', 'h5': 'header', 'h6': 'header', 'ul': 'ulist', 'ol': 'olist' } def markup_to_markdown(content): soup = BeautifulSoup(content) # Account for HTML snippets and full documents alike contents = soup.body.contents if soup.body is not None else soup.contents return _iterate_over_contents(contents) def _iterate_over_contents(contents): out = u'' for c in contents: if hasattr(c, 'contents'): c.string = _iterate_over_contents(c.contents) if c.name in TAGS: wrap = getattr(markgen, TAGS[c.name]) c = wrap(c.string) out += u"\n{0}".format(c) return out
import markgen from bs4 import BeautifulSoup TAGS = { 'p': 'paragraph', 'div': 'paragraph', 'a': 'link', 'strong': 'emphasis', 'em': 'emphasis', 'b': 'emphasis', 'i': 'emphasis', 'u': 'emphasis', 'img': 'image', 'image': 'image', 'blockquote': 'quote', 'pre': 'pre', 'code': 'pre', 'h1': 'header', 'h2': 'header', 'h3': 'header', 'h4': 'header', 'h5': 'header', 'h6': 'header', 'ul': 'ulist', 'ol': 'olist' } def markup_to_markdown(content): soup = BeautifulSoup(content) # Account for HTML snippets and full documents alike contents = soup.body.contents if soup.body is not None else soup.contents return _iterate_over_contents(contents) def _iterate_over_contents(contents): out = u'' for c in contents: if hasattr(c, 'contents'): c = _iterate_over_contents(c.contents) if c.name in TAGS: wrap = getattr(markgen, TAGS[c.name]) c = wrap(c) out += u"\n{0}".format(c) return out
FIX session are now remembered for 120 days
<?php // Keep session data for 120 days, unless explicit destroy in code ini_set('session.gc_maxlifetime', 1 * 60 * 60 * 24 * 120); // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), get_include_path(), ))); /** Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $application->bootstrap(); // we only run the application if this file were NOT included (otherwise, the file was included to access misc functions) if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) { $application->run(); } ?>
<?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), get_include_path(), ))); /** Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $application->bootstrap(); // we only run the application if this file were NOT included (otherwise, the file was included to access misc functions) if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) { $application->run(); } ?>
Fix wrong use of loop variables
package core import "github.com/tisp-lang/tisp/src/lib/systemt" type functionType struct { signature Signature function func(...*Thunk) Value } func (f functionType) call(args Arguments) Value { ts, err := f.signature.Bind(args) if err != nil { return err } return f.function(ts...) } // NewLazyFunction creates a function whose arguments are evaluated lazily. func NewLazyFunction(s Signature, f func(...*Thunk) Value) *Thunk { return Normal(functionType{ signature: s, function: f, }) } // NewStrictFunction creates a function whose arguments are evaluated strictly. func NewStrictFunction(s Signature, f func(...*Thunk) Value) *Thunk { return NewLazyFunction(s, func(ts ...*Thunk) Value { for _, t := range ts { tt := t systemt.Daemonize(func() { tt.Eval() }) } return f(ts...) }) } func (f functionType) string() Value { return StringType("<function>") }
package core import "github.com/tisp-lang/tisp/src/lib/systemt" type functionType struct { signature Signature function func(...*Thunk) Value } func (f functionType) call(args Arguments) Value { ts, err := f.signature.Bind(args) if err != nil { return err } return f.function(ts...) } // NewLazyFunction creates a function whose arguments are evaluated lazily. func NewLazyFunction(s Signature, f func(...*Thunk) Value) *Thunk { return Normal(functionType{ signature: s, function: f, }) } // NewStrictFunction creates a function whose arguments are evaluated strictly. func NewStrictFunction(s Signature, f func(...*Thunk) Value) *Thunk { return NewLazyFunction(s, func(ts ...*Thunk) Value { for _, t := range ts { systemt.Daemonize(func() { t.Eval() }) } return f(ts...) }) } func (f functionType) string() Value { return StringType("<function>") }
Change implementation of store url in session
<?php /** * @link https://github.com/nezhelskoy/yii2-return-url * @copyright Copyright (c) 2014 Dmitry Nezhelskoy * @license "BSD-3-Clause" */ namespace nezhelskoy\returnUrl; use Yii; use yii\base\ActionFilter; use yii\helpers\Url; /** * ReturnUrl filter * * Keep current URL (if it's not an AJAX url) in session so that the browser may * be redirected back. * * @author Dmitry Nezhelskoy <dmitry@nezhelskoy.ru> */ class ReturnUrl extends ActionFilter { public $visitedParam = 'visitedUrl'; /** * This method is invoked right after an action is executed. * You may override this method to do some postprocessing for the action. * @param Action $action the action just executed. * @param mixed $result the action execution result * @return mixed the processed action result. */ public function afterAction($action, $result) { if ( ! Yii::$app->request->getIsAjax()) { Url::remember(Yii::$app->request->getUrl(), $this->visitedParam); } return $result; } }
<?php /** * @link https://github.com/nezhelskoy/yii2-return-url * @copyright Copyright (c) 2014 Dmitry Nezhelskoy * @license "BSD-3-Clause" */ namespace nezhelskoy\returnUrl; use Yii; use yii\base\ActionFilter; /** * ReturnUrl filter * * Keep current URL (if it's not an AJAX url) in session so that the browser may * be redirected back. * * @author Dmitry Nezhelskoy <dmitry@nezhelskoy.ru> */ class ReturnUrl extends ActionFilter { /** * This method is invoked right after an action is executed. * You may override this method to do some postprocessing for the action. * @param Action $action the action just executed. * @param mixed $result the action execution result * @return mixed the processed action result. */ public function afterAction($action, $result) { if ( ! Yii::$app->request->getIsAjax()) { Yii::$app->user->setReturnUrl(Yii::$app->request->getUrl()); } return $result; } }
Update URLs on success page
<?php class Ebanx_Gateway_Block_Checkout_Success_CashPayment extends Ebanx_Gateway_Block_Checkout_Success_Payment { protected $_order; protected function _construct() { parent::_construct(); } public function getEbanxPaymentHash() { return $this->getOrder()->getPayment()->getEbanxPaymentHash(); } public function getEbanxDueDate() { return Mage::helper('core')->formatDate($this->getOrder()->getPayment()->getEbanxDueDate(), Mage_Core_Model_Locale::FORMAT_TYPE_FULL, false); } public function getEbanxUrl() { return Mage::getSingleton('ebanx/api')->getEbanxUrl(); } public function getEbanxUrlIframe() { return $this->getEbanxUrl() . '?hash=' . $this->getEbanxPaymentHash(); } public function getEbanxUrlPdf() { return $this->getEbanxUrlIframe() . '&format=pdf'; } public function getEbanxUrlPrint() { return $this->getEbanxUrlIframe() . '&format=print'; } }
<?php class Ebanx_Gateway_Block_Checkout_Success_CashPayment extends Ebanx_Gateway_Block_Checkout_Success_Payment { protected $_order; protected function _construct() { parent::_construct(); } public function getEbanxPaymentHash() { return $this->getOrder()->getPayment()->getEbanxPaymentHash(); } public function getEbanxDueDate() { return Mage::helper('core')->formatDate($this->getOrder()->getPayment()->getEbanxDueDate(), Mage_Core_Model_Locale::FORMAT_TYPE_FULL, false); } public function getEbanxUrl() { return Mage::getSingleton('ebanx/api')->getEbanxUrl() . '?hash=' . self::getEbanxPaymentHash(); } public function getEbanxUrlPdf() { return self::getEbanxUrl() . '&format=pdf'; } }
Disable secp256k1 tests on hhvm
<?php namespace BitWasp\Bitcoin\Tests; use BitWasp\Bitcoin\Bitcoin; use BitWasp\Bitcoin\Crypto\EcAdapter\PhpEcc; use BitWasp\Bitcoin\Crypto\EcAdapter\Secp256k1; class AbstractTestCase extends \PHPUnit_Framework_TestCase { /** * @return array */ public function getEcAdapters() { $math = Bitcoin::getMath(); $generator = Bitcoin::getGenerator(); $adapters = array( [new PhpEcc($math, $generator)] ); if (!defined('HHVM_VERSION') && extension_loaded('secp256k1')) { $adapters[] = [new Secp256k1($math, $generator)]; } return $adapters; } }
<?php namespace BitWasp\Bitcoin\Tests; use BitWasp\Bitcoin\Bitcoin; use BitWasp\Bitcoin\Crypto\EcAdapter\PhpEcc; use BitWasp\Bitcoin\Crypto\EcAdapter\Secp256k1; class AbstractTestCase extends \PHPUnit_Framework_TestCase { /** * @return array */ public function getEcAdapters() { $math = Bitcoin::getMath(); $generator = Bitcoin::getGenerator(); $adapters = array( [new PhpEcc($math, $generator)] ); if (extension_loaded('secp256k1')) { $adapters[] = [new Secp256k1($math, $generator)]; } return $adapters; } }
Add Python 3.9 to the list of supported versions.
from setuptools import setup long_description = open('README.rst').read() setup( name="celery-redbeat", description="A Celery Beat Scheduler using Redis for persistent storage", long_description=long_description, version="2.0.0", url="https://github.com/sibson/redbeat", license="Apache License, Version 2.0", author="Marc Sibson", author_email="sibson+redbeat@gmail.com", keywords="python celery beat redis".split(), packages=["redbeat"], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Topic :: System :: Distributed Computing', 'Topic :: Software Development :: Object Brokering', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: Implementation :: CPython', 'Operating System :: OS Independent', ], install_requires=['redis>=3.2', 'celery>=4.2', 'python-dateutil', 'tenacity'], tests_require=['pytest'], )
from setuptools import setup long_description = open('README.rst').read() setup( name="celery-redbeat", description="A Celery Beat Scheduler using Redis for persistent storage", long_description=long_description, version="2.0.0", url="https://github.com/sibson/redbeat", license="Apache License, Version 2.0", author="Marc Sibson", author_email="sibson+redbeat@gmail.com", keywords="python celery beat redis".split(), packages=["redbeat"], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Topic :: System :: Distributed Computing', 'Topic :: Software Development :: Object Brokering', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Operating System :: OS Independent', ], install_requires=['redis>=3.2', 'celery>=4.2', 'python-dateutil', 'tenacity'], tests_require=['pytest'], )
Move fully qualified class name to a use statement
<?php namespace Joindin\Model\Db; use \Joindin\Service\Db as DbService; class User { protected $keyName = 'users'; protected $db; public function __construct() { $this->db = new DbService(); } public function getUriFor($username) { $data = $this->db->getOneByKey($this->keyName, 'username', $username); return $data['uri']; } public function load($uri) { $data = $this->db->getOneByKey($this->keyName, 'uri', $uri); return $data; } public function saveSlugToDatabase($user) { $data = array( 'uri' => $user->getUri(), 'username' => $user->getUsername(), 'slug' => $user->getUsername(), 'verbose_uri' => $user->getVerboseUri() ); $mongoUser = $this->load($user->getUri()); if ($mongoUser) { // user is already known - update this record $data = array_merge($mongoUser, $data); } return $this->db->save($this->keyName, $data); } }
<?php namespace Joindin\Model\Db; class User { protected $keyName = 'users'; protected $db; public function __construct() { $this->db = new \Joindin\Service\Db; } public function getUriFor($username) { $data = $this->db->getOneByKey($this->keyName, 'username', $username); return $data['uri']; } public function load($uri) { $data = $this->db->getOneByKey($this->keyName, 'uri', $uri); return $data; } public function saveSlugToDatabase($user) { $data = array( 'uri' => $user->getUri(), 'username' => $user->getUsername(), 'slug' => $user->getUsername(), 'verbose_uri' => $user->getVerboseUri() ); $mongoUser = $this->load($user->getUri()); if ($mongoUser) { // user is already known - update this record $data = array_merge($mongoUser, $data); } return $this->db->save($this->keyName, $data); } }
Update options to be option that makes sense
/* jslint node: true */ 'use strict'; var _ = require( 'lodash' ); var Q = require( 'q' ); var dust = require( './dustjsExtended' ); var Joi = require( 'joi' ); function Templater( options ) { var self = this; // Maybe merge in some defaults here? self.settings = _.merge( { namespace: '' }, options ); var schema = Joi.object().keys( { namespace: Joi.any().optional() } ); Joi.validate( self.settings, schema, function( error ) { if ( error ) { throw new Error( error ); } } ); self.compile = function( compileOptions ) { var deferred = Q.defer(); try { var compiled = dust.compile( compileOptions.content, self.settings.namespace + compileOptions.identifier ); dust.loadSource( compiled ); deferred.resolve(); } catch ( error ) { deferred.reject( error.message ); } return deferred.promise; }; self.render = function( renderOptions ) { var deferred = Q.defer(); // Passing the template namespace to the template variable scope renderOptions.data.templateNamespace = self.settings.namespace; // Render the template dust.render( self.settings.namespace + renderOptions.template, renderOptions.data, function( error, out ) { if ( error ) { deferred.reject( error ); } else { deferred.resolve( out ); } } ); return deferred.promise; }; } module.exports = exports = Templater;
/* jslint node: true */ 'use strict'; var _ = require( 'lodash' ); var Q = require( 'q' ); var dust = require( './dustjsExtended' ); var Joi = require( 'joi' ); function Templater( options ) { var self = this; // Maybe merge in some defaults here? self.settings = _.merge( { namespace: '' }, options ); var schema = Joi.object().keys( { namespace: Joi.any().optional() } ); Joi.validate( self.settings, schema, function( err ) { if ( err ) { throw new Error( err ); } } ); self.compile = function( options2 ) { var deferred = Q.defer(); try { var compiled = dust.compile( options2.content, self.settings.namespace + options2.identifier ); dust.loadSource( compiled ); deferred.resolve(); } catch ( e ) { deferred.reject( e.message ); } return deferred.promise; }; self.render = function( options2 ) { var deferred = Q.defer(); // Passing the template namespace to the template variable scope options2.data.templateNamespace = self.settings.namespace; // Render the template dust.render( self.settings.namespace + options2.template, options2.data, function( err, out ) { if ( err ) { deferred.reject( err ); } else { deferred.resolve( out ); } } ); return deferred.promise; }; } module.exports = exports = Templater;
Set crowd password field as a password input
Meteor.startup(function() { RocketChat.settings.addGroup('Atlassian Crowd', function() { const enableQuery = {_id: 'CROWD_Enable', value: true}; this.add('CROWD_Enable', false, { type: 'boolean', public: true, i18nLabel: 'Enabled' }); this.add('CROWD_URL', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'URL' }); this.add('CROWD_Reject_Unauthorized', true, { type: 'boolean', enableQuery: enableQuery }); this.add('CROWD_APP_USERNAME', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'Username' }); this.add('CROWD_APP_PASSWORD', '', { type: 'password', enableQuery: enableQuery, i18nLabel: 'Password' }); this.add('CROWD_Sync_User_Data', false, { type: 'boolean', enableQuery: enableQuery, i18nLabel: 'Sync_Users' }); this.add('CROWD_Test_Connection', 'crowd_test_connection', { type: 'action', actionText: 'Test_Connection', i18nLabel: 'Test_Connection' }); }); });
Meteor.startup(function() { RocketChat.settings.addGroup('Atlassian Crowd', function() { const enableQuery = {_id: 'CROWD_Enable', value: true}; this.add('CROWD_Enable', false, { type: 'boolean', public: true, i18nLabel: 'Enabled' }); this.add('CROWD_URL', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'URL' }); this.add('CROWD_Reject_Unauthorized', true, { type: 'boolean', enableQuery: enableQuery }); this.add('CROWD_APP_USERNAME', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'Username' }); this.add('CROWD_APP_PASSWORD', '', { type: 'string', enableQuery: enableQuery, i18nLabel: 'Password' }); this.add('CROWD_Sync_User_Data', false, { type: 'boolean', enableQuery: enableQuery, i18nLabel: 'Sync_Users' }); this.add('CROWD_Test_Connection', 'crowd_test_connection', { type: 'action', actionText: 'Test_Connection', i18nLabel: 'Test_Connection' }); }); });
Remove change dir commands and now it sends directly.
from __future__ import print_function import sys import os from sh import cd, hg def _get_subdirectories(current_dir): return [directory for directory in os.listdir(current_dir) if os.path.isdir(os.path.join(current_dir, directory)) and directory[0] != '.'] def check(): current_working_directory = os.getcwd() child_dirs = _get_subdirectories(current_working_directory) for child in child_dirs: try: current_branch = hg('branch', '-R', './%s' % child) output = '%-25s is on branch: %s' % (child, current_branch) print(output, end='') except Exception as e: continue def main(): arguments = sys.argv if 'check' == arguments[1]: check() else: print("type watchman help for, you know, help.") if __name__ == '__main__': main()
from __future__ import print_function import sys import os from sh import cd, hg def _get_subdirectories(current_dir): return [directory for directory in os.listdir(current_dir) if os.path.isdir(os.path.join(current_dir, directory)) and directory[0] != '.'] def check(): current_working_directory = os.getcwd() child_dirs = _get_subdirectories(current_working_directory) for child in child_dirs: try: change_dir = '%s/%s' % (current_working_directory, child) cd(change_dir); current_branch = hg('branch') output = '%-25s is on branch: %s' % (child, current_branch) print(output, end=''); cd('..') # print and step back one dir except Exception: continue def main(): arguments = sys.argv if 'check' == arguments[1]: check() else: print("type watchman help for, you know, help.") if __name__ == '__main__': main()
Create model for session, add properties for user
""" Models for the Jukebox application User - All users Vote - Votes on songs """ import datetime import logging from peewee import SqliteDatabase, Model, CharField, DateTimeField, ForeignKeyField, UUIDField db = SqliteDatabase(None) logger = logging.getLogger(__name__) class User(Model): id = CharField(primary_key=True) name = CharField() picture = CharField() email = CharField() @staticmethod def current(): return User.get(User.name == 'q') class Meta: database = db class Vote(Model): # references a Mopidy track track_uri = CharField() user = ForeignKeyField(User, related_name='voter') timestamp = DateTimeField() class Meta: database = db class Session(Model): user = ForeignKeyField(User) secret = UUIDField() expires = DateTimeField(default=datetime.datetime.now() + datetime.timedelta(days=30)) # expires after 30 days class Meta: database = db def init(db_file): # Create db db.init(db_file) # Create tables if not Vote.table_exists(): Vote.create_table() if not User.table_exists(): User.create_table() if not Session.table_exists(): Session.create_table()
""" Models for the Jukebox application User - All users Vote - Votes on songs """ import logging from peewee import SqliteDatabase, Model, CharField, DateTimeField, ForeignKeyField db = SqliteDatabase(None) logger = logging.getLogger(__name__) class User(Model): name = CharField() @staticmethod def current(): return User.get(User.name == 'q') class Meta: database = db class Vote(Model): # references a Mopidy track track_uri = CharField() user = ForeignKeyField(User, related_name='voter') timestamp = DateTimeField() class Meta: database = db def init(db_file): # Create db db.init(db_file) # Create tables if not Vote.table_exists(): Vote.create_table() if not User.table_exists(): User.create_table() # create dummy user User(name="q").save()
Clean up controller use statements
<?php namespace Jmikola\JsAssetsHelperBundle\Controller; use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; use Symfony\Component\HttpFoundation\Request; class Controller { private $engine; private $defaultPackage; private $namedPackages; /** * Constructor. * * @param EngineInterface $engine * @param array $defaultPackage * @param array $namedPackages */ public function __construct(EngineInterface $engine, array $defaultPackage, array $namedPackages = array()) { $this->engine = $engine; $this->defaultPackage = $defaultPackage; $this->namedPackages = $namedPackages; } public function indexAction(Request $request) { return $this->engine->renderResponse('JmikolaJsAssetsHelperBundle::index.'.$request->getRequestFormat().'.twig', array( 'basePath' => $request->getBasePath(), 'defaultPackage' => $this->defaultPackage, 'namedPackages' => $this->namedPackages, )); } }
<?php namespace Jmikola\JsAssetsHelperBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; use Symfony\Component\HttpFoundation\Response; class Controller { private $engine; private $defaultPackage; private $namedPackages; /** * Constructor. * * @param EngineInterface $engine * @param array $defaultPackage * @param array $namedPackages */ public function __construct(EngineInterface $engine, array $defaultPackage, array $namedPackages = array()) { $this->engine = $engine; $this->defaultPackage = $defaultPackage; $this->namedPackages = $namedPackages; } public function indexAction(Request $request) { return $this->engine->renderResponse('JmikolaJsAssetsHelperBundle::index.'.$request->getRequestFormat().'.twig', array( 'basePath' => $request->getBasePath(), 'defaultPackage' => $this->defaultPackage, 'namedPackages' => $this->namedPackages, )); } }
Make sure custom thumbnails have upscaling enabled
<?php namespace Concrete\Core\File\Image\Thumbnail\Type; use Concrete\Core\Entity\File\Version as FileVersion; use Concrete\Core\File\Image\Thumbnail\Type\Version as ThumbnailVersion; use Concrete\Core\File\Image\Thumbnail\Type\Type as ThumbnailType; class CustomThumbnail extends ThumbnailVersion { protected $path; protected $cropped; /** * CustomThumbnail constructor. * @param int $width * @param int $height * @param string $path The full path to the file (whether it exists or not) * @param bool $cropped */ public function __construct($width, $height, $path, $cropped) { $width = (int) $width; $height = (int) $height; $sizingMode = $cropped ? ThumbnailType::RESIZE_EXACT : ThumbnailType::RESIZE_PROPORTIONAL; $cropped = (int) $cropped; $this->path = $path; $this->cropped = (bool) $cropped; parent::__construct(REL_DIR_FILES_CACHE, "ccm_{$width}x{$height}_{$cropped}", 'Custom', $width, $height, false, $sizingMode, false, [], true); } public function getFilePath(FileVersion $fv) { return $this->path; } public function isCropped() { return $this->cropped; } }
<?php namespace Concrete\Core\File\Image\Thumbnail\Type; use Concrete\Core\Entity\File\Version as FileVersion; use Concrete\Core\File\Image\Thumbnail\Type\Version as ThumbnailVersion; use Concrete\Core\File\Image\Thumbnail\Type\Type as ThumbnailType; class CustomThumbnail extends ThumbnailVersion { protected $path; protected $cropped; /** * CustomThumbnail constructor. * @param int $width * @param int $height * @param string $path The full path to the file (whether it exists or not) * @param bool $cropped */ public function __construct($width, $height, $path, $cropped) { $width = (int) $width; $height = (int) $height; $sizingMode = $cropped ? ThumbnailType::RESIZE_EXACT : ThumbnailType::RESIZE_PROPORTIONAL; $cropped = (int) $cropped; $this->path = $path; $this->cropped = (bool) $cropped; parent::__construct(REL_DIR_FILES_CACHE, "ccm_{$width}x{$height}_{$cropped}", 'Custom', $width, $height, false, $sizingMode); } public function getFilePath(FileVersion $fv) { return $this->path; } public function isCropped() { return $this->cropped; } }
Add help text for the tweet command
var util = require('util') , twitter = require('twitter') , Stream = require('stream') , repl = require('repl') , keys = require('./keys') , local = repl.start() , first = true local.context.repl = local local.defineCommand('tweet', function(tweet){ twish .verifyCredentials(function(data) { console.log(util.inspect(data)) }) .updateStatus(tweet, function(data) { console.log(util.inspect(data)) }) }) local.commands['.tweet'].help = 'Tweet as currently signed in user' var twish = new twitter(keys) //twish.get('/statuses/show/183682338646011904.json', function(data){ //console.log(data) //}) //twish.stream('statuses/sample', function(stream){ twish.stream('user', {track:'gkatsev', delimited:20}, function(stream){ stream.on('data', function(data){ if(first){ first = false return } setTimeout(function(){ process.stdout.write(JSON.stringify(data, null, ' ')) }, 500) }) }) module.exports = twish
var util = require('util') , twitter = require('twitter') , Stream = require('stream') , repl = require('repl') , keys = require('./keys') , local = repl.start() , first = true local.context.repl = local local.defineCommand('tweet', function(tweet){ twish .verifyCredentials(function(data) { console.log(util.inspect(data)) }) .updateStatus(tweet, function(data) { console.log(util.inspect(data)) }) }) var twish = new twitter(keys) //twish.get('/statuses/show/183682338646011904.json', function(data){ //console.log(data) //}) //twish.stream('statuses/sample', function(stream){ twish.stream('user', {track:'gkatsev', delimited:20}, function(stream){ stream.on('data', function(data){ if(first){ first = false return } setTimeout(function(){ process.stdout.write(JSON.stringify(data, null, ' ')) }, 500) }) }) module.exports = twish
Use KCommandContext::getSubject() instead of $command->caller
<?php /** * @version $Id$ * @package Nooku_Components * @subpackage Files * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * File Name Filter Class * * @author Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya> * @package Nooku_Components * @subpackage Files */ class ComFilesFilterFileName extends KFilterAbstract { protected $_walk = false; protected function _validate($context) { $value = $this->_sanitize($context->getSubject()->name); if ($value == '') { $context->setError(JText::_('Invalid file name')); return false; } } protected function _sanitize($value) { return $this->getService('com://admin/files.filter.path')->sanitize($value); } }
<?php /** * @version $Id$ * @package Nooku_Components * @subpackage Files * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * File Name Filter Class * * @author Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya> * @package Nooku_Components * @subpackage Files */ class ComFilesFilterFileName extends KFilterAbstract { protected $_walk = false; protected function _validate($context) { $value = $this->_sanitize($context->caller->name); if ($value == '') { $context->setError(JText::_('Invalid file name')); return false; } } protected function _sanitize($value) { return $this->getService('com://admin/files.filter.path')->sanitize($value); } }
Make constructor final to prevent overriding in child class
<?php /** * * @author newloki */ namespace Language\Languages\Indo\English; use Language\Languages\Indo\IndoAbstract, Language\Languages\LanguagesException; require_once realpath(__DIR__) . '/../IndoAbstract.php'; abstract class EnglishAbstract extends IndoAbstract { /** * Name of this language * @var string */ protected $_name = 'english_abstract'; /** * constructor for english languages, not called in this class, but in his * childs * @return void */ public final function __construct() { //in english Y is almost an vocal try { $this->replaceInCVMapping('y', IndoAbstract::VOCAL); } catch(LanguagesException $e) { throw new LanguagesException('Can\'t create ' . $this->_name, $e); } } }
<?php /** * * @author newloki */ namespace Language\Languages\Indo\English; use Language\Languages\Indo\IndoAbstract, Language\Languages\LanguagesException; require_once realpath(__DIR__) . '/../IndoAbstract.php'; abstract class EnglishAbstract extends IndoAbstract { /** * Name of this language * @var string */ protected $_name = 'english_abstract'; /** * constructor for english languages, not called in this class, but in his * childs * @return void */ public function __construct() { //in english Y is almost an vocal try { $this->replaceInCVMapping('y', IndoAbstract::VOCAL); } catch(LanguagesException $e) { throw new LanguagesException('Can\'t create ' . $this->_name, $e); } } }
Fix some more BC between v2 and v3
<?php declare(strict_types = 1); namespace unreal4u\TelegramAPI\Telegram\Types\Custom; use Psr\Log\LoggerInterface; use unreal4u\TelegramAPI\Abstracts\TraversableCustomType; use unreal4u\TelegramAPI\Telegram\Types\Message; /** * Used for methods that will return an array of messages */ class MessageArray extends TraversableCustomType { public function __construct(array $data = null, LoggerInterface $logger = null) { if (count($data) !== 0) { foreach ($data as $telegramResponse) { // Create an actual Update object and fill the array $this->data[] = new Message($telegramResponse, $logger); } } } /** * Traverses through our $data, yielding the result set * * @return Update[] */ public function traverseObject() { foreach ($this->data as $message) { yield $message; } } }
<?php declare(strict_types = 1); namespace unreal4u\TelegramAPI\Telegram\Types\Custom; use unreal4u\TelegramAPI\Abstracts\CustomType; use Psr\Log\LoggerInterface; use unreal4u\TelegramAPI\Interfaces\CustomArrayType; use unreal4u\TelegramAPI\Telegram\Types\Message; /** * Used for methods that will return an array of messages */ class MessageArray extends CustomType implements CustomArrayType { public function __construct(array $data = null, LoggerInterface $logger = null) { if (count($data) !== 0) { foreach ($data as $telegramResponse) { // Create an actual Update object and fill the array $this->data[] = new Message($telegramResponse, $logger); } } } /** * Traverses through our $data, yielding the result set * * @return Update[] */ public function traverseObject() { foreach ($this->data as $message) { yield $message; } } }
Add path for (future) explore service
/* * Copyright 2014 Codenvy, S.A. * * 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.codenvy.ide.ext.datasource.shared; public class ServicePaths { public static final String BASE_DATASOURCE_PATH = "datasource"; public static final String DATABASE_EXPLORE_PATH = "databaseExplore"; public static final String DATABASE_TYPES_PATH = "databasetypes"; public static final String RESULT_CSV_PATH = "csv"; public static final String EXECUTE_SQL_REQUEST_PATH = "executeSqlRequest"; public static final String TEST_DATABASE_CONNECTIVITY_PATH = "testDatabaseConnectivity"; public static final String DATABASE_METADATA_PATH = "databasemetadata"; }
/* * Copyright 2014 Codenvy, S.A. * * 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.codenvy.ide.ext.datasource.shared; public class ServicePaths { public static final String BASE_DATASOURCE_PATH = "datasource"; public static final String DATABASE_TYPES_PATH = "databasetypes"; public static final String RESULT_CSV_PATH = "csv"; public static final String EXECUTE_SQL_REQUEST_PATH = "executeSqlRequest"; public static final String TEST_DATABASE_CONNECTIVITY_PATH = "testDatabaseConnectivity"; public static final String DATABASE_METADATA_PATH = "databasemetadata"; }
Add comment about constant values
import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): # Constants - TODO move to config file global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
Jormungandr: Add error field to region
# coding=utf-8 from flask.ext.restful import Resource, fields, marshal_with from jormungandr import i_manager from make_links import add_coverage_link, add_coverage_link, add_collection_links, clean_links from converters_collection_type import collections_to_resource_type from collections import OrderedDict from fields import NonNullNested region_fields = { "id": fields.String(attribute="region_id"), "start_production_date": fields.String, "end_production_date": fields.String, "status": fields.String, "shape": fields.String, "error": NonNullNested({ "code": fields.String, "value": fields.String }) } regions_fields = OrderedDict([ ("regions", fields.List(fields.Nested(region_fields))) ]) collections = collections_to_resource_type.keys() class Coverage(Resource): @clean_links() @add_coverage_link() @add_collection_links(collections) @marshal_with(regions_fields) def get(self, region=None, lon=None, lat=None): return i_manager.regions(region, lon, lat), 200
# coding=utf-8 from flask.ext.restful import Resource, fields, marshal_with from jormungandr import i_manager from make_links import add_coverage_link, add_collection_links, clean_links from converters_collection_type import collections_to_resource_type from collections import OrderedDict region_fields = { "id": fields.String(attribute="region_id"), "start_production_date": fields.String, "end_production_date": fields.String, "status": fields.String, "shape": fields.String, } regions_fields = OrderedDict([ ("regions", fields.List(fields.Nested(region_fields))) ]) collections = collections_to_resource_type.keys() class Coverage(Resource): @clean_links() @add_coverage_link() @add_collection_links(collections) @marshal_with(regions_fields) def get(self, region=None, lon=None, lat=None): return i_manager.regions(region, lon, lat), 200
Use correct Exception class to catch
<?php namespace CedricZiel\ShariffBundle\Service; use CedricZiel\ShariffBundle\Model\ShariffConfig; use GuzzleHttp\Exception\GuzzleException; use Heise\Shariff\Backend; /** * @package CedricZiel\ShariffBundle\Service */ class ShariffService implements ShariffServiceInterface { /** * @var ShariffConfig */ protected $config; /** * @param ShariffConfig $config */ public function __construct(ShariffConfig $config) { $this->config = $config; } /** * Get the information from the backend for the given url * * @param string $url * * @return array */ public function get($url) { $backend = new Backend($this->config->toArray()); try { return $backend->get($url); } catch (GuzzleException $e) { return '{}'; } } }
<?php namespace CedricZiel\ShariffBundle\Service; use CedricZiel\ShariffBundle\ShariffConfig; use Heise\Shariff\Backend; /** * @package CedricZiel\ShariffBundle\Service */ class ShariffService implements ShariffServiceInterface { /** * @var ShariffConfig */ protected $config; /** * @param ShariffConfig $config */ public function __construct(ShariffConfig $config) { $this->config = $config; } /** * Get the information from the backend for the given url * * @param string $url * * @return array */ public function get($url) { $backend = new Backend($this->config->toArray()); try { return $backend->get($url); } catch (GuzzleException $e) { return '{}'; } } }
Implement CountNodes using the seen tag.
package stats import ( "fmt" "github.com/callpraths/gorobdd/internal/node" "github.com/callpraths/gorobdd/internal/tag" ) func CountNodes(n *node.Node) (int, error) { s := tag.NewSeenContext() return countNodesHelper(n, s) } func countNodesHelper(n *node.Node, s tag.SeenContext) (int, error) { if s.IsSeen(n) { return 0, nil } s.MarkSeen(n) switch n.Type { case node.LeafType: return 1, nil case node.InternalType: t, et := countNodesHelper(n.True, s) if et != nil { return t, et } f, ef := countNodesHelper(n.False, s) if ef != nil { return f, ef } return t + f + 1, nil default: return -1, fmt.Errorf("Malformed node: %v", n) } }
package stats import ( "fmt" "github.com/callpraths/gorobdd/internal/node" ) func CountNodes(n *node.Node) (int, error) { m := make(map[*node.Node]bool) return countNodesHelper(n, m) } func countNodesHelper(n *node.Node, m map[*node.Node]bool) (int, error) { _, seen := m[n] if seen { return 0, nil } m[n] = true switch n.Type { case node.LeafType: return 1, nil case node.InternalType: t, et := countNodesHelper(n.True, m) if et != nil { return t, et } f, ef := countNodesHelper(n.False, m) if ef != nil { return f, ef } return t + f + 1, nil default: return -1, fmt.Errorf("Malformed node: %v", n) } }
Make argparse an optional dependency (and avoid pinning in a library).
""" pip-tools keeps your pinned dependencies fresh. """ import sys from setuptools import setup def get_dependencies(): deps = [] if sys.version_info < (2, 7): deps += ['argparse'] return deps setup( name='pip-tools', version='0.2', url='https://github.com/nvie/pip-tools/', license='BSD', author='Vincent Driessen', author_email='vincent@3rdcloud.com', description=__doc__, #packages=[], scripts=['bin/pip-review', 'bin/pip-dump'], #include_package_data=True, zip_safe=False, platforms='any', install_requires=get_dependencies(), classifiers=[ # As from http://pypi.python.org/pypi?%3Aaction=list_classifiers #'Development Status :: 1 - Planning', #'Development Status :: 2 - Pre-Alpha', #'Development Status :: 3 - Alpha', 'Development Status :: 4 - Beta', #'Development Status :: 5 - Production/Stable', #'Development Status :: 6 - Mature', #'Development Status :: 7 - Inactive', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: System :: Systems Administration', ] )
""" pip-tools keeps your pinned dependencies fresh. """ import sys from setuptools import setup setup( name='pip-tools', version='0.2', url='https://github.com/nvie/pip-tools/', license='BSD', author='Vincent Driessen', author_email='vincent@3rdcloud.com', description=__doc__, #packages=[], scripts=['bin/pip-review', 'bin/pip-dump'], #include_package_data=True, zip_safe=False, platforms='any', install_requires=['argparse==1.2.1'], # needed for python 2.6 classifiers=[ # As from http://pypi.python.org/pypi?%3Aaction=list_classifiers #'Development Status :: 1 - Planning', #'Development Status :: 2 - Pre-Alpha', #'Development Status :: 3 - Alpha', 'Development Status :: 4 - Beta', #'Development Status :: 5 - Production/Stable', #'Development Status :: 6 - Mature', #'Development Status :: 7 - Inactive', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: System :: Systems Administration', ] )
Add results to LoadSessionServlet model. Each reservation may contain many results. Since clients may be depending on these results we will want to keep them constant when loading sessions from the CMS. This means that results must be included in the model that is used to update the reservation. Change-Id: I8318b3866573b71a4e02dbd43541021f78a57f34
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.server.schedule.reservations.model; import java.util.Map; /** * Representation of a Reservation object in RTDB. */ public class Reservation implements Comparable<Reservation> { public long last_status_changed; public String status; public Map<String, String> results; @Override public int compareTo(Reservation reservation) { if (last_status_changed < reservation.last_status_changed) { return -1; } else if (last_status_changed > reservation.last_status_changed) { return 1; } return 0; } }
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.server.schedule.reservations.model; /** * Representation of a Reservation object in RTDB. */ public class Reservation implements Comparable<Reservation> { public long last_status_changed; public String status; @Override public int compareTo(Reservation reservation) { if (last_status_changed < reservation.last_status_changed) { return -1; } else if (last_status_changed > reservation.last_status_changed) { return 1; } return 0; } }
Clean up some LiveFlotWidget params
# This file is part of Moksha. # # Moksha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Moksha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. # Authors: Luke Macken <lmacken@redhat.com> from tw.jquery.flot import FlotWidget from moksha.live import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_example' params = ['id', 'data', 'options', 'height', 'width', 'onmessageframe'] children = [FlotWidget('flot')] onmessageframe = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' height = '250px' width = '390px' options = {} data = [{}]
# This file is part of Moksha. # # Moksha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Moksha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. # Authors: Luke Macken <lmacken@redhat.com> from tw.jquery.flot import FlotWidget from moksha.live import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_example' children = [FlotWidget('flot')] params = ['id', 'data', 'options', 'height', 'width', 'onconnectedframe', 'onmessageframe'] onmessageframe = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' height = '250px' width = '390px' options = {} data = [{}]
Fix syntax problem in SendToUser.arguments
from twisted.protocols import amp from twisted.cred.error import UnauthorizedLogin # commands to server side class Login(amp.Command): arguments = [("username", amp.String()), ("password", amp.String())] response = [] errors = {UnauthorizedLogin: "UnauthorizedLogin"} class SendToAll(amp.Command): arguments = [("message", amp.String())] response = [] class SendToUser(amp.Command): arguments = [("message", amp.String()), ("username", amp.String())] response = [] # commands to client side class Send(amp.Command): arguments = [("message", amp.String()), ("sender", amp.String())] response = [] class AddUser(amp.Command): arguments = [("user", amp.String())] response = [] class DelUser(amp.Command): arguments = [("user", amp.String())] response = [] class LoggedIn(amp.Command): arguments = [("ok", amp.Boolean())] response = []
from twisted.protocols import amp from twisted.cred.error import UnauthorizedLogin # commands to server side class Login(amp.Command): arguments = [("username", amp.String()), ("password", amp.String())] response = [] errors = {UnauthorizedLogin: "UnauthorizedLogin"} class SendToAll(amp.Command): arguments = [("message", amp.String())] response = [] class SendToUser(amp.Command): arguments = [("message", amp.String()), "username", amp.String()] response = [] # commands to client side class Send(amp.Command): arguments = [("message", amp.String()), ("sender", amp.String())] response = [] class AddUser(amp.Command): arguments = [("user", amp.String())] response = [] class DelUser(amp.Command): arguments = [("user", amp.String())] response = [] class LoggedIn(amp.Command): arguments = [("ok", amp.Boolean())] response = []
Speed up the telnet process for HORIZONS Be very patient waiting for the other end to start its reply, but then only wait 1s for the rest of the data.
#!/usr/bin/env python2.7 #import argparse from telnetlib import Telnet def main(in_path, out_path): lines = read_lines(open(in_path)) tn = Telnet('horizons.jpl.nasa.gov', 6775) out = open(out_path, 'w') for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') index, match, data1 = tn.expect([b'.'], 5.0) data2 = tn.read_until(b'DUMMY PATTERN', 1.0) data = (data1 + data2).decode('ascii') print(repr(data)) out.write(data) out.flush() def read_lines(f): for line in f: line = line.strip() if (not line) or line.startswith('#'): continue yield line if __name__ == '__main__': try: main('horizons_input.txt', 'horizons_output.txt') except EOFError: print print('EOF')
#!/usr/bin/env python2.7 #import argparse from telnetlib import Telnet def main(in_path, out_path): lines = read_lines(open(in_path)) tn = Telnet('horizons.jpl.nasa.gov', 6775) out = open(out_path, 'w') for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') data = tn.read_until(b'DUMMY PATTERN', 5.0).decode('ascii') print(repr(data)) out.write(data) out.flush() def read_lines(f): for line in f: line = line.strip() if (not line) or line.startswith('#'): continue yield line if __name__ == '__main__': try: main('horizons_input.txt', 'horizons_output.txt') except EOFError: print print('EOF')
Add ItemUser to reactions event
package slack // reactionItem is a lighter-weight item than is returned by the reactions list. type reactionItem struct { Type string `json:"type"` Channel string `json:"channel,omitempty"` File string `json:"file,omitempty"` FileComment string `json:"file_comment,omitempty"` Timestamp string `json:"ts,omitempty"` } type reactionEvent struct { Type string `json:"type"` User string `json:"user"` ItemUser string `json:"item_user"` Item reactionItem `json:"item"` Reaction string `json:"reaction"` EventTimestamp string `json:"event_ts"` } // ReactionAddedEvent represents the Reaction added event type ReactionAddedEvent reactionEvent // ReactionRemovedEvent represents the Reaction removed event type ReactionRemovedEvent reactionEvent
package slack // reactionItem is a lighter-weight item than is returned by the reactions list. type reactionItem struct { Type string `json:"type"` Channel string `json:"channel,omitempty"` File string `json:"file,omitempty"` FileComment string `json:"file_comment,omitempty"` Timestamp string `json:"ts,omitempty"` } type reactionEvent struct { Type string `json:"type"` User string `json:"user"` Item reactionItem `json:"item"` Reaction string `json:"reaction"` EventTimestamp string `json:"event_ts"` } // ReactionAddedEvent represents the Reaction added event type ReactionAddedEvent reactionEvent // ReactionRemovedEvent represents the Reaction removed event type ReactionRemovedEvent reactionEvent
Fix CORS for list response
"use strict"; require('async-to-gen/register') const restify = require('restify'); var server = restify.createServer(); server.use(restify.CORS({ credentials: true })); server.use(restify.CORS()); server.post('/-/login', restify.bodyParser(), require('./login')); server.get('/-/files/:team/:user/:file', require('./serve-file')); server.get('/-/metadata/:team/:user/:file', require('./metadata')); server.get('/-/session/:session', require('./session')); server.get('/-/files.list', require('./list')()); server.opts('/-/files.list', allowCORS) server.post('/-/upload', require('./upload')()) server.opts('/-/upload', allowCORS) function allowCORS(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Authorization'); res.setHeader('Access-Control-Allow-Methods', '*'); res.send(200) next() } server.listen(process.env.PORT || 3001, function() { console.log('%s listening at %s', server.name, server.url); });
"use strict"; require('async-to-gen/register') const restify = require('restify'); var server = restify.createServer(); server.use(restify.CORS({ credentials: true })); server.use(restify.CORS()); server.post('/-/login', restify.bodyParser(), require('./login')); server.get('/-/files/:team/:user/:file', require('./serve-file')); server.get('/-/metadata/:team/:user/:file', require('./metadata')); server.get('/-/session/:session', require('./session')); server.get('/-/files.list', require('./list')()); server.post('/-/upload', require('./upload')()) server.opts('/-/upload', (req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Authorization'); res.setHeader('Access-Control-Allow-Methods', '*'); res.send(200) next() }) server.listen(process.env.PORT || 3001, function() { console.log('%s listening at %s', server.name, server.url); });
Remove GeneratedValue Special for Postgres
package de.schuermann.interactivedata.spring.sample.data; import javax.persistence.*; import java.util.Date; /** * Data Entity for Actions * * @author Philipp Sch&uuml;rmann */ @Entity public class Action { @Id @GeneratedValue private Long id; private Date time; @ManyToOne private Person person; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
package de.schuermann.interactivedata.spring.sample.data; import javax.persistence.*; import java.util.Date; /** * Data Entity for Actions * * @author Philipp Sch&uuml;rmann */ @Entity public class Action { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "action_seq_gen") @SequenceGenerator(name = "action_seq_gen", sequenceName = "action_id_seq") private Long id; private Date time; @ManyToOne private Person person; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
Add delegate constructor for the episodes/watched request
package com.alexrnl.jbetaseries.request.episodes; import com.alexrnl.jbetaseries.request.APIAddresses; import com.alexrnl.jbetaseries.request.Request; import com.alexrnl.jbetaseries.request.Verb; import com.alexrnl.jbetaseries.request.parameters.Bulk; import com.alexrnl.jbetaseries.request.parameters.Id; /** * Request which allow to mark episodes as seen.<br /> * @author Alex */ public class EpisodeWatched extends Request { /** * Constructor #1.<br /> * @param episodeId * the id of the episode to mark as seen. * @param bulk * <code>true</code> if the previous episode (i.e. from previous seasons) should be also * marked as seen. */ public EpisodeWatched (final Integer episodeId, final boolean bulk) { super(Verb.POST, APIAddresses.EPISODES_WATCHED); addParameter(new Id(episodeId)); if (bulk) { addParameter(new Bulk()); } } /** * Constructor #2.<br /> * This will mark <em>all</em> previous episodes as seen. * @param episodeId the id of the episode to mark as seen. * @see #EpisodeWatched(Integer, boolean) */ public EpisodeWatched (final Integer episodeId) { this(episodeId, true); } }
package com.alexrnl.jbetaseries.request.episodes; import com.alexrnl.jbetaseries.request.APIAddresses; import com.alexrnl.jbetaseries.request.Request; import com.alexrnl.jbetaseries.request.Verb; import com.alexrnl.jbetaseries.request.parameters.Bulk; import com.alexrnl.jbetaseries.request.parameters.Id; /** * Request which allow to mark episodes as seen.<br /> * @author Alex */ public class EpisodeWatched extends Request { /** * Constructor #.<br /> * @param episodeId * the id of the episode to mark as seen. * @param bulk * <code>true</code> if the previous episode (i.e. from previous seasons) should be also * marked as seen. */ public EpisodeWatched (final Integer episodeId, final boolean bulk) { super(Verb.POST, APIAddresses.EPISODES_WATCHED); addParameter(new Id(episodeId)); if (bulk) { addParameter(new Bulk()); } } }
Test the __toString() method of DrupalTestUser class.
<?php use \Codeception\Module\Drupal\UserRegistry\DrupalTestUser; use \Codeception\Util\Fixtures; /** * Unit tests for DrushTestUserManager class. */ class DrupalTestUserTest extends \Codeception\TestCase\Test { /** * @var \UnitTester * Store the Actor object being used to test. */ protected $tester; /** * Objects of this class should be instantiable. * * @test */ public function shouldBeInstantiatable() { $user = Fixtures::get("drupalTestUser"); $this->assertInstanceOf( '\Codeception\Module\Drupal\UserRegistry\DrupalTestUser', new DrupalTestUser($user->name, $user->pass) ); } /** * Test the class __toString() method. * * @test */ public function testToString() { $user = new DrupalTestUser("Test Username", "password"); $this->assertEquals("Test Username", $user->__toString()); $this->assertEquals("Test Username", $user . ""); } }
<?php use \Codeception\Module\Drupal\UserRegistry\DrupalTestUser; use \Codeception\Util\Fixtures; /** * Unit tests for DrushTestUserManager class. */ class DrupalTestUserTest extends \Codeception\TestCase\Test { /** * @var \UnitTester * Store the Actor object being used to test. */ protected $tester; /** * Objects of this class should be instantiable. * * @test */ public function shouldBeInstantiatable() { $user = Fixtures::get("drupalTestUser"); $this->assertInstanceOf( '\Codeception\Module\Drupal\UserRegistry\DrupalTestUser', new DrupalTestUser($user->name, $user->pass) ); } }
Change to positional argument for generate-token
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. """ Generate an authentication token for a sensor. This token is used by the sensor to send the sensor's data to the API. After generating a token, you have to place it in the sensor's configuration file if you want it to send data. """ import argparse import sys from api import db from api.tokens.models import Token from sqlalchemy.exc import IntegrityError def generate_token(name): token = Token(name) db.session.add(token) try: db.session.commit() except IntegrityError: db.session.rollback() sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name)) sys.exit(-1) return token def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('name', type=str, help='Name describing a sensor\'s location') args = parser.parse_args() token = generate_token(args.name) print(''' Successfully created token! Name: {} Token: {} Dont forget to save this token in the sensor's configuration file. '''.format(token.name, token.token.decode('utf-8'))) if __name__ == '__main__': main()
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. """ Generate an authentication token for a sensor. This token is used by the sensor to send the sensor's data to the API. After generating a token, you have to place it in the sensor's configuration file if you want it to send data. """ import argparse import sys from api import db from api.tokens.models import Token from sqlalchemy.exc import IntegrityError def generate_token(name): token = Token(name) db.session.add(token) try: db.session.commit() except IntegrityError: db.session.rollback() sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name)) sys.exit(-1) return token def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-n', '--name', type=str, required=True, help='Name describing a sensor\'s location') args = parser.parse_args() token = generate_token(args.name) print(''' Successfully created token! Name: {} Token: {} Dont forget to save this token in the sensor's configuration file. '''.format(token.name, token.token.decode('utf-8'))) if __name__ == '__main__': main()
Rename diff result to follow Go convention
package diff import ( "fmt" "path/filepath" "github.com/xchapter7x/enaml/pull" ) // Result is returned from a diff operation type Result struct { Deltas []string } // Differ implements diffing BOSH or Pivnet releases and their contained entities. type Differ interface { Diff() (Result, error) DiffJob(job string) (Result, error) } // New creates a Differ instance for comparing two releases func New(releaseRepo pull.Release, r1Path, r2Path string) (differ Differ, err error) { if filepath.Ext(r1Path) != filepath.Ext(r2Path) { err = fmt.Errorf("The specified releases didn't have matching file extensions, " + "assuming different release types.") return } if filepath.Ext(r1Path) == ".pivotal" { differ = pivnetReleaseDiffer{ ReleaseRepo: release, R1Path: r1Path, R2Path: r2Path, } } else { differ = boshReleaseDiffer{ ReleaseRepo: release, R1Path: r1Path, R2Path: r2Path, } } return }
package diff import ( "fmt" "path/filepath" "github.com/xchapter7x/enaml/pull" ) // Result is returned from a diff operation type Result struct { Deltas []string } // Differ implements diffing BOSH or Pivnet releases and their contained entities. type Differ interface { Diff() (DiffResult, error) DiffJob(job string) (DiffResult, error) } // New creates a Differ instance for comparing two releases func New(releaseRepo pull.Release, r1Path, r2Path string) (differ Differ, err error) { if filepath.Ext(r1Path) != filepath.Ext(r2Path) { err = fmt.Errorf("The specified releases didn't have matching file extensions, " + "assuming different release types.") return } if filepath.Ext(r1Path) == ".pivotal" { differ = pivnetReleaseDiffer{ ReleaseRepo: release, R1Path: r1Path, R2Path: r2Path, } } else { differ = boshReleaseDiffer{ ReleaseRepo: release, R1Path: r1Path, R2Path: r2Path, } } return }
Python: Return the vector rather than printing it.
# Copyright 2015 Carnegie Mellon University # # 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 subprocess import Popen, PIPE import os.path myDir = os.path.dirname(os.path.realpath(__file__)) class TorchWrap: def __init__(self, model='models/facenet/nn4.v1.t7', imgDim=96, cuda=False): cmd = ['/usr/bin/env', 'th', os.path.join(myDir,'facenet_server.lua'), '-model', model, '-imgDim', str(imgDim)] if cuda: cmd.append('-cuda') self.p = Popen(cmd, stdin=PIPE, stdout=PIPE, bufsize=0) def forward(self, imgPath, timeout=10): self.p.stdin.write(imgPath+"\n") return [float(x) for x in self.p.stdout.readline().strip().split(',')]
# Copyright 2015 Carnegie Mellon University # # 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 subprocess import Popen, PIPE import os.path myDir = os.path.dirname(os.path.realpath(__file__)) class TorchWrap: def __init__(self, model='models/facenet/nn4.v1.t7', imgDim=96, cuda=False): cmd = ['/usr/bin/env', 'th', os.path.join(myDir,'facenet_server.lua'), '-model', model, '-imgDim', str(imgDim)] if cuda: cmd.append('-cuda') self.p = Popen(cmd, stdin=PIPE, stdout=PIPE, bufsize=0) def forward(self, imgPath, timeout=10): self.p.stdin.write(imgPath+"\n") print([float(x) for x in self.p.stdout.readline().strip().split(',')])
Add set for OrFail functionality.
<?php namespace Shim\Model\Entity; use Cake\Utility\Inflector; use RuntimeException; /** * Trait to read/write entity properties in a way that the returned/passed value is ensured (not nullable). * * - get{PropertyName}OrFail() must return the property or throws exception otherwise * - set{PropertyName}OrFail($value) must have a non-null value or throws exception otherwise */ trait GetSetTrait { use GetTrait; use SetTrait; /** * @param string $name * @param array $arguments * @throws \RuntimeException * @return mixed */ public function __call(string $name, array $arguments) { if (!preg_match('/^(set|get)([A-Z][A-Za-z0-9]+)OrFail$/', $name, $matches)) { throw new RuntimeException('Method ' . $name . ' cannot be found; set{PropertyName}OrFail() expected.'); } if ($matches[1] === 'set' && !$arguments) { throw new RuntimeException('Method ' . $name . ' param for value not found, but expected.'); } $property = Inflector::underscore($matches[2]); if ($matches[1] === 'get') { return $this->getOrFail($property); } return $this->setOrFail($property, $arguments[1]); } }
<?php namespace Shim\Model\Entity; use Cake\Utility\Inflector; use RuntimeException; /** * Trait to read/write entity properties in a way that the returned/passed value is ensured (not nullable). * * - get{PropertyName}OrFail() must return the property or throws exception otherwise * - set{PropertyName}OrFail($value) must have a non-null value or throws exception otherwise */ trait GetSetTrait { use GetTrait; use SetTrait; /** * @param string $name * @param array $arguments * @throws \RuntimeException * @return mixed */ public function __call(string $name, array $arguments) { if (!preg_match('/^(set|get)([A-Z][A-Za-z0-9]+)OrFail$/', $name, $matches)) { throw new RuntimeException('Method ' . $name . ' cannot be found; set{PropertyName}OrFail() expected.'); } if ($matches[1] === 'set' && !$arguments) { throw new RuntimeException('Method ' . $name . ' param for value not found, but expected.'); } $property = Inflector::underscore($matches[2]); if ($matches[1] === 'get') { return $this->getOrFail($property); } $this->setOrFail($property, $arguments[1]); } }
Extend test case a bit
package blenc import ( "bytes" "io/ioutil" "strings" "testing" ) func allKG(f func(kg KeyGenerator)) { func() { f(constantKey("testkey")) }() } func TestEqualData(t *testing.T) { for _, data := range []string{ "", "a", "abc", "9876543210123456789098765432101234567890", strings.Repeat("data", 1025), } { data := []byte(data) allKG(func(kg KeyGenerator) { _, s, err := kg.GenerateKey(ioutil.NopCloser(bytes.NewReader(data))) errPanic(err) defer s.Close() read, err := ioutil.ReadAll(s) errPanic(err) if !bytes.Equal(data, read) { t.Fatalf("Data read from stream after key generation is invalid") } }) } }
package blenc import ( "bytes" "io/ioutil" "testing" ) func allKG(f func(kg KeyGenerator)) { func() { f(constantKey("testkey")) }() } func TestEqualData(t *testing.T) { for _, data := range []string{ "", "a", "abc", "9876543210123456789098765432101234567890", } { data := []byte(data) allKG(func(kg KeyGenerator) { _, s, err := kg.GenerateKey(ioutil.NopCloser(bytes.NewReader(data))) errPanic(err) defer s.Close() read, err := ioutil.ReadAll(s) errPanic(err) if !bytes.Equal(data, read) { t.Fatalf("Data read from stream after key generation is invalid") } }) } }
Fix issue where hex titles were not automatically generated.
<?php namespace Anomaly\ColorpickerFieldType\Handler; use Anomaly\ColorpickerFieldType\ColorpickerFieldType; use Anomaly\ColorpickerFieldType\Command\ParseColors; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Support\Collection; /** * Class DefaultHandler * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> * @package Anomaly\ColorpickerFieldType\Handler */ class DefaultHandler { use DispatchesJobs; /** * Handle the predefined colors. * * @param ColorpickerFieldType $fieldType */ public function handle(ColorpickerFieldType $fieldType) { $colors = $fieldType->config('colors', []); if (is_string($colors)) { $colors = $this->dispatch(new ParseColors($colors)); } if (is_array($colors) && count(array_filter(array_keys($colors), 'is_string')) == 0) { $colors = array_combine($colors, $colors); } $fieldType->setColors((array)$colors); } }
<?php namespace Anomaly\ColorpickerFieldType\Handler; use Anomaly\ColorpickerFieldType\ColorpickerFieldType; use Anomaly\ColorpickerFieldType\Command\ParseColors; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Support\Collection; /** * Class DefaultHandler * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> * @package Anomaly\ColorpickerFieldType\Handler */ class DefaultHandler { use DispatchesJobs; /** * Handle the predefined colors. * * @param ColorpickerFieldType $fieldType */ public function handle(ColorpickerFieldType $fieldType) { $colors = $fieldType->config('colors', []); if (is_string($colors)) { $colors = $this->dispatch(new ParseColors($colors)); } $fieldType->setColors((array)$colors); } }
Remove deprecations on Ember.keys with the latest Ember release.
import Ember from 'ember'; import canUseNewSyntax from './utils/can-use-new-syntax'; const { computed } = Ember; export default function newComputed() { var polyfillArguments = []; var config = arguments[arguments.length - 1]; if (typeof config === 'function' || canUseNewSyntax) { return computed(...arguments); } for (var i = 0, l = arguments.length - 1; i < l; i++) { polyfillArguments.push(arguments[i]); } var func; if (config.set) { func = function(key, value) { if (arguments.length > 1) { return config.set.call(this, key, value); } else { return config.get.call(this, key); } }; } else { func = function(key) { return config.get.call(this, key); }; } polyfillArguments.push(func); return computed(...polyfillArguments); } const getKeys = Object.keys || Ember.keys; const computedKeys = getKeys(computed); for (let i = 0, l = computedKeys.length; i < l; i++) { newComputed[computedKeys[i]] = computed[computedKeys[i]]; }
import Ember from 'ember'; import canUseNewSyntax from './utils/can-use-new-syntax'; const { computed } = Ember; export default function newComputed() { var polyfillArguments = []; var config = arguments[arguments.length - 1]; if (typeof config === 'function' || canUseNewSyntax) { return computed(...arguments); } for (var i = 0, l = arguments.length - 1; i < l; i++) { polyfillArguments.push(arguments[i]); } var func; if (config.set) { func = function(key, value) { if (arguments.length > 1) { return config.set.call(this, key, value); } else { return config.get.call(this, key); } }; } else { func = function(key) { return config.get.call(this, key); }; } polyfillArguments.push(func); return computed(...polyfillArguments); } const computedKeys = Ember.keys(computed); for (let i = 0, l = computedKeys.length; i < l; i++) { newComputed[computedKeys[i]] = computed[computedKeys[i]]; }
Use libreoffice rather than soffice to distinguish from OpenOffice.
<?php namespace Witti\FileConverter\Engine\Convert; use Witti\FileConverter\Engine\EngineBase; class LibreOffice extends EngineBase { protected $cmd_source_safe = FALSE; public function getConvertFileShell($source, &$destination) { $destination = str_replace('.' . $this->conversion[0], '.' . $this->conversion[1], $source); return array( $this->cmd, '--headless', '--convert-to', $this->conversion[1], '--outdir', $this->settings['temp_dir'], $source ); } public function getHelpInstallation($os, $os_version) { $help = ""; switch ($os) { case 'Ubuntu': $help .= "/usr/bin/libreoffice is symlink to /usr/lib/libreoffice/program/soffice\n"; $help .= "sudo apt-get install libreoffice\n"; return $help; } return parent::getHelpInstallation(); } public function getVersionInfo() { $info = array( 'LibreOffice' => $this->shell($this->cmd . " --version") ); $info["LibreOffice"] = preg_replace('@LibreOffice *@si', '', $info['LibreOffice']); return $info; } public function isAvailable() { $this->cmd = $this->shellWhich('libreoffice'); return isset($this->cmd); } }
<?php namespace Witti\FileConverter\Engine\Convert; use Witti\FileConverter\Engine\EngineBase; class LibreOffice extends EngineBase { public function getConvertFileShell($source, &$destination) { $destination = str_replace('.' . $this->conversion[0], '.' . $this->conversion[1], $source); return array( $this->cmd, '--headless', '--convert-to', $this->conversion[1], '--outdir', $this->settings['temp_dir'], $source ); } public function getHelpInstallation($os, $os_version) { switch ($os) { case 'Ubuntu': return "sudo apt-get install libreoffice"; } return parent::getHelpInstallation(); } public function getVersionInfo() { $info = array( 'LibreOffice' => $this->shell($this->cmd . " --version") ); $info["LibreOffice"] = preg_replace('@LibreOffice *@si', '', $info['LibreOffice']); return $info; } public function isAvailable() { $this->cmd = $this->shellWhich('soffice'); return isset($this->cmd); } }
Refactor MockConversation to new model Renamed MockChat to MockConversation, remove removed administratedBy Trait
from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory, PostGeneration from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False display_name = LazyAttribute(lambda _: faker.name()) first_name = LazyAttribute(lambda _: faker.name()) last_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = PostGeneration(lambda obj, *args, **kwargs: obj.set_password(obj.display_name)) class MockConversation(Mock): class Meta: model = "yunity.Conversation" strategy = CREATE_STRATEGY @post_generation def participants(self, created, participants, **kwargs): if not created: return if participants: for participant in participants: self.participants.add(participant)
from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory, PostGeneration from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False display_name = LazyAttribute(lambda _: faker.name()) first_name = LazyAttribute(lambda _: faker.name()) last_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = PostGeneration(lambda obj, *args, **kwargs: obj.set_password(obj.display_name)) class MockChat(Mock): class Meta: model = "yunity.Conversation" strategy = CREATE_STRATEGY administrated_by = SubFactory(MockUser) @post_generation def participants(self, created, participants, **kwargs): if not created: return if participants: for participant in participants: self.participants.add(participant)
Update help text to only display the andom alias
package commands import ( "fmt" "github.com/camd67/moebot/moebot_bot/util/db" "github.com/camd67/moebot/moebot_bot/util/reddit" ) type RandomCommand struct { RedditHandle *reddit.Handle } func (ac *RandomCommand) Execute(pack *CommPackage) { send, err := ac.RedditHandle.GetRandomImage("awwnime") if err != nil { pack.session.ChannelMessageSend(pack.channel.ID, "Ooops... Looks like this command isn't working right now. Sorry!") return } pack.session.ChannelMessageSendComplex(pack.channel.ID, send) } func (ac *RandomCommand) GetPermLevel() db.Permission { return db.PermAll } func (ac *RandomCommand) GetCommandKeys() []string { return []string{"RANDOM", "R"} } func (ac *RandomCommand) GetCommandHelp(commPrefix string) string { return fmt.Sprintf("`%[1]s random` - Posts a cute anime character.", commPrefix) }
package commands import ( "fmt" "github.com/camd67/moebot/moebot_bot/util/db" "github.com/camd67/moebot/moebot_bot/util/reddit" ) type RandomCommand struct { RedditHandle *reddit.Handle } func (ac *RandomCommand) Execute(pack *CommPackage) { send, err := ac.RedditHandle.GetRandomImage("awwnime") if err != nil { pack.session.ChannelMessageSend(pack.channel.ID, "Ooops... Looks like this command isn't working right now. Sorry!") return } pack.session.ChannelMessageSendComplex(pack.channel.ID, send) } func (ac *RandomCommand) GetPermLevel() db.Permission { return db.PermAll } func (ac *RandomCommand) GetCommandKeys() []string { return []string{"RANDOM", "R"} } func (ac *RandomCommand) GetCommandHelp(commPrefix string) string { return fmt.Sprintf("`%[1]s r` or `%[1]s random` - Posts a cute anime character.", commPrefix) }
Split index route into get and post
from flask import Flask, request, render_template, flash, url_for, abort from itsdangerous import URLSafeSerializer from ca import app, db from ca.forms import RequestForm from ca.models import Request s = URLSafeSerializer(app.config['SECRET_KEY']) @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/', methods=['POST']) def post_request(): form = RequestForm(request.form) if form.validate(): req = Request(form.id.data, form.email.data) db.session.add(req) db.session.commit() token = s.dumps(req.id, salt='freifunk-ca-service') confirm_url = url_for('get_certificate', token=token, _external=True) return render_template('thanks.html') else: return render_template('index.html', form=form) @app.route('/certificates/<token>', methods=['GET']) def get_certificate(token): try: cert_id = s.loads(token, salt='freifunk-ca-service') except: abort(404) ca_req = Request.query.get_or_404(cert_id) print(ca_req) return "return key + cert here + {}".format(ca_req)
from flask import Flask, request, render_template, flash, url_for, abort from itsdangerous import URLSafeSerializer from ca import app, db from ca.forms import RequestForm from ca.models import Request s = URLSafeSerializer(app.config['SECRET_KEY']) @app.route('/', methods=['GET', 'POST']) def index(): form = RequestForm(request.form) if request.method == 'POST' and form.validate(): req = Request(form.id.data, form.email.data) db.session.add(req) db.session.commit() token = s.dumps(req.id, salt='freifunk-ca-service') confirm_url = url_for('get_certificate', token=token, _external=True) return render_template('thanks.html') return render_template('index.html', form=form) @app.route('/certificates/<token>', methods=['GET']) def get_certificate(token): try: cert_id = s.loads(token, salt='freifunk-ca-service') except: abort(404) ca_req = Request.query.get_or_404(cert_id) print(ca_req) return "return key + cert here + {}".format(ca_req)
Add forward sync support to Atom PDF opener Calls forwardSync on the PDF view on opening
'use babel' import Opener from '../opener' export default class AtomPdfOpener extends Opener { open (filePath, texPath, lineNumber, callback) { // Opens PDF in a new pane -- requires pdf-view module function forwardSync(pdfView) { if (pdfView != null && pdfView.forwardSync != null) { pdfView.forwardSync(texPath, lineNumber) } } const openPaneItems = atom.workspace.getPaneItems() for (const openPaneItem of openPaneItems) { // File is already open in another pane if (openPaneItem.filePath === filePath) { forwardSync(openPaneItem) return } } const activePane = atom.workspace.getActivePane() // TODO: Make this configurable? atom.workspace.open(filePath, {'split': 'right'}).done(function (pdfView) { forwardSync(pdfView) }) // TODO: Check for actual success? if (callback) { callback(0) } } }
'use babel' import Opener from '../opener' export default class AtomPdfOpener extends Opener { open (filePath, texPath, lineNumber, callback) { // Opens PDF in a new pane -- requires pdf-view module const openPanes = atom.workspace.getPaneItems() for (const openPane of openPanes) { // File is already open in another pane if (openPane.filePath === filePath) { return } } const pane = atom.workspace.getActivePane() // TODO: Make this configurable? // FIXME: Migrate to Pane::splitRight. const newPane = pane.split('horizontal', 'after') // FIXME: Use public API instead. atom.workspace.openURIInPane(filePath, newPane) // TODO: Check for actual success? if (callback) { callback(0) } } }
Fix parsing height and width to numbers
const numbers = [ "height", "width", "thumbnail_height", "thumbnail_width" ]; function getMetadata(text) { const parts = text.match(/\[!\[([^\]]+)+\]\(([^\)]+)\)\]\(([^\)]+)\)/); if (parts && parts.length) { const title = parts[1]; const thumbnailUrlParts = parts[2].split("#"); const originalUrl = parts[3]; const metadata = { type: "photo", url: originalUrl, thumbnail_url: thumbnailUrlParts[0].trim(), title }; const data = thumbnailUrlParts[1]; if (data) { const pairs = data.split("&"); for (let i = 0, l = pairs.length; i < l; i++) { const kv = pairs[i].split("="); metadata[kv[0]] = numbers.indexOf(kv[0]) > -1 ? parseInt(kv[1], 10) : kv[1]; } } return metadata; } else { return null; } } function getTextFromMetadata(data) { if (data.type === "photo") { return `[![${data.title}](${data.thumbnail_url}#width=${data.width}&height=${data.height}&thumbnail_width=${data.thumbnail_width}&thumbnail_height=${data.thumbnail_height})](${data.url})`; } } export default { getMetadata, getTextFromMetadata };
const numbers = [ "height", "width", "thumbnail_height", "thumbnail_width" ]; function getMetadata(text) { const parts = text.match(/\[!\[([^\]]+)+\]\(([^\)]+)\)\]\(([^\)]+)\)/); if (parts && parts.length) { const title = parts[1]; const thumbnailUrlParts = parts[2].split("#"); const originalUrl = parts[3]; const metaData = { type: "photo", url: originalUrl, thumbnail_url: thumbnailUrlParts[0].trim(), title }; const data = thumbnailUrlParts[1]; if (data) { const pairs = data.split("&"); for (let i = 0, l = pairs.length; i < l; i++) { const kv = pairs[i].split("="); metaData[kv[0]] = numbers.indexOf(kv[1]) > -1 ? parseInt(kv[1], 10) : kv[1]; } } return metaData; } else { return null; } } function getTextFromMetadata(data) { if (data.type === "photo") { return `[![${data.title}](${data.thumbnail_url}#width=${data.width}&height=${data.height}&thumbnail_width=${data.thumbnail_width}&thumbnail_height=${data.thumbnail_height})](${data.url})`; } } export default { getMetadata, getTextFromMetadata };
:bug: Fix default child route naming
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'landing-page', component: require('@/components/LandingPage') }, { path: '/new', name: 'new', component: require('@/components/NewReportSetup') }, { path: '/report', name: 'report', component: require('@/components/Report') }, { path: '/load', name: 'load', component: require('@/components/Load') }, { path: '/config', component: require('@/components/Config'), children: [ { path: '', name: 'config', redirect: 'sites' }, { path: 'sites', component: require('@/components/Config/Sites') }, { path: 'email', component: require('@/components/Config/Email') } ] } ] })
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'landing-page', component: require('@/components/LandingPage') }, { path: '/new', name: 'new', component: require('@/components/NewReportSetup') }, { path: '/report', name: 'report', component: require('@/components/Report') }, { path: '/load', name: 'load', component: require('@/components/Load') }, { path: '/config', name: 'config', component: require('@/components/Config'), children: [ { path: '', redirect: 'sites' }, { path: 'sites', component: require('@/components/Config/Sites') }, { path: 'email', component: require('@/components/Config/Email') } ] } ] })
Update jinja example to recommended syntax
""" On-demand logging ================= .. versionadded:: 2017.7.0 The sole purpose of this module is logging messages in the (proxy) minion. It comes very handy when debugging complex Jinja templates, for example: .. code-block:: jinja {%- for var in range(10) %} {%- do salt["log.info"](var) -%} {%- endfor %} CLI Example: .. code-block:: bash salt '*' log.error "Please don't do that, this module is not for CLI use!" """ import logging log = logging.getLogger(__name__) __virtualname__ = "log" __proxyenabled__ = ["*"] def __virtual__(): return __virtualname__ def debug(message): """ Log message at level DEBUG. """ log.debug(message) return True def info(message): """ Log message at level INFO. """ log.info(message) return True def warning(message): """ Log message at level WARNING. """ log.warning(message) return True def error(message): """ Log message at level ERROR. """ log.error(message) return True def critical(message): """ Log message at level CRITICAL. """ log.critical(message) return True def exception(message): """ Log message at level EXCEPTION. """ log.exception(message) return True
""" On-demand logging ================= .. versionadded:: 2017.7.0 The sole purpose of this module is logging messages in the (proxy) minion. It comes very handy when debugging complex Jinja templates, for example: .. code-block:: jinja {%- for var in range(10) %} {%- do salt.log.info(var) -%} {%- endfor %} CLI Example: .. code-block:: bash salt '*' log.error "Please don't do that, this module is not for CLI use!" """ import logging log = logging.getLogger(__name__) __virtualname__ = "log" __proxyenabled__ = ["*"] def __virtual__(): return __virtualname__ def debug(message): """ Log message at level DEBUG. """ log.debug(message) return True def info(message): """ Log message at level INFO. """ log.info(message) return True def warning(message): """ Log message at level WARNING. """ log.warning(message) return True def error(message): """ Log message at level ERROR. """ log.error(message) return True def critical(message): """ Log message at level CRITICAL. """ log.critical(message) return True def exception(message): """ Log message at level EXCEPTION. """ log.exception(message) return True
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/')) print dbs # dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check # # for db in dbs: # t1 = ibmcnx.functions.getDSId( db ) # AdminConfig.show( t1 ) # print '\n\n' # AdminConfig.showall( t1 ) # AdminConfig.showAttribute(t1,'statementCacheSize' ) # AdminConfig.showAttribute(t1,'[statementCacheSize]' )
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check for db in dbs: t1 = ibmcnx.functions.getDSId( db ) AdminConfig.show( t1 ) print '\n\n' AdminConfig.showall( t1 ) AdminConfig.showAttribute(t1,'statementCacheSize' ) AdminConfig.showAttribute(t1,'[statementCacheSize]' )
Fix tests for Mockery 0.9
<?php namespace Omnipay\MultiSafepay\Message; use Mockery as m; use Omnipay\Tests\TestCase; use ReflectionMethod; class AbstractRequestTest extends TestCase { /** * @var AbstractRequest */ private $request; protected function setUp() { $this->request = m::mock('\Omnipay\MultiSafepay\Message\AbstractRequest')->makePartial(); } /** * @covers \Omnipay\MultiSafepay\Message\AbstractRequest::getHeaders() */ public function testUserAgentHeaderMustNotBeSet() { $method = new ReflectionMethod('\Omnipay\MultiSafepay\Message\AbstractRequest', 'getHeaders'); $method->setAccessible(true); $headers = $method->invoke($this->request); $this->assertArrayHasKey('User-Agent', $headers, 'Omitting User-Agent header not allowed because then Guzzle will set it and cause 403 Forbidden on the gateway'); $this->assertEquals('Omnipay', $headers['User-Agent'], 'User-Agent header set'); } }
<?php namespace Omnipay\MultiSafepay\Message; use Mockery as m; use Omnipay\Tests\TestCase; use ReflectionMethod; class AbstractRequestTest extends TestCase { /** * @var AbstractRequest */ private $request; protected function setUp() { $this->request = m::mock('\Omnipay\MultiSafepay\Message\AbstractRequest[getData,sendData]'); } /** * @covers \Omnipay\MultiSafepay\Message\AbstractRequest::getHeaders() */ public function testUserAgentHeaderMustNotBeSet() { $method = new ReflectionMethod('\Omnipay\MultiSafepay\Message\AbstractRequest', 'getHeaders'); $method->setAccessible(true); $headers = $method->invoke($this->request); $this->assertArrayHasKey('User-Agent', $headers, 'Omitting User-Agent header not allowed because then Guzzle will set it and cause 403 Forbidden on the gateway'); $this->assertEquals('Omnipay', $headers['User-Agent'], 'User-Agent header set'); } }
Update favicon on UniqueFeed update
from django.conf import settings from django.db import connection from ..tasks import raven @raven def update_feed(feed_url, use_etags=True): from .models import UniqueFeed UniqueFeed.objects.update_feed(feed_url, use_etags) close_connection() @raven def read_later(entry_pk): from .models import Entry # circular imports Entry.objects.get(pk=entry_pk).read_later() close_connection() @raven def update_unique_feed(feed_url): from .models import UniqueFeed, Feed, Favicon feed, created = UniqueFeed.objects.get_or_create( url=feed_url, defaults={'subscribers': 1}, ) if not created: feed.subscribers = Feed.objects.filter(url=feed_url).count() feed.save() Favicon.objects.update_favicon(feed.link) def close_connection(): """Close the connection only if not in eager mode""" if hasattr(settings, 'RQ'): if not settings.RQ.get('eager', True): connection.close()
from django.conf import settings from django.db import connection from ..tasks import raven @raven def update_feed(feed_url, use_etags=True): from .models import UniqueFeed UniqueFeed.objects.update_feed(feed_url, use_etags) close_connection() @raven def read_later(entry_pk): from .models import Entry # circular imports Entry.objects.get(pk=entry_pk).read_later() close_connection() @raven def update_unique_feed(feed_url): from .models import UniqueFeed, Feed feed, created = UniqueFeed.objects.get_or_create( url=feed_url, defaults={'subscribers': 1}, ) if not created: feed.subscribers = Feed.objects.filter(url=feed_url).count() feed.save() def close_connection(): """Close the connection only if not in eager mode""" if hasattr(settings, 'RQ'): if not settings.RQ.get('eager', True): connection.close()
Add support for (t) subexpressions
/** An HTMLBars AST transformation that updates all {{t}} statements to ensure they have a namespace argument. */ var path = require('path'); function EnsureTNamespace(options) { this.syntax = null; this.options = options; } EnsureTNamespace.prototype.transform = function EnsureTNamespace_transform(ast) { var traverse = this.syntax.traverse; var builders = this.syntax.builders; var options = this.options; traverse(ast, { MustacheStatement: function(node) { if (isT(node)) { ensureNamespace(node, builders, options); } }, SubExpression: function(node) { if (isT(node)) { ensureNamespace(node, builders, options); } } }); return ast; }; function isT(node) { return node.path.original === 't'; } function ensureNamespace(node, builders, options) { var params = node.params; var templateModuleName = options.moduleName || 'unknown'; templateModuleName = templateModuleName.replace(/\.hbs$/, ''); params.push(builders.string(templateModuleName)); } module.exports = EnsureTNamespace;
/** An HTMLBars AST transformation that updates all {{t}} statements to ensure they have a namespace argument. */ var path = require('path'); function EnsureTNamespace(options) { this.syntax = null; this.options = options; } EnsureTNamespace.prototype.transform = function EnsureTNamespace_transform(ast) { var traverse = this.syntax.traverse; var builders = this.syntax.builders; var options = this.options; traverse(ast, { MustacheStatement(node) { if (isT(node)) { ensureNamespace(node, builders, options); } } }); return ast; }; function isT(node) { return node.path.original === 't'; } function ensureNamespace(node, builders, options) { var params = node.params; var templateModuleName = options.moduleName || 'unknown'; templateModuleName = templateModuleName.replace(/\.hbs$/, ''); params.push(builders.string(templateModuleName)); } module.exports = EnsureTNamespace;
Update copy and formatting for referral info
import React, { Component } from 'react'; export default class ReferralInfo extends Component { render() { return ( <div className="row text-center"> <div className= "col-xs-12 col-sm-8 col-sm-push-2 col-md-6 col-md-push-3" > <div className="spacer20"></div> <h2>Give 50GB, Get 50GB</h2> <p> Give your friends 50GB of storage and 50GB of bandwidth per month on Storj, for the next three months — all on us. <br/> After they've spent $10 on Storj, we'll give you the same. <br/>There is no limit to how many friends you can refer. </p> <div className="spacer40"></div> </div> </div> ); } }
import React, { Component } from 'react'; export default class ReferralInfo extends Component { render() { return ( <div className="row text-center"> <div className= "col-xs-12 col-sm-8 col-sm-push-2 col-md-6 col-md-push-3" > <div className="spacer20"></div> <h2>Give 50GB, Get 50GB</h2> <p>Give your friends 50GB of storage and 50GB of bandwidth on Storj for free. Once they spend $10, we'll add the same amount to your account. There is no limit to how many friends you can refer.</p> <div className="spacer40"></div> </div> </div> ); } }
Fix class name in test event
const EventEmitter = require('events').EventEmitter; /** * A very classy class with lots of class * @extends EventEmitter */ class ClassyClass extends EventEmitter { /** * Constructs a thing. */ constructor() { super(); /** * Just some thing * @type {number} */ this.thing = 42; } /** * Does stuff. * @param {?string} stuff Stuff to do * @returns {number} A thing */ doStuff(stuff) { console.log(`Doing some pretty crazy stuff with ${stuff}`); return this.thing; } /** * Who knows what this does. */ hmm() { console.log('Hmmmm..'); /** * Emitted when a thing is done * @event ClassyClass#thingDone * @param {SomeThing} thingy Thing */ this.emit('thingDone', 4242424242); } } /** * Just some thing * @typedef {Object} SomeThing * @property {number} someNumber A really cool number */ /** * Oh boy, an export! * @type {function} */ module.exports = ClassyClass;
const EventEmitter = require('events').EventEmitter; /** * A very classy class with lots of class * @extends EventEmitter */ class ClassyClass extends EventEmitter { /** * Constructs a thing. */ constructor() { super(); /** * Just some thing * @type {number} */ this.thing = 42; } /** * Does stuff. * @param {?string} stuff Stuff to do * @returns {number} A thing */ doStuff(stuff) { console.log(`Doing some pretty crazy stuff with ${stuff}`); return this.thing; } /** * Who knows what this does. */ hmm() { console.log('Hmmmm..'); /** * Emitted when a thing is done * @event SomeClass#thingDone * @param {SomeThing} thingy Thing */ this.emit('thingDone', 4242424242); } } /** * Just some thing * @typedef {Object} SomeThing * @property {number} someNumber A really cool number */ /** * Oh boy, an export! * @type {function} */ module.exports = ClassyClass;