text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Move config file to user home directory
#!/usr/local/bin/python2.7 -u __author__ = "Peter Shipley" import os import keyring import ConfigParser from ISY.IsyEvent import ISYEvent def main() : config = ConfigParser.ConfigParser() config.read(os.path.expanduser('~/isy.cfg')) server = ISYEvent() # you can subscribe to multiple devices # server.subscribe('10.1.1.25') isy_addr = config.get('isy', 'addr') isy_user = config.get('isy', 'user') server.subscribe( addr=isy_addr, userl=isy_user, userp=keyring.get_password("isy", isy_user) ) server.set_process_func(ISYEvent.print_event, "") try: print('Use Control-C to exit') server.events_loop() #no return # for d in server.event_iter( ignorelist=["_0", "_11"] ): # server.print_event(d, "") except KeyboardInterrupt: print('Exiting') if __name__ == '__main__' : main() exit(0)
#!/usr/local/bin/python2.7 -u __author__ = "Peter Shipley" import os import keyring import ConfigParser from ISY.IsyEvent import ISYEvent def main() : config = ConfigParser.ConfigParser() config.read('isy.cfg') server = ISYEvent() # you can subscribe to multiple devices # server.subscribe('10.1.1.25') isy_addr = config.get('isy', 'addr') isy_user = config.get('isy', 'user') server.subscribe( addr=isy_addr, userl=isy_user, userp=keyring.get_password("isy", isy_user) ) server.set_process_func(ISYEvent.print_event, "") try: print('Use Control-C to exit') server.events_loop() #no return # for d in server.event_iter( ignorelist=["_0", "_11"] ): # server.print_event(d, "") except KeyboardInterrupt: print('Exiting') if __name__ == '__main__' : main() exit(0)
Remove tenantId attribute, it's not used at all
package com.rcarrillocruz.android.openstackdroid; import java.io.UnsupportedEncodingException; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import android.net.Uri; import android.os.Bundle; import com.google.gson.Gson; public class GetTokenOperation implements ApiOperation { private Gson gson; private static final String urlTail = "/v2.0/tokens"; public GetTokenOperation() { super(); gson = new Gson(); } @Override public HttpRequestBase invoke(Uri endpoint, String token, String tenantId, Bundle params) { // TODO Auto-generated method stub HttpPost httpPost = new HttpPost(endpoint.toString()+urlTail); httpPost.setHeader("Content-type", "application/json"); String username = params.getString("username"); String password = params.getString("password"); GetTokenRequest request = new GetTokenRequest(new AuthObject(new PasswordCredentialsObject(params.getString("username"), params.getString("password")), tenantId)); StringEntity se = null; try { se = new StringEntity(gson.toJson(request)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } httpPost.setEntity(se); return httpPost; } }
package com.rcarrillocruz.android.openstackdroid; import java.io.UnsupportedEncodingException; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import android.net.Uri; import android.os.Bundle; import com.google.gson.Gson; public class GetTokenOperation implements ApiOperation { private Gson gson; private static final String urlTail = "/v2.0/tokens"; public GetTokenOperation() { super(); gson = new Gson(); } @Override public HttpRequestBase invoke(Uri endpoint, String token, String tenantId, Bundle params) { // TODO Auto-generated method stub HttpPost httpPost = new HttpPost(endpoint.toString()+urlTail); httpPost.setHeader("Content-type", "application/json"); String username = params.getString("username"); String password = params.getString("password"); tenantId = params.getString("tenantId"); GetTokenRequest request = new GetTokenRequest(new AuthObject(new PasswordCredentialsObject(params.getString("username"), params.getString("password")), params.getString(tenantId))); StringEntity se = null; try { se = new StringEntity(gson.toJson(request)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } httpPost.setEntity(se); return httpPost; } }
Move some requirements to extras.
from setuptools import setup, find_packages setup( name='barsystem', version='1.0.0', packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, entry_points={ 'console_scripts': [ 'barsystem-installer = barsystem.install:main' ] }, install_requires=[ 'django>=1.10,<=1.10.99', 'django-translatable', 'pytz', 'python-dateutil', 'Pillow', ], extras_require={ 'uwsgi': ['uwsgi'], 'mqtt': ['paho-mqtt'], }, license='MIT', description='', long_description='', url='https://github.com/TkkrLab/barsystem', author='Jasper Seidel', author_email='code@jawsper.nl', )
from setuptools import setup, find_packages setup( name='barsystem', version='1.0.0', packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, entry_points={ 'console_scripts': [ 'barsystem-installer = barsystem.install:main' ] }, install_requires=[ 'django>=1.10,<=1.10.99', 'django-translatable', 'pytz', 'python-dateutil', 'Pillow', 'uwsgi', 'paho-mqtt' ], license='MIT', description='', long_description='', url='https://github.com/TkkrLab/barsystem', author='Jasper Seidel', author_email='code@jawsper.nl', )
Return in releaseLocalPort funcions the number of remainder processes using them.
/* * Kurento Android Media: Android Media Library based on FFmpeg. * Copyright (C) 2011 Tikal Technologies * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.kurento.kas.media.ports; import com.kurento.kas.media.Native; public class MediaPortManager extends Native { public static int takeAudioLocalPort(){ return takeAudioLocalPort(-1); } public static native int takeAudioLocalPort(int audioPort); public static native int releaseAudioLocalPort(); public static int takeVideoLocalPort() { return takeVideoLocalPort(-1); } public static native int takeVideoLocalPort(int videoPort); public static native int releaseVideoLocalPort(); }
/* * Kurento Android Media: Android Media Library based on FFmpeg. * Copyright (C) 2011 Tikal Technologies * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.kurento.kas.media.ports; import com.kurento.kas.media.Native; public class MediaPortManager extends Native { public static int takeAudioLocalPort(){ return takeAudioLocalPort(-1); } public static native int takeAudioLocalPort(int audioPort); public static native void releaseAudioLocalPort(); public static int takeVideoLocalPort() { return takeVideoLocalPort(-1); } public static native int takeVideoLocalPort(int videoPort); public static native void releaseVideoLocalPort(); }
Make methods static where possible
package beaform.entities; import org.junit.Test; import junit.framework.TestCase; /** * Test for the formula tag. * @author Steven Post * */ public class FormulaTagTest extends TestCase { /** * Test equals. */ @Test public static void testEquals() { final FormulaTag tag1 = new FormulaTag("test"); final FormulaTag tag2 = new FormulaTag("test"); assertEquals("The tags are not equal", tag1, tag2); } /** * Test not equals. */ @Test public static void testNotEqual() { final FormulaTag tag1 = new FormulaTag("test1"); final FormulaTag tag2 = new FormulaTag("test2"); assertFalse("The tags are equal", tag1.equals(tag2)); } /** * Test hash. */ @Test public static void testEqualsHash() { final FormulaTag tag1 = new FormulaTag("test"); final FormulaTag tag2 = new FormulaTag("test"); assertEquals("The tags are not equal", tag1.hashCode(), tag2.hashCode()); } /** * Test not equals. */ @Test public static void testNotEqualsHash() { final FormulaTag tag1 = new FormulaTag("test1"); final FormulaTag tag2 = new FormulaTag("test2"); assertFalse("The tags are equal", tag1.hashCode() == tag2.hashCode()); } }
package beaform.entities; import org.junit.Test; import junit.framework.TestCase; /** * Test for the formula tag. * @author Steven Post * */ public class FormulaTagTest extends TestCase { /** * Test equals. */ @Test public void testEquals() { final FormulaTag tag1 = new FormulaTag("test"); final FormulaTag tag2 = new FormulaTag("test"); assertEquals("The tags are not equal", tag1, tag2); } /** * Test not equals. */ @Test public void testNotEqual() { final FormulaTag tag1 = new FormulaTag("test1"); final FormulaTag tag2 = new FormulaTag("test2"); assertFalse("The tags are equal", tag1.equals(tag2)); } /** * Test hash. */ @Test public void testEqualsHash() { final FormulaTag tag1 = new FormulaTag("test"); final FormulaTag tag2 = new FormulaTag("test"); assertEquals("The tags are not equal", tag1.hashCode(), tag2.hashCode()); } /** * Test not equals. */ @Test public void testNotEqualsHash() { final FormulaTag tag1 = new FormulaTag("test1"); final FormulaTag tag2 = new FormulaTag("test2"); assertFalse("The tags are equal", tag1.hashCode() == tag2.hashCode()); } }
Structure view contains value of \def or \let definition.
package nl.rubensten.texifyidea.structure; import com.intellij.navigation.ItemPresentation; import nl.rubensten.texifyidea.psi.LatexCommands; import nl.rubensten.texifyidea.util.TexifyUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author Ruben Schellekens */ public class LatexOtherCommandPresentation implements ItemPresentation { private final String commandName; private final Icon icon; private final String locationString; public LatexOtherCommandPresentation(LatexCommands command, Icon icon) { this.commandName = command.getName(); this.icon = icon; LatexCommands firstNext = TexifyUtil.getNextCommand(command); if (firstNext == null) { locationString = ""; return; } String lookup = firstNext.getCommandToken().getText(); this.locationString = lookup == null ? "" : lookup; } @Nullable @Override public String getPresentableText() { return commandName; } @Nullable @Override public String getLocationString() { return locationString; } @Nullable @Override public Icon getIcon(boolean b) { return icon; } }
package nl.rubensten.texifyidea.structure; import nl.rubensten.texifyidea.psi.LatexCommands; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author Ruben Schellekens */ public class LatexOtherCommandPresentation implements EditableHintPresentation { private final String commandName; private final Icon icon; private String hint = ""; public LatexOtherCommandPresentation(LatexCommands command, Icon icon) { this.commandName = command.getName(); this.icon = icon; } @Nullable @Override public String getPresentableText() { return commandName; } @Nullable @Override public String getLocationString() { return hint; } @Nullable @Override public Icon getIcon(boolean b) { return icon; } @Override public void setHint(@NotNull String hint) { this.hint = hint; } }
Replace outdated join function with implode
<?php /** * This file is part of PHP Mess Detector. * * Copyright (c) Manuel Pichler <mapi@phpmd.org>. * All rights reserved. * * Licensed under BSD License * For full copyright and license information, please see the LICENSE file. * Redistributions of files must retain the above copyright notice. * * @author Manuel Pichler <mapi@phpmd.org> * @copyright Manuel Pichler. All rights reserved. * @license https://opensource.org/licenses/bsd-license.php BSD License * @link http://phpmd.org/ */ namespace PHPMD\Stubs; use PHPMD\AbstractWriter; /** * Simple test implementation of PHPMD's writer. */ class WriterStub extends AbstractWriter { /** * The written data chunks. * * @var array */ public $chunks = array(); /** * Writes a data string to the concrete output. * * @param string $data The data to write. * * @return void */ public function write($data) { $this->chunks[] = $data; } /** * Returns a concated string of all data chunks. * * @return string */ public function getData() { return implode('', $this->chunks); } /** * Returns the written data chunks. * * @return array */ public function getChunks() { return $this->chunks; } }
<?php /** * This file is part of PHP Mess Detector. * * Copyright (c) Manuel Pichler <mapi@phpmd.org>. * All rights reserved. * * Licensed under BSD License * For full copyright and license information, please see the LICENSE file. * Redistributions of files must retain the above copyright notice. * * @author Manuel Pichler <mapi@phpmd.org> * @copyright Manuel Pichler. All rights reserved. * @license https://opensource.org/licenses/bsd-license.php BSD License * @link http://phpmd.org/ */ namespace PHPMD\Stubs; use PHPMD\AbstractWriter; /** * Simple test implementation of PHPMD's writer. */ class WriterStub extends AbstractWriter { /** * The written data chunks. * * @var array */ public $chunks = array(); /** * Writes a data string to the concrete output. * * @param string $data The data to write. * * @return void */ public function write($data) { $this->chunks[] = $data; } /** * Returns a concated string of all data chunks. * * @return string */ public function getData() { return join('', $this->chunks); } /** * Returns the written data chunks. * * @return array */ public function getChunks() { return $this->chunks; } }
Fix for requiring `*.ios.js` modules Also temporary workaround for `require('StaticContainer.react')`. Fixes #22
'use strict'; var fs = require('fs'); var path = require('path'); /** * Extract the React Native module paths for a given directory * * @param {String} rootDir * @return {Object} */ function getReactNativeExternals(rootDir) { var externals = {}; var file; var walk = function(dir) { fs.readdirSync(dir).forEach(function(mod) { file = path.resolve(dir, mod); if (fs.lstatSync(file).isDirectory()) { walk(file); } else if (path.extname(mod) === '.js') { mod = mod.replace(/(\.android|\.ios)?\.js$/, ''); // FIXME(mj): // This is a temporary hack until we move to getting the dependencies // from the RN packager. // See: https://github.com/mjohnston/react-native-webpack-server/issues/23 if (mod === 'StaticContainer') { mod = 'StaticContainer.react'; } // Only externalize RN's "React" dependency (uppercase). if (mod !== 'react') { externals[mod] = 'commonjs ' + mod; } } }); } walk(rootDir); // 'react-native' is aliased as `React` in the global object externals['react-native'] = 'React'; return externals; } module.exports = getReactNativeExternals;
'use strict'; var fs = require('fs'); var path = require('path'); /** * Extract the React Native module paths for a given directory * * @param {String} rootDir * @return {Object} */ function getReactNativeExternals(rootDir) { var externals = {}; var file; var walk = function(dir) { fs.readdirSync(dir).forEach(function(mod) { file = path.resolve(dir, mod); if (fs.lstatSync(file).isDirectory()) { walk(file); } else if (path.extname(mod) === '.js') { mod = mod.replace(/\.js$/, ''); // Only externalize RN's "React" dependency (uppercase). if (mod !== 'react') { externals[mod] = 'commonjs ' + mod; } } }); } walk(rootDir); // 'react-native' is aliased as `React` in the global object externals['react-native'] = 'React'; return externals; } module.exports = getReactNativeExternals;
Fix typo and use the weak boolean on the correct place.
Package.describe({ name: 'meteorflux:reactive-state', version: '1.3.5', summary: 'ReactiveState is a reactive object to save complex state data.', git: 'https://github.com/worona/meteorflux', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2'); api.use('meteorflux:namespace@1.0.0'); api.imply('meteorflux:namespace'); api.use('ecmascript'); api.use('check'); api.use('underscore'); api.use('tracker'); api.use('blaze-html-templates', { weak: true }); api.addFiles('lib/reactive-state.js', 'client'); api.export('ReactiveState', 'client'); }); Package.onTest(function(api) { api.use('ecmascript'); api.use('check'); api.use('tracker'); api.use('reactive-var'); api.use('tinytest'); api.use('blaze-html-templates'); api.use('mongo'); api.use('meteorflux:reactive-state', 'client'); api.addFiles('tests/client/reactive-state-tests.js', 'client'); api.addFiles('tests/client/reactive-state-tests.html', 'client'); });
Package.describe({ name: 'meteorflux:reactive-state', version: '1.3.5', summary: 'ReactiveState is a reactive object to save complex state data.', git: 'https://github.com/worona/meteorflux', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2'); api.use('meteorflux:namespace@1.0.0'); api.imply('meteorflux:namespace'); api.use('ecmascript'); api.use('check'); api.use('underscore'); api.use('tracker'); api.use('blaze-html-templates'); api.addFiles('lib/reactive-state.js', 'client'); api.export('ReactiveState', 'client'); }); Package.onTest(function(api) { api.use('ecmascript'); api.use('check'); api.use('tracker'); api.use('reactive-var'); api.use('tinytest'); api.use('blaze-html-templates', {week: true}); api.use('mongo'); api.use('meteorflux:reactive-state', 'client'); api.addFiles('tests/client/reactive-state-tests.js', 'client'); api.addFiles('tests/client/reactive-state-tests.html', 'client'); });
Raise ConfigurationError error that causes server to fail and dump whole stacktrace
from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: raise ConfigurationError("Unknown store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: raise ConfigurationError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass
from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: raise CubesError("Unable to find store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: raise CubesError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass
Change casing from livescript to LiveScript Hi. Interpret currently fails at loading LiveScript files because of the (unfortunate) casing of the module : https://www.npmjs.org/package/livescript vs https://www.npmjs.org/package/LiveScript Bug found while attending to load a gulpfile in ls.
var extensions = { '.co': 'coco', '.coffee': 'coffee-script/register', '.csv': 'require-csv', '.iced': 'iced-coffee-script/register', '.ini': 'require-ini', '.js': null, '.json': null, '.litcoffee': 'coffee-script/register', '.ls': 'LiveScript', '.toml': 'toml-require', '.xml': 'require-xml', '.yaml': 'require-yaml', '.yml': 'require-yaml' }; var register = { 'toml-require': function (module) { module.install(); } }; var jsVariantExtensions = [ '.co', '.coffee', '.iced', '.js', '.litcoffee', '.ls' ]; module.exports = { extensions: extensions, register: register, jsVariants: jsVariantExtensions.reduce(function (result, ext) { result[ext] = extensions[ext]; return result; }, {}) };
var extensions = { '.co': 'coco', '.coffee': 'coffee-script/register', '.csv': 'require-csv', '.iced': 'iced-coffee-script/register', '.ini': 'require-ini', '.js': null, '.json': null, '.litcoffee': 'coffee-script/register', '.ls': 'livescript', '.toml': 'toml-require', '.xml': 'require-xml', '.yaml': 'require-yaml', '.yml': 'require-yaml' }; var register = { 'toml-require': function (module) { module.install(); } }; var jsVariantExtensions = [ '.co', '.coffee', '.iced', '.js', '.litcoffee', '.ls' ]; module.exports = { extensions: extensions, register: register, jsVariants: jsVariantExtensions.reduce(function (result, ext) { result[ext] = extensions[ext]; return result; }, {}) };
Add the photo listing to use the proper image size
import React from 'react'; export default class PhotoList extends React.Component { render() { return ( <div className="row"> {this.props.photos.map((photo) => { return this.renderPhoto(photo); })} </div> ); } renderPhoto(photo) { return ( <div key={`photo-${photo.id}`} className="col-xs-6 col-md-4"> <div className="thumbnail"> <img src={`/photos/${photo.id}/medium`} /> <div className="caption"> <h5>{photo.name}</h5> <p>{photo.height}</p> <p>{photo.width}</p> <p>{photo.ext}</p> </div> </div> </div> ) } }
import React from 'react'; export default class PhotoList extends React.Component { render() { return ( <div className="row"> {this.props.photos.map((photo) => { return this.renderPhoto(photo); })} </div> ); } renderPhoto(photo) { return ( <div key={`photo-${photo.id}`} className="col-xs-6 col-md-3"> <div className="thumbnail"> <img src={`/photos/${photo.id}/large`} /> <div className="caption"> <h5>{photo.name}</h5> <p>{photo.height}</p> <p>{photo.width}</p> <p>{photo.ext}</p> </div> </div> </div> ) } }
Fix nconf to source multiple files
// Copyright 2014, Renasar Technologies Inc. /* jshint node: true */ 'use strict'; var di = require('di'), fs = require('fs'); module.exports = nconfServiceFactory; di.annotate(nconfServiceFactory, new di.Provide('Services.Configuration')); di.annotate(nconfServiceFactory, new di.Inject( 'nconf' ) ); function nconfServiceFactory(nconf) { var defaults = process.cwd() + '/config.json', overrides = process.cwd() + '/overrides.json'; nconf.use('memory'); if (fs.existsSync(overrides)) { nconf.file('overrides', overrides); } nconf.argv() .env() .file('config', defaults); return nconf; }
// Copyright 2014, Renasar Technologies Inc. /* jshint node: true */ 'use strict'; var di = require('di'), fs = require('fs'); module.exports = nconfServiceFactory; di.annotate(nconfServiceFactory, new di.Provide('Services.Configuration')); di.annotate(nconfServiceFactory, new di.Inject( 'nconf' ) ); function nconfServiceFactory(nconf) { var defaults = process.cwd() + '/config.json', overrides = process.cwd() + '/overrides.json'; nconf.use('memory') .argv() .env() .defaults(require(defaults)); if (fs.existsSync(overrides)) { nconf.defaults(require(overrides)); } return nconf; }
Remove unused fixture from orderer
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import pytest from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture def orderer(): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-')
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import pytest from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture def orderer(normal_user): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-')
Remove unneeded fix to cast setting to array.
/** * Module dependencies. */ var pkginfo = require('pkginfo') , path = require('path'); /** * Creates an entity object. * * An entity is an object with properties used to identify the application. * These properties can be used in any context in which an identifier is * needed, such as security where stable identifiers are crucial. * * @param {Settings} settings * @param {Logger} logger * @returns {Object} * @api public */ exports = module.exports = function(settings, logger) { var entity = new Object(); var id = settings.get('entity/id'); if (id) { entity.id = id; } else { entity.id = 'file://' + path.dirname(pkginfo.find(require.main)); } entity.aliases = settings.get('entity/aliases'); logger.info('Operating as entity: ' + entity.id); return entity; } /** * Component annotations. */ exports['@singleton'] = true; exports['@require'] = [ 'settings', 'logger' ];
/** * Module dependencies. */ var pkginfo = require('pkginfo') , path = require('path'); /** * Creates an entity object. * * An entity is an object with properties used to identify the application. * These properties can be used in any context in which an identifier is * needed, such as security where stable identifiers are crucial. * * @param {Settings} settings * @param {Logger} logger * @returns {Object} * @api public */ exports = module.exports = function(settings, logger) { var entity = new Object(); var id = settings.get('entity/id'); if (id) { entity.id = id; } else { entity.id = 'file://' + path.dirname(pkginfo.find(require.main)); } var aliases = settings.get('entity/aliases'); // FIX TOML var arr, i, len; if (typeof aliases == 'object') { arr = []; for (i = 0, len = Object.keys(aliases).length; i < len; ++i) { arr[i] = aliases[i]; } aliases = arr; } if (aliases) { entity.aliases = aliases; } logger.info('Operating as entity: ' + entity.id); return entity; } /** * Component annotations. */ exports['@singleton'] = true; exports['@require'] = [ 'settings', 'logger' ];
Rewrite logic as per latest syntax -@locks review
/* eslint-disable ember/classic-decorator-no-classic-methods */ import AnchorComponent from 'ember-anchor/components/ember-anchor'; import config from 'ember-api-docs/config/environment'; import getOffset from 'ember-api-docs/utils/get-offset'; export default class EmberAnchor extends AnchorComponent { // This overrides Ember Anchor to support scrolling within a fixed position element _scrollToElemPosition() { let qp = this.anchorQueryParam; let qpVal = this.a ?? this.controller[qp]; let elem = document.querySelector(`[data-${qp}="${qpVal}"]`); if (elem && elem.offsetHeight) { const offsetToScroll = getOffset( elem, config.APP.scrollContainerSelector ); const scrollContainer = document.querySelector( config.APP.scrollContainerSelector ); if (scrollContainer.scrollTo) { scrollContainer.scrollTo(0, offsetToScroll); } else { // fallback for IE11 scrollContainer.scrollTop = offsetToScroll; } } } }
import AnchorComponent from 'ember-anchor/components/ember-anchor'; import config from 'ember-api-docs/config/environment'; import getOffset from 'ember-api-docs/utils/get-offset'; export default class EmberAnchor extends AnchorComponent { // This overrides Ember Anchor to support scrolling within a fixed position element _scrollToElemPosition() { let qp = this.anchorQueryParam; let qpVal = this[this['attrs.a'] ? 'a' : `controller.${qp}`]; let elem = document.querySelector(`[data-${qp}="${qpVal}"]`); if (elem && elem.offsetHeight) { const offsetToScroll = getOffset( elem, config.APP.scrollContainerSelector ); const scrollContainer = document.querySelector( config.APP.scrollContainerSelector ); if (scrollContainer.scrollTo) { scrollContainer.scrollTo(0, offsetToScroll); } else { // fallback for IE11 scrollContainer.scrollTop = offsetToScroll; } } } }
Fix improperly instantiated class name
<?php /* * Bear Framework HTML Template * https://github.com/bearframework/html-template * Copyright (c) 2016 Ivo Petkov * Free to use under the MIT license. */ namespace BearFramework; /** * */ class HTMLTemplate { private $htmlCode = ''; private $insertedData = []; public function __construct($htmlCode) { $this->htmlCode = $htmlCode; } public function insert($name, $htmlCode) { $this->insertedData[$name] = $htmlCode; } public function getResult() { if ($this->htmlCode === '') { return ''; } $domDocument = new \IvoPetkov\HTML5DOMDocument(); $htmlCode = $this->htmlCode; foreach ($this->insertedData as $targetName => $targetHtmlCode) { $htmlCode = str_replace('{{' . $targetName . '}}', $domDocument->createInsertTarget($targetName), $htmlCode); } $domDocument->loadHTML($htmlCode); foreach ($this->insertedData as $targetName => $targetHtmlCode) { $domDocument->insertHTML($targetHtmlCode, $targetName); } return $domDocument->saveHTML(); } }
<?php /* * Bear Framework HTML Template * https://github.com/bearframework/html-template * Copyright (c) 2016 Ivo Petkov * Free to use under the MIT license. */ namespace BearFramework; /** * */ class HTMLTemplate { private $htmlCode = ''; private $insertedData = []; public function __construct($htmlCode) { $this->htmlCode = $htmlCode; } public function insert($name, $htmlCode) { $this->insertedData[$name] = $htmlCode; } public function getResult() { if ($this->htmlCode === '') { return ''; } $domDocument = new \IvoPetkov\HTML5DomDocument(); $htmlCode = $this->htmlCode; foreach ($this->insertedData as $targetName => $targetHtmlCode) { $htmlCode = str_replace('{{' . $targetName . '}}', $domDocument->createInsertTarget($targetName), $htmlCode); } $domDocument->loadHTML($htmlCode); foreach ($this->insertedData as $targetName => $targetHtmlCode) { $domDocument->insertHTML($targetHtmlCode, $targetName); } return $domDocument->saveHTML(); } }
Call the method from the willTransition method
import Ember from 'ember'; import ResetScrollMixin from '../mixins/reset-scroll'; import Analytics from '../mixins/analytics'; /** * @module ember-preprints * @submodule routes */ /** * Loads all preprint providers to search page * @class Discover Route Handler */ export default Ember.Route.extend(Analytics, ResetScrollMixin, { queryParams: { queryString: { replace: true } }, model() { return this .get('store') .findAll('preprint-provider', { reload: true }) .then(result => result.filter(item => item.id !== 'osf')); }, actions: { willTransition() { let controller = this.controllerFor('discover'); controller._clearFilters(); controller._clearQueryString(); } } });
import Ember from 'ember'; import ResetScrollMixin from '../mixins/reset-scroll'; import Analytics from '../mixins/analytics'; /** * @module ember-preprints * @submodule routes */ /** * Loads all preprint providers to search page * @class Discover Route Handler */ export default Ember.Route.extend(Analytics, ResetScrollMixin, { queryParams: { queryString: { replace: true } }, model() { return this .get('store') .findAll('preprint-provider', { reload: true }) .then(result => result.filter(item => item.id !== 'osf')); }, actions: { willTransition() { let controller = this.controllerFor('discover'); controller._clearFilters(); } } });
Set attribute of comment frame.
function receiveMessage(event) { var commentPath, frameURL; // get url of comment commentPath = event.data.commentURL; frameURL = "https://news.ycombinator.com/" + commentPath; showComments( frameURL ) } var showComments = function( URL ) { var commentFrame; commentFrame = document.querySelector( "#frameID" ); commentFrame.setAttribute( "src", URL ); } var drawIframe = function() { var frameset, pageURL, pageFrame, commentFrame, html, body; html = document.querySelector( "html" ); body = document.querySelector( "body" ); frameset = document.createElement( "frameset" ); pageFrame = document.createElement( "frame" ); commentFrame = document.createElement( "frame" ); pageFrame.setAttribute( "id", "page-frame" ); commentFrame.setAttribute( "id", "comment-frame" ); pageURL = document.URL; if ( body ) body.parentNode.removeChild( body ); frameset.appendChild( pageFrame ); frameset.appendChild( commentFrame ); html.appendChild( frameset ); pageFrame.setAttribute( "src", pageURL ); } drawIframe(); window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) { var commentPath, frameURL; // get url of comment commentPath = event.data.commentURL; frameURL = "https://news.ycombinator.com/" + commentPath; showComments( frameURL ) } var showComments = function( URL ) { var commentFrame; } var drawIframe = function() { var frameset, pageURL, pageFrame, commentFrame, html, body; html = document.querySelector( "html" ); body = document.querySelector( "body" ); frameset = document.createElement( "frameset" ); pageFrame = document.createElement( "frame" ); commentFrame = document.createElement( "frame" ); pageFrame.setAttribute( "id", "page-frame" ); commentFrame.setAttribute( "id", "comment-frame" ); pageURL = document.URL; if ( body ) body.parentNode.removeChild( body ); frameset.appendChild( pageFrame ); frameset.appendChild( commentFrame ); html.appendChild( frameset ); pageFrame.setAttribute( "src", pageURL ); } drawIframe(); window.addEventListener("message", receiveMessage, false);
Remove leftover annotation after renaming parameters
<?php namespace Illuminate\Database\Eloquent; use RuntimeException; class JsonEncodingException extends RuntimeException { /** * Create a new JSON encoding exception for the model. * * @param mixed $model * @param string $message * @return static */ public static function forModel($model, $message) { return new static('Error encoding model ['.get_class($model).'] with ID ['.$model->getKey().'] to JSON: '.$message); } /** * Create a new JSON encoding exception for an attribute. * * @param mixed $key * @param string $message * @return static */ public static function forAttribute($key, $message) { return new static('Error encoding value of attribute ['.$key.'] to JSON: '.$message); } }
<?php namespace Illuminate\Database\Eloquent; use RuntimeException; class JsonEncodingException extends RuntimeException { /** * Create a new JSON encoding exception for the model. * * @param mixed $model * @param string $message * @return static */ public static function forModel($model, $message) { return new static('Error encoding model ['.get_class($model).'] with ID ['.$model->getKey().'] to JSON: '.$message); } /** * Create a new JSON encoding exception for an attribute. * * @param mixed $key * @param string $message * @return static * @internal param mixed $key */ public static function forAttribute($key, $message) { return new static('Error encoding value of attribute ['.$key.'] to JSON: '.$message); } }
fab: Add docs and autodocs tasks
from fabric.api import execute, local, settings, task @task def preprocess_header(): local('cpp -nostdinc spotify/api.h > spotify/api.processed.h || true') @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(): local('nosetests') @task def autotest(): auto(test) def auto(task): while True: local('clear') with settings(warn_only=True): execute(task) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r spotify/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
from fabric.api import execute, local, settings, task @task def preprocess_header(): local('cpp -nostdinc spotify/api.h > spotify/api.processed.h || true') @task def test(): local('nosetests') @task def autotest(): while True: local('clear') with settings(warn_only=True): execute(test) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r spotify/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
Read text from passed in array of strings
export default function getListFieldText(data, listField) { if (typeof data === 'string') { return data } else if (typeof listField === 'string') { return buildStringFromData(data, listField) } else { if (typeof listField.fields !== 'undefined') { let connector = listField.connector ? listField.connector : ' ' return buildStringFromData(data, listField.fields, connector) } else { throw new Error('DataSelect listField must either be a string or an object') } } } function buildStringFromData(data, properties, connector=' ') { let error = 'DataSelect properties must either be a string or an array of strings' if (typeof properties === 'string') { return data.get(properties) } else if (Object.prototype.toString.call( properties ) === '[object Array]') { let string = '' for (let i = 0; i < properties.length; i++) { if (typeof properties[i] !== 'string') { throw new Error(error) } if (i !== 0) { string += connector } string += data.get(properties[i]) } return string } else { throw new Error(error) } }
export default function getListFieldText(data, listField) { if (typeof listField === 'string') { return buildStringFromData(data, listField) } else { if (typeof listField.fields !== 'undefined') { let connector = listField.connector ? listField.connector : ' ' return buildStringFromData(data, listField.fields, connector) } else { throw new Error('DataSelect listField must either be a string or an object') } } } function buildStringFromData(data, properties, connector=' ') { let error = 'DataSelect properties must either be a string or an array of strings' if (typeof properties === 'string') { return data.get(properties) } else if (Object.prototype.toString.call( properties ) === '[object Array]') { let string = '' for (let i = 0; i < properties.length; i++) { if (typeof properties[i] !== 'string') { throw new Error(error) } if (i !== 0) { string += connector } string += data.get(properties[i]) } return string } else { throw new Error(error) } }
Update first round test, create huffman based on knownalphabet
from mock import patch from breach.tests.base import RuptureTestCase from breach.strategy import Strategy class StrategyTestCase(RuptureTestCase): @patch('breach.strategy.Sniffer') def test_first_round(self, Sniffer): strategy0 = Strategy(self.victim) work0 = strategy0.get_work() self.assertEqual( work0['url'], 'https://di.uoa.gr/?breach=^testsecret0^1^' ) self.assertTrue('amount' in work0) self.assertTrue('timeout' in work0) strategy1 = Strategy(self.victim) work1 = strategy1.get_work() self.assertEqual( work1['url'], 'https://di.uoa.gr/?breach=^testsecret1^0^' ) def test_same_round_same_batch(self): pass def test_same_round_different_batch(self): pass def test_advance_round(self): pass
from mock import patch from breach.tests.base import RuptureTestCase from breach.strategy import Strategy class StrategyTestCase(RuptureTestCase): @patch('breach.strategy.Sniffer') def test_first_round(self, Sniffer): strategy0 = Strategy(self.victim) work0 = strategy0.get_work() self.assertEqual( work0['url'], 'https://di.uoa.gr/?breach=^testsecret0^1^3^2^5^4^7^6^9^8^' ) self.assertTrue('amount' in work0) self.assertTrue('timeout' in work0) strategy1 = Strategy(self.victim) work1 = strategy1.get_work() self.assertEqual( work1['url'], 'https://di.uoa.gr/?breach=^testsecret1^0^3^2^5^4^7^6^9^8^' ) def test_same_round_same_batch(self): pass def test_same_round_different_batch(self): pass def test_advance_round(self): pass
Fix isValid return statement logic
package com.epam.rft.atsy.service.passwordchange.validation.impl; import com.epam.rft.atsy.service.domain.PasswordChangeDTO; import com.epam.rft.atsy.service.passwordchange.validation.PasswordValidationRule; import org.apache.commons.lang3.StringUtils; public class PasswordAllFieldFilledRule implements PasswordValidationRule { private static final String MESSAGE_KEY = "passwordchange.validation.allfieldfilled"; @Override public boolean isValid(PasswordChangeDTO passwordChangeDTO) { String newPassword = passwordChangeDTO.getNewPassword(); String oldPassword = passwordChangeDTO.getOldPassword(); String newPasswordConfirm = passwordChangeDTO.getNewPasswordConfirm(); return StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPasswordConfirm); } @Override public String getErrorMessageKey() { return MESSAGE_KEY; } }
package com.epam.rft.atsy.service.passwordchange.validation.impl; import com.epam.rft.atsy.service.domain.PasswordChangeDTO; import com.epam.rft.atsy.service.passwordchange.validation.PasswordValidationRule; import org.apache.commons.lang3.StringUtils; public class PasswordAllFieldFilledRule implements PasswordValidationRule { private static final String MESSAGE_KEY = "passwordchange.validation.allfieldfilled"; @Override public boolean isValid(PasswordChangeDTO passwordChangeDTO) { String newPassword = passwordChangeDTO.getNewPassword(); return StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(newPassword); } @Override public String getErrorMessageKey() { return MESSAGE_KEY; } }
TASK: Send redirect after the resource was read and this imported from proxy
<?php namespace Sitegeist\MagicWand\Controller; use Neos\Flow\Annotations as Flow; use Neos\Flow\Mvc\Controller\ActionController; use Neos\Flow\ResourceManagement\PersistentResource; use Neos\Flow\ResourceManagement\ResourceRepository; use Neos\Flow\ResourceManagement\ResourceManager; use Sitegeist\MagicWand\ResourceManagement\ResourceNotFoundException; class ResourceController extends ActionController { /** * @var ResourceRepository * @Flow\Inject */ protected $resourceRepository; /** * @var ResourceManager * @Flow\Inject */ protected $resourceManager; /** * @param string $resourceIdentifier */ public function indexAction(string $resourceIdentifier) { /** * @var PersistentResource $resource */ $resource = $this->resourceRepository->findByIdentifier($resourceIdentifier); if ($resource) { $sourceStream = $resource->getStream(); if ($sourceStream !== false) { fclose($sourceStream); $this->redirectToUri($this->resourceManager->getPublicPersistentResourceUri($resource), 0, 302); } } throw new ResourceNotFoundException("Unknown resource"); } }
<?php namespace Sitegeist\MagicWand\Controller; use Neos\Flow\Annotations as Flow; use Neos\Flow\Mvc\Controller\ActionController; use Neos\Flow\ResourceManagement\PersistentResource; use Neos\Flow\ResourceManagement\ResourceRepository; use Sitegeist\MagicWand\ResourceManagement\ResourceNotFoundException; class ResourceController extends ActionController { /** * @var ResourceRepository * @Flow\Inject */ protected $resourceRepository; /** * @param string $resourceIdentifier */ public function indexAction(string $resourceIdentifier) { /** * @var PersistentResource $resource */ $resource = $this->resourceRepository->findByIdentifier($resourceIdentifier); if ($resource) { $headers = $this->response->getHeaders(); $headers->set('Content-Type', $resource->getMediaType(), true); $this->response->setHeaders($headers); $sourceStream = $resource->getStream(); $streamContent = stream_get_contents($sourceStream); fclose($sourceStream); return $streamContent; } else { throw new ResourceNotFoundException("Unkonwn Resource"); } } }
Change 'div' element of validation error to 'p'
/** * Copyright 2015 Jaime Pajuelo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; fmval.validators.ValidationError = (function () { /** * @constructor * @param {String} message */ var ValidationError = function ValidationError(message) { this.parentClass.captureStackTrace(this, this.constructor); this.message = message; this.element = document.createElement('p'); this.element.className = "control-error"; this.element.textContent = message; }; ValidationError.inherit(Error); /** * @type {String} */ ValidationError.member('name', "ValidationError"); return ValidationError; })();
/** * Copyright 2015 Jaime Pajuelo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; fmval.validators.ValidationError = (function () { /** * @constructor * @param {String} message */ var ValidationError = function ValidationError(message) { this.parentClass.captureStackTrace(this, this.constructor); this.message = message; this.element = document.createElement('div'); this.element.className = "control-error"; this.element.textContent = message; }; ValidationError.inherit(Error); /** * @type {String} */ ValidationError.member('name', "ValidationError"); return ValidationError; })();
Fix a bug with the hardcoded location for the name search API - Implemented getHostLocation() in appConfig.js
(function($, window, _, undefined){ $(function() { jQuery.extend(jQuery.validator.messages, { required : "Това поле е задължително", minlength : jQuery.validator.format("Моля въведете поне {0} символа") }); }); var getHostLocation = function() { var loc = window.location; return loc.protocol + "//" + loc.hostname + ":" + loc.port; }; var appConfig = { projectName : "Diaphanum", textAreaValidationReq : { required: true, minlength: 140 }, nameSearchUrl : getHostLocation() + "/search/" }; window.Diaphanum = {}; window.Diaphanum.appConfig = appConfig; window.Diaphanum.validationRequirementsFromAttributes=function(inputNameValue) { var inputObject=$("input[name="+inputNameValue+"]"); var resultObject = {}; if ( inputObject.is('[maxlength]') ) { resultObject.maxlength=inputObject.attr('maxlength'); } if ( inputObject.is('[minlength]') ) { resultObject.minlength=inputObject.attr('minlength'); } if ( inputObject.is('[required]') ) { resultObject.required=true; } if ( inputObject.is("input[type=email]") ) { resultObject.email=true; } return resultObject; }; })($, window, _);
(function($, window, _, undefined){ $(function() { jQuery.extend(jQuery.validator.messages, { required : "Това поле е задължително", minlength : jQuery.validator.format("Моля въведете поне {0} символа") }); }); var appConfig = { projectName : "Diaphanum", textAreaValidationReq : { required: true, minlength: 140 }, nameSearchUrl : "http://localhost:8000/search/" }; window.Diaphanum = {}; window.Diaphanum.appConfig = appConfig; window.Diaphanum.validationRequirementsFromAttributes=function(inputNameValue) { var inputObject=$("input[name="+inputNameValue+"]"); var resultObject = {}; if ( inputObject.is('[maxlength]') ) { resultObject.maxlength=inputObject.attr('maxlength'); } if ( inputObject.is('[minlength]') ) { resultObject.minlength=inputObject.attr('minlength'); } if ( inputObject.is('[required]') ) { resultObject.required=true; } if ( inputObject.is("input[type=email]") ) { resultObject.email=true; } return resultObject; }; })($, window, _);
Fix bug causing components to not show up in data-selection
import Service from '@ember/service'; import Evented from '@ember/object/evented'; export default Service.extend(Evented, { shownComponents: null, data: null, showWindow: false, addComponent(path) { if(!this.get('shownComponents')) this.set('shownComponents', []); if (!this.get('shownComponents').includes(path)) { this.get('shownComponents').push(path); } }, removeComponent(path) { if(!this.get('shownComponents')) return; var index = this.get('shownComponents').indexOf(path); if (index !== -1) this.get('shownComponents').splice(index, 1); // close everything when no components are left if (this.get('shownComponents.length') == 0) this.emptyAdditionalData() }, emptyAdditionalData() { this.closeAdditionalData(); this.set('shownComponents.length', 0); this.set('data', null); }, closeAdditionalData() { this.set('showWindow', false); this.trigger('showWindow'); }, openAdditionalData() { this.set('showWindow', true); this.trigger('showWindow'); } });
import Service from '@ember/service'; import Evented from '@ember/object/evented'; export default Service.extend(Evented, { shownComponents: null, data: null, showWindow: false, addComponent(path) { if(!this.get('shownComponents')) this.set('shownComponents', []); if (!this.get('shownComponents').includes(path)) { this.get('shownComponents').push(path); } }, removeComponent(path) { if(!this.get('shownComponents')) return; var index = this.get('shownComponents').indexOf(path); if (index !== -1) this.get('shownComponents').splice(index, 1); // close everything when no components are left if (this.get('shownComponents.length') == 0) this.emptyAdditionalData() }, emptyAdditionalData() { this.set('shownComponents', []); this.set('data', null); }, closeAdditionalData() { this.set('showWindow', false); this.trigger('showWindow'); }, openAdditionalData() { this.set('showWindow', true); this.trigger('showWindow'); } });
Set my email address from contact form
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $to = 'zbeekman@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@izaakbeekman.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $to = 'jerome.lachaud@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
Update theming for select month view
<?php defined('BASEPATH') or exit('No direct script access allowed'); // select_month.php Chris Dart Dec 29, 2013 5:04:43 PM // chrisdart@cerebratorium.com $buttons[] = array( "item" => "expense", "text" => "Go", "type" => "span", "class" => "button btn btn-sm btn-primary go-to-month" ); $buttons[] = array( "item" => "expense", "text" => "Current Month", "type" => "span", "class" => "button btn btn-sm btn-primary show-current-month" ); ?> <div id="month-selector"> <p> <?php echo form_dropdown("search-month",$month_list,$default_month,"id='search-month'");?> &nbsp;<input type="text" size="5" maxlength="4" id="search-year" name="search-year" value="<?php echo $default_year;?>" /> </p> <?php echo create_button_bar($buttons);?> </div>
<?php defined('BASEPATH') or exit('No direct script access allowed'); // select_month.php Chris Dart Dec 29, 2013 5:04:43 PM // chrisdart@cerebratorium.com $buttons[] = array( "item" => "expense", "text" => "Go", "type" => "span", "class" => "button go-to-month" ); $buttons[] = array( "item" => "expense", "text" => "Current Month", "type" => "span", "class" => "button show-current-month" ); ?> <div id="month-selector"> <p> <?php echo form_dropdown("search-month",$month_list,$default_month,"id='search-month'");?> &nbsp;<input type="text" size="5" maxlength="4" id="search-year" name="search-year" value="<?php echo $default_year;?>" /> </p> <?php echo create_button_bar($buttons);?> </div>
Use Write instead of Create fsnotify event I noticed that occasionally the cert file would get created and autosignr would pick up on it before the cert would get written out. This would lead to a `No PEM data found in block` error, when in fact the cert just hadn't been written to the file yet. This change now waits until the file is written to and should now contain the data.
package autosignr import ( log "github.com/Sirupsen/logrus" "gopkg.in/fsnotify.v1" ) func WatchDir(conf Config) { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() done := make(chan bool) go func() { for { select { case event := <-watcher.Events: if event.Op&fsnotify.Write == fsnotify.Write { result, _ := CheckCert(conf, event.Name) if result { SignCert(conf, CertnameFromFilename(event.Name)) } } case err := <-watcher.Errors: log.Println("error:", err) } } }() log.Printf("watching %s", conf.Dir) err = watcher.Add(conf.Dir) if err != nil { log.Fatal(err) } <-done }
package autosignr import ( log "github.com/Sirupsen/logrus" "gopkg.in/fsnotify.v1" ) func WatchDir(conf Config) { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() done := make(chan bool) go func() { for { select { case event := <-watcher.Events: if event.Op&fsnotify.Create == fsnotify.Create { result, _ := CheckCert(conf, event.Name) if result { SignCert(conf, CertnameFromFilename(event.Name)) } } case err := <-watcher.Errors: log.Println("error:", err) } } }() log.Printf("watching %s", conf.Dir) err = watcher.Add(conf.Dir) if err != nil { log.Fatal(err) } <-done }
Put $this->lang and $this->db in the entity translate
<?php namespace ContentTranslator\Entity; class Translate { protected $lang; protected $db; public function __construct() { global $wpdb; $this->db = $wpdb; $this->lang = \ContentTranslator\Switcher::$currentLanguage->code; } /** * Creates a language specific meta/options key * @param string $key The meta/option key * @return string Langual meta/option key */ protected function createLangualKey(string $key) : string { if ($this->isLangualOption($key)) { return $key; } return $key . TRANSLATE_DELIMITER . $this->lang; } /** * Check if key is a langual option * @param string $key Option key * @return boolean */ protected function isLangualOption($key) { return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false; } }
<?php namespace ContentTranslator\Entity; class Translate { /** * Creates a language specific meta/options key * @param string $key The meta/option key * @return string Langual meta/option key */ protected function createLangualKey(string $key) : string { if ($this->isLangualOption($key)) { return $key; } return $key . TRANSLATE_DELIMITER . $this->lang; } /** * Check if key is a langual option * @param string $key Option key * @return boolean */ protected function isLangualOption($key) { return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false; } }
Add docstring to function and refactor some code for clarification
import os import json import sys CURRENT_DIR = os.path.abspath(os.path.dirname(sys.argv[0])) def get_item(key): """Return content in cached file in JSON format""" CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key) try: return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"] except (IOError, ValueError): return None def set_item(key,value): """Write JSON content from value argument to cached file and return""" CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key) open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8')) return value def delete_item(key): """Delete cached file if present""" CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key) if os.path.isfile(CACHED_KEY_FILE): os.remove(CACHED_KEY_FILE)
import os import json import sys def get_item(key): try: return json.loads(open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "rb").read().decode('UTF-8'))["_"] except (IOError, ValueError): return None def set_item(key,value): open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "wb").write(json.dumps({"_": value}).encode('UTF-8')) return value def delete_item(key): if os.path.isfile(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key)): os.remove(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key))
:children_crossing: Set app infos from environments automatically (for JS SDK 4)
'use strict'; var AV = require('leancloud-storage/live-query'); AV._config.disableCurrentUser = true; if (process.env.LEANCLOUD_REGION) { AV._config.region = process.env.LEANCLOUD_REGION; } if (process.env.LEANCLOUD_APP_ANDX_KEY) { AV._config.androidxKey = process.env.LEANCLOUD_APP_ANDX_KEY; } if (process.env.LC_API_SERVER) { AV.setServerURLs(process.env.LC_API_SERVER); } if (process.env.LEANCLOUD_API_SERVER) { AV.setServerURLs(process.env.LEANCLOUD_API_SERVER); } if (AV.version && !AV.version.match(/^[0123]\./)) { AV._config.applicationId = process.env.LEANCLOUD_APP_ID; AV._config.applicationKey = process.env.LEANCLOUD_APP_KEY; AV._config.masterKey = process.env.LEANCLOUD_APP_MASTER_KEY; AV._config.hookKey = process.env.LEANCLOUD_APP_HOOK_KEY; } AV._sharedConfig.userAgent = 'AVOS Cloud Code Node ' + require('../package').version; AV.Cloud.__prod = process.env.NODE_ENV === 'production' ? 1 : 0; AV.setProduction(AV.Cloud.__prod); module.exports = AV;
'use strict'; var AV = require('leancloud-storage/live-query'); AV._config.disableCurrentUser = true; if (process.env.LEANCLOUD_REGION) { AV._config.region = process.env.LEANCLOUD_REGION; } if (process.env.LEANCLOUD_APP_ANDX_KEY) { AV._config.androidxKey = process.env.LEANCLOUD_APP_ANDX_KEY; } if (process.env.LC_API_SERVER) { AV.setServerURLs(process.env.LC_API_SERVER); } if (process.env.LEANCLOUD_API_SERVER) { AV.setServerURLs(process.env.LEANCLOUD_API_SERVER); } AV._sharedConfig.userAgent = 'AVOS Cloud Code Node ' + require('../package').version; AV.Cloud.__prod = process.env.NODE_ENV === 'production' ? 1 : 0; AV.setProduction(AV.Cloud.__prod); module.exports = AV;
Use l instead of t
'use strict' module.exports = tempest tempest.compile = compile tempest.render = render function tempest (s) { for (var i = 0, p = [], e = [], f, l, o = '{{', c = '}}';;) { f = s.indexOf(o, l) if (f < 0) break p[i] = s.slice(l, f) l = s.indexOf(c, f) e[i++] = s.slice(f + 2, l) l = l + 2 } p[i] = s.slice(l) return [p, e] } function compile (t, d) { for (var i = 0, s = '', p = t[0], e = t[1], l = e.length; i < l; s += p[i] + (d[e[i++]] || '')); return s + p[i] } function render (s, d) { return compile(tempest(s), d) }
'use strict' module.exports = tempest tempest.compile = compile tempest.render = render function tempest (s) { for (var i = 0, t = 0, p = [], e = [], f, l, o = '{{', c = '}}';;) { f = s.indexOf(o, t) if (f < 0) break p[i] = s.slice(t, f) l = s.indexOf(c, f) e[i++] = s.slice(f + 2, l) t = l + 2 } p[i] = s.slice(t) return [p, e] } function compile (t, d) { for (var i = 0, s = '', p = t[0], e = t[1], l = e.length; i < l; s += p[i] + (d[e[i++]] || '')); return s + p[i] } function render (s, d) { return compile(tempest(s), d) }
Change object to retrieve if the tab is active or not for onUpdated.
chrome.tabs.onActivated.addListener(function(info) { chrome.tabs.get(info.tabId, function(tab) { updateIcon(tab.url); }); }); chrome.tabs.onUpdated.addListener(function(tabID, changeInfo, tab) { if (tab.active) { updateIcon(tab.url); } }); function updateIcon(url) { chrome.storage.sync.get('sites', function(items) { sites = items['sites']; changeIcon(false, null); if (url.substring(url.length - 1) == '/') { url = url.substring(0, url.length - 1); } if (sites) { for (var i = 0; i < sites.length; i++) { if (sites[i].url == url) { changeIcon(true, null); break; } } } }); } function changeIcon(colors, callback) { var details = {}; if (colors) { details.path = '../icons/icon-bitty.png'; } else { details.path = '../icons/icon-bitty-gray.png'; } chrome.browserAction.setIcon(details, callback); }
chrome.tabs.onActivated.addListener(function(info) { chrome.tabs.get(info.tabId, function(tab) { updateIcon(tab.url); }); }); chrome.tabs.onUpdated.addListener(function(tabID, changeInfo, tab) { if (changeInfo.active) { updateIcon(tab.url); } }); function updateIcon(url) { chrome.storage.sync.get('sites', function(items) { sites = items['sites']; changeIcon(false, null); if (url.substring(url.length - 1) == '/') { url = url.substring(0, url.length - 1); } if (sites) { for (var i = 0; i < sites.length; i++) { if (sites[i].url == url) { changeIcon(true, null); break; } } } }); } function changeIcon(colors, callback) { var details = {}; if (colors) { details.path = '../icons/icon-bitty.png'; } else { details.path = '../icons/icon-bitty-gray.png'; } chrome.browserAction.setIcon(details, callback); }
Update calendar constructors to take in recurrence types.
<?php namespace Plummer\Calendar; class Calendar { protected $events; protected $recurrenceTypes; protected function __construct(\Iterator $events, $recurrenceTypes) { $this->events = $events; $this->addRecurrenceTypes($recurrenceTypes); } public static function make(\Iterator $events, $recurrenceTypes = []) { return new static($events, $recurrenceTypes); } public function addEvents(array $events) { foreach($events as $event) { $this->addEvent($event); } } public function addEvent(Event $event) { $event->setCalendar($this); $this->events[] = $event; } public function addRecurrenceTypes(array $recurrenceTypes) { foreach($recurrenceTypes as $recurrenceType) { $this->addRecurrenceType($recurrenceType); } } public function addRecurrenceType(RecurrenceInterface $recurrenceType) { $this->recurrenceTypes[] = $recurrenceType; } }
<?php namespace Plummer\Calendar; class Calendar { protected $events; protected $recurrenceTypes; protected function __construct(\Iterator $events) { $this->events = $events; } public static function make(\Iterator $events) { return new static($events); } public function addEvents(array $events) { foreach($events as $event) { $this->addEvent($event); } } public function addEvent(Event $event) { $event->setCalendar($this); $this->events[] = $event; } public function addRecurrenceTypes(array $recurrenceTypes) { foreach($recurrenceTypes as $recurrenceType) { $this->addRecurrenceType($recurrenceType); } } public function addRecurrenceType(RecurrenceInterface $recurrenceType) { $this->recurrenceTypes[] = $recurrenceType; } }
Rename dependant to dependent (American English)
'use strict' var semver = require('semver') var sub = require('subleveldown') var DepDb = require('dependency-db') module.exports = function (db, name, range, opts) { range = String(range || '*') var depDb = new DepDb(sub(db, 'depdb')) if (!name) throw new Error('missing required name') if (!opts.csv) console.log('Looking up %s %s dependents...', name, range) var pkgCount = 0 var lastName var lastVersion var lastDependency var results = depDb.query(name, range, {all: opts.all || opts.outdated, devDependencies: opts.dev}) results.on('error', function (err) { throw err }) results.on('data', function (pkg) { if (opts.all || !opts.outdated || (lastName && lastName !== pkg.name)) { flush() } else if (lastVersion && semver.lt(pkg.version, lastVersion)) { return } lastName = pkg.name lastVersion = pkg.version lastDependency = opts.dev ? pkg.devDependencies[name] : pkg.dependencies[name] }) results.on('end', function () { flush() if (!opts.csv) console.log('Found %d results', pkgCount) }) function flush () { if (!lastName) return pkgCount++ console.log(opts.csv ? '%s,%s,%s' : '- %s@%s (dependency: %s)', lastName, lastVersion, lastDependency) } }
'use strict' var semver = require('semver') var sub = require('subleveldown') var DepDb = require('dependency-db') module.exports = function (db, name, range, opts) { range = String(range || '*') var depDb = new DepDb(sub(db, 'depdb')) if (!name) throw new Error('missing required name') if (!opts.csv) console.log('Looking up %s %s dependants...', name, range) var pkgCount = 0 var lastName var lastVersion var lastDependency var results = depDb.query(name, range, {all: opts.all || opts.outdated, devDependencies: opts.dev}) results.on('error', function (err) { throw err }) results.on('data', function (pkg) { if (opts.all || !opts.outdated || (lastName && lastName !== pkg.name)) { flush() } else if (lastVersion && semver.lt(pkg.version, lastVersion)) { return } lastName = pkg.name lastVersion = pkg.version lastDependency = opts.dev ? pkg.devDependencies[name] : pkg.dependencies[name] }) results.on('end', function () { flush() if (!opts.csv) console.log('Found %d results', pkgCount) }) function flush () { if (!lastName) return pkgCount++ console.log(opts.csv ? '%s,%s,%s' : '- %s@%s (dependency: %s)', lastName, lastVersion, lastDependency) } }
Revert table ordering tweaks to alert list This causes weird behaviour in GMail because of how it hides duplicated content. The header toggles between under/over the alert list on every other email.
<?php namespace FOO; ?> <div style="<?= $panel_style ?>; display: table; width: 100%"> <div style="display:table-header-group;"> <h2 style="<?= $panel_content_style ?>"> <a style="<?= $link_style ?>" href="<?= $base_url ?>/search/<?= $search['id'] ?>"><?= Util::escape($search['name']) ?></a> <small style="<?= $sub_style ?>">[<?= count($alerts) ?> Alert<?= count($alerts) != 1 ? 's':'' ?>]</small> </h2> <p style="<?= $panel_content_style ?>"> <?= nl2br(Util::escape($search['description'])) ?> <?php if($search->isTimeBased()): ?> <br> <br> <b>Time range: </b><?= $search['range'] ?> minute(s) <?php endif ?> </p> </div> <div style="<?= $table_container_style ?>"> <?php if($vertical): ?> <?php require(__DIR__ . '/alert_list.php'); ?> <?php else: ?> <?php require(__DIR__ . '/alert_table.php'); ?> <?php endif ?> </div> </div>
<?php namespace FOO; ?> <div style="<?= $panel_style ?>; display: table; width: 100%"> <div style="<?= $table_container_style ?>"> <?php if($vertical): ?> <?php require(__DIR__ . '/alert_list.php'); ?> <?php else: ?> <?php require(__DIR__ . '/alert_table.php'); ?> <?php endif ?> </div> <div style="display:table-header-group;"> <h2 style="<?= $panel_content_style ?>"> <a style="<?= $link_style ?>" href="<?= $base_url ?>/search/<?= $search['id'] ?>"><?= Util::escape($search['name']) ?></a> <small style="<?= $sub_style ?>">[<?= count($alerts) ?> Alert<?= count($alerts) != 1 ? 's':'' ?>]</small> </h2> <p style="<?= $panel_content_style ?>"> <?= nl2br(Util::escape($search['description'])) ?> <?php if($search->isTimeBased()): ?> <br> <br> <b>Time range: </b><?= $search['range'] ?> minute(s) <?php endif ?> </p> </div> </div>
Use stderr to output an error
package main import ( "bufio" "fmt" "os" "regexp" ) func grep(pattern string, infile *os.File) { scanner := bufio.NewScanner(infile) for scanner.Scan() { line := scanner.Text() matched, err := regexp.MatchString(pattern, line) if err != nil { panic(err) } if matched { fmt.Println(line) } } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } } func main() { var pattern string var infile *os.File var err error switch count := len(os.Args); { case count > 2: pattern = os.Args[1] infile, err = os.Open(os.Args[2]) if err != nil { panic(err) } case count > 1: infile = os.Stdin default: fmt.Fprintln(os.Stderr, "usage: grep pattern [file]") os.Exit(1) } grep(pattern, infile) }
package main import ( "bufio" "fmt" "os" "regexp" ) func grep(pattern string, infile *os.File) { scanner := bufio.NewScanner(infile) for scanner.Scan() { line := scanner.Text() matched, err := regexp.MatchString(pattern, line) if err != nil { panic(err) } if matched { fmt.Println(line) } } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } } func main() { var pattern string var infile *os.File var err error switch count := len(os.Args); { case count > 2: pattern = os.Args[1] infile, err = os.Open(os.Args[2]) if err != nil { panic(err) } case count > 1: infile = os.Stdin default: fmt.Println("usage: grep pattern [file]") os.Exit(1) } grep(pattern, infile) }
Make sure HOME is set when installing busket. Erlang requires it
import os from kokki import * Package("erlang") # ubuntu's erlang is a bit messed up.. remove the man link File("/usr/lib/erlang/man", action = "delete") # Package("mercurial", # provider = "kokki.providers.package.easy_install.EasyInstallProvider") command = os.path.join(env.config.busket.path, "bin", "busket") Service("busket", start_command = "%s start" % command, stop_command = "%s stop" % command, restart_command = "{0} start || {0} restart".format(command), status_command = "%s ping" % command, action = "nothing") Script("install-busket", not_if = lambda:os.path.exists(env.config.busket.path), cwd = "/usr/local/src", code = ( "git clone git://github.com/samuel/busket.git busket\n" "cd busket\n" "mkdir /tmp/erlhome\n" "export HOME=/tmp/erlhome\n" "make release\n" "mv rel/busket {install_path}\n" ).format(install_path=env.config.busket.path), notifies = [("start", env.resources["Service"]["busket"])], )
import os from kokki import * Package("erlang") # ubuntu's erlang is a bit messed up.. remove the man link File("/usr/lib/erlang/man", action = "delete") # Package("mercurial", # provider = "kokki.providers.package.easy_install.EasyInstallProvider") command = os.path.join(env.config.busket.path, "bin", "busket") Service("busket", start_command = "%s start" % command, stop_command = "%s stop" % command, restart_command = "{0} start || {0} restart".format(command), status_command = "%s ping" % command, action = "nothing") Script("install-busket", not_if = lambda:os.path.exists(env.config.busket.path), cwd = "/usr/local/src", code = ( "git clone git://github.com/samuel/busket.git busket\n" "cd busket\n" "make release\n" "mv rel/busket {install_path}\n" ).format(install_path=env.config.busket.path), notifies = [("start", env.resources["Service"]["busket"])], )
Add message browser out of date for all msie
import addFavicon from './helpers'; import LazyLoad from 'vanilla-lazyload'; const bowser = require('bowser'); if (bowser.msie) { $('.browser').removeClass('hide'); } else if (bowser.msedge && bowser.version < 12) { $('.browser').removeClass('hide'); } else if (bowser.chrome && bowser.version < 64) { $('.browser').removeClass('hide'); } else if (bowser.firefox && bowser.version < 58) { $('.browser').removeClass('hide'); } $(document).ready(() => { new LazyLoad(); $(document).foundation(); if(document.cookie.indexOf('cookie_enabled') == -1) { $('.header__cookies').removeClass('hide'); } $('#js-cookie__validate').click(() => { if(document.cookie.indexOf('cookie_enabled') == -1) { document.cookie = 'cookie_enabled=true; expires=Fri, 3 Aug 2100 20:47:11 UTC; path=/'; $('.header__cookies').addClass('hide'); } }); addFavicon(); });
import addFavicon from './helpers'; import LazyLoad from 'vanilla-lazyload'; const bowser = require('bowser'); if (bowser.msie && bowser.version < 11) { $('.browser').removeClass('hide'); } else if (bowser.chrome && bowser.version < 64) { $('.browser').removeClass('hide'); } else if (bowser.firefox && bowser.version < 58) { $('.browser').removeClass('hide'); } $(document).ready(() => { new LazyLoad(); $(document).foundation(); if(document.cookie.indexOf('cookie_enabled') == -1) { $('.header__cookies').removeClass('hide'); } $('#js-cookie__validate').click(() => { if(document.cookie.indexOf('cookie_enabled') == -1) { document.cookie = 'cookie_enabled=true; expires=Fri, 3 Aug 2100 20:47:11 UTC; path=/'; $('.header__cookies').addClass('hide'); } }); addFavicon(); });
Increase timeout of update_graph job to 7 days
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def queue_update_job(): q.enqueue(jobs.update_graph, timeout=604800) # 7 day timeout @sched.scheduled_job('interval', minutes=1) def queue_stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', minutes=1) def queue_export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() # Wait a bit for Sesame to start time.sleep(10) # Queue the stats job first. This creates the repository before any other # jobs are run. q.enqueue(jobs.calculate_stats) # Start the scheduler sched.start()
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def queue_update_job(): q.enqueue(jobs.update_graph, timeout=3600) # 1hr timeout @sched.scheduled_job('interval', minutes=1) def queue_stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', minutes=1) def queue_export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() # Wait a bit for Sesame to start time.sleep(10) # Queue the stats job first. This creates the repository before any other # jobs are run. q.enqueue(jobs.calculate_stats) # Start the scheduler sched.start()
Fix eslint import resolver path.
var path = require('path'); module.exports = { env: { es6: true, browser: true, node: true, }, parserOptions: { sourceType: 'module', ecmaVersion: 7, ecmaFeatures: { impliedStrict: true, experimentalObjectRestSpread: true, }, }, globals: { __version: true, __coreAPISpec: true, __filename: true, __publicPath: true, }, extends: [ 'eslint:recommended', 'prettier', 'plugin:vue/recommended', 'plugin:import/errors', 'plugin:import/warnings', ], plugins: ['import', 'vue'], settings: { 'import/resolver': { [path.resolve( path.join(path.dirname(__filename), './frontend_build/src/alias_import_resolver.js') )]: { extensions: ['.js', '.vue'], }, }, }, rules: { 'vue/v-bind-style': 2, 'vue/v-on-style': 2, 'vue/html-quotes': [2, 'double'], 'vue/order-in-components': 2, 'comma-style': 2, }, };
var path = require('path'); module.exports = { env: { es6: true, browser: true, node: true, }, parserOptions: { sourceType: 'module', ecmaVersion: 7, ecmaFeatures: { impliedStrict: true, experimentalObjectRestSpread: true, }, }, globals: { __version: true, __coreAPISpec: true, __filename: true, __publicPath: true, }, extends: [ 'eslint:recommended', 'prettier', 'plugin:vue/recommended', 'plugin:import/errors', 'plugin:import/warnings', ], plugins: ['import', 'vue'], settings: { 'import/resolver': { [path.resolve('./frontend_build/src/alias_import_resolver.js')]: { extensions: ['.js', '.vue'], }, }, }, rules: { 'vue/v-bind-style': 2, 'vue/v-on-style': 2, 'vue/html-quotes': [2, 'double'], 'vue/order-in-components': 2, 'comma-style': 2, }, };
Convert print statement to sys.stderr.write()
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK import os, imp, inspect, sys from interpreter import cli_interface def k_runner(): """CLI interpreter for the k command.""" # Check every directory from the current all the way to / for a file named key.py checkdirectory = os.getcwd() directories_checked = [] keypy_filename = None while not os.path.ismount(checkdirectory): directories_checked.append(checkdirectory) if os.path.exists("{0}{1}key.py".format(checkdirectory, os.sep)): keypy_filename = "{0}{1}key.py".format(checkdirectory, os.sep) break else: checkdirectory = os.path.abspath(os.path.join(checkdirectory, os.pardir)) if not keypy_filename: sys.stderr.write("key.py not found in the following directories:\n\n") sys.stderr.write('\n'.join(directories_checked)) sys.stderr.write("\n\nSee http://projectkey.readthedocs.org/en/latest/quickstart.html\n") sys.exit(1) else: cli_interface(imp.load_source("key", keypy_filename))
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK import os, imp, inspect from interpreter import cli_interface def k_runner(): """CLI interpreter for the k command.""" # Check every directory from the current all the way to / for a file named key.py checkdirectory = os.getcwd() directories_checked = [] keypy_filename = None while not os.path.ismount(checkdirectory): directories_checked.append(checkdirectory) if os.path.exists("{0}{1}key.py".format(checkdirectory, os.sep)): keypy_filename = "{0}{1}key.py".format(checkdirectory, os.sep) break else: checkdirectory = os.path.abspath(os.path.join(checkdirectory, os.pardir)) if not keypy_filename: print "key.py not found in the following directories:\n" print '\n'.join(directories_checked) print "\nSee http://projectkey.readthedocs.org/en/latest/quickstart.html" return 1 else: cli_interface(imp.load_source("key", keypy_filename))
Remove another instance of flyway baseline For consistency with 681d234e1b7bddd03f356ddab80b367de3626702 - we should configure flyway the same way everywhere.
package uk.gov.register.resources; import org.flywaydb.core.Flyway; import javax.annotation.security.PermitAll; import javax.inject.Inject; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/") public class DeleteRegisterDataResource { private Flyway flyway; @Inject public DeleteRegisterDataResource(Flyway flyway) { this.flyway = flyway; } @DELETE @PermitAll @Path("/delete-register-data") @DataDeleteNotAllowed public Response deleteRegisterData() { flyway.clean(); flyway.migrate(); return Response.status(200).entity("Data has been deleted").build(); } }
package uk.gov.register.resources; import org.flywaydb.core.Flyway; import javax.annotation.security.PermitAll; import javax.inject.Inject; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/") public class DeleteRegisterDataResource { private Flyway flyway; @Inject public DeleteRegisterDataResource(Flyway flyway) { this.flyway = flyway; } @DELETE @PermitAll @Path("/delete-register-data") @DataDeleteNotAllowed public Response deleteRegisterData() { flyway.clean(); flyway.setBaselineVersionAsString("0"); flyway.migrate(); return Response.status(200).entity("Data has been deleted").build(); } }
Add query and response in function call
$(document).ready(function() { $("#input").focus(); $("#input").on("keydown", function(event) { if (event.keyCode === 13) { event.preventDefault(); controllers.submitQuery(); } }); }); var controllers = { submitQuery: function() { var query = $("#input").val(); $.post({ url: '/submit', data: query }).done(function(data) { if (data.success) { view.addQueryAndResponse(query, data.response); } else { console.log(err); } }).fail(function(err) { console.log(err); }); } }; var view = { addQueryAndResponse: function(query, response) { $("#bash").apppend("<br>$ <span class='yellow'> "+ query + "</span>\ <br>chatbot$ <span class='green'> " + response + "</span>"); } };
$(document).ready(function() { $("#input").focus(); $("#input").on("keydown", function(event) { if (event.keyCode === 13) { event.preventDefault(); controllers.submitQuery(); } }); }); var controllers = { submitQuery: function() { $.post({ url: '/submit', data: $("#input").val() }).done(function(data) { view.addQueryAndResponse(); }).fail(function(err) { console.log(err); }); } }; var view = { addQueryAndResponse: function(query, response) { $("#bash").apppend("<br>$ <span class='yellow'> "+ query + "</span>\ <br>chatbot$ <span class='green'> " + response + "</span>"); } };
Add default value on property
from filter import FilterException from common import PluginType from yapsy.IPlugin import IPlugin import logging class DepthFilter(IPlugin): category = PluginType.FILTER id = "depth" def __init__(self): self.__log = logging.getLogger(__name__) self.__conf = None def setConf(self, conf): self.__conf = conf def setJournal(self, journal): pass def filter(self, transaction): maxDepth = self.__conf.getProperty("maxDepth", 0) if maxDepth == 0: return # unlimited if transaction.depth > maxDepth: self.__log.debug("Skipping " + transaction.uri + " as it's depth " + str(transaction.depth) + " and max depth condition is " + str(maxDepth)) raise FilterException()
from filter import FilterException from common import PluginType from yapsy.IPlugin import IPlugin import logging class DepthFilter(IPlugin): category = PluginType.FILTER id = "depth" def __init__(self): self.__log = logging.getLogger(__name__) self.__conf = None def setConf(self, conf): self.__conf = conf def setJournal(self, journal): pass def filter(self, transaction): maxDepth = self.__conf.getProperty("maxDepth") if maxDepth == 0: return # unlimited if transaction.depth > maxDepth: self.__log.debug("Skipping " + transaction.uri + " as it's depth " + str(transaction.depth) + " and max depth condition is " + str(maxDepth)) raise FilterException()
Return copy of notes sorted
import Marked from 'marked' export const orderedNotes = state => { return state.notes.slice(0).sort((a, b) => { const aOrder = state.notesOrder[a['.key']] const bOrder = state.notesOrder[b['.key']] if (aOrder === undefined || aOrder === null) return -1 if (aOrder === bOrder) return 0 if (aOrder < bOrder) return -1 return 1 }) } export const markdown = state => text => { return Marked(text) } let mdRenderer = new Marked.Renderer() mdRenderer.image = function (href, title, text) { return '<p><img src="' + href + '" alt="' + text + '" class="ui image"></p>' } mdRenderer.link = function (href, title, text) { return '<a href="' + href + '" target="_blank">' + text + '</a>' } Marked.setOptions({ renderer: mdRenderer })
import Marked from 'marked' export const orderedNotes = state => { return state.notes.sort((a, b) => { var aOrder = state.notesOrder[a['.key']] var bOrder = state.notesOrder[b['.key']] if (aOrder === undefined || aOrder === null) return -1 if (aOrder === bOrder) return 0 if (aOrder < bOrder) return -1 return 1 }) } export const markdown = state => text => { return Marked(text) } let mdRenderer = new Marked.Renderer() mdRenderer.image = function (href, title, text) { return '<p><img src="' + href + '" alt="' + text + '" class="ui image"></p>' } mdRenderer.link = function (href, title, text) { return '<a href="' + href + '" target="_blank">' + text + '</a>' } Marked.setOptions({ renderer: mdRenderer })
Change package name to vxtwinio
from setuptools import setup, find_packages setup( name="vxtwinio", version="0.0.1a", url="https://github.com/praekelt/vumi-twilio-api", license="BSD", description="Provides a REST API to Vumi that emulates the Twilio API", long_description=open("README.rst", "r").read(), author="Praekelt Foundation", author_email="dev@praekeltfoundation.org", packages=find_packages(), scripts=[], install_requires=[], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
from setuptools import setup, find_packages setup( name="vumi_twilio_api", version="0.0.1a", url="https://github.com/praekelt/vumi-twilio-api", license="BSD", description="Provides a REST API to Vumi that emulates the Twilio API", long_description=open("README.rst", "r").read(), author="Praekelt Foundation", author_email="dev@praekeltfoundation.org", packages=find_packages(), scripts=[], install_requires=[], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
:guitar: Make custom fields viewable by guests
import { Posts } from 'meteor/example-forum'; /* Let's assign a color to each post (why? cause we want to, that's why). We'll do that by adding a custom field to the Posts collection. Note that this requires our custom package to depend on vulcan:posts and vulcan:users. */ Posts.addField([ { fieldName: 'soundcloud', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['guests'], }, }, { fieldName: 'canBring', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['guests'], }, }, { fieldName: 'minimumCharge', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['guests'], }, }, ])
import { Posts } from 'meteor/example-forum'; /* Let's assign a color to each post (why? cause we want to, that's why). We'll do that by adding a custom field to the Posts collection. Note that this requires our custom package to depend on vulcan:posts and vulcan:users. */ Posts.addField([ { fieldName: 'soundcloud', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['members'], }, }, { fieldName: 'canBring', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['members'], }, }, { fieldName: 'minimumCharge', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['members'], }, }, ])
Fix single event class bindings
import Ember from 'ember'; import { default as CalendarEvent } from 'el-calendar/components/calendar-event'; import layout from '../templates/components/ilios-calendar-event'; import moment from 'moment'; const {computed, Handlebars} = Ember; const {SafeString} = Handlebars; export default CalendarEvent.extend({ layout, event: null, timeFormat: 'h:mma', classNameBindings: [':event', ':event-pos', ':ilios-calendar-event', 'event.eventClass', ':day'], tooltipContent: computed('event', function(){ let str = this.get('event.location') + '<br />' + moment(this.get('event.startDate')).format(this.get('timeFormat')) + ' - ' + moment(this.get('event.endDate')).format(this.get('timeFormat')) + '<br />' + this.get('event.name'); return str; }), style: computed(function() { let escape = Handlebars.Utils.escapeExpression; return new SafeString( `top: ${escape(this.calculateTop())}%; height: ${escape(this.calculateHeight())}%; left: ${escape(this.calculateLeft())}%; width: ${escape(this.calculateWidth())}%;` ); }), click(){ this.sendAction('action', this.get('event')); } });
import Ember from 'ember'; import { default as CalendarEvent } from 'el-calendar/components/calendar-event'; import layout from '../templates/components/ilios-calendar-event'; import moment from 'moment'; const {computed, Handlebars} = Ember; const {SafeString} = Handlebars; export default CalendarEvent.extend({ layout, event: null, timeFormat: 'h:mma', classNames: ['event', 'event-pos', 'ilios-calendar-event', 'event.eventClass', 'day'], tooltipContent: computed('event', function(){ let str = this.get('event.location') + '<br />' + moment(this.get('event.startDate')).format(this.get('timeFormat')) + ' - ' + moment(this.get('event.endDate')).format(this.get('timeFormat')) + '<br />' + this.get('event.name'); return str; }), style: computed(function() { let escape = Handlebars.Utils.escapeExpression; return new SafeString( `top: ${escape(this.calculateTop())}%; height: ${escape(this.calculateHeight())}%; left: ${escape(this.calculateLeft())}%; width: ${escape(this.calculateWidth())}%;` ); }), click(){ this.sendAction('action', this.get('event')); } });
Allow errors/exceptions to be returned in JSON format.
<?php /* * Copyright (c) 2014 Chris Wells (https://chriswells.io) * * 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. * */ namespace CWA\MVC\Views; require_once \CWA\LIB_PATH . 'cwa/mvc/views/View.php'; class ErrorView extends View { /* Protected methods: */ protected function detectFormat() { parent::detectFormat(); // Prevent recursive "partial not found" errors. -- cwells if ($this->format !== 'json' && !file_exists("views/Error/view.$this->format.php")) { $this->format = 'html'; } } } ?>
<?php /* * Copyright (c) 2014 Chris Wells (https://chriswells.io) * * 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. * */ namespace CWA\MVC\Views; require_once \CWA\LIB_PATH . 'cwa/mvc/views/View.php'; class ErrorView extends View { /* Protected methods: */ protected function detectFormat() { parent::detectFormat(); // Prevent recursive "partial not found" errors. -- cwells if (!file_exists("views/Error/default.$this->format.php")) { $this->format = 'html'; } } } ?>
Adjust packaging for non-public classes Motivation: In order to generate javadocs of our public API, we need to not have public and internal classes in the same packages. Modifications: * mostly moving internal classes to the appropriate internal package Result: Generating public javadocs is easier.
/** * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * 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 org.wildfly.swarm.topology.webapp; import org.wildfly.swarm.container.Fraction; import org.wildfly.swarm.topology.internal.IdentityExternalAddressMapper; /** * @author Lance Ball */ public class TopologyWebAppFraction implements Fraction { private Class externalAddressMapper = IdentityExternalAddressMapper.class; public TopologyWebAppFraction() { } public Class externalAddressMapper() { return externalAddressMapper; } public void externalAddressMapper(Class externalAddressMapper) { this.externalAddressMapper = externalAddressMapper; } }
/** * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * 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 org.wildfly.swarm.topology.webapp; import org.wildfly.swarm.container.Fraction; import org.wildfly.swarm.topology.IdentityExternalAddressMapper; /** * @author Lance Ball */ public class TopologyWebAppFraction implements Fraction { private Class externalAddressMapper = IdentityExternalAddressMapper.class; public TopologyWebAppFraction() { } public Class externalAddressMapper() { return externalAddressMapper; } public void externalAddressMapper(Class externalAddressMapper) { this.externalAddressMapper = externalAddressMapper; } }
Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
"""engine.SCons.Platform.darwin Platform-specific initialization for Mac OS X systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import posix import os def generate(env): posix.generate(env) env['SHLIBSUFFIX'] = '.dylib'
"""engine.SCons.Platform.darwin Platform-specific initialization for Mac OS X systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004 Steven Knight # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # import posix import os def generate(env): posix.generate(env) env['SHLIBSUFFIX'] = '.dylib'
Make K transport bar graph
# -*- coding: utf-8 -*- """ This script generates all the relevant figures from the experiment. """ from Modules.processing import * from Modules.plotting import * set_sns() save = True savetype = ".eps" show = True def main(): plot_perf_curves(save=save, savetype=savetype) plot_perf_curves(subplots=False, save=save, savetype=savetype) plot_perf_re_dep(save=save, savetype=savetype, errorbars=False, dual_xaxes=True) PerfCurve(1.0).plotcp(save=save, savetype=savetype, show=False) wm = WakeMap() wm.plot_meancontquiv(save=save, savetype=savetype) wm.plot_k(save=save, savetype=savetype) wm.make_K_bar_graph(save=save, savetype=savetype) plot_no_blades_all(save=save, savetype=savetype) plot_cp_covers(save=save, savetype=savetype, add_strut_torque=False) plot_cp_covers(save=save, savetype=savetype, add_strut_torque=True) if show: plt.show() if __name__ == "__main__": if not os.path.isdir("Figures"): os.mkdir("Figures") main()
# -*- coding: utf-8 -*- """ This script generates all the relevant figures from the experiment. """ from Modules.processing import * from Modules.plotting import * set_sns() save = True savetype = ".eps" show = True def main(): plot_perf_curves(save=save, savetype=savetype) plot_perf_curves(subplots=False, save=save, savetype=savetype) plot_perf_re_dep(save=save, savetype=savetype, errorbars=False, dual_xaxes=True) PerfCurve(1.0).plotcp(save=save, savetype=savetype, show=False) wm = WakeMap() wm.plot_meancontquiv(save=save, savetype=savetype) wm.plot_k(save=save, savetype=savetype) plot_no_blades_all(save=save, savetype=savetype) plot_cp_covers(save=save, savetype=savetype, add_strut_torque=False) plot_cp_covers(save=save, savetype=savetype, add_strut_torque=True) if show: plt.show() if __name__ == "__main__": if not os.path.isdir("Figures"): os.mkdir("Figures") main()
Add suppression to try and fix test errors
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; @RunWith(JUnit4.class) @SuppressStaticInitializationFor({"com.google.sps.Firebase"}) public final class FirebaseTest { @Test public void userLoggedIn() throws IOException { boolean result = Firebase.isUserLoggedIn("test"); assertEquals(true, result); } @Test public void userLoggedInEmpty() throws IOException { boolean result = Firebase.isUserLoggedIn(""); assertEquals(false, result); } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class FirebaseTest { @Test public void userLoggedIn() throws IOException { boolean result = Firebase.isUserLoggedIn("test"); assertEquals(true, result); } @Test public void userLoggedInEmpty() throws IOException { boolean result = Firebase.isUserLoggedIn(""); assertEquals(false, result); } }
Drop eval from plugin execution
<?php namespace App\Libs; use \App\Model\Plugin as Plugin; class ShortCode extends Model{ public $table = 'plugins'; private static $widgets = array(); public static function initalize(){ foreach(app()->plugins as $plugin){ $namespace = $plugin->getRegisterClass(); if(Plugin::exists($plugin->root_dir) && method_exists($namespace, 'widget')){ \View::addNamespace('plugin', [ 'plugins'.DIRECTORY_SEPARATOR.$plugin->root_dir.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."View", 'plugins'.DIRECTORY_SEPARATOR.$plugin->root_dir.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."resources".DIRECTORY_SEPARATOR."views" ]); self::$widgets["{[".$plugin->root_dir."]}"] = $namespace::widget(); } } } public static function getAll(){ return self::$widgets; } public static function resolve($shortcode){ echo isset(self::$widgets["{[".$shortcode."]}"])? self::$widgets["{[".$shortcode."]}"] : ""; } public static function compile($page){ echo count(self::$widgets) === 0? $page : str_replace(array_keys(self::$widgets), array_values(self::$widgets), $page); } }
<?php namespace App\Libs; use \App\Model\Plugin as Plugin; class ShortCode extends Model{ public $table = 'plugins'; private static $widgets = array(); public static function initalize(){ foreach(app()->plugins as $plugin){ $namespace = $plugin->getRegisterClass(); if(Plugin::exists($plugin->root_dir) && method_exists($namespace, 'widget')){ \View::addNamespace('plugin', [ 'plugins'.DIRECTORY_SEPARATOR.$plugin->root_dir.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."View", 'plugins'.DIRECTORY_SEPARATOR.$plugin->root_dir.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."resources".DIRECTORY_SEPARATOR."views" ]); self::$widgets["{[".$plugin->root_dir."]}"] = $namespace::widget(); } } } public static function getAll(){ return self::$widgets; } public static function resolve($shortcode){ return isset(self::$widgets["{[".$shortcode."]}"])? eval("?>".self::$widgets["{[".$shortcode."]}"]."<?php") : NULL; } public static function compile($page){ return count(self::$widgets) === 0? $page : eval("?>".str_replace(array_keys(self::$widgets), array_values(self::$widgets), $page)."<?php"); } }
Improve error message on project creation.
<?php class Project extends Eloquent { protected $fillable = ['title', 'slug']; /** * @return \Illuminate\Database\Eloquent\Collection */ public function sprints() { return $this->hasMany('Sprint')->orderBy('sprint_start', 'desc'); } /** * @return \Illuminate\Validation\Validator */ public function validate() { return Validator::make( $this->getAttributes(), ['title' => 'required|unique:projects'], ['unique' => 'A project with this title already exists.'] ); } public function currentSprint() { return $this->newestPastSprint() ?: $this->closestFutureSprint(); } private function newestPastSprint() { return Sprint::where('sprint_start', '<=', date('Y-m-d')) ->where('project_id', $this->id) ->orderBy('sprint_start', 'desc') ->first(); } private function closestFutureSprint() { return Sprint::where('sprint_start', '>', date('Y-m-d')) ->where('project_id', $this->id) ->orderBy('sprint_start', 'asc') ->first(); } }
<?php class Project extends Eloquent { protected $fillable = ['title', 'slug']; /** * @return \Illuminate\Database\Eloquent\Collection */ public function sprints() { return $this->hasMany('Sprint')->orderBy('sprint_start', 'desc'); } /** * @return \Illuminate\Validation\Validator */ public function validate() { return Validator::make( $this->getAttributes(), ['title' => 'required|unique:projects'] ); } public function currentSprint() { return $this->newestPastSprint() ?: $this->closestFutureSprint(); } private function newestPastSprint() { return Sprint::where('sprint_start', '<=', date('Y-m-d')) ->where('project_id', $this->id) ->orderBy('sprint_start', 'desc') ->first(); } private function closestFutureSprint() { return Sprint::where('sprint_start', '>', date('Y-m-d')) ->where('project_id', $this->id) ->orderBy('sprint_start', 'asc') ->first(); } }
Make it .html to prevent confusion If someone would like to add some html to the output, he could get confused because the browser won't render. (For example <br />) Making it $('#timer').html(...); Changes nothing but solves this problem for people that want to use it with html.
$(document).ready(function() { var endTime = new Date(); endTime.setFullYear(2014); endTime.setMonth(0); endTime.setDate(1); endTime.setHours(0); endTime.setMinutes(0); var id = setInterval(function() { var startTime = new Date(); var msec = endTime.getTime() - startTime.getTime(); var sec = Math.floor(msec / 1000); var min = Math.floor(sec / 60); var hour = Math.floor(min / 60); var day = Math.floor(hour / 24); sec = sec % 60; min = min % 60; hour = hour % 24; if (sec < 10) { sec = '0' + sec; } if (min < 10) { min = '0' + min; } if (hour < 10) { hour = '0' + hour; } if (msec - 1000 < 0) { clearInterval(id); } $('#timer').html(day + ':' + hour + ':' + min + ':' + sec); }, 1000); });
$(document).ready(function() { var endTime = new Date(); endTime.setFullYear(2014); endTime.setMonth(0); endTime.setDate(1); endTime.setHours(0); endTime.setMinutes(0); var id = setInterval(function() { var startTime = new Date(); var msec = endTime.getTime() - startTime.getTime(); var sec = Math.floor(msec / 1000); var min = Math.floor(sec / 60); var hour = Math.floor(min / 60); var day = Math.floor(hour / 24); sec = sec % 60; min = min % 60; hour = hour % 24; if (sec < 10) { sec = '0' + sec; } if (min < 10) { min = '0' + min; } if (hour < 10) { hour = '0' + hour; } if (msec - 1000 < 0) { clearInterval(id); } $('#timer').text(day + ':' + hour + ':' + min + ':' + sec); }, 1000); });
Fix windows build by replacing back to forward slashes in icon paths.
import fs from 'fs'; import rrs from 'recursive-readdir-sync'; const outArray = []; const svgIconPath = 'src/svg-icons/'; rrs(svgIconPath).forEach((file) => { if (file !== 'index-generator.js' && file !== 'index.js') { const fileLines = fs.readFileSync(file, 'utf8').split('\n'); let index = 0; let found = false; while (found === false && index < fileLines.length) { if (fileLines[index].indexOf('export default') > -1) { const moduleName = fileLines[index].split(' ')[2].replace(';', '').trim(); const modulePath = file.substring(0, file.length - 3).replace(/\\/g, '/').replace(svgIconPath, ''); outArray.push(`export ${moduleName} from './${modulePath}';\n`); found = true; } else { index++; } } } }); fs.writeFileSync(`./${svgIconPath}/index.js`, outArray.join(''));
import fs from 'fs'; import rrs from 'recursive-readdir-sync'; const outArray = []; const svgIconPath = 'src/svg-icons/'; rrs(svgIconPath).forEach((file) => { if (file !== 'index-generator.js' && file !== 'index.js') { const fileLines = fs.readFileSync(file, 'utf8').split('\n'); let index = 0; let found = false; while (found === false && index < fileLines.length) { if (fileLines[index].indexOf('export default') > -1) { const moduleName = fileLines[index].split(' ')[2].replace(';', '').trim(); const modulePath = file.substring(0, file.length - 3).replace(svgIconPath, ''); outArray.push(`export ${moduleName} from './${modulePath}';\n`); found = true; } else { index++; } } } }); fs.writeFileSync(`./${svgIconPath}/index.js`, outArray.join(''));
Remove Pypy from list of supported Python versions
from setuptools import setup, find_packages def parse_requirements(requirement_file): with open(requirement_file) as f: return f.readlines() setup( name="swimlane", author="Swimlane LLC", author_email="info@swimlane.com", url="https://github.com/swimlane/swimlane-python", packages=find_packages(exclude=('tests', 'tests.*')), description="A Python client for Swimlane.", install_requires=parse_requirements('./requirements.txt'), setup_requires=[ 'setuptools_scm', 'pytest-runner' ], use_scm_version=True, tests_require=parse_requirements('./test-requirements.txt'), classifiers=[ "License :: OSI Approved :: GNU Affero General Public License v3", "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ] )
from setuptools import setup, find_packages def parse_requirements(requirement_file): with open(requirement_file) as f: return f.readlines() setup( name="swimlane", author="Swimlane LLC", author_email="info@swimlane.com", url="https://github.com/swimlane/swimlane-python", packages=find_packages(exclude=('tests', 'tests.*')), description="A Python client for Swimlane.", install_requires=parse_requirements('./requirements.txt'), setup_requires=[ 'setuptools_scm', 'pytest-runner' ], use_scm_version=True, tests_require=parse_requirements('./test-requirements.txt'), classifiers=[ "License :: OSI Approved :: GNU Affero General Public License v3", "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: PyPy" ] )
Fix LiveReload for all .styl files
var gulp = require('gulp'), connect = require('gulp-connect'), stylus = require('gulp-stylus'), prefix = require('gulp-autoprefixer'); var paths = { styles: 'css/**/*.styl', html: './*.html' }; gulp.task('connect', function() { connect.server({ livereload: true }); }); gulp.task('html', function () { gulp.src(paths.html) .pipe(connect.reload()); }); gulp.task('styles', function () { gulp.src('css/bare-ninja.styl') .pipe(stylus()) .pipe(prefix('last 2 version', 'ie 8', 'ie 9')) .pipe(gulp.dest('./css')) .pipe(connect.reload()); }); gulp.task('watch', function () { gulp.watch(paths.styles, ['styles']); gulp.watch(paths.html, ['html']); }); // The default task (called when you run `gulp` from cli) gulp.task('default', ['styles', 'connect', 'watch']);
var gulp = require('gulp'), connect = require('gulp-connect'), stylus = require('gulp-stylus'), prefix = require('gulp-autoprefixer'); var paths = { styles: 'css/bare-ninja.styl', html: './*.html' }; gulp.task('connect', function() { connect.server({ livereload: true }); }); gulp.task('html', function () { gulp.src(paths.html) .pipe(connect.reload()); }); gulp.task('styles', function () { gulp.src(paths.styles) .pipe(stylus()) .pipe(prefix('last 2 version', 'ie 8', 'ie 9')) .pipe(gulp.dest('./css')) .pipe(connect.reload()); }); gulp.task('watch', function () { gulp.watch(paths.styles, ['styles']); gulp.watch(paths.html, ['html']); }); // The default task (called when you run `gulp` from cli) gulp.task('default', ['styles', 'connect', 'watch']);
Fix Git Show path call
<?php namespace Github\Api\GitData; use Github\Api\AbstractApi; use Github\Exception\MissingArgumentException; /** * @link http://developer.github.com/v3/git/commits/ * @author Joseph Bielawski <stloyd@gmail.com> */ class Commits extends AbstractApi { public function show($username, $repository, $sha) { return $this->get('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/git/commits/'.rawurlencode($sha)); } public function create($username, $repository, array $params) { if (!isset($params['message'], $params['tree'], $params['parents'])) { throw new MissingArgumentException(array('message', 'tree', 'parents')); } return $this->post('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/git/commits', $params); } }
<?php namespace Github\Api\GitData; use Github\Api\AbstractApi; use Github\Exception\MissingArgumentException; /** * @link http://developer.github.com/v3/git/commits/ * @author Joseph Bielawski <stloyd@gmail.com> */ class Commits extends AbstractApi { public function show($username, $repository, $sha) { return $this->get('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/commits/'.rawurlencode($sha)); } public function create($username, $repository, array $params) { if (!isset($params['message'], $params['tree'], $params['parents'])) { throw new MissingArgumentException(array('message', 'tree', 'parents')); } return $this->post('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/git/commits', $params); } }
BB-4056: Add or adjust implementation of the SKU filters from the grid. Both use StringFilter in the ORM version - namespace fix
<?php namespace Oro\Bundle\SearchBundle\Event; use Symfony\Component\EventDispatcher\Event; use Oro\Bundle\DataGridBundle\Datagrid\DatagridInterface; use Oro\Bundle\SearchBundle\Extension\SearchQueryInterface; class SearchResultBefore extends Event { const NAME = 'oro_datagrid.search_datasource.result.before'; /** * @var DatagridInterface */ protected $datagrid; /** * @var SearchQueryInterface */ protected $query; /** * @param DatagridInterface $datagrid * @param SearchQueryInterface $query */ public function __construct( DatagridInterface $datagrid, SearchQueryInterface $query ) { $this->datagrid = $datagrid; $this->query = $query; } /** * @return SearchQueryInterface */ public function getQuery() { return $this->query; } }
<?php namespace Oro\Bundle\SearchBundle\Event; use Oro\Bundle\DataGridBundle\Datagrid\DatagridInterface; use Oro\Bundle\SearchBundle\Extension\SearchQueryInterface; use Symfony\Component\EventDispatcher\Event; class SearchResultBefore extends Event { const NAME = 'oro_datagrid.search_datasource.result.before'; /** * @var DatagridInterface */ protected $datagrid; /** * @var SearchQueryInterface */ protected $query; /** * @param DatagridInterface $datagrid * @param SearchQueryInterface $query */ public function __construct( DatagridInterface $datagrid, SearchQueryInterface $query ) { $this->datagrid = $datagrid; $this->query = $query; } /** * @return SearchQueryInterface */ public function getQuery() { return $this->query; } }
Update header name change for turbolinks 5
<?php namespace App\Http\Middleware; use Closure; class TurbolinksSupport { /** * Add turbolinks-redirect header if previous request * was a redirect. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $turbolinksLocation = session('_turbolinks-location'); if (present($turbolinksLocation)) { $response = $next($request); return $response->header('Turbolinks-Location', $turbolinksLocation); } else { return $next($request); } } }
<?php namespace App\Http\Middleware; use Closure; class TurbolinksSupport { /** * Add turbolinks-redirect header if previous request * was a redirect. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $turbolinksLocation = session('_turbolinks-location'); if (present($turbolinksLocation)) { $response = $next($request); return $response->header('X-XHR-Redirected-To', $turbolinksLocation); } else { return $next($request); } } }
Update the version to 3.0.1
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi; /** * Used to track the version of the API. An API version * consists of a Major, Minor, and Patch version. * * @author Brady * @since 8/16/2017 7:11 PM */ public final class Version { private Version() {} /** * Incremented when a new version of Minecraft is released, never reset */ public static final int MAJOR = 3; /** * Incremented when API-breaking changes are made, reset when major version is modified */ public static final int MINOR = 0; /** * Incremented every release, reset when the minor version is modified */ public static final int PATCH = 1; /** * @return The version formatted as {@code MAJOR.MINOR.PATCH} */ public static String getVersion() { return String.format("%d.%d.%d", MAJOR, MINOR, PATCH); } }
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi; /** * Used to track the version of the API. An API version * consists of a Major, Minor, and Patch version. * * @author Brady * @since 8/16/2017 7:11 PM */ public final class Version { private Version() {} /** * Incremented when a new version of Minecraft is released, never reset */ public static final int MAJOR = 3; /** * Incremented when API-breaking changes are made, reset when major version is modified */ public static final int MINOR = 0; /** * Incremented every release, reset when the minor version is modified */ public static final int PATCH = 0; /** * @return The version formatted as {@code MAJOR.MINOR.PATCH} */ public static String getVersion() { return String.format("%d.%d.%d", MAJOR, MINOR, PATCH); } }
Fix error in last commit
angular.module('proxtop').controller('MainController', ['$scope', 'ipcManager', '$state', '$mdToast', '$translate', 'settings', function($scope, ipcManager, $state, $mdToast, $translate, settings) { const ipc = ipcManager($scope); ipc.once('check-login', function(ev, result) { if(result) { ipc.send('watchlist-update'); $state.go('profile'); } else { $state.go('login'); } }); $translate.use(settings.get('general').language); ipc.send('check-login'); }]);
angular.module('proxtop').controller('MainController', ['$scope', 'ipcManager', '$state', 'notification', '$mdToast', '$translate', 'settings', '$mdDialog', 'open', '$window', 'debounce', function($scope, ipcManager, $state, notification, $mdToast, $translate, settings, $mdDialog, open, $window, debounce) { const ipc = ipcManager($scope); ipc.once('check-login', function(ev, result) { if(result) { ipc.send('watchlist-update'); $state.go('profile'); } else { $state.go('login'); } }); $translate.use(settings.get('general').language); ipc.send('check-login'); }]);
Convert firmware version to a readable format
'use strict'; var utils = require('../../lifx').utils; var Packet = { size: 20 }; /** * Converts packet specific data from a buffer to an object * @param {Buffer} buf Buffer containing only packet specific data no header * @return {Object} Information contained in packet */ Packet.toObject = function(buf) { var obj = {}; var offset = 0; // Check length if (buf.length !== this.size) { throw new Error('Invalid length given for stateHostFirmware LIFX packet'); } obj.build = utils.readUInt64LE(buf, offset); offset += 8; obj.install = utils.readUInt64LE(buf, offset); offset += 8; var version = buf.readUInt32LE(offset); obj.majorVersion = (version >> 16) & 0xFF; obj.minorVersion = version & 0xFF; offset += 4; return obj; }; /** * Converts the given packet specific object into a packet * @param {Object} obj object with configuration data * @return {Buffer} packet */ Packet.toBuffer = function(obj) { var buf = new Buffer(this.size); buf.fill(0); var offset = 0; utils.writeUInt64LE(buf, offset, obj.build); offset += 8; utils.writeUInt64LE(buf, offset, obj.install); offset += 8; buf.writeUInt32LE(obj.version, offset); offset += 4; return buf; }; module.exports = Packet;
'use strict'; var utils = require('../../lifx').utils; var Packet = { size: 20 }; /** * Converts packet specific data from a buffer to an object * @param {Buffer} buf Buffer containing only packet specific data no header * @return {Object} Information contained in packet */ Packet.toObject = function(buf) { var obj = {}; var offset = 0; // Check length if (buf.length !== this.size) { throw new Error('Invalid length given for stateHostFirmware LIFX packet'); } obj.build = utils.readUInt64LE(buf, offset); offset += 8; obj.install = utils.readUInt64LE(buf, offset); offset += 8; obj.version = buf.readUInt32LE(offset); offset += 4; return obj; }; /** * Converts the given packet specific object into a packet * @param {Object} obj object with configuration data * @return {Buffer} packet */ Packet.toBuffer = function(obj) { var buf = new Buffer(this.size); buf.fill(0); var offset = 0; utils.writeUInt64LE(buf, offset, obj.build); offset += 8; utils.writeUInt64LE(buf, offset, obj.install); offset += 8; buf.writeUInt32LE(obj.version, offset); offset += 4; return buf; }; module.exports = Packet;
Add Example for Cancel Upload
package surc.test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; /** * Servlet implementation class CancelUpload */ @WebServlet("/cancelUpload") public class CancelUpload extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CancelUpload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse * response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // please add this segment to all your current servlets and your // servlets creating in the future. response.setContentType("application/json;charset=utf-8"); PrintWriter out = response.getWriter(); JSONObject obj = new JSONObject(); // get the name of file that will be deleted. String name = request.getParameter("name"); // Remove the file from both the file list in session and the hard // drive. System.out.println(name); obj.put("status", "ok"); out.println(obj); } }
package surc.test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; /** * Servlet implementation class CancelUpload */ @WebServlet("/cancelUpload") public class CancelUpload extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CancelUpload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse * response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); JSONObject obj = new JSONObject(); String name = request.getParameter("name"); obj.put("name", name); out.println(obj); } }
[improve] Return a null product if there isn't a saved one
package com.oce.springboot.training.d02.s04.repository; import com.oce.springboot.training.d02.s04.model.Product; import org.springframework.stereotype.Repository; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; @Repository public class ProductRepository { // an in-memory list of products private List<Product> products = new ArrayList<>(1); @PostConstruct public void init() { products.add(getDefaultProduct()); } @SuppressWarnings("unused") public Product get(int id) { return id < products.size() ? products.get(id) : null; } public List<Product> getAll() { return products; } public void create(final Product product) { products.add(product); } public void update(final int id, final Product product) { final Product currentProduct = products.get(id < products.size() ? id : 0); currentProduct.setName(product.getName()); } public void delete(final int id) { products.remove(id < products.size() ? id : 0); } private Product getDefaultProduct() { final Product product = new Product(); product.setId(24); product.setName("Dell XPS 9360"); return product; } }
package com.oce.springboot.training.d02.s04.repository; import com.oce.springboot.training.d02.s04.model.Product; import org.springframework.stereotype.Repository; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; @Repository public class ProductRepository { // an in-memory list of products private List<Product> products = new ArrayList<>(1); @PostConstruct public void init() { products.add(getDefaultProduct()); } @SuppressWarnings("unused") public Product get(int id) { return getDefaultProduct(); } public List<Product> getAll() { return products; } public void create(final Product product) { products.add(product); } public void update(final int id, final Product product) { final Product currentProduct = products.get(id < products.size() ? id : 0); currentProduct.setName(product.getName()); } public void delete(final int id) { products.remove(id < products.size() ? id : 0); } private Product getDefaultProduct() { final Product product = new Product(); product.setId(24); product.setName("Dell XPS 9360"); return product; } }
Fix package name for PCL ref assemblies
import glob import os import shutil class PCLReferenceAssembliesPackage(Package): def __init__(self): Package.__init__(self, name='PortableReferenceAssemblies', version='2014-04-14', sources=['http://storage.bos.xamarin.com/bot-provisioning/PortableReferenceAssemblies-2014-04-14.zip']) def prep(self): self.extract_archive(self.sources[0], validate_only=False, overwrite=True) def build(self): pass # A bunch of shell script written inside python literals ;( def install(self): dest = os.path.join(self.prefix, "lib", "mono", "xbuild-frameworks", ".NETPortable") if not os.path.exists(dest): os.makedirs(dest) shutil.rmtree(dest, ignore_errors=True) pcldir = os.path.join(self.package_build_dir(), self.source_dir_name, ".NETPortable") self.sh("rsync -abv -q %s/* %s" % (pcldir, dest)) PCLReferenceAssembliesPackage()
import glob import os import shutil class PCLReferenceAssembliesPackage(Package): def __init__(self): Package.__init__(self, name='PortableReferenceAssemblies-2014-04-14', version='2014-04-14', sources=['http://storage.bos.xamarin.com/bot-provisioning/PortableReferenceAssemblies-2014-04-14.zip']) def prep(self): self.extract_archive(self.sources[0], validate_only=False, overwrite=True) def build(self): pass # A bunch of shell script written inside python literals ;( def install(self): dest = os.path.join(self.prefix, "lib", "mono", "xbuild-frameworks", ".NETPortable") if not os.path.exists(dest): os.makedirs(dest) shutil.rmtree(dest, ignore_errors=True) pcldir = os.path.join(self.package_build_dir(), self.source_dir_name, ".NETPortable") self.sh("rsync -abv -q %s/* %s" % (pcldir, dest)) PCLReferenceAssembliesPackage()
Add alert post guestbook sign (remove this later)
import { useMoralis } from 'react-moralis'; import { navigate } from 'gatsby-link'; export function GuestbookAuth() { const { authenticate, logout, Moralis } = useMoralis(); return { login: async () => { Moralis.Web3.getSigningData = () => 'Sign the web3 guestbook on iammatthias.com'; try { await authenticate({ provider: 'walletconnect', onSuccess: () => { navigate('/guestbook'); logout(); alert('yay'); }, }); } catch (e) { console.error(e.message, e); } }, }; }
import { useMoralis } from 'react-moralis'; import { navigate } from 'gatsby-link'; export function GuestbookAuth() { const { authenticate, logout, Moralis } = useMoralis(); return { login: async () => { Moralis.Web3.getSigningData = () => 'Sign the web3 guestbook on iammatthias.com'; try { await authenticate({ provider: 'walletconnect', onSuccess: () => { navigate('/guestbook'); logout(); }, }); } catch (e) { console.error(e.message, e); } }, }; }
Fix IE 8 by using compatible date methods `Date.now()` is not supported in IE8
/* * raf.js * https://github.com/ngryman/raf.js * * original requestAnimationFrame polyfill by Erik Möller * inspired from paul_irish gist and post * * Copyright (c) 2013 ngryman * Licensed under the MIT license. */ (function(window) { var lastTime = 0, vendors = ['webkit', 'moz'], requestAnimationFrame = window.requestAnimationFrame, cancelAnimationFrame = window.cancelAnimationFrame, i = vendors.length; // try to un-prefix existing raf while (--i >= 0 && !requestAnimationFrame) { requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame']; cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame']; } // polyfill with setTimeout fallback // heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945 if (!requestAnimationFrame || !cancelAnimationFrame) { requestAnimationFrame = function(callback) { var now = new Date().getTime(), nextTime = Math.max(lastTime + 16, now); return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now); }; cancelAnimationFrame = clearTimeout; } // export to window window.requestAnimationFrame = requestAnimationFrame; window.cancelAnimationFrame = cancelAnimationFrame; }(window));
/* * raf.js * https://github.com/ngryman/raf.js * * original requestAnimationFrame polyfill by Erik Möller * inspired from paul_irish gist and post * * Copyright (c) 2013 ngryman * Licensed under the MIT license. */ (function(window) { var lastTime = 0, vendors = ['webkit', 'moz'], requestAnimationFrame = window.requestAnimationFrame, cancelAnimationFrame = window.cancelAnimationFrame, i = vendors.length; // try to un-prefix existing raf while (--i >= 0 && !requestAnimationFrame) { requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame']; cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame']; } // polyfill with setTimeout fallback // heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945 if (!requestAnimationFrame || !cancelAnimationFrame) { requestAnimationFrame = function(callback) { var now = Date.now(), nextTime = Math.max(lastTime + 16, now); return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now); }; cancelAnimationFrame = clearTimeout; } // export to window window.requestAnimationFrame = requestAnimationFrame; window.cancelAnimationFrame = cancelAnimationFrame; }(window));
Remove old assert that was wrong
import unittest import os from mock import call, patch from packages.lyrics import lyrics #TODO: add tests for PyLyricsClone class Lyrics_Test(unittest.TestCase): def setUp(self): self.song_name = "everybody dies" self.artist_name = "ayreon" self.complete_info = "everybody dies-ayreon" self.wrong_info = "everybody dies-arebon" self.module = lyrics() def test_lyrics_found_given_full_parameters(self): self.assertIsNotNone(self.module.find(self.complete_info)) def test_lyrics_not_found_given_incomplete_parameter(self): self.assertEqual(self.module.find(self.song_name), "you forgot to add either song name or artist name") def test_lyrics_not_found_given_wrong_parameter(self): self.assertEqual(self.module.find(self.wrong_info), "Song or Singer does not exist or the API does not have lyrics") def test_split_works(self): self.assertEqual(self.module.parse(self.complete_info), ["everybody dies", "ayreon"])
import unittest import os from mock import call, patch from packages.lyrics import lyrics #TODO: add tests for PyLyricsClone class Lyrics_Test(unittest.TestCase): def setUp(self): self.song_name = "everybody dies" self.artist_name = "ayreon" self.complete_info = "everybody dies-ayreon" self.wrong_info = "everybody dies-arebon" self.module = lyrics() def test_lyrics_found_given_full_parameters(self): self.assertIsNotNone(self.module.find(self.complete_info)) def test_lyrics_not_found_given_incomplete_parameter(self): self.assertEqual(self.module.find(self.song_name), "you forgot to add either song name or artist name") def test_lyrics_not_found_given_wrong_parameter(self): self.assertEqual(self.module.find(self.wrong_info), "Song or Singer does not exist or the API does not have lyrics") self.assertIsNone(self.module.find(self.wrong_info)) def test_split_works(self): self.assertEqual(self.module.parse(self.complete_info), ["everybody dies", "ayreon"])
Test played changes including firefox report
({ name: 'prop-played', description: 'Property "played"', spec: 'http://dev.w3.org/html5/spec/the-iframe-element.html#dom-media-played', reports: { firefox: { desc: 'Patch should get landed soon.', link: 'https://bugzilla.mozilla.org/show_bug.cgi?id=462959' } }, assert: function(finish) { var audio = this.audio = new Audio(); audio.addEventListener('timeupdate', function() { if (audio.currentTime > 0) { try { finish(audio.played.length); } catch (e) { finish(false); } } }, false); audio.addEventListener('loadedmetadata', function() { audio.volume = 0; audio.play(); }, false); audio.setAttribute('src', AWPY.sound.mini.stream_url()); } })
({ name: 'prop-played', description: 'Property "played"', spec: 'http://dev.w3.org/html5/spec/Overview.html#dom-mediacontroller-played', assert: function(finish) { var audio = this.audio = new Audio(); audio.addEventListener('timeupdate', function() { if (audio.currentTime > 0) { try { finish(audio.played.length); } catch (e) { finish(false); } } }, false); audio.addEventListener('loadedmetadata', function() { audio.volume = 0; audio.play(); }, false); audio.setAttribute('src', AWPY.sound.mini.stream_url()); } })
Use event emitter in copy event test
'use strict'; /** * Module dependencies. */ require('should'); var events = require('events'); var utils = require('../lib/utils'); /** * Helper */ describe('utils', function() { describe('copyEvent', function() { it('should copy properties', function() { var src = { hello: 'world', one: 2 }; var dst = {}; utils.copyEvent(src, dst); dst.should.have.keys('hello', 'one'); dst.should.have.property('hello', 'world'); dst.should.have.property('one', 2); }); it('should omit hidden and excluded properties', function() { var src = new events.EventEmitter(); src.hello = 'world'; src._one = 'one'; src.__two = 'two'; if (!src.domain) src.domain = {}; src.deadline = 123; var dst = {}; utils.copyEvent(src, dst); dst.should.have.keys('hello'); }); }); });
'use strict'; /** * Module dependencies. */ require('should'); var utils = require('../lib/utils'); /** * Helper */ describe('utils', function() { describe('copyEvent', function() { it('should copy properties', function() { var src = { hello: 'world', one: 2 }; var dst = {}; utils.copyEvent(src, dst); dst.should.have.keys('hello', 'one'); dst.should.have.property('hello', 'world'); dst.should.have.property('one', 2); }); it('should omit hidden and excluded properties', function() { var Test = function() { this.hello1 = 'world1'; this._one = 'one'; this.__two = 'two'; this.domain = {}; this.deadline = 123; }; Test.prototype.create = function() { this.hello2 = 'world2'; }; var src = new Test(); src.create(); var dst = {}; utils.copyEvent(src, dst); dst.should.have.keys('hello1', 'hello2'); dst.should.have.property('hello1', 'world1'); dst.should.have.property('hello2', 'world2'); }); }); });
Add max length to comment field
from django import forms from django.utils.translation import gettext_lazy as _ from django_comments.forms import ( CommentForm as DjangoCommentForm, COMMENT_MAX_LENGTH ) class CommentForm(DjangoCommentForm): name = forms.CharField( label=_('Name'), required=True, max_length=50, help_text=_('Your name will only be visible to logged in users.'), widget=forms.TextInput( attrs={ 'class': 'form-control' } ) ) comment = forms.CharField( label=_('Comment'), widget=forms.Textarea( attrs={ 'class': 'form-control', 'rows': '4' } ), max_length=COMMENT_MAX_LENGTH )
from django import forms from django.utils.translation import gettext_lazy as _ from django_comments.forms import ( CommentForm as DjangoCommentForm, COMMENT_MAX_LENGTH ) class CommentForm(DjangoCommentForm): name = forms.CharField( label=_('Name'), required=True, help_text=_('Your name will only be visible to logged in users.'), widget=forms.TextInput( attrs={ 'class': 'form-control' } ) ) comment = forms.CharField( label=_('Comment'), widget=forms.Textarea( attrs={ 'class': 'form-control', 'rows': '4' } ), max_length=COMMENT_MAX_LENGTH )
Add matched callback command example
import React, { useState } from 'react' import Dictaphone from './Dictaphone' const DictaphoneWidgetA = () => { const [message, setMessage] = useState('') const commands = [ { command: 'I would like to order *', callback: (food) => setMessage(`Your order is for: ${food}`), matchInterim: true }, { command: 'The weather is :condition today', callback: (condition) => setMessage(`Today, the weather is ${condition}`) }, { command: ['Hello', 'Hi'], callback: ({ command }) => setMessage(`Hi there! You said: "${command}"`), matchInterim: true }, { command: 'Beijing', callback: (command, spokenPhrase, similarityRatio) => setMessage(`${command} and ${spokenPhrase} are ${similarityRatio * 100}% similar`), // If the spokenPhrase is "Benji", the message would be "Beijing and Benji are 40% similar" isFuzzyMatch: true, fuzzyMatchingThreshold: 0.2 }, { command: 'clear', callback: ({ resetTranscript }) => resetTranscript(), matchInterim: true }, ] return ( <div> <h3>Dictaphone A</h3> <p>{message}</p> <Dictaphone commands={commands} /> </div> ) } export default DictaphoneWidgetA
import React, { useState } from 'react' import Dictaphone from './Dictaphone' const DictaphoneWidgetA = () => { const [message, setMessage] = useState('') const commands = [ { command: 'I would like to order *', callback: (food) => setMessage(`Your order is for: ${food}`), matchInterim: true }, { command: 'The weather is :condition today', callback: (condition) => setMessage(`Today, the weather is ${condition}`) }, { command: ['Hello', 'Hi'], callback: () => setMessage('Hi there'), matchInterim: true }, { command: 'Beijing', callback: (command, spokenPhrase, similarityRatio) => setMessage(`${command} and ${spokenPhrase} are ${similarityRatio * 100}% similar`), // If the spokenPhrase is "Benji", the message would be "Beijing and Benji are 40% similar" isFuzzyMatch: true, fuzzyMatchingThreshold: 0.2 }, { command: 'clear', callback: ({ resetTranscript }) => resetTranscript(), matchInterim: true }, ] return ( <div> <h3>Dictaphone A</h3> <p>{message}</p> <Dictaphone commands={commands} /> </div> ) } export default DictaphoneWidgetA
Fix invalid error code from test
var path = require('path'), exec = require('child_process').exec, rimraf = require('rimraf') ; exports.tests = { 'setUp': function(done) { done(); }, 'tearDown': function(done) { // Clean build directory after each test run.... rimraf(path.join(__dirname, 'build'), function() { done(); }); }, 'should end up sucessfull': function(test) { test.expect(1); exec('grunt pluginbuilder:tests_task_success', function(error) { test.equal(error, null); test.done(); }); }, 'should end up with error (code=1)': function(test) { test.expect(2); exec('grunt pluginbuilder:tests_task_fail', function(error, stdout) { test.ok(stdout.indexOf('Your build failed') > -1); test.equal(error.code, 1); test.done(); }); } };
var path = require('path'), exec = require('child_process').exec, rimraf = require('rimraf') ; exports.tests = { 'setUp': function(done) { done(); }, 'tearDown': function(done) { // Clean build directory after each test run.... rimraf(path.join(__dirname, 'build'), function() { done(); }); }, 'should end up sucessfull': function(test) { test.expect(1); exec('grunt pluginbuilder:tests_task_success', function(error) { test.equal(error, null); test.done(); }); }, 'should end up with error (code=6)': function(test) { test.expect(2); exec('grunt pluginbuilder:tests_task_fail', function(error, stdout) { test.ok(stdout.indexOf('Your build failed') > -1); test.equal(error.code, 6); test.done(); }); } };
Use integral derivative decorator for test
from addons import * from utils import * tdir = 'Response-Theory' def test_beta(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/beta') def test_CPHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/CPHF') def test_helper_CPHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/helper_CPHF') def test_TDHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/TDHF') @using_psi4_python_integral_deriv def test_vcd(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/vcd') def test_polar_cc(workspace): exe_py(workspace, tdir, 'Coupled-Cluster/RHF/polar') def test_optrot_cc(workspace): exe_py(workspace, tdir, 'Coupled-Cluster/RHF/optrot')
from addons import * from utils import * tdir = 'Response-Theory' def test_beta(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/beta') def test_CPHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/CPHF') def test_helper_CPHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/helper_CPHF') def test_TDHF(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/TDHF') def test_vcd(workspace): exe_py(workspace, tdir, 'Self-Consistent-Field/vcd') def test_polar_cc(workspace): exe_py(workspace, tdir, 'Coupled-Cluster/RHF/polar') def test_optrot_cc(workspace): exe_py(workspace, tdir, 'Coupled-Cluster/RHF/optrot')
Test name changed to reflect behaviour
import pytest pytestmark = pytest.mark.slow version_file_content = """ major = 0 minor = 2 patch = 0 """ config_file_content = """ __config_version__ = 1 GLOBALS = { 'serializer': '{{major}}.{{minor}}.{{patch}}', } FILES = ["VERSION"] VERSION = ['major', 'minor', 'patch'] VCS = { 'name': 'git', } """ def test_check_no_silent_addition_happens(test_environment): test_environment.ensure_file_is_present("VERSION", "0.2.0") test_environment.ensure_file_is_present( "punch_version.py", version_file_content ) test_environment.ensure_file_is_present( "punch_config.py", config_file_content ) test_environment.output(["git", "init"]) test_environment.output(["git", "add", "punch_config.py"]) test_environment.output(["git", "commit", "-m", "some message"]) test_environment.ensure_file_is_present("untracked_file") test_environment.call(["punch", "--part", "minor"]) out = test_environment.output( ["git", "ls-tree", "-r", "master", "--name-only"] ) assert "untracked_file" not in out
import pytest pytestmark = pytest.mark.slow version_file_content = """ major = 0 minor = 2 patch = 0 """ config_file_content = """ __config_version__ = 1 GLOBALS = { 'serializer': '{{major}}.{{minor}}.{{patch}}', } FILES = ["VERSION"] VERSION = ['major', 'minor', 'patch'] VCS = { 'name': 'git', } """ def test_update_major(test_environment): test_environment.ensure_file_is_present("VERSION", "0.2.0") test_environment.ensure_file_is_present( "punch_version.py", version_file_content ) test_environment.ensure_file_is_present( "punch_config.py", config_file_content ) test_environment.output(["git", "init"]) test_environment.output(["git", "add", "punch_config.py"]) test_environment.output(["git", "commit", "-m", "some message"]) test_environment.ensure_file_is_present("untracked_file") test_environment.call(["punch", "--part", "minor"]) out = test_environment.output( ["git", "ls-tree", "-r", "master", "--name-only"] ) assert "untracked_file" not in out
Make form field names consistent.
<?php namespace Ice\ExternalUserBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface, Symfony\Component\OptionsResolver\OptionsResolverInterface; class UpdateAttributeType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('value', 'text', array( 'description' => 'Value of attribute', 'required' => true, )) ->add('updatedBy', 'text', array( 'description' => 'Username of User who initiated the update', 'required' => true, )) ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Ice\ExternalUserBundle\Entity\Attribute', 'csrf_protection' => false, 'validation_groups' => array('rest_update'), )); } public function getName() { return ''; } }
<?php namespace Ice\ExternalUserBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface, Symfony\Component\OptionsResolver\OptionsResolverInterface; class UpdateAttributeType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('value', 'text', array( 'description' => 'Value of attribute', 'required' => true, )) ->add('updated_by', 'text', array( 'description' => 'Username of User who initiated the update', 'required' => true, )) ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Ice\ExternalUserBundle\Entity\Attribute', 'csrf_protection' => false, 'validation_groups' => array('rest_update'), )); } public function getName() { return ''; } }
Correct inter sphinx path to Tornado docs.
#!/usr/bin/env python import alabaster from sprockets.mixins import cors project = 'sprockets.mixins.cors' copyright = '2015, AWeber Communication, Inc.' version = cors.__version__ release = '.'.join(str(v) for v in cors.version_info[0:2]) needs_sphinx = '1.0' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'sphinxcontrib.httpdomain', ] templates_path = [] source_suffix = '.rst' master_doc = 'index' exclude_patterns = [] pygments_style = 'sphinx' html_theme = 'alabaster' html_style = 'custom.css' html_theme_path = [alabaster.get_path()] html_static_path = ['static'] html_sidebars = { '**': ['about.html', 'navigation.html'], } html_theme_options = { 'github_user': 'sprockets', 'github_repo': 'sprockets.mixins.cors', 'description': 'Tornado CORS helper', 'github_banner': True, 'travis_button': True, } intersphinx_mapping = { 'python': ('https://docs.python.org/', None), 'tornado': ('http://www.tornadoweb.org/en/latest/', None), }
#!/usr/bin/env python import alabaster from sprockets.mixins import cors project = 'sprockets.mixins.cors' copyright = '2015, AWeber Communication, Inc.' version = cors.__version__ release = '.'.join(str(v) for v in cors.version_info[0:2]) needs_sphinx = '1.0' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'sphinxcontrib.httpdomain', ] templates_path = [] source_suffix = '.rst' master_doc = 'index' exclude_patterns = [] pygments_style = 'sphinx' html_theme = 'alabaster' html_style = 'custom.css' html_theme_path = [alabaster.get_path()] html_static_path = ['static'] html_sidebars = { '**': ['about.html', 'navigation.html'], } html_theme_options = { 'github_user': 'sprockets', 'github_repo': 'sprockets.mixins.cors', 'description': 'Tornado CORS helper', 'github_banner': True, 'travis_button': True, } intersphinx_mapping = { 'python': ('https://docs.python.org/', None), 'tornado': ('https://tornadoweb.org/en/latest/', None), }
Make sure there are no decimal points in the (pasteable) level change output.
function numberToString(number) { var r = Math.round(number * 1000) / 1000; return ""+r; } /** * There are some difficulties with locales with this script's number * output (when number > 1e21) and Clicker Heroes' input formatting. * This function makes sure there are no decimal points in the output. */ function numberToClickerHeroesPasteableString(number) { var b = Math.floor(Math.log(number)/Math.log(10)); if(b >= 21) { var intPart; intPart = Math.round(number / Math.pow(10, b-10)); return intPart + "e" + (b-10); } else { return ""+number; } } function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } function numberToStringFormatted(number) { var number = Number(number); if(number > 1000000) { return number.toPrecision(3); } else { number = Math.round(number * 1000) / 1000; return addCommas(number); } }
function numberToString(number) { var r = Math.round(number * 1000) / 1000; return ""+r; } function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } function numberToStringFormatted(number) { var number = Number(number); if(number > 1000000) { return number.toPrecision(3); } else { number = Math.round(number * 1000) / 1000; return addCommas(number); } }
Update according to the django wiki https://code.djangoproject.com/wiki/DosAndDontsForApplicationWriters
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = "django-webmaster-verification", version = "0.1", author = "Nicolas Kuttler", author_email = "pypi@nicolaskuttler.com", description = "Webmaster tools verification for Django", long_description = open("README.rst").read(), license = "BSD", url = "http://github.com/nkuttler/django-webmaster-verification", packages = ['webmaster_verification'], classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ], zip_safe = True, )
from distutils.core import setup from setuptools import setup, find_packages setup( name = "django-webmaster-verification", version = "0.1", author = "Nicolas Kuttler", author_email = "pypi@nicolaskuttler.com", description = "Webmaster tools verification for Django", long_description = open("README.rst").read(), license = "BSD", url = "http://github.com/nkuttler/django-webmaster-verification", packages = find_packages(), classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ], )
Fix gulp not minifying the css Since Gulp doesn't wait for one task to be completed in order to execute the second one, we hade some troubles with our default gulp task: the css wasn't minified because there was no css to minify in the dist folder yet. This commit fixes this by adding the "css" task to the "minify-css" task. So "css" is executed first and then the "minify-css" task is executed if you call the "minify-css" task.
const gulp = require('gulp'), minify = require('gulp-minify'), cssmin = require('gulp-cssmin'), rename = require('gulp-rename'), postcss = require('gulp-postcss'); // compress javascript files and move them to the dist folder gulp.task('compress', () => { return gulp.src('src/*.js') .pipe(minify({ ext:{ src:'.js', min:'.min.js' }, exclude: ['tasks'] })) .pipe(gulp.dest('dist')) }); // apply post css actions on the css and move to the dist folder gulp.task('css', function () { return gulp.src('./src/*.css') .pipe(postcss()) .pipe(gulp.dest('dist')); }); // minify the css that's in the dist folder gulp.task('minify-css',['css'], function () { gulp.src('dist/scroll-top.css') .pipe(cssmin()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('dist')); }); // go nuts gulp.task('default', ['compress', 'minify-css']);
const gulp = require('gulp'), minify = require('gulp-minify'), cssmin = require('gulp-cssmin'), rename = require('gulp-rename'), postcss = require('gulp-postcss'); // compress javascript files and move them to the dist folder gulp.task('compress', () => { gulp.src('src/*.js') .pipe(minify({ ext:{ src:'.js', min:'.min.js' }, exclude: ['tasks'] })) .pipe(gulp.dest('dist')) }); // apply post css actions on the css and move to the dist folder gulp.task('css', function () { return gulp.src('./src/*.css') .pipe(postcss()) .pipe(gulp.dest('dist')); }); // minify the css that's in the dist folder gulp.task('minify-css', function () { gulp.src('dist/scroll-top.css') .pipe(cssmin()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('dist')); }); // go nuts gulp.task('default', ['compress', 'css', 'minify-css']);
Add support for scatter plots in Backend Utilities
package gr.demokritos.iit.ydsapi.model; import java.util.HashSet; import java.util.Set; /** * accepted component types. * * @author George K. <gkiom@iit.demokritos.gr> */ public enum ComponentType { LINE("line"), SCATTER("scatter"), PIE("pie"), BAR("bar"), MAP("map"), GRID("grid"), RESULT("result"), RESULTSET("resultset"); private final String type; private ComponentType(String type) { this.type = type; } public String getDecl() { return type; } public static final Set<String> ACCEPTED = new HashSet(); static { ACCEPTED.add(LINE.getDecl()); ACCEPTED.add(SCATTER.getDecl()); ACCEPTED.add(PIE.getDecl()); ACCEPTED.add(BAR.getDecl()); ACCEPTED.add(MAP.getDecl()); ACCEPTED.add(GRID.getDecl()); ACCEPTED.add(RESULT.getDecl()); ACCEPTED.add(RESULTSET.getDecl()); } }
package gr.demokritos.iit.ydsapi.model; import java.util.HashSet; import java.util.Set; /** * accepted component types. * * @author George K. <gkiom@iit.demokritos.gr> */ public enum ComponentType { LINE("line"), PIE("pie"), BAR("bar"), MAP("map"), GRID("grid"), RESULT("result"), RESULTSET("resultset"); private final String type; private ComponentType(String type) { this.type = type; } public String getDecl() { return type; } public static final Set<String> ACCEPTED = new HashSet(); static { ACCEPTED.add(LINE.getDecl()); ACCEPTED.add(PIE.getDecl()); ACCEPTED.add(BAR.getDecl()); ACCEPTED.add(MAP.getDecl()); ACCEPTED.add(GRID.getDecl()); ACCEPTED.add(RESULT.getDecl()); ACCEPTED.add(RESULTSET.getDecl()); } }
Add difficulty to stub challenge to allow cheat calculation to happen
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const expect = chai.expect const chaiAsPromised = require('chai-as-promised') chai.use(chaiAsPromised) describe('webhook', () => { const webhook = require('../../lib/webhook') const challenge = { key: 'key', name: 'name', difficulty: 1 } describe('notify', () => { it('fails when no webhook URL is provided via environment variable', () => { expect(webhook.notify(challenge)).to.eventually.throw('options.uri is a required argument') }) it('fails when supplied webhook is not a valid URL', () => { expect(webhook.notify(challenge, 'localhorst')).to.eventually.throw('Invalid URI "localhorst"') }) it('submits POST with payload to existing URL', () => { expect(webhook.notify(challenge, 'https://enlm7zwniuyah.x.pipedream.net/')).to.eventually.not.throw() }) }) })
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const expect = chai.expect const chaiAsPromised = require('chai-as-promised') chai.use(chaiAsPromised) describe('webhook', () => { const webhook = require('../../lib/webhook') const challenge = { key: 'key', name: 'name' } describe('notify', () => { it('fails when no webhook URL is provided via environment variable', () => { expect(webhook.notify(challenge)).to.eventually.throw('options.uri is a required argument') }) it('fails when supplied webhook is not a valid URL', () => { expect(webhook.notify(challenge, 'localhorst')).to.eventually.throw('Invalid URI "localhorst"') }) it('submits POST with payload to existing URL', () => { expect(webhook.notify(challenge, 'https://enlm7zwniuyah.x.pipedream.net/')).to.eventually.not.throw() }) }) })
Connect error state adn signupRequest action
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { createStructuredSelector } from 'reselect'; import { signupRequest } from 'containers/App/actions'; import { makeSelectError } from 'containers/App/selectors'; import Header from 'components/Header'; import SignupCard from 'components/SignupCard'; export class SignupPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <Helmet title="Signup Page" meta={[ { name: 'description', content: 'Signup Page of Book Trader application' }, ]} /> <Header location={this.props.location.pathname} /> <div className="container"> <SignupCard signup={this.props.signup} error={this.props.error} /> </div> </div> ); } } SignupPage.propTypes = { signup: PropTypes.func.isRequired, location: PropTypes.object, error: PropTypes.oneOfType([ PropTypes.string, PropTypes.bool, ]), }; const mapStateToProps = createStructuredSelector({ error: makeSelectError(), }); function mapDispatchToProps(dispatch) { return { signup: (payload) => dispatch(signupRequest(payload)), }; } export default connect(mapStateToProps, mapDispatchToProps)(SignupPage);
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import Header from 'components/Header'; import SignupCard from 'components/SignupCard'; export class SignupPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <Helmet title="Signup Page" meta={[ { name: 'description', content: 'Signup Page of Book Trader application' }, ]} /> <Header location={this.props.location.pathname} /> <div className="container"> <SignupCard signup={() => { console.log('signup'); }} /> </div> </div> ); } } SignupPage.propTypes = { dispatch: PropTypes.func.isRequired, location: PropTypes.object, }; function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(null, mapDispatchToProps)(SignupPage);
Fix compile error in Go 1.14 due to time.Ticker.Reset
package clock import "time" type Clock interface { NewTicker(time.Duration) Ticker Now() time.Time } func New() Clock { return clock{} } type clock struct{} func (c clock) NewTicker(d time.Duration) Ticker { return &ticker{ ticker: time.NewTicker(d), } } func (c clock) Now() time.Time { return time.Now() } type Ticker interface { C() <-chan time.Time Stop() Reset(time.Duration) } type ticker struct { ticker *time.Ticker } func (t *ticker) Stop() { t.ticker.Stop() } func (t *ticker) Reset(d time.Duration) { ticker, ok := (interface{})(t.ticker).(interface { Reset(time.Duration) }) if !ok { panic("Ticker.Reset not implemented in this Go version.") } ticker.Reset(d) } func (t *ticker) C() <-chan time.Time { return t.ticker.C } var _ Ticker = &ticker{}
package clock import "time" type Clock interface { NewTicker(time.Duration) Ticker Now() time.Time } func New() Clock { return clock{} } type clock struct{} func (c clock) NewTicker(d time.Duration) Ticker { return &ticker{ ticker: time.NewTicker(d), } } func (c clock) Now() time.Time { return time.Now() } type Ticker interface { C() <-chan time.Time Stop() Reset(time.Duration) } type ticker struct { ticker *time.Ticker } func (t *ticker) Stop() { t.ticker.Stop() } func (t *ticker) Reset(d time.Duration) { t.ticker.Reset(d) } func (t *ticker) C() <-chan time.Time { return t.ticker.C } var _ Ticker = &ticker{}
Remove duplicate call to repo.Init()
// Provides a simple REST API implementing a basic to-do list package main import ( "expvar" "log" "net/http" "sync" "todolist/repo" "todolist/spi" ) var repository spi.Repo // Starts two HTTP services: // one at port 8080 for exposing the ToDoList REST service, // one at port 8081 for exposing the expvar service. // The application runs as long as both HTTP services are up func main() { repository = repo.NewRepo() wg := new(sync.WaitGroup) wg.Add(1) go registerBusinessServer(wg) go registerExpvarServer(wg) wg.Wait() } func registerBusinessServer(wg *sync.WaitGroup) { log.Fatal(http.ListenAndServe(":8080", NewRouter())) wg.Done() } func registerExpvarServer(wg *sync.WaitGroup) { log.Fatal(http.ListenAndServe(":8081", expvar.Handler())) wg.Done() }
// Provides a simple REST API implementing a basic to-do list package main import ( "expvar" "log" "net/http" "sync" "todolist/repo" "todolist/spi" ) var repository spi.Repo // Starts two HTTP services: // one at port 8080 for exposing the ToDoList REST service, // one at port 8081 for exposing the expvar service. // The application runs as long as both HTTP services are up func main() { repository = repo.NewRepo() err := repository.Init() if nil != err { panic(err) } wg := new(sync.WaitGroup) wg.Add(1) go registerBusinessServer(wg) go registerExpvarServer(wg) wg.Wait() } func registerBusinessServer(wg *sync.WaitGroup) { log.Fatal(http.ListenAndServe(":8080", NewRouter())) wg.Done() } func registerExpvarServer(wg *sync.WaitGroup) { log.Fatal(http.ListenAndServe(":8081", expvar.Handler())) wg.Done() }
Remove clean command from build system
import os import json # Get project settings projectData = open("project.json") projectConfig = json.load(projectData) buildVersion = projectConfig["version"] buildCultures = projectConfig["cultures"] buildConfiguration = projectConfig["configuration"] projectData.close() # Get system settings systemData = open("system.json") systemConfig = json.load(systemData) buildPlatform = systemConfig["platform"] inputDir = systemConfig["inputDir"] outputDir = systemConfig["outputDir"] engineDir = systemConfig["engineDir"] systemData.close() # Generate paths inputProject = os.path.join(inputDir, "HeliumRain.uproject") buildTool = os.path.join(engineDir, "Engine", "Build", "BatchFiles", "RunUAT.bat") # Generate full command line commandLine = buildTool commandLine += " BuildCookRun -project=" + inputProject + " -nocompile -nocompileeditor -installed -nop4 -clientconfig=" + buildConfiguration commandLine += " -cook -allmaps -stage -archive -archivedirectory=" + outputDir commandLine += " -package -ue4exe=UE4Editor-Cmd.exe -build -pak -prereqs -distribution -nodebuginfo -createreleaseversion=" + buildVersion commandLine += " -utf8output -CookCultures=" + buildCultures # Call print(commandLine) os.system(commandLine)
import os import json # Get project settings projectData = open("project.json") projectConfig = json.load(projectData) buildVersion = projectConfig["version"] buildCultures = projectConfig["cultures"] buildConfiguration = projectConfig["configuration"] projectData.close() # Get system settings systemData = open("system.json") systemConfig = json.load(systemData) buildPlatform = systemConfig["platform"] inputDir = systemConfig["inputDir"] outputDir = systemConfig["outputDir"] engineDir = systemConfig["engineDir"] systemData.close() # Generate paths inputProject = os.path.join(inputDir, "HeliumRain.uproject") buildTool = os.path.join(engineDir, "Engine", "Build", "BatchFiles", "RunUAT.bat") # Generate full command line commandLine = buildTool commandLine += " BuildCookRun -project=" + inputProject + " -nocompile -nocompileeditor -installed -nop4 -clientconfig=" + buildConfiguration commandLine += " -cook -allmaps -stage -archive -archivedirectory=" + outputDir commandLine += " -package -ue4exe=UE4Editor-Cmd.exe -build -clean -pak -prereqs -distribution -nodebuginfo -createreleaseversion=" + buildVersion commandLine += " -utf8output -CookCultures=" + buildCultures # Call print(commandLine) os.system(commandLine)
Fix param/return documentation for internal curryN fix(_curryN) fix capitalization in return type
var _arity = require('./_arity'); /** * Internal curryN function. * * @private * @category Function * @param {Number} length The arity of the curried function. * @param {Array} An array of arguments received thus far. * @param {Function} fn The function to curry. * @return {Function} The curried function. */ module.exports = function _curryN(length, received, fn) { return function() { var combined = []; var argsIdx = 0; var left = length; var combinedIdx = 0; while (combinedIdx < received.length || argsIdx < arguments.length) { var result; if (combinedIdx < received.length && (received[combinedIdx] == null || received[combinedIdx]['@@functional/placeholder'] !== true || argsIdx >= arguments.length)) { result = received[combinedIdx]; } else { result = arguments[argsIdx]; argsIdx += 1; } combined[combinedIdx] = result; if (result == null || result['@@functional/placeholder'] !== true) { left -= 1; } combinedIdx += 1; } return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn)); }; };
var _arity = require('./_arity'); /** * Internal curryN function. * * @private * @category Function * @param {Number} length The arity of the curried function. * @return {array} An array of arguments received thus far. * @param {Function} fn The function to curry. */ module.exports = function _curryN(length, received, fn) { return function() { var combined = []; var argsIdx = 0; var left = length; var combinedIdx = 0; while (combinedIdx < received.length || argsIdx < arguments.length) { var result; if (combinedIdx < received.length && (received[combinedIdx] == null || received[combinedIdx]['@@functional/placeholder'] !== true || argsIdx >= arguments.length)) { result = received[combinedIdx]; } else { result = arguments[argsIdx]; argsIdx += 1; } combined[combinedIdx] = result; if (result == null || result['@@functional/placeholder'] !== true) { left -= 1; } combinedIdx += 1; } return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn)); }; };
Create history manager in state navigator constructor Easier to document than the configure call. More consistent with the mobile docs, too
import React from 'react'; import {Platform} from 'react-native'; import {StateNavigator} from 'navigation'; import {NavigationStack} from 'navigation-react-native'; import Grid from './Grid'; import Detail from './Detail'; const colors = [ 'maroon', 'red', 'crimson', 'orange', 'brown', 'sienna', 'olive', 'purple', 'fuchsia', 'indigo', 'green', 'navy', 'blue', 'teal', 'black' ]; export default () => { const stateNavigator = new StateNavigator([ {key: 'grid', route: ''}, {key: 'detail', route: '{color}', trackCrumbTrail: true}, ], NavigationStack.HistoryManager && new NavigationStack.HistoryManager(url => { const {state, data} = stateNavigator.parseLink(url); return stateNavigator.fluent() .navigate('grid') .navigate(state.key, data).url; })); const {grid, detail} = stateNavigator.states; grid.renderScene = () => <Grid colors={colors} />; detail.renderScene = ({color}) => <Detail colors={colors} color={color} />; detail.truncateCrumbTrail = (state, data, crumbs) => ( crumbs.slice(-1)[0].state === detail ? crumbs.slice(0, -1) : crumbs ); if (Platform.OS === 'web') stateNavigator.start() else stateNavigator.navigate('grid'); return stateNavigator; }
import React from 'react'; import {Platform} from 'react-native'; import {StateNavigator} from 'navigation'; import {NavigationStack} from 'navigation-react-native'; import Grid from './Grid'; import Detail from './Detail'; const colors = [ 'maroon', 'red', 'crimson', 'orange', 'brown', 'sienna', 'olive', 'purple', 'fuchsia', 'indigo', 'green', 'navy', 'blue', 'teal', 'black' ]; export default () => { const stateNavigator = new StateNavigator([ {key: 'grid', route: ''}, {key: 'detail', route: '{color}', trackCrumbTrail: true}, ]); const {grid, detail} = stateNavigator.states; grid.renderScene = () => <Grid colors={colors} />; detail.renderScene = ({color}) => <Detail colors={colors} color={color} />; detail.truncateCrumbTrail = (state, data, crumbs) => ( crumbs.slice(-1)[0].state === detail ? crumbs.slice(0, -1) : crumbs ); if (Platform.OS === 'web') { const buildStartUrl = url => { const {state, data} = stateNavigator.parseLink(url); return stateNavigator.fluent() .navigate('grid') .navigate(state.key, data).url; }; stateNavigator.configure(stateNavigator, new NavigationStack.HistoryManager(buildStartUrl)); stateNavigator.start() } else { stateNavigator.navigate('grid'); } return stateNavigator; }
:bug: Fix logic in queue removal
const logger = require('winston') const { Module } = require('../../core') class Queue extends Module { constructor (...args) { super(...args, { name: 'music:queue' }) this.redis = this.bot.engine.cache.client } add (guildID, video, prepend = false) { if (typeof video === 'object') video = JSON.stringify(video) return this.redis[`${prepend ? 'lpush' : 'rpush'}Async`](`music:queues:${guildID}`, video) } async remove (guildID, index = 0, count = 1) { const info = await this.getSongs(guildID, index) const res = await this.redis.lremAsync(`music:queues:${guildID}`, count, info[0]) if (res) return JSON.parse(info[0]) return null } async shift (guildID) { return JSON.parse(await this.redis.lpopAsync(`music:queues:${guildID}`)) } clear (guildID) { return this.redis.delAsync(`music:queues:${guildID}`) } getLength (guildID) { return this.redis.llenAsync(`music:queues:${guildID}`) } isRepeat (guildID) { return this.redis.sismemberAsync('music:repeats', guildID) } async getSongs (guildID, start = 0, stop = start) { return await this.redis.lrangeAsync(`music:queues:${guildID}`, start, stop) } } module.exports = Queue
const logger = require('winston') const { Module } = require('../../core') class Queue extends Module { constructor (...args) { super(...args, { name: 'music:queue' }) this.redis = this.bot.engine.cache.client } add (guildID, video, prepend = false) { if (typeof video === 'object') video = JSON.stringify(video) return this.redis[`${prepend ? 'lpush' : 'rpush'}Async`](`music:queues:${guildID}`, video) } async remove (guildID, index = 0, count = 1) { const info = await this.getSongs(guildID, index) const res = await this.redis.lremAsync(`music:queues:${guildID}`, count, info) if (res) return JSON.parse(info[0]) return null } async shift (guildID) { return JSON.parse(await this.redis.lpopAsync(`music:queues:${guildID}`)) } clear (guildID) { return this.redis.delAsync(`music:queues:${guildID}`) } getLength (guildID) { return this.redis.llenAsync(`music:queues:${guildID}`) } isRepeat (guildID) { return this.redis.sismemberAsync('music:repeats', guildID) } async getSongs (guildID, start = 0, stop = start) { return await this.redis.lrangeAsync(`music:queues:${guildID}`, start, stop) } } module.exports = Queue
Fix for active class not being set properly
scms.create('ProductVariationsViewBridge', function(){ return { attachEvents:function () { var self = this; $('.product-variation-tab', this.viewNode).click(function(event) { if (!event.target.classList.contains('fa')) { self.changeTab($(this).parent()); } else { if (confirm('Are you sure you want to remove this variation?')) { self.raiseServerEvent('VariationDelete', $(this).data('id')); } } }); }, changeTab:function(tab){ var lastSelected = $('.product-list-tabs.active'); this.raiseProgressiveServerEvent('changeVariation', lastSelected.data('id'), tab.data('id')); lastSelected.removeClass('active'); tab.addClass('active'); } }; });
scms.create('ProductVariationsViewBridge', function(){ return { attachEvents:function () { var self = this; $(this.viewNode, '.product-variation-tab').click(function(event) { if (!event.target.classList.contains('fa')) { self.changeTab($(this).parent()); } else { if (confirm('Are you sure you want to remove this variation?')) { self.raiseServerEvent('VariationDelete', $(this).data('id')); } } }); }, changeTab:function(tab){ var lastSelected = $('.product-list-tabs.active a'); this.raiseProgressiveServerEvent('changeVariation', lastSelected.data('id'), tab.data('id')); lastSelected.removeClass('active'); tab.addClass('active'); } }; });
Remove comment list from video view - It doesn't work anymore and will belong on performances instead
import * as _ from 'lodash' import React from 'react' import {connect} from 'react-redux' import {compose, withProps} from 'recompose' import {updateVideo} from '../../actions/videos' import {withDatabaseSubscribe} from '../hocs' const mapStateToProps = ({videos}) => ({ videos }) const enhance = compose( connect(mapStateToProps), withProps(({match}) => ({ videoId: match.params.videoId, })), withDatabaseSubscribe( 'value', (props) => (`videos/${props.videoId}`), (props) => (snapshot) => ( props.dispatch(updateVideo( { videoId: props.videoId, videoSnapshot: snapshot.val() })) ) ), ) const styles = { videoContainer: { height: 'calc(100vh - 56px)', display: 'flex', flexWrap: 'wrap', } } const VideoView = ({videos, videoId}) => ( <div style={styles.videoContainer}> {JSON.stringify(_.get(videos, videoId, {}))} </div> ) export default enhance(VideoView)
import * as _ from 'lodash' import React from 'react' import {connect} from 'react-redux' import {compose, withProps} from 'recompose' import {updateVideo} from '../../actions/videos' import CommentList from '../CommentList' import {withDatabaseSubscribe} from '../hocs' const mapStateToProps = ({videos}) => ({ videos }) const enhance = compose( connect(mapStateToProps), withProps(({match}) => ({ videoId: match.params.videoId, })), withDatabaseSubscribe( 'value', (props) => (`videos/${props.videoId}`), (props) => (snapshot) => ( props.dispatch(updateVideo( { videoId: props.videoId, videoSnapshot: snapshot.val() })) ) ), ) const styles = { videoContainer: { height: 'calc(100vh - 56px)', display: 'flex', flexWrap: 'wrap', } } const VideoView = ({videos, videoId}) => ( <div style={styles.videoContainer}> {JSON.stringify(_.get(videos, videoId, {}))} <CommentList videoId={videoId}/> </div> ) export default enhance(VideoView)
Update secret key generator to exclude pantuations
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def secret_key_gen(): filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.txt' generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(50)]) with open(filepath, 'w') as secret_file: secret_file.write( '%(key)s' % dict(key=generated_key) ) print('Find your secret key at %(path)s' % dict(path=filepath))
import os import random import string from datetime import date, datetime def random_name(): return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)]) def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def secret_key_gen(): filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.txt' generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(50)]) with open(filepath, 'w') as secret_file: secret_file.write( '%(key)s' % dict(key=generated_key) ) print('Find your secret key at %(path)s' % dict(path=filepath))
Add support for jsmin PHP extension
<?php App::uses('AssetFilter', 'AssetCompress.Lib'); /** * JsMin filter. * * Allows you to filter Javascript files through JSMin. You need either the * `jsmin` PHP extension installed, or a copy of `jsmin-php` in one of your * application's `vendors` directories. * * @link https://github.com/sqmk/pecl-jsmin * @link http://github.com/rgrove/jsmin-php */ class JsMinFilter extends AssetFilter { /** * Where JSMin can be found. * * @var array */ protected $_settings = array( 'path' => 'jsmin/jsmin.php' ); /** * Apply JSMin to $content. * * @param string $filename * @param string $content Content to filter. * @throws Exception * @return string */ public function output($filename, $content) { if (function_exists('jsmin')) { return jsmin($content); } App::import('Vendor', 'jsmin', array('file' => $this->_settings['path'])); if (!class_exists('JSMin')) { throw new Exception(sprintf('Cannot not load filter class "%s".', 'JSMin')); } return JSMin::minify($content); } }
<?php App::uses('AssetFilter', 'AssetCompress.Lib'); /** * JsMin filter. * * Allows you to filter Javascript files through JSMin. You need to put JSMin in your application's * vendors directories. You can get it from http://github.com/rgrove/jsmin-php/ * */ class JsMinFilter extends AssetFilter { /** * Where JSMin can be found. * * @var array */ protected $_settings = array( 'path' => 'jsmin/jsmin.php' ); /** * Apply JSMin to $content. * * @param string $filename * @param string $content Content to filter. * @throws Exception * @return string */ public function output($filename, $content) { App::import('Vendor', 'jsmin', array('file' => $this->_settings['path'])); if (!class_exists('JSMin')) { throw new Exception(sprintf('Cannot not load filter class "%s".', 'JSMin')); } return JSMin::minify($content); } }