text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use `yield_fixture` instead of classic `fixture` with pytest
import random import pytest from Pyro4.errors import NamingError from osbrain.nameserver import NameServer from osbrain.address import SocketAddress @pytest.yield_fixture(scope='function') def nsaddr(request): while True: try: # Bind to random port host = '127.0.0.1' port = random.randrange(10000, 20000) addr = SocketAddress(host, port) nameserver = NameServer(addr) nameserver.start() break except RuntimeError: continue except: raise yield addr nameserver.shutdown()
import random import pytest from Pyro4.errors import NamingError from osbrain.nameserver import NameServer from osbrain.address import SocketAddress @pytest.fixture(scope='function') def nsaddr(request): while True: try: # Bind to random port host = '127.0.0.1' port = random.randrange(10000, 20000) addr = SocketAddress(host, port) nameserver = NameServer(addr) def terminate(): nameserver.shutdown() request.addfinalizer(terminate) nameserver.start() return addr except NamingError: continue except PermissionError: continue except: raise
Change it so / has the latest, greatest view.
"use strict"; /* global process */ /******************************************************************************* * Copyright (c) 2015 IBM Corp. * * All rights reserved. * * Contributors: * David Huffman - Initial implementation *******************************************************************************/ var express = require('express'); var router = express.Router(); var base64 = require('base64-js'); var fs = require("fs"); // Load our modules. var aux = require("./site_aux.js"); var rest = require("../utils/rest.js"); var b64 = require("../utils/b64.js"); // ============================================================================================================================ // Home // ============================================================================================================================ router.route("/old").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); } catch(e){ console.log('error loading cc.json', e); }; res.render('home', {title: 'Home', bag: cc} ); }); // ============================================================================================================================ // Chain Code Investigator // ============================================================================================================================ router.route("/").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); } catch(e){ console.log('error loading cc.json', e); }; res.render('investigate', {title: 'Investigator', bag: cc} ); }); module.exports = router;
"use strict"; /* global process */ /******************************************************************************* * Copyright (c) 2015 IBM Corp. * * All rights reserved. * * Contributors: * David Huffman - Initial implementation *******************************************************************************/ var express = require('express'); var router = express.Router(); var base64 = require('base64-js'); var fs = require("fs"); // Load our modules. var aux = require("./site_aux.js"); var rest = require("../utils/rest.js"); var b64 = require("../utils/b64.js"); // ============================================================================================================================ // Home // ============================================================================================================================ router.route("/").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); } catch(e){ console.log('error loading cc.json', e); }; res.render('home', {title: 'Home', bag: cc} ); }); // ============================================================================================================================ // Chain Code Investigator // ============================================================================================================================ router.route("/investigate").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); } catch(e){ console.log('error loading cc.json', e); }; res.render('investigate', {title: 'Investigator', bag: cc} ); }); module.exports = router;
Make CardImageHeader use imageProp from propTypes
import React, { Component } from 'react'; import { StyleSheet } from 'react-native'; import { Thumbnail, CardItem } from 'native-base'; import CardImageHeaderStyle from './cardImageHeaderStyle'; import GlobalStyle from '../../common/globalStyle'; import { imageProp } from '../../common/propTypes'; // Card header with image and icon. export default class CardImageHeader extends Component { static propTypes = { cover: imageProp.isRequired, icon: imageProp.isRequired, toNextScreen: React.PropTypes.func, }; static defaultProps = { icon: undefined, toNextScreen: () => alert('hej!'), }; render() { // Only show icon if it is provided as a prop let iconIfProvided = []; if (this.props.icon !== undefined) { iconIfProvided = ( <Thumbnail source={this.props.icon} /> ); } return ( <CardItem style={StyleSheet.flatten(GlobalStyle.noPadding)} onPress={this.props.toNextScreen} > <Thumbnail square resizeMode="cover" style={StyleSheet.flatten(CardImageHeaderStyle.coverPhoto)} source={this.props.cover} > {iconIfProvided} </Thumbnail> </CardItem> ); } }
import React, { Component } from 'react'; import { StyleSheet } from 'react-native'; import { Thumbnail, CardItem } from 'native-base'; import CardImageHeaderStyle from './cardImageHeaderStyle'; import GlobalStyle from '../../common/globalStyle'; // Card header with image and icon. export default class CardImageHeader extends Component { static propTypes = { cover: React.PropTypes.string.isRequired, icon: React.PropTypes.string, toNextScreen: React.PropTypes.func, }; static defaultProps = { icon: undefined, toNextScreen: () => alert('hej!'), }; render() { // Only show icon if it is provided as a prop let iconIfProvided = []; if (this.props.icon !== undefined) { iconIfProvided = ( <Thumbnail source={{ uri: this.props.icon }} /> ); } return ( <CardItem style={StyleSheet.flatten(GlobalStyle.noPadding)} onPress={this.props.toNextScreen} > <Thumbnail square resizeMode="cover" style={StyleSheet.flatten(CardImageHeaderStyle.coverPhoto)} source={{ uri: this.props.cover }} > {iconIfProvided} </Thumbnail> </CardItem> ); } }
Fix IndexOutOfBoundEx for empty numeric values
package com.axonivy.ivy.process.element.rule.ui.cellEdit; import org.apache.commons.lang3.math.NumberUtils; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.widgets.Text; public class NumericValueVerifier implements VerifyListener { @Override public void verifyText(VerifyEvent e) { e.doit = NumberUtils.isParsable(getText(e)); } private String getText(VerifyEvent e) { if (e.getSource() instanceof Text) { final String old = ((Text)e.getSource()).getText(); String current = old.substring(0, e.start) + e.text + old.substring(e.end); if (current.isEmpty()) { return current; } if (current.indexOf(".") == current.length()-1 || current.indexOf(",") == current.length()-1) { // allow one decimal separator at the end return current.substring(0, current.length()-1); } return current; } return e.text; } }
package com.axonivy.ivy.process.element.rule.ui.cellEdit; import org.apache.commons.lang3.math.NumberUtils; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.widgets.Text; public class NumericValueVerifier implements VerifyListener { @Override public void verifyText(VerifyEvent e) { e.doit = NumberUtils.isParsable(getText(e)); } private String getText(VerifyEvent e) { if (e.getSource() instanceof Text) { final String old = ((Text)e.getSource()).getText(); String current = old.substring(0, e.start) + e.text + old.substring(e.end); if (current.indexOf(".") == current.length()-1 || current.indexOf(",") == current.length()-1) { // allow one decimal separator at the end return current.substring(0, current.length()-1); } return current; } return e.text; } }
FIX partner person not instalable
# -*- coding: utf-8 -*- { 'name': 'Partners Persons Management', 'version': '1.0', 'category': 'Tools', 'sequence': 14, 'summary': '', 'description': """ Partners Persons Management =========================== Openerp consider a person those partners that have not "is_company" as true, now, those partners can have: ---------------------------------------------------------------------------------------------------------- * First Name and Last Name * Birthdate * Sex * Mother and Father * Childs * Age (functional field) * Nationality * Husband/Wife * National Identity * Passport * Marital Status It also adds a configuration menu for choosing which fields do you wanna see. """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'base', ], 'data': [ 'res_partner_view.xml', 'res_config_view.xml', 'security/partner_person_security.xml', ], 'demo': [ ], 'test': [ ], 'installable': False, 'auto_install': False, 'application': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- { 'name': 'Partners Persons Management', 'version': '1.0', 'category': 'Tools', 'sequence': 14, 'summary': '', 'description': """ Partners Persons Management =========================== Openerp consider a person those partners that have not "is_company" as true, now, those partners can have: ---------------------------------------------------------------------------------------------------------- * First Name and Last Name * Birthdate * Sex * Mother and Father * Childs * Age (functional field) * Nationality * Husband/Wife * National Identity * Passport * Marital Status It also adds a configuration menu for choosing which fields do you wanna see. """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'base', ], 'data': [ 'res_partner_view.xml', 'res_config_view.xml', 'security/partner_person_security.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Test file contents are now Buffers.
/* jshint node: true */ /* global describe, it */ 'use strict'; var expect = require('chai').expect, gutil = require('gulp-util'), csso = require('./index'); var basestyle = 'h1 { color: yellow; } \n h1 { font-size: 2em; }', optimalmin = 'h1{color:#ff0;font-size:2em}', nonoptimal = 'h1{color:#ff0}h1{font-size:2em}'; describe('gulp-csso', function() { it('should minify css with csso, performing structural optimisation', function (cb) { var stream = csso(); stream.on('data', function(data) { expect(String(data.contents)).to.equal(optimalmin); cb(); }); stream.write(new gutil.File({ contents: new Buffer(basestyle) })); }); it('should minify css with csso, with no structural optimisation', function (cb) { var stream = csso(true); stream.on('data', function(data) { expect(String(data.contents)).to.equal(nonoptimal); cb(); }); stream.write(new gutil.File({ contents: new Buffer(basestyle) })); }); });
/* jshint node: true */ /* global describe, it */ 'use strict'; var expect = require('chai').expect, gutil = require('gulp-util'), csso = require('./index'); var basestyle = 'h1 { color: yellow; } \n h1 { font-size: 2em; }', optimalmin = 'h1{color:#ff0;font-size:2em}', nonoptimal = 'h1{color:#ff0}h1{font-size:2em}'; describe('gulp-csso', function() { it('should minify css with csso, performing structural optimisation', function (cb) { var stream = csso(); stream.on('data', function(data) { expect(String(data.contents)).to.equal(optimalmin); cb(); }); stream.write(new gutil.File({ contents: basestyle })); }); it('should minify css with csso, with no structural optimisation', function (cb) { var stream = csso(true); stream.on('data', function(data) { expect(String(data.contents)).to.equal(nonoptimal); cb(); }); stream.write(new gutil.File({ contents: basestyle })); }); });
Remove ".git" from project names
<?php declare(strict_types=1); namespace Wnx\LaravelStats\ShareableMetrics; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use Symfony\Component\Process\Process; class ProjectName { public const RC_FILE = '.laravelstatsrc'; public function get(): ?string { if ($this->hasStoredProjectName()) { return File::get($this->pathToRcFile()); } return null; } public function determineProjectNameFromGit(): ?string { $process = Process::fromShellCommandline('/usr/local/bin/git config --get remote.origin.url'); $process->run(); if ($process->isSuccessful() === false) { return null; } $remoteUrl = parse_url(trim($process->getOutput())); $remoteUrl = Str::replaceLast('.git', '', $remoteUrl['path']); return Str::replaceFirst('/', '', $remoteUrl); } protected function pathToRcFile(): string { return base_path(self::RC_FILE); } public function hasStoredProjectName(): bool { return File::exists($this->pathToRcFile()); } public function storeNameInRcFile(string $projectName): void { File::put($this->pathToRcFile(), $projectName); } }
<?php declare(strict_types=1); namespace Wnx\LaravelStats\ShareableMetrics; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use Symfony\Component\Process\Process; class ProjectName { public const RC_FILE = '.laravelstatsrc'; public function get(): ?string { if ($this->hasStoredProjectName()) { return File::get($this->pathToRcFile()); } return null; } public function determineProjectNameFromGit(): ?string { $process = Process::fromShellCommandline('/usr/local/bin/git config --get remote.origin.url'); $process->run(); if ($process->isSuccessful() === false) { return null; } $remoteUrl = parse_url(trim($process->getOutput())); return Str::replaceFirst('/', '', $remoteUrl['path']); } protected function pathToRcFile(): string { return base_path(self::RC_FILE); } public function hasStoredProjectName(): bool { return File::exists($this->pathToRcFile()); } public function storeNameInRcFile(string $projectName): void { File::put($this->pathToRcFile(), $projectName); } }
Add G1 example and utf-8
# -*- coding: UTF-8 -*- import os import sys import json import feedparser from bs4 import BeautifulSoup FEED_URL = 'http://g1.globo.com/dynamo/rss2.xml' fp = feedparser.parse(FEED_URL) print "Fetched %s entries from '%s'" % (len(fp.entries[0].title), fp.feed.title) blog_posts = [] for e in fp.entries: blog_posts.append({'title': e.title, 'published': e.published, 'summary': BeautifulSoup(e.summary, 'lxml').get_text(), 'link': e.link}) out_file = os.path.join('./', 'feed.json') f = open(out_file, 'w') f.write(json.dumps(blog_posts, indent=1, ensure_ascii=False).encode('utf8')) f.close() print 'Wrote output file to %s' % (f.name, )
import os import sys import json import feedparser from bs4 import BeautifulSoup FEED_URL = 'http://g1.globo.com/dynamo/rss2.xml' def cleanHtml(html): return BeautifulSoup(html, 'lxml').get_text() fp = feedparser.parse(FEED_URL) print "Fetched %s entries from '%s'" % (len(fp.entries[0].title), fp.feed.title) blog_posts = [] for e in fp.entries: blog_posts.append({'title': e.title, 'published': e.published, 'summary': cleanHtml(e.summary), 'link': e.link}) out_file = os.path.join('./', 'feed.json') f = open(out_file, 'w') f.write(json.dumps(blog_posts, indent=1)) f.close() print 'Wrote output file to %s' % (f.name, )
Add missing required heroku config variable
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
Add a new line before displaying the current dir This makes it easier for my brain to read.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import subprocess import sys def execute_command(target): os.chdir(target) command = sys.argv[1:] try: subprocess.check_call(command) except Exception as e: print "ERROR in %s: %s" % (target, e) def main(): base = os.getcwdu() + "/" targets = None # Get immediate child directories. for root, dirs, files in os.walk('.'): targets = dirs break # dirty hack so we only get the first level # Traverse through the directories. for target in sorted(targets, key=lambda s: s.lower()): target_full_path = base + target print "\nwalker: in %s" % target_full_path execute_command(target_full_path) os.chdir(base) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import subprocess import sys def execute_command(target): os.chdir(target) command = sys.argv[1:] try: subprocess.check_call(command) except Exception as e: print "ERROR in %s: %s" % (target, e) def main(): base = os.getcwdu() + "/" targets = None # Get immediate child directories. for root, dirs, files in os.walk('.'): targets = dirs break # dirty hack so we only get the first level # Traverse through the directories. for target in sorted(targets, key=lambda s: s.lower()): target_full_path = base + target print "walker: in %s" % target_full_path execute_command(target_full_path) os.chdir(base) if __name__ == '__main__': main()
Update requests requirement from <2.25,>=2.4.2 to >=2.4.2,<2.26 Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version. - [Release notes](https://github.com/psf/requests/releases) - [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md) - [Commits](https://github.com/psf/requests/compare/v2.4.2...v2.25.0) Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.3.0', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.26', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.3.0', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.25', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
Use duck-typing instead of strong type checking
var _ = require('lodash'); var defaultOptions = { assignField: 'auth' }; function validAuthority(authority) { return authority.getUser !== undefined; } function identify(auth, opts) { opts = _.defaults(opts || {}, defaultOptions); if (!validAuthority(auth)) throw new TypeError; return function(req, res, next) { if (req[opts.assignField] !== undefined) return next(); getUserAndRole(auth, req, function(err, authInfo) { if (err) return next(err); req[opts.assignField] = authInfo; next(); }); }; } function getUserAndRole(auth, req, cb) { auth.getUser(req, function(err, user) { if (err || !user) return cb(err, null); user.getRole(function(err, role) { if (err || !role) return cb(err, null); cb(null, { user: user, role: role }); }); }); } module.exports = exports = identify; exports.defaultOptions = defaultOptions;
var _ = require('lodash'); var Authority = require('../authority'); var defaultOptions = { assignField: 'auth' }; function identify(auth, opts) { opts = _.defaults(opts || {}, defaultOptions); if (!(auth instanceof Authority)) throw new TypeError; return function(req, res, next) { if (req[opts.assignField] !== undefined) return next(); getUserAndRole(auth, req, function(err, authInfo) { if (err) return next(err); req[opts.assignField] = authInfo; next(); }); }; } function getUserAndRole(auth, req, cb) { auth.getUser(req, function(err, user) { if (err || !user) return cb(err, null); user.getRole(function(err, role) { if (err || !role) return cb(err, null); cb(null, { user: user, role: role }); }); }); } module.exports = exports = identify; exports.defaultOptions = defaultOptions;
Add a runtime version of if. elif/else can't have runtime versions 'cause they are purely syntactic.
import builtins import operator import functools from ..compile import varary builtins.__dict__.update({ # Runtime counterparts of some stuff in `Compiler.builtins`. '$': lambda f, *xs: f(*xs) , ':': lambda f, *xs: f(*xs) , ',': lambda a, *xs: (a,) + xs , '<': operator.lt , '<=': operator.le , '==': operator.eq , '!=': operator.ne , '>': operator.gt , '>=': operator.ge , 'is': operator.is_ , 'in': lambda a, b: a in b , 'not': operator.not_ , '~': operator.invert , '+': varary(operator.pos, operator.add) , '-': varary(operator.neg, operator.sub) , '*': operator.mul , '**': operator.pow , '/': operator.truediv , '//': operator.floordiv , '%': operator.mod , '!!': operator.getitem , '&': operator.and_ , '^': operator.xor , '|': operator.or_ , '<<': operator.lshift , '>>': operator.rshift # Useful stuff. , 'foldl': functools.reduce , '~:': functools.partial # Not so useful stuff. , 'if': lambda cond, then, else_=None: then if cond else else_ })
import builtins import operator import functools from ..compile import varary builtins.__dict__.update({ # Runtime counterparts of some stuff in `Compiler.builtins`. '$': lambda f, *xs: f(*xs) , ':': lambda f, *xs: f(*xs) , ',': lambda a, *xs: (a,) + xs , '<': operator.lt , '<=': operator.le , '==': operator.eq , '!=': operator.ne , '>': operator.gt , '>=': operator.ge , 'is': operator.is_ , 'in': lambda a, b: a in b , 'not': operator.not_ , '~': operator.invert , '+': varary(operator.pos, operator.add) , '-': varary(operator.neg, operator.sub) , '*': operator.mul , '**': operator.pow , '/': operator.truediv , '//': operator.floordiv , '%': operator.mod , '!!': operator.getitem , '&': operator.and_ , '^': operator.xor , '|': operator.or_ , '<<': operator.lshift , '>>': operator.rshift # Useful stuff. , 'foldl': functools.reduce , '~:': functools.partial })
Add support for line continuation (\ at end of line) for long SQL strings
package com.johnlpage.mongosyphon; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.json.*; public class JobDescription { private Document jobDesc; Logger logger; JobDescription(String configFile) throws FileNotFoundException { logger = LoggerFactory.getLogger(JobDescription.class); String config = ""; try { config = new String(Files.readAllBytes(Paths.get(configFile)), StandardCharsets.UTF_8); } catch (IOException e) { logger.error(e.getMessage()); System.exit(1); } // Handle \ followed by newline as line continuation config = config.replaceAll("\\\\\n", ""); // Better errors from this parser try { @SuppressWarnings("unused") JSONObject obj = new JSONObject(config); } catch (Exception e) { logger.error(e.getMessage()); System.exit(1); } jobDesc = Document.parse(config); } public Map<String, Object> getJobDesc() { return jobDesc; } public Document getSection(String heading) { if (heading == null) { return jobDesc.get("start", Document.class); } return jobDesc.get(heading, Document.class); } }
package com.johnlpage.mongosyphon; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.json.*; public class JobDescription { private Document jobDesc; Logger logger; JobDescription(String configFile) throws FileNotFoundException { logger = LoggerFactory.getLogger(JobDescription.class); String config = ""; try { config = new String(Files.readAllBytes(Paths.get(configFile)), StandardCharsets.UTF_8); } catch (IOException e) { logger.error(e.getMessage()); System.exit(1); } // Better errors from this parser try { @SuppressWarnings("unused") JSONObject obj = new JSONObject(config); } catch (Exception e) { logger.error(e.getMessage()); System.exit(1); } jobDesc = Document.parse(config); } public Map<String, Object> getJobDesc() { return jobDesc; } public Document getSection(String heading) { if (heading == null) { return jobDesc.get("start", Document.class); } return jobDesc.get(heading, Document.class); } }
Initialize district on territory change
import Ember from "ember"; import { translationMacro as t } from "ember-i18n"; export default Ember.Controller.extend({ i18n: Ember.inject.service(), delivery: Ember.computed.alias("deliveryController.model"), user: Ember.computed.alias("delivery.offer.createdBy"), selectedTerritory: null, selectedDistrict: null, initSelectedTerritories: Ember.on("init", function() { if (this.get("selectedDistrict") === null) { this.set( "selectedTerritory", this.get("user.address.district.territory") ); this.set("selectedDistrict", this.get("user.address.district")); } }), territoriesPrompt: t("all"), destrictPrompt: t("delivery.select_district"), territories: Ember.computed(function() { return this.store.peekAll("territory"); }), districtsByTerritory: Ember.computed("selectedTerritory", function() { if (this.selectedTerritory && this.selectedTerritory.id) { return this.selectedTerritory.get("districts").sortBy("name"); } else { return this.store.peekAll("district").sortBy("name"); } }), actions: { onTerritoryChange(value) { this.set("selectedTerritory", value); this.set( "selectedDistrict", this.selectedTerritory.get("districts").sortBy("name").firstObject ); } } });
import Ember from 'ember'; import { translationMacro as t } from "ember-i18n"; export default Ember.Controller.extend({ i18n: Ember.inject.service(), delivery: Ember.computed.alias("deliveryController.model"), user: Ember.computed.alias('delivery.offer.createdBy'), selectedTerritory: null, selectedDistrict: null, initSelectedTerritories: Ember.on('init', function() { if(this.get("selectedDistrict") === null) { this.set("selectedTerritory", this.get("user.address.district.territory")); this.set("selectedDistrict", this.get("user.address.district")); } }), territoriesPrompt: t("all"), destrictPrompt: t("delivery.select_district"), territories: Ember.computed(function(){ return this.store.peekAll('territory'); }), districtsByTerritory: Ember.computed('selectedTerritory', function(){ if(this.selectedTerritory && this.selectedTerritory.id) { return this.selectedTerritory.get('districts').sortBy('name'); } else { return this.store.peekAll('district').sortBy('name'); } }) });
Fix capitalization error in Hungarian translation We do not capitalize the second letter of digraphs in Hungarian
// Hungarian jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december' ], monthsShort: [ 'jan', 'febr', 'márc', 'ápr', 'máj', 'jún', 'júl', 'aug', 'szept', 'okt', 'nov', 'dec' ], weekdaysFull: [ 'vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat' ], weekdaysShort: [ 'V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo' ], today: 'Ma', clear: 'Törlés', firstDay: 1, format: 'yyyy. mmmm dd.', formatSubmit: 'yyyy/mm/dd' }); jQuery.extend( jQuery.fn.pickatime.defaults, { clear: 'Törlés' });
// Hungarian jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december' ], monthsShort: [ 'jan', 'febr', 'márc', 'ápr', 'máj', 'jún', 'júl', 'aug', 'szept', 'okt', 'nov', 'dec' ], weekdaysFull: [ 'vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat' ], weekdaysShort: [ 'V', 'H', 'K', 'SZe', 'CS', 'P', 'SZo' ], today: 'Ma', clear: 'Törlés', firstDay: 1, format: 'yyyy. mmmm dd.', formatSubmit: 'yyyy/mm/dd' }); jQuery.extend( jQuery.fn.pickatime.defaults, { clear: 'Törlés' });
Revert "New default Overpass server" This reverts commit a32767d2d697313c452f6a06aac16360b75e3619.
define([], function () { 'use strict'; return { 'oauthConsumerKey': 'wPfXjdZViPvrRWSlenSWBsAWhYKarmOkOKk5WS4U', 'oauthSecret': 'kaBZXTHZHKSk2jvBUr8vzk7JRI1cryFI08ubv7Du', // 'overpassServer': 'http://overpass-api.de/api/', 'overpassServer': 'http://overpass.osm.rambler.ru/cgi/', // 'overpassServer': 'http://api.openstreetmap.fr/oapi/', 'overpassTimeout': 30 * 1000, // Milliseconds 'defaultAvatar': 'img/default_avatar.png', 'apiPath': 'api/', 'largeScreenMinWidth': 800, 'largeScreenMinHeight': 600, 'shareIframeWidth': 100, 'shareIframeWidthUnit': '%', 'shareIframeHeight': 400, 'shareIframeHeightUnit': 'px', }; });
define([], function () { 'use strict'; return { 'oauthConsumerKey': 'wPfXjdZViPvrRWSlenSWBsAWhYKarmOkOKk5WS4U', 'oauthSecret': 'kaBZXTHZHKSk2jvBUr8vzk7JRI1cryFI08ubv7Du', 'overpassServer': 'http://overpass-api.de/api/', // 'overpassServer': 'http://overpass.osm.rambler.ru/cgi/', // 'overpassServer': 'http://api.openstreetmap.fr/oapi/', 'overpassTimeout': 30 * 1000, // Milliseconds 'defaultAvatar': 'img/default_avatar.png', 'apiPath': 'api/', 'largeScreenMinWidth': 800, 'largeScreenMinHeight': 600, 'shareIframeWidth': 100, 'shareIframeWidthUnit': '%', 'shareIframeHeight': 400, 'shareIframeHeightUnit': 'px', }; });
Add dashboard node for transaction list
from django.conf.urls import patterns, url from django.contrib.admin.views.decorators import staff_member_required from oscar.core.application import Application from oscar.apps.dashboard.nav import register, Node from . import views node = Node('Datacash', 'sagepay-transaction-list') register(node, 100) class SagepayDashboard(Application): name = None list_view = views.Transactions detail_view = views.Transaction def get_urls(self): urlpatterns = patterns('', url(r'^transactions/$', self.list_view.as_view(), name='sagepay-transaction-list'), url(r'^transactions/(?P<pk>\d+)/$', self.detail_view.as_view(), name='sagepay-transaction-detail'), ) return self.post_process_urls(urlpatterns) def get_url_decorator(self, url_name): return staff_member_required application = SagepayDashboard()
from django.conf.urls import patterns, url from django.contrib.admin.views.decorators import staff_member_required from oscar.core.application import Application from . import views class SagepayDashboard(Application): name = None list_view = views.Transactions detail_view = views.Transaction def get_urls(self): urlpatterns = patterns('', url(r'^transactions/$', self.list_view.as_view(), name='sagepay-transaction-list'), url(r'^transactions/(?P<pk>\d+)/$', self.detail_view.as_view(), name='sagepay-transaction-detail'), ) return self.post_process_urls(urlpatterns) def get_url_decorator(self, url_name): return staff_member_required application = SagepayDashboard()
Fix unit tests for Django 1.8
from django.test import TestCase from django.conf import settings class SettingsTestCase(TestCase): def test_modified_settings(self): with self.settings(CHATTERBOT={'name': 'Jim'}): self.assertIn('name', settings.CHATTERBOT) self.assertEqual('Jim', settings.CHATTERBOT['name']) def test_name_setting(self): from django.core.urlresolvers import reverse api_url = reverse('chatterbot:chatterbot') response = self.client.get(api_url) self.assertEqual(response.status_code, 405) self.assertIn('detail', response.content) self.assertIn('name', response.content) self.assertIn('Django ChatterBot Example', response.content)
from django.test import TestCase from django.conf import settings class SettingsTestCase(TestCase): def test_modified_settings(self): with self.settings(CHATTERBOT={'name': 'Jim'}): self.assertIn('name', settings.CHATTERBOT) self.assertEqual('Jim', settings.CHATTERBOT['name']) def test_name_setting(self): from django.core.urlresolvers import reverse api_url = reverse('chatterbot:chatterbot') response = self.client.get(api_url) self.assertEqual(response.status_code, 405) self.assertIn('detail', response.json()) self.assertIn('name', response.json()) self.assertEqual('Django ChatterBot Example', response.json()['name'])
Fix Critical CSS Destination Path
/** * Critical CSS * @description Generate Inline CSS for the Above the fold optimization */ import kc from '../../config.json' import gulp from 'gulp' import critical from 'critical' import yargs from 'yargs' const args = yargs.argv const criticalCss = () => { // Default Build Variable var generateCritical = args.critical || false; if(generateCritical) { kc.cssabove.sources.forEach(function(item) { return critical.generate({ inline: kc.cssabove.inline, base: kc.dist.markup, src: item, dest: item, minify: kc.cssabove.minify, width: kc.cssabove.width, height: kc.cssabove.height }) }) } } gulp.task('optimize:criticalCss', criticalCss) module.exports = criticalCss
/** * Critical CSS * @description Generate Inline CSS for the Above the fold optimization */ import kc from '../../config.json' import gulp from 'gulp' import critical from 'critical' import yargs from 'yargs' const args = yargs.argv const criticalCss = () => { // Default Build Variable var generateCritical = args.critical || false; if(generateCritical) { kc.cssabove.sources.forEach(function(item) { return critical.generate({ inline: kc.cssabove.inline, base: kc.dist.markup, src: item, dest: kc.dist.markup + item, minify: kc.cssabove.minify, width: kc.cssabove.width, height: kc.cssabove.height }) }) } } gulp.task('optimize:criticalCss', criticalCss) module.exports = criticalCss
Add Rotate with view option Use a checkbox to demonstrate the rotateWithView option
import Map from '../src/ol/Map.js'; import View from '../src/ol/View.js'; import {defaults as defaultControls, OverviewMap} from '../src/ol/control.js'; import {defaults as defaultInteractions, DragRotateAndZoom} from '../src/ol/interaction.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; const rotateWithView = document.getElementById('rotateWithView'); const overviewMapControl = new OverviewMap({ // see in overviewmap-custom.html to see the custom CSS used className: 'ol-overviewmap ol-custom-overviewmap', layers: [ new TileLayer({ source: new OSM({ 'url': 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' + '?apikey=0e6fc415256d4fbb9b5166a718591d71' }) }) ], collapseLabel: '\u00BB', label: '\u00AB', collapsed: false }); rotateWithView.addEventListener('change', function() { overviewMapControl.setRotateWithView(this.checked); }); const map = new Map({ controls: defaultControls().extend([ overviewMapControl ]), interactions: defaultInteractions().extend([ new DragRotateAndZoom() ]), layers: [ new TileLayer({ source: new OSM() }) ], target: 'map', view: new View({ center: [500000, 6000000], zoom: 7 }) });
import Map from '../src/ol/Map.js'; import View from '../src/ol/View.js'; import {defaults as defaultControls, OverviewMap} from '../src/ol/control.js'; import {defaults as defaultInteractions, DragRotateAndZoom} from '../src/ol/interaction.js'; import TileLayer from '../src/ol/layer/Tile.js'; import OSM from '../src/ol/source/OSM.js'; const overviewMapControl = new OverviewMap({ // see in overviewmap-custom.html to see the custom CSS used className: 'ol-overviewmap ol-custom-overviewmap', layers: [ new TileLayer({ source: new OSM({ 'url': 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' + '?apikey=0e6fc415256d4fbb9b5166a718591d71' }) }) ], collapseLabel: '\u00BB', label: '\u00AB', collapsed: false }); const map = new Map({ controls: defaultControls().extend([ overviewMapControl ]), interactions: defaultInteractions().extend([ new DragRotateAndZoom() ]), layers: [ new TileLayer({ source: new OSM() }) ], target: 'map', view: new View({ center: [500000, 6000000], zoom: 7 }) });
Update indentation as per style guide
import unittest2 from mlabns.util import distance class DistanceTestCase(unittest2.TestCase): def testValidSmallDistance(self): dist = distance.distance(0, 0, 10, 10) self.assertEqual(1568.5205567985761, dist) def testValidLargeDistance(self): dist = distance.distance(20, 20, 100, 100) self.assertEqual(8009.5721050828461, dist) def testInvalidInputs(self): import math from numbers import Number dist = 0 try: dist = distance.distance(-700,1000,999,-5454) except Exception: self.fail("distance threw an exception on invalid entry") self.assertTrue(isinstance(dist, Number)) self.assertFalse(math.isnan(dist)) if __name__ == '__main__': unittest2.main()
import unittest2 from mlabns.util import distance class DistanceTestCase(unittest2.TestCase): def testValidSmallDistance(self): dist = distance.distance(0, 0, 10, 10) self.assertEqual(1568.5205567985761, dist) def testValidLargeDistance(self): dist = distance.distance(20, 20, 100, 100) self.assertEqual(8009.5721050828461, dist) def testInvalidInputs(self): import math from numbers import Number dist = 0 try: dist = distance.distance(-700,1000,999,-5454) except Exception: self.fail("distance threw an exception on invalid entry") self.assertTrue(isinstance(dist, Number)) self.assertFalse(math.isnan(dist)) if __name__ == '__main__': unittest2.main()
Add _ as valid parameter symbol
package me.konsolas.conditionalcommands.placeholders; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class AbstractParameteredPlaceholder implements Placeholder { private final Pattern pattern; AbstractParameteredPlaceholder(String base) { this.pattern = Pattern.compile("-" + base + ":([A-Za-z0-9%._]*)-"); } @Override public boolean shouldApply(String test) { return pattern.matcher(test).find(); } protected abstract String getSub(Player player, String param); @Override public String doSubstitution(String input, Player player) { Matcher matcher = pattern.matcher(input); while (matcher.find()) { input = input.replaceAll(Pattern.quote(matcher.group()), getSub(player, matcher.group(1))); } return input; } @Override public void init(Plugin plugin) { } }
package me.konsolas.conditionalcommands.placeholders; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class AbstractParameteredPlaceholder implements Placeholder { private final Pattern pattern; AbstractParameteredPlaceholder(String base) { this.pattern = Pattern.compile("-" + base + ":([A-Za-z0-9%.]*)-"); } @Override public boolean shouldApply(String test) { return pattern.matcher(test).find(); } protected abstract String getSub(Player player, String param); @Override public String doSubstitution(String input, Player player) { Matcher matcher = pattern.matcher(input); while (matcher.find()) { input = input.replaceAll(Pattern.quote(matcher.group()), getSub(player, matcher.group(1))); } return input; } @Override public void init(Plugin plugin) { } }
Fix duplicate unique index issue
<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSessionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create(config('session.table'), function (Blueprint $table) { // Columns $table->string('id'); $table->integer('user_id')->unsigned()->nullable(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->text('payload'); $table->integer('last_activity'); // Indexes $table->unique('id'); $table->foreign('user_id')->references('id')->on(config('rinvex.fort.tables.users'))->onDelete('cascade')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(config('session.table')); } }
<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSessionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create(config('session.table'), function (Blueprint $table) { // Columns $table->string('id')->unique(); $table->integer('user_id')->unsigned()->nullable(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->text('payload'); $table->integer('last_activity'); // Indexes $table->unique('id'); $table->foreign('user_id')->references('id')->on(config('rinvex.fort.tables.users'))->onDelete('cascade')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(config('session.table')); } }
Support only python versions 3.6+ explicitly …which has been the assumption for a while as 3.6 features are already in use and base docker images use 3.6.
#!/usr/bin/env python if __name__ == '__main__': import os import sys if sys.version_info[0:2] < (3, 6): raise SystemExit('Python 3.6+ is required') root_path = os.path.abspath(os.path.dirname(__file__)) try: import mtp_common # NB: this version does not need to be updated unless mtp_common changes significantly if mtp_common.VERSION < (10,): raise ImportError except ImportError: try: import pkg_resources except ImportError: raise SystemExit('setuptools and pip are required') try: pip = pkg_resources.load_entry_point('pip', 'console_scripts', 'pip') except pkg_resources.ResolutionError: raise SystemExit('setuptools and pip are required') print('Pre-installing MTP-common and base requirements') pip(['install', '--requirement', f'{root_path}/requirements/base.txt']) from mtp_common.build_tasks.executor import Executor import mtp_transaction_uploader.build_tasks # noqa exit(Executor(root_path=root_path).run())
#!/usr/bin/env python if __name__ == '__main__': import os import sys if sys.version_info[0:2] < (3, 4): raise SystemExit('python 3.4+ is required') root_path = os.path.abspath(os.path.dirname(__file__)) try: import mtp_common # NB: this version does not need to be updated unless mtp_common changes significantly if mtp_common.VERSION < (10,): raise ImportError except ImportError: try: import pkg_resources except ImportError: raise SystemExit('setuptools and pip are required') try: pip = pkg_resources.load_entry_point('pip', 'console_scripts', 'pip') except pkg_resources.ResolutionError: raise SystemExit('setuptools and pip are required') print('Pre-installing MTP-common and base requirements') pip(['install', '--requirement', f'{root_path}/requirements/base.txt']) from mtp_common.build_tasks.executor import Executor import mtp_transaction_uploader.build_tasks # noqa exit(Executor(root_path=root_path).run())
Add ERROR: keyword in error message return
from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message": "ERROR: " + str(err)}) def request_test(function): result = function return result
from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message":str(err)}) def request_test(function): result = function return result
Clean up test for BinaryFILE writer
package com.paritytrading.nassau.binaryfile; import static com.paritytrading.nassau.Strings.*; import static java.util.Arrays.*; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import org.junit.Test; public class BinaryFILEWriterTest { @Test public void write() throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); BinaryFILEWriter writer = new BinaryFILEWriter(stream); List<String> messages = asList("foo", "bar", "baz", "quux", ""); for (String message : messages) writer.write(wrap(message)); byte[] writtenBytes = stream.toByteArray(); byte[] expectedBytes = Files.readAllBytes(Paths.get(getClass().getResource("/binaryfile.dat").toURI())); assertArrayEquals(expectedBytes, writtenBytes); } }
package com.paritytrading.nassau.binaryfile; import static com.paritytrading.nassau.Strings.*; import static java.util.Arrays.*; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.List; import org.junit.Test; public class BinaryFILEWriterTest { @Test public void write() throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); BinaryFILEWriter writer = new BinaryFILEWriter(stream); List<String> messages = asList("foo", "bar", "baz", "quux", ""); for (String message : messages) writer.write(wrap(message)); byte[] writtenBytes = stream.toByteArray(); byte[] expectedBytes = toByteArray(getClass().getResourceAsStream("/binaryfile.dat")); assertArrayEquals(expectedBytes, writtenBytes); } private byte[] toByteArray(InputStream input) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); int b; while ((b = input.read()) != -1) output.write(b); return output.toByteArray(); } }
Change placeholder text in sign in form
<form name="loginform" action="<?php echo wp_login_url($_SERVER['REQUEST_URI']);?>" method="post"> <input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" /> <input type="hidden" name="user-cookie" value="1" /> <p> <input type="text" name="log" placeholder="CID eller e-postadress" <?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?> /> <input type="password" name="pwd" placeholder="Lösenord" /> </p> <p> <label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" /> Håll mig inloggad</label> <input type="submit" name="submit" class="small" value="Logga in" /> </p> </form>
<form name="loginform" action="<?php echo wp_login_url($_SERVER['REQUEST_URI']);?>" method="post"> <input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" /> <input type="hidden" name="user-cookie" value="1" /> <p> <input type="text" name="log" placeholder="E-postadress eller nick" <?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?> /> <input type="password" name="pwd" placeholder="Lösenord" /> </p> <p> <label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" /> Håll mig inloggad</label> <input type="submit" name="submit" class="small" value="Logga in" /> </p> </form>
Add the author, and build HTML with jQuery
$(function() { $('.band_messages, .fan_messages').each(function() { var $this = $(this) var url = $this.attr('data-update-uri') $.getJSON(url+'?callback=?', function(json) { $.each(json.messages, function() { $('<li>', { style: "display: none", class: this.network }).append( $('<span>', { class: 'author', text: this.author }) ).append( $('<span>', { class: 'message', text: this.message }) ).append( $('<a>', { href: this.link, target: '_blank', text: 'view' }) ).appendTo($this); }); $this.find('li:lt(3)').show() }); setInterval(function() { var html = $this.find('li:first').html(); var klass = $this.find('li:first').attr('class') $this.find('li:first').fadeOut('slow', function() { $(this).remove() $this.find('li:nth(2)').fadeIn() }) $this.append($('<li>', {class: klass}).html(html).hide()); }, 4000) }) })
$(function() { $('.band_messages, .fan_messages').each(function() { var $this = $(this) var url = $this.attr('data-update-uri') $.getJSON(url+'?callback=?', function(json) { $.each(json.messages, function() { $this.append('<li style="display: none" class="'+ this.network + '">' + this.message +' <a href="'+ this.link +'" target="_blank">view</a></li>'); }); $this.find('li:lt(3)').show() }); setInterval(function() { var html = $this.find('li:first').html(); $this.find('li:first').fadeOut('slow', function() { $(this).remove() $this.find('li:nth(2)').fadeIn() }) $this.append('<li style="display:none">' + html + '</li>'); }, 4000) }) })
Add example for aside-only <Text>
import React from 'react'; import Text from 'src/Text'; import DebugBox from '../DebugBox'; function BasicTextExample() { return ( <div> <DebugBox> <Text basic="Basic Text" /> </DebugBox> <DebugBox> <Text align="center" basic="Basic Text" aside="I am center-aligned" /> </DebugBox> <DebugBox> <Text align="right" basic="A Long Long Long Basic Text" aside="I am right-aligned" tag="Tag" /> </DebugBox> <DebugBox> <Text aside="Aside Only Text" /> </DebugBox> </div> ); } export default BasicTextExample;
import React from 'react'; import Text from 'src/Text'; import DebugBox from '../DebugBox'; function BasicTextExample() { return ( <div> <DebugBox> <Text basic="Basic Text" /> </DebugBox> <DebugBox> <Text align="center" basic="Basic Text" aside="I am center-aligned" /> </DebugBox> <DebugBox> <Text align="right" basic="A Long Long Long Basic Text" aside="I am right-aligned" tag="Tag" /> </DebugBox> </div> ); } export default BasicTextExample;
Add aync notification processing support
from django.conf import settings from django.http import HttpResponse from .models import Notification def create_notification(request): topic = request.GET.get('topic', None) resource_id = request.GET.get('id', None) if topic is None: return HttpResponse( '<h1>400 Bad Request.</h1>Missing parameter topic', status=400 ) if resource_id is None: return HttpResponse( '<h1>400 Bad Request.</h1>Missing parameter id', status=400 ) if topic == 'merchant_order': topic = Notification.TOPIC_ORDER elif topic == 'payment': topic = Notification.TOPIC_PAYMENT else: return HttpResponse('invalid topic', status=400) notification, created = Notification.objects.get_or_create( topic=topic, resource_id=resource_id, ) if not created: notification.processed = False notification.save() if not settings.MERCADOPAGO_ASYNC: notification.process() # TODO: Else add to some queue? return HttpResponse("<h1>200 OK</h1>", status=201)
from django.http import HttpResponse from .models import Notification def create_notification(request): topic = request.GET.get('topic', None) resource_id = request.GET.get('id', None) if topic is None: return HttpResponse( '<h1>400 Bad Request.</h1>Missing parameter topic', status=400 ) if resource_id is None: return HttpResponse( '<h1>400 Bad Request.</h1>Missing parameter id', status=400 ) if topic == 'merchant_order': topic = Notification.TOPIC_ORDER elif topic == 'payment': topic = Notification.TOPIC_PAYMENT else: return HttpResponse('invalid topic', status=400) notification, created = Notification.objects.get_or_create( topic=topic, resource_id=resource_id, ) if not created: notification.processed = False notification.save() return HttpResponse("<h1>200 OK</h1>", status=201)
Update noscript method to output rather than return.
<?php /** * Trait Google\Site_Kit\Core\Util\Requires_Javascript_Trait * * @package Google\Site_Kit\Core\Util * @copyright 2020 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ namespace Google\Site_Kit\Core\Util; /** * Trait to display no javascript fallback message. * * @since n.e.x.t * @access private * @ignore */ trait Requires_Javascript_Trait { /** * Outputs a fallback message when Javascript is disabled. * * @since n.e.x.t */ protected function render_noscript_html() { ?> <noscript> <div class="googlesitekit-noscript notice notice-warning"> <div class="mdc-layout-grid"> <div class="mdc-layout-grid__inner"> <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-12"> <p class="googlesitekit-noscript__text"> <?php esc_html_e( 'The Site Kit by Google plugin requires JavaScript to be enabled in your browser.', 'google-site-kit' ) ?> </p> </div> </div> </div> </div> </noscript> <?php } }
<?php /** * Trait Google\Site_Kit\Core\Util\Requires_Javascript_Trait * * @package Google\Site_Kit\Core\Util * @copyright 2020 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ namespace Google\Site_Kit\Core\Util; /** * Trait to display no javascript fallback message. * * @since n.e.x.t * @access private * @ignore */ trait Requires_Javascript_Trait { /** * Display fallback message when Javascript is disabled * * @since n.e.x.t * * @return string noscript HTML tag, */ protected function get_noscript_html() { ob_start(); ?> <noscript> <div class="googlesitekit-noscript notice notice-warning"> <div class="mdc-layout-grid"> <div class="mdc-layout-grid__inner"> <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-12"> <p class="googlesitekit-noscript__text"> <?php esc_html_e( 'The Site Kit by Google plugin requires JavaScript to be enabled in your browser.', 'google-site-kit' ) ?> </p> </div> </div> </div> </div> </noscript> <?php return ob_get_clean(); } }
Fix for non-remark parsers or compilers
'use strict'; var commentMarker = require('mdast-comment-marker'); module.exports = commentconfig; /* Modify `processor` to read configuration from comments. */ function commentconfig() { var proto = this.Parser && this.Parser.prototype; var Compiler = this.Compiler; var block = proto && proto.blockTokenizers; var inline = proto && proto.inlineTokenizers; var compiler = Compiler && Compiler.prototype && Compiler.prototype.visitors; if (block && block.html) { block.html = factory(block.html); } if (inline && inline.html) { inline.html = factory(inline.html); } if (compiler && compiler.html) { compiler.html = factory(compiler.html); } } /* Wrapper factory. */ function factory(original) { replacement.locator = original.locator; return replacement; /* Replacer for tokeniser or visitor. */ function replacement(node) { var self = this; var result = original.apply(self, arguments); var marker = commentMarker(result && result.type ? result : node); if (marker && marker.name === 'remark') { try { self.setOptions(marker.parameters); } catch (err) { self.file.fail(err.message, marker.node); } } return result; } }
'use strict'; var commentMarker = require('mdast-comment-marker'); module.exports = commentconfig; /* Modify `processor` to read configuration from comments. */ function commentconfig() { var Parser = this.Parser; var Compiler = this.Compiler; var block = Parser && Parser.prototype.blockTokenizers; var inline = Parser && Parser.prototype.inlineTokenizers; var compiler = Compiler && Compiler.prototype.visitors; if (block && block.html) { block.html = factory(block.html); } if (inline && inline.html) { inline.html = factory(inline.html); } if (compiler && compiler.html) { compiler.html = factory(compiler.html); } } /* Wrapper factory. */ function factory(original) { replacement.locator = original.locator; return replacement; /* Replacer for tokeniser or visitor. */ function replacement(node) { var self = this; var result = original.apply(self, arguments); var marker = commentMarker(result && result.type ? result : node); if (marker && marker.name === 'remark') { try { self.setOptions(marker.parameters); } catch (err) { self.file.fail(err.message, marker.node); } } return result; } }
Fix Wholeness of the World to be max 1 per round
const DrawCard = require('../../drawcard.js'); class WholenessOfTheWorld extends DrawCard { setupCardAbilities(ability) { this.wouldInterrupt({ title: 'Keep a claimed ring', when: { onReturnRing: (event, context) => event.ring.claimedBy === context.player.name }, cannotBeMirrored: true, effect: 'prevent {1} from returning to the unclaimed pool', effectArgs: context => context.event.ring, handler: context => context.cancel(), max: ability.limit.perRound(1) }); } } WholenessOfTheWorld.id = 'wholeness-of-the-world'; module.exports = WholenessOfTheWorld;
const DrawCard = require('../../drawcard.js'); class WholenessOfTheWorld extends DrawCard { setupCardAbilities() { this.wouldInterrupt({ title: 'Keep a claimed ring', when: { onReturnRing: (event, context) => event.ring.claimedBy === context.player.name }, cannotBeMirrored: true, effect: 'prevent {1} from returning to the unclaimed pool', effectArgs: context => context.event.ring, handler: context => context.cancel() }); } } WholenessOfTheWorld.id = 'wholeness-of-the-world'; module.exports = WholenessOfTheWorld;
Allow using "test" as and environment name
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var _ = require('underscore'); // sanity check arguments var ENV = process.argv[2]; if (ENV != 'development' && ENV != 'production' && ENV != 'test') { console.error("\n./app [environment]"); console.error("environments: [development, test, production]"); process.exit(1); } // set Node.js app settings and boot global.settings = require(__dirname + '/config/settings'); var env = require(__dirname + '/config/environments/' + ENV); _.extend(global.settings, env); // kick off controller var app = require(global.settings.app_root + '/app/controllers/app'); app.listen(global.settings.node_port, global.settings.node_host, function() { console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port); });
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var _ = require('underscore'); // sanity check arguments var ENV = process.argv[2]; if (ENV != 'development' && ENV != 'production') { console.error("\n./app [environment]"); console.error("environments: [development, test, production]"); process.exit(1); } // set Node.js app settings and boot global.settings = require(__dirname + '/config/settings'); var env = require(__dirname + '/config/environments/' + ENV); _.extend(global.settings, env); // kick off controller var app = require(global.settings.app_root + '/app/controllers/app'); app.listen(global.settings.node_port, global.settings.node_host, function() { console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port); });
Allow Timber output from tests
/* * Copyright 2020 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.android.gnd; import android.app.Application; import android.content.Context; import androidx.test.runner.AndroidJUnitRunner; import dagger.hilt.android.testing.HiltTestApplication; import timber.log.Timber; import timber.log.Timber.DebugTree; public class CustomTestRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Timber.plant(new DebugTree()); return super.newApplication(cl, HiltTestApplication.class.getName(), context); } }
/* * Copyright 2020 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.android.gnd; import android.app.Application; import android.content.Context; import androidx.test.runner.AndroidJUnitRunner; import dagger.hilt.android.testing.HiltTestApplication; public class CustomTestRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws ClassNotFoundException, IllegalAccessException, InstantiationException { return super.newApplication(cl, HiltTestApplication.class.getName(), context); } }
Move this out of RobotInit so we can use the robot for other things. Swap to "autonomous" mode to trigger the ImageProcess event. In the near future this should either be moved to a self-instantiated default-command from the related subsystem, or it should be triggered with a joystick button or other event.
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.templates.commands.*; /** * Main Robot Class. */ public class RobotMain extends IterativeRobot { /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { // Initialize all subsystems CommandBase.init(); } public void autonomousInit() { ImageProcess ip = new ImageProcess(); ip.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { } /** * This function is called periodically during operator control. */ public void teleopPeriodic() { Scheduler.getInstance().run(); } /** * This function is called periodically during test mode. */ public void testPeriodic() { LiveWindow.run(); } public void disabledPeriodic() { } public void disabledInit() { System.out.println("Robot Main disabledInit(): Called"); } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.templates.commands.*; /** * Main Robot Class. */ public class RobotMain extends IterativeRobot { private ImageProcess ip; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { //ip = new ImageProcess(); // Initialize all subsystems CommandBase.init(); } public void autonomousInit() { ip.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { } /** * This function is called periodically during operator control. */ public void teleopPeriodic() { Scheduler.getInstance().run(); } /** * This function is called periodically during test mode. */ public void testPeriodic() { LiveWindow.run(); } public void disabledPeriodic() { } public void disabledInit() { System.out.println("Robot Main disabledInit(): Called"); } }
Remove empty lines that make it harder to read
package org.oskari.map.userlayer.service; import fi.nls.oskari.domain.map.userlayer.UserLayer; import fi.nls.oskari.domain.map.userlayer.UserLayerData; import fi.nls.oskari.domain.map.userlayer.UserLayerStyle; import fi.nls.oskari.service.OskariComponent; import fi.nls.oskari.service.ServiceException; import java.util.List; public abstract class UserLayerDbService extends OskariComponent { //UserLayer related public abstract int insertUserLayer(final UserLayer userlayer, final UserLayerStyle userLayerStyle, final List<UserLayerData> userLayerDataList) throws ServiceException; public abstract int updateUserLayerCols(final UserLayer userlayer); public abstract UserLayer getUserLayerById(long id); public abstract List<UserLayer> getUserLayerByUuid(String uuid); public abstract void deleteUserLayerById(final long id) throws ServiceException; public abstract void deleteUserLayer(final UserLayer userlayer) throws ServiceException; public abstract void deleteUserLayersByUuid(String uuid) throws ServiceException; public abstract int updatePublisherName(final long id, final String uuid, final String name); public abstract String getUserLayerExtent (final long id); //UserLayerStyle related public abstract int updateUserLayerStyleCols(final UserLayerStyle userLayerStyle); public abstract UserLayerStyle getUserLayerStyleById(final long id); //UserLayerData related public abstract int updateUserLayerDataCols(final UserLayerData userlayerdata); }
package org.oskari.map.userlayer.service; import fi.nls.oskari.domain.map.userlayer.UserLayer; import fi.nls.oskari.domain.map.userlayer.UserLayerData; import fi.nls.oskari.domain.map.userlayer.UserLayerStyle; import fi.nls.oskari.service.OskariComponent; import fi.nls.oskari.service.ServiceException; import java.util.List; public abstract class UserLayerDbService extends OskariComponent { //UserLayer related public abstract int insertUserLayer(final UserLayer userlayer, final UserLayerStyle userLayerStyle, final List<UserLayerData> userLayerDataList) throws ServiceException; public abstract int updateUserLayerCols(final UserLayer userlayer); public abstract UserLayer getUserLayerById(long id); public abstract List<UserLayer> getUserLayerByUuid(String uuid); public abstract void deleteUserLayerById(final long id) throws ServiceException; public abstract void deleteUserLayer(final UserLayer userlayer) throws ServiceException; public abstract void deleteUserLayersByUuid(String uuid) throws ServiceException; public abstract int updatePublisherName(final long id, final String uuid, final String name); public abstract String getUserLayerExtent (final long id); //UserLayerStyle related public abstract int updateUserLayerStyleCols(final UserLayerStyle userLayerStyle); public abstract UserLayerStyle getUserLayerStyleById(final long id); //UserLayerData related public abstract int updateUserLayerDataCols(final UserLayerData userlayerdata); }
Enhance readability of test output
"""Use Mayapy for testing Usage: $ mayapy run_maya_tests.py """ import sys import nose import logging import warnings from nose_exclude import NoseExclude warnings.filterwarnings("ignore", category=DeprecationWarning) if __name__ == "__main__": from maya import standalone standalone.initialize() log = logging.getLogger() # Discard default Maya logging handler log.handlers[:] = [] argv = sys.argv[:] argv.extend([ # Sometimes, files from Windows accessed # from Linux cause the executable flag to be # set, and Nose has an aversion to these # per default. "--exe", "--verbose", "--with-doctest", "--with-coverage", "--cover-html", "--cover-tests", "--cover-erase", "--exclude-dir=mindbender/nuke", "--exclude-dir=mindbender/houdini", "--exclude-dir=mindbender/schema", "--exclude-dir=mindbender/plugins", # We can expect any vendors to # be well tested beforehand. "--exclude-dir=mindbender/vendor", ]) nose.main(argv=argv, addplugins=[NoseExclude()])
"""Use Mayapy for testing Usage: $ mayapy run_maya_tests.py """ import sys import nose import warnings from nose_exclude import NoseExclude warnings.filterwarnings("ignore", category=DeprecationWarning) if __name__ == "__main__": from maya import standalone standalone.initialize() argv = sys.argv[:] argv.extend([ # Sometimes, files from Windows accessed # from Linux cause the executable flag to be # set, and Nose has an aversion to these # per default. "--exe", "--verbose", "--with-doctest", "--with-coverage", "--cover-html", "--cover-tests", "--cover-erase", "--exclude-dir=mindbender/nuke", "--exclude-dir=mindbender/houdini", "--exclude-dir=mindbender/schema", "--exclude-dir=mindbender/plugins", # We can expect any vendors to # be well tested beforehand. "--exclude-dir=mindbender/vendor", ]) nose.main(argv=argv, addplugins=[NoseExclude()])
Sort the context list in alphabetical order
# Copyright (C) 2010 Jonathan Harker <jon@jon.geek.nz> # # This file is part of Libravatar # # Libravatar is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Libravatar 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Libravatar. If not, see <http://www.gnu.org/licenses/>. import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} context['analytics_propertyid'] = settings.ANALYTICS_PROPERTYID context['avatar_url'] = settings.AVATAR_URL context['disable_signup'] = settings.DISABLE_SIGNUP context['libravatar_version'] = settings.LIBRAVATAR_VERSION context['media_url'] = settings.MEDIA_URL context['secure_avatar_url'] = settings.SECURE_AVATAR_URL context['site_name'] = settings.SITE_NAME context['site_url'] = settings.SITE_URL context['support_email'] = settings.SUPPORT_EMAIL return context
# Copyright (C) 2010 Jonathan Harker <jon@jon.geek.nz> # # This file is part of Libravatar # # Libravatar is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Libravatar 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Libravatar. If not, see <http://www.gnu.org/licenses/>. import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} context["site_name"] = settings.SITE_NAME context["libravatar_version"] = settings.LIBRAVATAR_VERSION context["avatar_url"] = settings.AVATAR_URL context["secure_avatar_url"] = settings.SECURE_AVATAR_URL context["media_url"] = settings.MEDIA_URL context["site_url"] = settings.SITE_URL context["disable_signup"] = settings.DISABLE_SIGNUP context["analytics_propertyid"] = settings.ANALYTICS_PROPERTYID context['support_email'] = settings.SUPPORT_EMAIL return context
Remove set-comprehensions so that tests will pass on 2.6
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_generalwords ---------------------------------- All the tests for the generalword module. Simple module, simple tests. """ import unittest from generalwords import get_word class TestGeneralwords(unittest.TestCase): def setUp(self): pass def test_get_word(self): self.assertIsNotNone(get_word) def test_get_word_is_somewhat_random(self): sample_size = 100 words = set(get_word() for i in range(sample_size)) self.assertAlmostEqual(len(words), sample_size, delta=int((sample_size * 0.1))) def tearDown(self): pass if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_generalwords ---------------------------------- All the tests for the generalword module. Simple module, simple tests. """ import unittest from generalwords import get_word class TestGeneralwords(unittest.TestCase): def setUp(self): pass def test_get_word(self): self.assertIsNotNone(get_word) def test_get_word_is_somewhat_random(self): sample_size = 100 words = {get_word() for i in range(sample_size)} self.assertAlmostEqual(len(words), sample_size, delta=int((sample_size * 0.1))) def tearDown(self): pass if __name__ == '__main__': unittest.main()
Add command action for player's commands and refactor
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const store = new Vuex.Store({ state: { messages: [], playerName: "", inputText: "" }, getters: { playerName: (state) => state.playerName, messages: (state) => state.messages, inputText: (state) => state.inputText }, actions: { setPlayerName({ commit }, name) { commit("SET_PLAYER_NAME", name); }, addMessage({ commit }, data) { commit("ADD_MESSAGE", data); }, enterCommand({ commit, state }, text) { commit("ADD_MESSAGE", { entity: state.playerName, message: text }); commit("SET_INPUT_TEXT", ""); console.log(`Parsing ${text}`); }, setInputText({ commit }, text) { commit("SET_INPUT_TEXT", text); } }, mutations: { SET_PLAYER_NAME(state, name) { state.playerName = name; }, ADD_MESSAGE(state, data) { state.messages.push({ entity: data.entity, message: data.message }); }, SET_INPUT_TEXT(state, text) { state.inputText = text; } } }); export default store;
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const store = new Vuex.Store({ state: { messages: [], playerName: "", inputText: "" }, getters: { playerName: (state) => state.playerName, messages: (state) => state.messages, inputText: (state) => state.inputText }, actions: { setPlayerName({ commit }, name) { commit("SET_PLAYER_NAME", name); }, addMessage({ commit }, data) { commit("ADD_MESSAGE", data); // Have to wait for DOM to be updated before scrolling Vue.nextTick(() => { document.getElementById("output").lastChild.scrollIntoView(); }); }, setInputText({ commit }, text) { commit("SET_INPUT_TEXT", text); } }, mutations: { SET_PLAYER_NAME(state, name) { state.playerName = name; }, ADD_MESSAGE(state, data) { state.messages.push({ entity: data.entity, message: data.message }); }, SET_INPUT_TEXT(state, text) { state.inputText = text; } } }); export default store;
Fix resource loading to work with files bigger than a kilobyte Signed-off-by: Ben Grohbiel <f31bec9830c462ca5208f6f388c04b025df0947c@pivotal.io>
package io.pivotal.labs.cfenv; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class ResourceUtils { public static String loadResource(String name) throws IOException { try (InputStream stream = openResource(name)) { StringBuilder buffer = new StringBuilder(); InputStreamReader reader = new InputStreamReader(stream); while (true) { int character = reader.read(); if (character == -1) break; buffer.append((char) character); } return buffer.toString(); } } public static InputStream openResource(String name) throws FileNotFoundException { InputStream stream = ResourceUtils.class.getResourceAsStream(name); if (stream == null) throw new FileNotFoundException(name); return stream; } }
package io.pivotal.labs.cfenv; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class ResourceUtils { public static String loadResource(String name) throws IOException { try (InputStream stream = openResource(name)) { Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name()).useDelimiter("\\z"); String content = scanner.next(); IOException exception = scanner.ioException(); if (exception != null) throw exception; return content; } } public static InputStream openResource(String name) throws FileNotFoundException { InputStream stream = ResourceUtils.class.getResourceAsStream(name); if (stream == null) throw new FileNotFoundException(name); return stream; } }
Allow enum to be created more easily
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, *elements): self.elements = tuple(elements) def __getattr__(self, name): if name not in self.elements: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum('LINK', 'IMAGE', 'TOKEN') INLINE_STYLES = Enum('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE')
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, tuple_list): self.tuple_list = tuple_list def __getattr__(self, name): if name not in self.tuple_list: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN')) INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE'))
Remove extraneous prop declaration for availablePermissions (This is loaded using stripes-connect, not passed in by the parent component.)
// We have to remove node_modules/react to avoid having multiple copies loaded. // eslint-disable-next-line import/no-unresolved import React, { PropTypes } from 'react'; import { connect } from '@folio/stripes-connect'; // eslint-disable-line import RenderPermissions from '../lib/RenderPermissions'; class PermissionSet extends React.Component { static propTypes = { data: PropTypes.shape({ availablePermissions: PropTypes.arrayOf(PropTypes.object), }).isRequired, addPermission: PropTypes.func.isRequired, removePermission: PropTypes.func.isRequired, selectedSet: PropTypes.object.isRequired, }; static manifest = Object.freeze({ availablePermissions: { type: 'okapi', records: 'permissions', path: 'perms/permissions?length=1000&query=(mutable=false)', }, }); render() { return (<RenderPermissions {...this.props} heading="Contains" addPermission={this.props.addPermission} removePermission={this.props.removePermission} availablePermissions={this.props.data.availablePermissions} listedPermissions={this.props.selectedSet.subPermissions} />); } } export default connect(PermissionSet, '@folio/users');
// We have to remove node_modules/react to avoid having multiple copies loaded. // eslint-disable-next-line import/no-unresolved import React, { PropTypes } from 'react'; import { connect } from '@folio/stripes-connect'; // eslint-disable-line import RenderPermissions from '../lib/RenderPermissions'; class PermissionSet extends React.Component { static propTypes = { data: PropTypes.shape({ availablePermissions: PropTypes.arrayOf(PropTypes.object), }).isRequired, addPermission: PropTypes.func.isRequired, removePermission: PropTypes.func.isRequired, availablePermissions: PropTypes.func.isRequired, selectedSet: PropTypes.object.isRequired, }; static manifest = Object.freeze({ availablePermissions: { type: 'okapi', records: 'permissions', path: 'perms/permissions?length=1000&query=(mutable=false)', }, }); render() { return (<RenderPermissions {...this.props} heading="Contains" addPermission={this.props.addPermission} removePermission={this.props.removePermission} availablePermissions={this.props.data.availablePermissions} listedPermissions={this.props.selectedSet.subPermissions} />); } } export default connect(PermissionSet, '@folio/users');
Upgrade get params of mobile pagination
export class Pagination { events () { $('[data-role="mobile-pagination"]').on('change', $.proxy(this.goToPage, this)) } goToPage (event) { let $current = $(event.currentTarget) let nextPageId = $current.val() this.changePageInUrlAndReload(nextPageId) } changePageInUrlAndReload (value) { const key = 'page' let parameters = document.location.search.substr(1).split('&') let i = parameters.length value = encodeURI(value) while (i--) { let parameter = parameters[i].split('=') if (parameter[0] === key) { parameter[1] = value parameters[i] = parameter.join('=') break } } if (i < 0) { parameters[parameters.length] = [key, value].join('=') } document.location.search = parameters.join('&') } }
export class Pagination { events () { $('[data-role="mobile-pagination"]').on('change', $.proxy(this.goToPage, this)) } goToPage (event) { let $current = $(event.currentTarget) let nextPageId = $current.val() let url = window.location.href.split('?')[0] let parameters = this.getParameters() parameters["page"] = nextPageId window.location.replace(url + '?' + decodeURIComponent($.param(parameters))) } getParameters () { if (typeof window.location.href.split('?')[1] === 'undefined') { return {} } let parameters = {} let queryString = window.location.href.split('?')[1] let rawParameters = queryString.split('&') $.each(rawParameters, (index, rawParameter) => { let parameterPair = rawParameter.split('=') parameters[parameterPair[0]] = parameterPair[1] }) return parameters } }
Clear clipboard before writing... just in case
const { clipboard, ipcRenderer } = require('electron'); const beautify_js = require('js-beautify'); const lang = require('language-classifier'); ipcRenderer.on('shortcut-hit', (event, arg) => { console.log(arg); }) function formatClipboard() { let clipboard_contents = clipboard.readText(), language = lang(clipboard_contents), output = ''; if (clipboard_contents.length === 0) return; switch(language) { case 'css': output = beautify_js.css(clipboard_contents); break; case 'html': output = beautify_js.html(clipboard_contents); break; case 'javascript': default: output = beautify_js.js_beautify(clipboard_contents); break; } clipboard.clear(); clipboard.writeText(output); }
const { clipboard, ipcRenderer } = require('electron'); const beautify_js = require('js-beautify'); const lang = require('language-classifier'); ipcRenderer.on('shortcut-hit', (event, arg) => { console.log(arg); }) function formatClipboard() { let clipboard_contents = clipboard.readText(), language = lang(clipboard_contents), output = ''; if (clipboard_contents.length === 0) return; switch(language) { case 'css': output = beautify_js.css(clipboard_contents); break; case 'html': output = beautify_js.html(clipboard_contents); break; case 'javascript': default: output = beautify_js.js_beautify(clipboard_contents); break; } clipboard.writeText(output); }
Declare 'verbosity' as global variable to placate linters
import sys import zlib import imp z = zlib.decompressobj() while 1: global verbosity name = sys.stdin.readline().strip() if name: name = name.decode("ASCII") nbytes = int(sys.stdin.readline()) if verbosity >= 2: sys.stderr.write('server: assembling %r (%d bytes)\n' % (name, nbytes)) content = z.decompress(sys.stdin.read(nbytes)) module = imp.new_module(name) parents = name.rsplit(".", 1) if len(parents) == 2: parent, parent_name = parents setattr(sys.modules[parent], parent_name, module) code = compile(content, name, "exec") exec(code, module.__dict__) # nosec sys.modules[name] = module else: break sys.stderr.flush() sys.stdout.flush() import sshuttle.helpers sshuttle.helpers.verbose = verbosity import sshuttle.cmdline_options as options from sshuttle.server import main main(options.latency_control, options.auto_hosts, options.to_nameserver)
import sys import zlib import imp z = zlib.decompressobj() while 1: name = sys.stdin.readline().strip() if name: name = name.decode("ASCII") nbytes = int(sys.stdin.readline()) if verbosity >= 2: sys.stderr.write('server: assembling %r (%d bytes)\n' % (name, nbytes)) content = z.decompress(sys.stdin.read(nbytes)) module = imp.new_module(name) parents = name.rsplit(".", 1) if len(parents) == 2: parent, parent_name = parents setattr(sys.modules[parent], parent_name, module) code = compile(content, name, "exec") exec(code, module.__dict__) # nosec sys.modules[name] = module else: break sys.stderr.flush() sys.stdout.flush() import sshuttle.helpers sshuttle.helpers.verbose = verbosity import sshuttle.cmdline_options as options from sshuttle.server import main main(options.latency_control, options.auto_hosts, options.to_nameserver)
Join the welcome message on script init
/*Tell users to read the rules, with a direct link to the channel, when they join.*/ var info = console.log.bind(console, "[Welcomer]"); var message = [ "Welcome to the server!", "We have rules that we'd like you to follow, so make sure to check out the <#155309620540342272> channel.", "We hope you enjoy your stay!" ].join("\n"); function Welcomer(client, serverID) { client.on('any', function handleWelcomerEvent(event) { return (event.t === 'GUILD_MEMBER_ADD' && event.d.guild_id === serverID) ? (setTimeout( welcome, 3000, client, event.d.user.id ), true) : false; }); } function welcome(client, userID) { client.sendMessage({ to: userID, message: message }, function(err, res) { if (!err) return info(err.message); info(err.stack); }); } module.exports = Welcomer;
/*Tell users to read the rules, with a direct link to the channel, when they join.*/ var info = console.log.bind(console, "[Welcomer]"); var message = [ "Welcome to the server!", "We have rules that we'd like you to follow, so make sure to check out the <#155309620540342272> channel.", "We hope you enjoy your stay!" ]; function Welcomer(client, serverID) { client.on('any', function handleWelcomerEvent(event) { return (event.t === 'GUILD_MEMBER_ADD' && event.d.guild_id === serverID) ? (setTimeout( welcome, 3000, client, event.d.user.id ), true) : false; }); } module.exports = Welcomer; function welcome(client, userID) { client.sendMessage({ to: userID, message: message.join("\n") }, function(err, res) { if (err) return info(JSON.stringify(err)); }); }
Change to match on part of string rather than only on entire string. This allows the given regExp pattern decide if it must match at start ("^"), end ("$"), or both ("^*$).
// $Id: RegExpMatchOnNameFilter.java 63 2006-07-12 21:50:51Z edavis $ package thredds.crawlabledataset.filter; import thredds.crawlabledataset.CrawlableDatasetFilter; import thredds.crawlabledataset.CrawlableDataset; /** * CrawlableDatasetFilter implementation that accepts datasets whose * names are matched by the given regular expression. * * @author edavis * @since Nov 5, 2005 12:51:56 PM */ public class RegExpMatchOnNameFilter implements CrawlableDatasetFilter { // private static org.apache.commons.logging.Log log = // org.apache.commons.logging.LogFactory.getLog( RegExpMatchOnNameFilter.class ); private String regExpString; private java.util.regex.Pattern pattern; public RegExpMatchOnNameFilter( String regExpString ) { this.regExpString = regExpString; this.pattern = java.util.regex.Pattern.compile( regExpString ); } public Object getConfigObject() { return regExpString; } public String getRegExpString() { return regExpString; } public boolean accept( CrawlableDataset dataset ) { java.util.regex.Matcher matcher = this.pattern.matcher( dataset.getName() ); if ( matcher.find() ) return true; return false; } }
// $Id: RegExpMatchOnNameFilter.java 63 2006-07-12 21:50:51Z edavis $ package thredds.crawlabledataset.filter; import thredds.crawlabledataset.CrawlableDatasetFilter; import thredds.crawlabledataset.CrawlableDataset; /** * CrawlableDatasetFilter implementation that accepts datasets whose * names are matched by the given regular expression. * * @author edavis * @since Nov 5, 2005 12:51:56 PM */ public class RegExpMatchOnNameFilter implements CrawlableDatasetFilter { // private static org.apache.commons.logging.Log log = // org.apache.commons.logging.LogFactory.getLog( RegExpMatchOnNameFilter.class ); private String regExpString; private java.util.regex.Pattern pattern; public RegExpMatchOnNameFilter( String regExpString ) { this.regExpString = regExpString; this.pattern = java.util.regex.Pattern.compile( regExpString ); } public Object getConfigObject() { return regExpString; } public String getRegExpString() { return regExpString; } public boolean accept( CrawlableDataset dataset ) { java.util.regex.Matcher matcher = this.pattern.matcher( dataset.getName() ); if ( matcher.matches() ) return true; return false; } }
Fix view routing in DatasetSelectCtrl
'use strict'; /** * @ngdoc function * @name ocwUiApp.controller:DatasetSelectCtrl * @description * # DatasetSelectCtrl * Controller of the ocwUiApp */ angular.module('ocwUiApp') .controller('DatasetSelectCtrl', ['$scope', 'selectedDatasetInformation', function($scope, selectedDatasetInformation) { // Grab a copy of the datasets so we can display a count to the user! $scope.datasetCount = selectedDatasetInformation.getDatasets(); $scope.shouldDisableClearButton = function() { return (selectedDatasetInformation.getDatasetCount() === 0); }; $scope.clearDatasets = function() { selectedDatasetInformation.clearDatasets(); }; $scope.open = function () { $scope.datasetSelect = true; }; $scope.close = function () { $scope.datasetSelect = false; }; $scope.opts = { backdropFade: true, dialogFade: true, }; $scope.templates = [ {title:'Local File', url: 'views/selectObservation.html'}, {title:'RCMED', url: 'views/selectRcmed.html'}, {title:'ESG', disabled: true} ]; $scope.template = $scope.templates[0]; } ]);
'use strict'; /** * @ngdoc function * @name ocwUiApp.controller:DatasetSelectCtrl * @description * # DatasetSelectCtrl * Controller of the ocwUiApp */ angular.module('ocwUiApp') .controller('DatasetSelectCtrl', ['$scope', 'selectedDatasetInformation', function($scope, selectedDatasetInformation) { // Grab a copy of the datasets so we can display a count to the user! $scope.datasetCount = selectedDatasetInformation.getDatasets(); $scope.shouldDisableClearButton = function() { return (selectedDatasetInformation.getDatasetCount() === 0); }; $scope.clearDatasets = function() { selectedDatasetInformation.clearDatasets(); }; $scope.open = function () { $scope.datasetSelect = true; }; $scope.close = function () { $scope.datasetSelect = false; }; $scope.opts = { backdropFade: true, dialogFade: true, }; $scope.templates = [ {title:'Local File', url: 'partials/selectObservation.html'}, {title:'RCMED', url: 'partials/selectRcmed.html'}, {title:'ESG', disabled: true} ]; $scope.template = $scope.templates[0]; } ]);
Change URL and LED blinking.
var util = require('util'); var os = require('os'); var bleno = require('eddystone-beacon/node_modules/bleno'); var eddystone = require('eddystone-beacon'); var five = require('johnny-five'); var Edison = require('edison-io'); var led = ''; var board = new five.Board({ io: new Edison() }); board.on('ready', function () { led = new five.Led('J19-6'); led.on(); }); board.on('warn', function () { led.off(); }); var name = 'PW_Coffee'; var url = 'https://goo.gl/TWmm3H'; bleno.on('stateChange', function (state) { console.log('on -> stateChange: ' + state); if (state === 'poweredOn') { bleno.startAdvertising(); startBeacon(); } else { bleno.stopAdvertising(); } }); bleno.on('advertisingStart', function (error) { console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success')); if (error) { console.error('Can not start advertising'); exit(); } }); function startBeacon() { console.log('Starting beacon.'); var config = { 'name': name }; eddystone.advertiseUrl(url, config); led.off(); led.blink(); }
var util = require('util'); var os = require('os'); var bleno = require('eddystone-beacon/node_modules/bleno'); var eddystone = require('eddystone-beacon'); if (process.arch !== 'x64') { var five = require('johnny-five'); var Edison = require('edison-io'); var led; var board = new five.Board({ io: new Edison() }); board.on('ready', function () { led = new five.Led('J19-6'); led.on(); }); board.on('warn', function () { led.off(); }); } var name = 'PW_Coffee'; var url = 'https://google.fr'; bleno.on('stateChange', function (state) { console.log('on -> stateChange: ' + state); if (state === 'poweredOn') { bleno.startAdvertising(); startBeacon(); } else { bleno.stopAdvertising(); } }); bleno.on('advertisingStart', function (error) { console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success')); if (error) { console.error('Can not start advertising'); exit(); } }); function startBeacon() { console.log('Starting beacon.'); var config = { 'name': name }; eddystone.advertiseUrl(url, config); }
Add try/catch for state board display
<?php /* Copyright (C) 2010-2016 by the FusionInventory Development Team Copyright (C) 2016 Teclib' This file is part of Armadito Plugin for GLPI. Armadito Plugin for GLPI is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Armadito Plugin for GLPI 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>. **/ include("../../../inc/includes.php"); if (PluginArmaditoMenu::canView()) { Html::header(__('Armadito', 'armadito'), $_SERVER["PHP_SELF"], "plugins", "pluginarmaditomenu", "stateboard"); PluginArmaditoMenu::displayHeader(); PluginArmaditoMenu::displayMenu("mini"); try { $board = new PluginArmaditoStateBoard(); $board->displayBoard(); } catch(Exception $e) { PluginArmaditoLog::Error($e->getMessage(), 500); } } else { Html::displayRightError(); } Html::footer(); ?>
<?php /* Copyright (C) 2010-2016 by the FusionInventory Development Team Copyright (C) 2016 Teclib' This file is part of Armadito Plugin for GLPI. Armadito Plugin for GLPI is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Armadito Plugin for GLPI 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>. **/ include("../../../inc/includes.php"); if (PluginArmaditoMenu::canView()) { Html::header(__('Armadito', 'armadito'), $_SERVER["PHP_SELF"], "plugins", "pluginarmaditomenu", "stateboard"); PluginArmaditoMenu::displayHeader(); PluginArmaditoMenu::displayMenu("mini"); $board = new PluginArmaditoStateBoard(); $board->displayBoard(); } else { Html::displayRightError(); } Html::footer(); ?>
Change exported name to plivo
const plivo = require('plivo'); class Plivo { constructor (Config) { this.config = Config; const authId = this.config.get('sms.plivo.authId'); const authToken = this.config.get('sms.plivo.authToken'); if (!authId) throw new Error('Auth Id not found in Plivo config.'); if (!authToken) throw new Error('Auth Token not found in Plivo config.'); this.plivo = plivo.RestAPI({ authId, authToken }); } send (message, config) { if (config) this.config = config; return new Promise((resolve, reject) => { this.plivo.send_message({ src: message.from, dst: message.to, text: message.text }, (status, response) => { if (status < 200 || status > 299) { return reject(`${status} response - ${response.error}`); } return resolve(response.message_uuid); }); }); } } module.exports = Plivo;
const plivo = require('plivo'); class Log { constructor (Config) { this.config = Config; const authId = this.config.get('sms.plivo.authId'); const authToken = this.config.get('sms.plivo.authToken'); if (!authId) throw new Error('Auth Id not found in Plivo config.'); if (!authToken) throw new Error('Auth Token not found in Plivo config.'); this.plivo = plivo.RestAPI({ authId, authToken }); } send (message, config) { if (config) this.config = config; return new Promise((resolve, reject) => { this.plivo.send_message({ src: message.from, dst: message.to, text: message.text }, (status, response) => { if (status < 200 || status > 299) { return reject(`${status} response - ${response.error}`); } return resolve(response.message_uuid); }); }); } } module.exports = Log;
Correct path for the "node_modules" directory
"use strict"; /* * Configuration for the application * @type { * npm: '', // Absolute path to "node_modules" directory for NPM installed libraries and modules * libraries: { * nodejs: {}, // Node.js included libraries as "alias: name" * npm: {} // NPM installed libraries as "alias: name" * }, * directory: '', // Absolute path to directory with the application/bundle modules * modules: { * npm: {}, // NPM installed modules with the configuration as "name: config" * directory: {} // Modules of the directory with the configuration as "name: config" * } * } */ module.exports = { npm: __dirname + '/../node_modules/', libraries: {}, directory: __dirname + '/modules/', modules: { directory: { example: { // Configuration for the module } } } };
"use strict"; /* * Configuration for the application * @type { * npm: '', // Absolute path to "node_modules" directory for NPM installed libraries and modules * libraries: { * nodejs: {}, // Node.js included libraries as "alias: name" * npm: {} // NPM installed libraries as "alias: name" * }, * directory: '', // Absolute path to directory with the application/bundle modules * modules: { * npm: {}, // NPM installed modules with the configuration as "name: config" * directory: {} // Modules of the directory with the configuration as "name: config" * } * } */ module.exports = { npm: __dirname + '/node_modules/', libraries: {}, directory: __dirname + '/modules/', modules: { directory: { example: { // Configuration for the module } } } };
Check that output is expected JSON
<?php declare(strict_types = 1); /** * /tests/Integration/Controller/VersionControllerTest.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\Tests\Integration\Controller; use App\Controller\VersionController; use App\Service\Version; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; /** * Class VersionControllerTest * * @package App\Tests\Integration\Controller * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ class VersionControllerTest extends KernelTestCase { /** * @testdox Test that `__invoke` method calls expected service methods */ public function testThatInvokeMethodIsCallingExpectedMethods(): void { $version = $this->getMockBuilder(Version::class) ->disableOriginalConstructor() ->getMock(); $version ->expects(self::once()) ->method('get') ->willReturn('1.0.0'); $response = (new VersionController($version))(); $content = $response->getContent(); self::assertSame(200, $response->getStatusCode()); self::assertNotFalse($content); self::assertJson($content); self::assertJsonStringEqualsJsonString('{"version": "1.0.0"}', $content); } }
<?php declare(strict_types = 1); /** * /tests/Integration/Controller/VersionControllerTest.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\Tests\Integration\Controller; use App\Controller\VersionController; use App\Service\Version; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; /** * Class VersionControllerTest * * @package App\Tests\Integration\Controller * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ class VersionControllerTest extends KernelTestCase { /** * @testdox Test that `__invoke` method calls expected service methods */ public function testThatInvokeMethodIsCallingExpectedMethods(): void { $version = $this->getMockBuilder(Version::class) ->disableOriginalConstructor() ->getMock(); $version ->expects(self::once()) ->method('get') ->willReturn('1.0.0'); $response = (new VersionController($version))(); $content = $response->getContent(); self::assertSame(200, $response->getStatusCode()); self::assertNotFalse($content); self::assertJson($content); } }
Include error message when logging caught exception
module.exports = {}; function calculateMove(game_state) { try { if(gameDecision.wantToBet()) { return gameDecision.getBetAmount(); } else if(gameDecision.canWeKeepCards()) { // keep the cards if we can check // TODO: return current bet!!! return gameDecision.getCheckAmount(); } else { //FOLD THE CARDS; return 0; } var bet = 110; var me = game_state["players"][game_state["in_action"]]; var cards = me["hole_cards"]; var first = cards[0]; var second = cards[1]; bet = get_minimum_raise(game_state) + bet; if(isNaN(parseInt(bet))){ bet = 1100; } console.log("DO BET: "+bet); return bet; } catch(e) { console.log('caught horrible exception:', e, 'folding!'); return 0; } }; module.exports.calculateMove = calculateMove; function get_minimum_raise(game_state){ return parseInt(game_state["current_buy_in"] - game_state["players"][game_state["in_action"]][game_state["bet"]] + game_state["minimum_raise"]); }
module.exports = {}; function calculateMove(game_state) { try { if(gameDecision.wantToBet()) { return gameDecision.getBetAmount(); } else if(gameDecision.canWeKeepCards()) { // keep the cards if we can check // TODO: return current bet!!! return gameDecision.getCheckAmount(); } else { //FOLD THE CARDS; return 0; } var bet = 110; var me = game_state["players"][game_state["in_action"]]; var cards = me["hole_cards"]; var first = cards[0]; var second = cards[1]; bet = get_minimum_raise(game_state) + bet; if(isNaN(parseInt(bet))){ bet = 1100; } console.log("DO BET: "+bet); return bet; } catch(e) { console.log('caught horrible exception; folding!'); return 0; } }; module.exports.calculateMove = calculateMove; function get_minimum_raise(game_state){ return parseInt(game_state["current_buy_in"] - game_state["players"][game_state["in_action"]][game_state["bet"]] + game_state["minimum_raise"]); }
Fix broken site admin links
package org.vivoweb.webapp.startup; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.InstitutionalInternalClassController; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.SiteAdminController; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.utils.menuManagement.MenuManagementDataUtils; import edu.cornell.mannlib.vitro.webapp.utils.menuManagement.VIVOMenuManagementDataUtils; import edu.cornell.mannlib.vitro.webapp.visualization.tools.ToolsRequestHandler; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class SiteAdminSetup implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { SiteAdminController.registerSiteMaintenanceUrl("rebuildVisCache", "/vis/tools", null, ToolsRequestHandler.REQUIRED_ACTIONS); SiteAdminController.registerSiteConfigData("internalClass", "/processInstitutionalInternalClass", null, InstitutionalInternalClassController.REQUIRED_ACTIONS); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
package org.vivoweb.webapp.startup; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.InstitutionalInternalClassController; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.SiteAdminController; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.utils.menuManagement.MenuManagementDataUtils; import edu.cornell.mannlib.vitro.webapp.utils.menuManagement.VIVOMenuManagementDataUtils; import edu.cornell.mannlib.vitro.webapp.visualization.tools.ToolsRequestHandler; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class SiteAdminSetup implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { SiteAdminController.registerSiteMaintenanceUrl("rebuildVisCache", UrlBuilder.getUrl("/vis/tools"), ToolsRequestHandler.REQUIRED_ACTIONS); SiteAdminController.registerSiteConfigData("internalClass", UrlBuilder.getUrl("/processInstitutionalInternalClass"), InstitutionalInternalClassController.REQUIRED_ACTIONS); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
Allow additional properties on Text git-svn-id: ec97508af0aa29a1d296967d6f0ba22a468c79d6@350 286bb87c-ec97-11de-a004-2f18c49ebcc3
from rctk.widgets.control import Control, remote_attribute from rctk.task import Task from rctk.event import Changable, Submittable class Text(Control, Changable, Submittable): name = "text" value = remote_attribute('value', "") def __init__(self, tk, value="", rows=1, columns=20, **properties): self._value = value self._rows = rows self._columns = columns super(Text, self).__init__(tk, **properties) def create(self): self.tk.create_control(self, value=self._value, rows=self._rows, columns=self._columns) def sync(self, **data): if 'value' in data: self._value = data['value'] class Password(Text): name = "password"
from rctk.widgets.control import Control, remote_attribute from rctk.task import Task from rctk.event import Changable, Submittable class Text(Control, Changable, Submittable): name = "text" value = remote_attribute('value', "") def __init__(self, tk, value="", rows=1, columns=20): self._value = value self._rows = rows self._columns = columns super(Text, self).__init__(tk) def create(self): self.tk.create_control(self, value=self._value, rows=self._rows, columns=self._columns) def sync(self, **data): if 'value' in data: self._value = data['value'] class Password(Text): name = "password"
Fix can't insert when grouping.
/** * Created by dungvn3000 on 3/11/14. */ Ext.define('sunerp.controller.sophancong.SoPhanCongListCtr', { extend: 'sunerp.controller.core.BaseListEditController', modelClass: 'sunerp.model.SoPhanCong', inject: ['soPhanCongStore', 'userService'], config: { soPhanCongStore: null, phongBangId: null, userService: null }, searchField: "nhanVien.maNv", init: function () { this.mainStore = this.getSoPhanCongStore(); this.setPhongBangId(this.getUserService().getCurrentUser().phongBangId); this.callParent(arguments); }, addNewRow: function () { var lastModel = this.getView().getStore().last(); var rec = Ext.create(this.modelClass); rec.set('phongBangId', this.getPhongBangId()); rec.set('ngayPhanCong', lastModel.get('ngayPhanCong')); this.mainStore.insert(this.mainStore.count(), rec); } });
/** * Created by dungvn3000 on 3/11/14. */ Ext.define('sunerp.controller.sophancong.SoPhanCongListCtr', { extend: 'sunerp.controller.core.BaseListEditController', modelClass: 'sunerp.model.SoPhanCong', inject: ['soPhanCongStore', 'userService'], config: { soPhanCongStore: null, phongBangId: null, userService: null }, searchField: "nhanVien.maNv", init: function () { this.mainStore = this.getSoPhanCongStore(); this.setPhongBangId(this.getUserService().getCurrentUser().phongBangId); this.callParent(arguments); }, addNewRow: function () { var rec = Ext.create(this.modelClass); rec.set('phongBangId', this.getPhongBangId()); this.mainStore.insert(this.mainStore.count(), rec); } });
Use es6 style object function
module.exports = function (sequelize, DataTypes) { const Rating = sequelize.define('Rating', { id: { primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, value: { type: DataTypes.INTEGER, allowNull: false, validate: { min: 0 } }, BikeId: { type: DataTypes.UUID, allowNull: false }, VoteId: { type: DataTypes.UUID, allowNull: false } }, { classMethods: { associate (models) { Rating.belongsTo(models.Bike) Rating.belongsTo(models.Vote) } } }) return Rating }
module.exports = function (sequelize, DataTypes) { const Rating = sequelize.define('Rating', { id: { primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, value: { type: DataTypes.INTEGER, allowNull: false, validate: { min: 0 } }, BikeId: { type: DataTypes.UUID, allowNull: false }, VoteId: { type: DataTypes.UUID, allowNull: false } }, { classMethods: { associate: function associate (models) { Rating.belongsTo(models.Bike) Rating.belongsTo(models.Vote) } } }) return Rating }
Fix rmdup handling in wrapper script.
#!python # Load libraries import sys, getopt import pysam import libPipeline # Set constants helpMsg =''' SYNOPSIS parseSAMOutput parseSAMOutput [OPTIONS] SAMFILE # DESCRIPTION parseSAMOutput.py Parses SAM alignments into paired-end read summaries. Prints results to stdout. OPTIONS --rmdup Remove duplicate reads (reduces PCR effects) -h/--help Print help message and exit ''' if __name__ == "__main__": # Set defaults rmdup = False # Parse arguments options, args = getopt.getopt(sys.argv[1:], 'h', ["help", "rmdup"]) for opt, value in options: if opt in ("-h", "--help"): print >> sys.stderr, helpMsg sys.exit(2) elif opt == "--rmdup": rmdup = True else: print >> sys.stderr, "Error -- option %s not recognized" % opt sys.exit(1) # Parse arguments & options if len(args) > 0: alignmentPath = args[0] else: print >> sys.stderr, "Error -- need path to SAM file" sys.exit(1) libPipeline.processSAMOutput(alignmentPath, sys.stdout, rmdup=rmdup)
#!python # Load libraries import sys, getopt import pysam import libPipeline # Set constants helpMsg =''' SYNOPSIS parseSAMOutput parseSAMOutput [OPTIONS] SAMFILE # DESCRIPTION parseSAMOutput.py Parses SAM alignments into paired-end read summaries. Prints results to stdout. OPTIONS --rmdup Remove duplicate reads (reduces PCR effects) -h/--help Print help message and exit ''' if __name__ == "__main__": # Set defaults rmdup = False # Parse arguments options, args = getopt.getopt(sys.argv[1:], 'h', ["help", "rmdup"]) for opt, value in options: if opt in ("-h", "--help"): print >> sys.stderr, helpMsg sys.exit(2) elif opt == "--rmdup": rmdup = True else: print >> sys.stderr, "Error -- option %s not recognized" % opt sys.exit(1) # Parse arguments & options if len(args) > 0: alignmentPath = args[0] else: print >> sys.stderr, "Error -- need path to SAM file" sys.exit(1) libPipeline.processSAMOutput(alignmentPath, sys.stdout)
Clarify docstring from previous PR suggestion
import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent move to Kubernetes, obviating this view """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data)
import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent infra changes """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data)
[Base] Rewrite button with flow and PureComponent
// @flow import React, { PureComponent } from 'react'; import { TouchableOpacity, Text, StyleSheet, View } from 'react-native'; import appStyle from '<%= appName %>/src/appStyle'; const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems: 'center', minHeight: appStyle.dimensions.touchableHeight, marginVertical: appStyle.grid.x1, }, button: { alignSelf: 'stretch', justifyContent: 'center', height: appStyle.dimensions.visibleButtonHeight, backgroundColor: appStyle.colors.primary, paddingHorizontal: appStyle.grid.x1, }, text: { textAlign: 'center', color: appStyle.colors.lightText, fontSize: appStyle.font.size.default, }, }); class Button extends PureComponent { static defaultProps: PropsTypes = { children: null, onPress: () => {}, }; props: PropsTypes; render() { return ( <TouchableOpacity onPress={this.props.onPress} style={styles.container}> <View style={styles.button}> <Text style={[styles.text]}>{this.props.children.toUpperCase()}</Text> </View> </TouchableOpacity> ); } } type PropsTypes = { children: string, onPress: () => void, }; export default Button;
import React, { PropTypes } from 'react'; import { TouchableOpacity, Text, StyleSheet, View } from 'react-native'; import appStyle from '<%= appName %>/src/appStyle'; const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems: 'center', minHeight: appStyle.dimensions.touchableHeight, marginVertical: appStyle.grid.x1, }, button: { alignSelf: 'stretch', justifyContent: 'center', height: appStyle.dimensions.visibleButtonHeight, backgroundColor: appStyle.colors.primary, paddingHorizontal: appStyle.grid.x1, }, text: { textAlign: 'center', color: appStyle.colors.lightText, fontSize: appStyle.font.size.default, }, }); const Button = props => ( <TouchableOpacity onPress={props.onPress} style={styles.container}> <View style={styles.button}> <Text style={[styles.text]}>{props.children.toUpperCase()}</Text> </View> </TouchableOpacity> ); Button.propTypes = { children: PropTypes.string, onPress: PropTypes.func, buttonType: PropTypes.string, }; Button.defaultProps = { children: null, onPress: () => {}, }; export default Button;
Allow internal services to be used in ingresses
package service import "github.com/containerum/kube-client/pkg/model" type ServiceList []Service func ServiceListFromKube(kubeList model.ServicesList) ServiceList { var list ServiceList = make([]Service, 0, len(kubeList.Services)) for _, kubeService := range kubeList.Services { list = append(list, ServiceFromKube(kubeService)) } return list } func (list ServiceList) Names() []string { names := make([]string, 0, len(list)) for _, serv := range list { names = append(names, serv.Name) } return names } func (list ServiceList) GetByName(name string) (Service, bool) { for _, serv := range list { if serv.Name == name { return serv, true } } return Service{}, false } func (list ServiceList) AvailableForIngress() ServiceList { var sortedList ServiceList = make([]Service, 0) for _, svc := range list { for _, port := range svc.Ports { if port.Protocol == "TCP" { sortedList = append(sortedList, svc) break } } } return sortedList }
package service import "github.com/containerum/kube-client/pkg/model" type ServiceList []Service func ServiceListFromKube(kubeList model.ServicesList) ServiceList { var list ServiceList = make([]Service, 0, len(kubeList.Services)) for _, kubeService := range kubeList.Services { list = append(list, ServiceFromKube(kubeService)) } return list } func (list ServiceList) Names() []string { names := make([]string, 0, len(list)) for _, serv := range list { names = append(names, serv.Name) } return names } func (list ServiceList) GetByName(name string) (Service, bool) { for _, serv := range list { if serv.Name == name { return serv, true } } return Service{}, false } func (list ServiceList) AvailableForIngress() ServiceList { var sortedList ServiceList = make([]Service, 0) for _, svc := range list { if svc.Domain != "" { for _, port := range svc.Ports { if port.Protocol == "TCP" { sortedList = append(sortedList, svc) break } } } } return sortedList }
Split tests for different functionality
import pytest import textwrap @pytest.fixture def warnings_demo(tmpdir): demo = tmpdir.joinpath('warnings_demo.py') demo.write_text(textwrap.dedent(''' from logging import basicConfig from pip._internal.utils import deprecation deprecation.install_warning_logger() basicConfig() deprecation.deprecated("deprecated!", replacement=None, gone_in=None) ''')) return demo def test_deprecation_warnings_are_correct(script, warnings_demo): result = script.run('python', warnings_demo, expect_stderr=True) expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n' assert result.stderr == expected def test_deprecation_warnings_can_be_silenced(script, warnings_demo): script.environ['PYTHONWARNINGS'] = 'ignore' result = script.run('python', warnings_demo) assert result.stderr == ''
import pytest import textwrap @pytest.fixture def warnings_demo(tmpdir): demo = tmpdir.joinpath('warnings_demo.py') demo.write_text(textwrap.dedent(''' from logging import basicConfig from pip._internal.utils import deprecation deprecation.install_warning_logger() basicConfig() deprecation.deprecated("deprecated!", replacement=None, gone_in=None) ''')) return demo def test_deprecation_warnings_are_correct(script, warnings_demo): result = script.run('python', warnings_demo, expect_stderr=True) expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n' assert result.stderr == expected # NOTE: PYTHONWARNINGS was added in 2.7 script.environ['PYTHONWARNINGS'] = 'ignore' result = script.run('python', warnings_demo) assert result.stderr == ''
Add an exception useful for prototyping. Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
""" Error heirarchy for stratis cli. """ class StratisCliError(Exception): """ Top-level stratis cli error. """ pass class StratisCliValueError(StratisCliError): """ Raised when a parameter has an unacceptable value. May also be raised when the parameter has an unacceptable type. """ _FMT_STR = "value '%s' for parameter %s is unacceptable" def __init__(self, value, param, msg=None): """ Initializer. :param object value: the value :param str param: the parameter :param str msg: an explanatory message """ # pylint: disable=super-init-not-called self._value = value self._param = param self._msg = msg def __str__(self): # pragma: no cover if self._msg: fmt_str = self._FMT_STR + ": %s" return fmt_str % (self._value, self._param, self._msg) else: return self._FMT_STR % (self._value, self._param) class StratisCliValueUnimplementedError(StratisCliValueError): """ Raised if a parameter is not intrinsically bad but functionality is unimplemented for this value. """ pass
""" Error heirarchy for stratis cli. """ class StratisCliError(Exception): """ Top-level stratis cli error. """ pass class StratisCliValueError(StratisCliError): """ Raised when a parameter has an unacceptable value. May also be raised when the parameter has an unacceptable type. """ _FMT_STR = "value '%s' for parameter %s is unacceptable" def __init__(self, value, param, msg=None): """ Initializer. :param object value: the value :param str param: the parameter :param str msg: an explanatory message """ # pylint: disable=super-init-not-called self._value = value self._param = param self._msg = msg def __str__(self): # pragma: no cover if self._msg: fmt_str = self._FMT_STR + ": %s" return fmt_str % (self._value, self._param, self._msg) else: return self._FMT_STR % (self._value, self._param)
Remove active class when .list or aside is clicked.
/* PSEUDO CODE FOR LOGIN MENU 1. COLLECT DATA ENTERED INTO THE <INPUT> 2. WHEN .LOGIN-SUBMIT IS 'CLICKED' `GET/users/id` TO DATABASE TO BE VERIFIED? */ ;(function(){ angular.module('Front-Rails', [ ]) .run(function($http, $rootScope) { $http.get('https://stackundertow.herokuapp.com/questions') .then(function(response){ // $rootScope.query = "hello"; $rootScope.query = response.data[0].query; // $rootScope.questions = response.data; }) }) })(); /* Signup and Login menu drop down*/ $('.search a[href]').on('click', function(event){ event.preventDefault(); $(this).add(this.hash) .toggleClass('active') .siblings().removeClass('active'); }); $('.redirect a[href]').on('click', function(event){ event.preventDefault(); $(this).add(this.hash) .toggleClass('active') .siblings().removeClass('active'); }); $('.list').on('click', function(event){ event.preventDefault(); console.log("HEY"); $('.active').removeClass('active'); }); $('aside').on('click', function(event){ event.preventDefault(); console.log("HEY"); $('.active').removeClass('active'); }); /* Signup and Login menu drop down*/
/* PSEUDO CODE FOR LOGIN MENU 1. COLLECT DATA ENTERED INTO THE <INPUT> 2. WHEN .LOGIN-SUBMIT IS 'CLICKED' `GET/users/id` TO DATABASE TO BE VERIFIED? */ ;(function(){ angular.module('Front-Rails', [ ]) .run(function($http, $rootScope) { $http.get('https://stackundertow.herokuapp.com/questions') .then(function(response){ // $rootScope.query = "hello"; $rootScope.query = response.data[0].query; // $rootScope.questions = response.data; }) }) })(); $('.search a[href]').on('click', function(event){ event.preventDefault(); $(this).add(this.hash) .toggleClass('active') .siblings().removeClass('active'); }); $('.redirect a[href]').on('click', function(event){ event.preventDefault(); $(this).add(this.hash) .toggleClass('active') .siblings().removeClass('active'); });
Fix bad import in api
import EPSG21781 from '@geoblocks/proj/src/EPSG_21781.js'; /** * @type {string} */ export const themesUrl = 'https://geomapfish-demo-dc.camptocamp.com/2.4/themes?version=2&background=background'; /** * @type {string} */ export const projection = EPSG21781; /** * @type {Array.<number>} */ export const resolutions = [250, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.25, 0.1, 0.05]; /** * @type {Array.<number>} */ export const extent = [420000, 30000, 660000, 350000]; /** * The name of the layer to use as background. May be a single value * (WMTS) or a comma-separated list of layer names (WMS). * @type {string} */ //export const backgroundLayer = 'default'; // WMS export const backgroundLayer = 'asitvd.fond_gris_sans_labels'; // WMTS
import EPSG21781 from '@geoblocks/sources/EPSG21781.js'; /** * @type {string} */ export const themesUrl = 'https://geomapfish-demo-dc.camptocamp.com/2.4/themes?version=2&background=background'; /** * @type {string} */ export const projection = EPSG21781; /** * @type {Array.<number>} */ export const resolutions = [250, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.25, 0.1, 0.05]; /** * @type {Array.<number>} */ export const extent = [420000, 30000, 660000, 350000]; /** * The name of the layer to use as background. May be a single value * (WMTS) or a comma-separated list of layer names (WMS). * @type {string} */ //export const backgroundLayer = 'default'; // WMS export const backgroundLayer = 'asitvd.fond_gris_sans_labels'; // WMTS
Add feedback for unidentified errors
import config from '../config' export const feedback: (feedback) => any = (feedback) => { const options = { method: 'POST', headers: { 'Content-Type': "application/json", "Voter-ID": feedback.uuid }, body: JSON.stringify(feedback.feedback) } return fetch(`${config.urls.devnull}/events/${feedback.eventId}/sessions/${feedback.sessionId}/feedbacks`, options) .then(res => { if (res.status === 202) { return { message: 'Feedback submitted' } } else if(res.status === 403) { return { message : 'Please try again. Feedback opens 10 min before session ends.' } } else { return { message: 'Ops somthing went wrong.' } } } ) }
import config from '../config' export const feedback: (feedback) => any = (feedback) => { const options = { method: 'POST', headers: { 'Content-Type': "application/json", "Voter-ID": feedback.uuid }, body: JSON.stringify(feedback.feedback) } return fetch(`${config.urls.devnull}/events/${feedback.eventId}/sessions/${feedback.sessionId}/feedbacks`, options) .then(res => { if (res.status === 202) { return { message: 'Feedback submitted' } } else if(res.status === 403) { return { message : 'Please try again. Feedback opens 10 min before session ends.' } } else { return res.status } } ) }
Use NCMBInstallationEx instead of NCMB.Installation to register device.
"use strict" var Converter = module.exports = (function() { function Converter(ncmb, type) { this.__proto__.ncmb = ncmb; this._type = type; } Converter.prototype.convert = function(obj) { let map = { appName: 'applicationName' , createdAt: 'parseCreateAt' , updatedAt: 'parseUpdateAt' , objectId: 'parseObjectId' }; let NCMBInstallationEx = require('./installation_ex'); let installation = new NCMBInstallationEx(this.ncmb); let attrs = {}; Object.keys(obj).forEach(function(key) { if (map[key] == undefined) { attrs[key] = obj[key]; } else { attrs[map[key]] = obj[key]; } }); installation.register(attrs) .catch(function(err) { console.log(err); }); } return Converter; })();
"use strict" var Converter = module.exports = (function() { function Converter(ncmb, type) { this.__proto__.ncmb = ncmb; this._type = type; } Converter.prototype.convert = function(obj) { let map = { appName: 'applicationName' , appVersion: 'appVersion' , badge: 'badge' , channels: 'channels' , deviceToken: 'deviceToken' , deviceType: 'deviceType' , timeZone: 'timeZone' , createdAt: 'createDate' , updatedAt: 'updateDate' , objectId: 'parseObjectId' }; let Installation = this.ncmb.Installation; let attrs = {}; Object.keys(obj).forEach(function(key) { if (map[key] == undefined) { return; } attrs[map[key]] = obj[key]; }); let installation = new Installation(attrs); installation.update() .catch(function(err) { console.log(err); }); } return Converter; })();
Remove an aborted test and add a docstring explaining why this test-less testcase is still here.
from mock import Mock import testify as T import create_service class SrvReaderWriterTestCase(T.TestCase): """I bailed out of this test, but I'll leave this here for now as an example of how to interact with the Srv* classes.""" @T.setup def init_service(self): paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder") self.srw = create_service.SrvReaderWriter(paths) class ValidateOptionsTestCase(T.TestCase): def test_enable_puppet_requires_puppet_root(self): parser = Mock() options = Mock() options.enable_puppet = True options.puppet_root = None with T.assert_raises(SystemExit): create_service.validate_options(parser, options) def test_enable_nagios_requires_nagios_root(self): parser = Mock() options = Mock() options.enable_nagios = True options.nagios_root = None with T.assert_raises(SystemExit): create_service.validate_options(parser, options) if __name__ == "__main__": T.run()
from mock import Mock import testify as T import create_service class SrvReaderWriterTestCase(T.TestCase): @T.setup def init_service(self): paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder") self.srw = create_service.SrvReaderWriter(paths) def test_append_raises_when_file_dne(self): self.srw._append() class ValidateOptionsTestCase(T.TestCase): def test_enable_puppet_requires_puppet_root(self): parser = Mock() options = Mock() options.enable_puppet = True options.puppet_root = None with T.assert_raises(SystemExit): create_service.validate_options(parser, options) def test_enable_nagios_requires_nagios_root(self): parser = Mock() options = Mock() options.enable_nagios = True options.nagios_root = None with T.assert_raises(SystemExit): create_service.validate_options(parser, options) if __name__ == "__main__": T.run()
Update colors for task cards
package tars.ui; import javafx.scene.paint.Color; /** * Manages color for UI parts * @@author A0121533W * */ public class UiColor { public static final String STATUS_UNDONE_TEXT_FILL_DARK = "-fx-text-fill: #212121"; public static final String STATUS_UNDONE_TEXT_FILL_LIGHT = "-fx-text-fill: #757575"; public static final String STATUS_DONE_TEXT_FILL = "-fx-text-fill: lightgrey"; public static final String CIRCLE_LABEL_COLOR = "-fx-text-fill: white;"; public static final String TASK_CARD_NEWLY_ADDED_BORDER = "-fx-border-color: #2E8AF7"; public static final String TASK_CARD_DEFAULT_BORDER = "-fx-border-color: lightgrey"; public enum CircleColor { HIGH(Color.RED), MEDIUM(Color.ORANGE), LOW(Color.GREEN), DONE(Color.LIGHTGREY), NONE(Color.TRANSPARENT); private Color circleColor; CircleColor(Color circleColor) { this.circleColor = circleColor; } Color getCircleColor() { return circleColor; } } }
package tars.ui; import javafx.scene.paint.Color; /** * Manages color for UI parts * @@author A0121533W * */ public class UiColor { public static final String STATUS_UNDONE_TEXT_FILL = "-fx-text-fill: #212121"; public static final String STATUS_DONE_TEXT_FILL = "-fx-text-fill: lightgrey"; public static final String CIRCLE_LABEL_COLOR = "-fx-text-fill: white;"; public static final String TASK_CARD_NEWLY_ADDED_BORDER = "-fx-border-color: lightblue"; public static final String TASK_CARD_DEFAULT_BORDER = "-fx-border-color: #455A64"; public enum CircleColor { HIGH(Color.RED), MEDIUM(Color.ORANGE), LOW(Color.GREEN), DONE(Color.LIGHTGREY), NONE(Color.TRANSPARENT); private Color circleColor; CircleColor(Color circleColor) { this.circleColor = circleColor; } Color getCircleColor() { return circleColor; } } }
Add logger name to default log format.
""" A logging handler that's tty aware. """ import logging from . import rendering class VTMLHandler(logging.StreamHandler): """ Parse VTML messages to colorize and embolden logs. """ log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \ '[%(levelname)s] %(message)s' level_fmt = { 10: '<dim>%s</dim>', 20: '%s', 30: '<b>%s</b>', 40: '<red>%s</red>', 50: '<red><b>%s</b></red>', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setFormatter(VTMLFormatter(self.log_format)) def format(self, record): record.levelname = self.level_fmt[record.levelno] % record.levelname return str(rendering.vtmlrender(super().format(record))) class VTMLFormatter(logging.Formatter): def formatException(self, ei): return '\n'.join(rendering.format_exception(ei[1]))
""" A logging handler that's tty aware. """ import logging from . import rendering class VTMLHandler(logging.StreamHandler): """ Parse VTML messages to colorize and embolden logs. """ log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s' level_fmt = { 10: '<dim>%s</dim>', 20: '%s', 30: '<b>%s</b>', 40: '<red>%s</red>', 50: '<red><b>%s</b></red>', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setFormatter(VTMLFormatter(self.log_format)) def format(self, record): record.levelname = self.level_fmt[record.levelno] % record.levelname return str(rendering.vtmlrender(super().format(record))) class VTMLFormatter(logging.Formatter): def formatException(self, ei): return '\n'.join(rendering.format_exception(ei[1]))
Add some logging, leave files around for debugging
package utils import ( "io/ioutil" "os" "syscall" "github.com/zenoss/glog" ) var BASH_SCRIPT = ` DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)" COMMAND="$@" #trap "rm -f ${DIR}/$$.stderr" EXIT for i in {1..10}; do SEEN=0 ${COMMAND} 2> >(tee ${DIR}/$$.stderr >&2) RESULT=$? [ "${RESULT}" == 0 ] && exit 0 grep setns ${DIR}/$$.stderr || exit ${RESULT} done exit ${RESULT} ` func NSInitWithRetry(cmd []string) error { f, err := ioutil.TempFile("", "nsinit") if err != nil { return err } defer f.Close() //defer os.Remove(f.Name()) if _, err := f.WriteString(BASH_SCRIPT); err != nil { return err } if err := f.Sync(); err != nil { return err } command := []string{f.Name()} command = append(command, cmd...) glog.V(0).Infof("Here's the command: %s", command) err = syscall.Exec("/bin/bash", command, os.Environ()) return nil }
package utils import ( "io/ioutil" "os" "syscall" ) var BASH_SCRIPT = ` DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)" COMMAND="$@" trap "rm -f ${DIR}/$$.stderr" EXIT for i in {1..10}; do SEEN=0 ${COMMAND} 2> >(tee ${DIR}/$$.stderr >&2) RESULT=$? [ "${RESULT}" == 0 ] && exit 0 grep setns ${DIR}/$$.stderr || exit ${RESULT} done exit ${RESULT} ` func NSInitWithRetry(cmd []string) error { f, err := ioutil.TempFile("", "nsinit") if err != nil { return err } defer f.Close() defer os.Remove(f.Name()) if _, err := f.WriteString(BASH_SCRIPT); err != nil { return err } if err := f.Sync(); err != nil { return err } command := []string{f.Name()} command = append(command, cmd...) err = syscall.Exec("/bin/bash", command, os.Environ()) return nil }
Make port removing migrating a bit less flaky
# Generated by Django 2.0.13 on 2019-12-29 21:11 from django.db import migrations, IntegrityError from django.db.migrations import RunPython def forward(apps, schema): Node = apps.get_model("thefederation", "Node") for node in Node.objects.filter(host__contains=":"): node.host = node.host.split(":")[0] if node.name.split(':')[0] == node.host: node.name = node.host try: Node.objects.filter(id=node.id).update(host=node.host, name=node.name) except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('thefederation', '0019_add_some_defaults_for_node_organization_fields'), ] operations = [ RunPython(forward, RunPython.noop) ]
# Generated by Django 2.0.13 on 2019-12-29 21:11 from django.db import migrations from django.db.migrations import RunPython def forward(apps, schema): Node = apps.get_model("thefederation", "Node") for node in Node.objects.filter(host__contains=":"): node.host = node.host.split(":")[0] if node.name.split(':')[0] == node.host: node.name = node.host Node.objects.filter(id=node.id).update(host=node.host, name=node.name) class Migration(migrations.Migration): dependencies = [ ('thefederation', '0019_add_some_defaults_for_node_organization_fields'), ] operations = [ RunPython(forward, RunPython.noop) ]
Set some fields as tranlate
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmDepartment(models.Model): _name = 'crm.department' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Department" name = fields.Char(required=True, translate=True) parent_id = fields.Many2one(comodel_name='crm.department') children = fields.One2many(comodel_name='crm.department', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmDepartment(models.Model): _name = 'crm.department' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Department" name = fields.Char(required=True) parent_id = fields.Many2one(comodel_name='crm.department') children = fields.One2many(comodel_name='crm.department', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
Replace subprocess.Popen with check_output to avoid git zombies
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014, GEM Foundation. # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake 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 Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. import os import subprocess def git_suffix(fname): """ :returns: `<short git hash>` if Git repository found """ try: po = subprocess.check_output( ['git', 'rev-parse', '--short', 'HEAD'], cwd=os.path.dirname(fname)) return "-git" + po.stdout.read().strip() except: # trapping everything on purpose; git may not be installed or it # may not work properly return ''
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014, GEM Foundation. # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake 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 Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. import os import subprocess def git_suffix(fname): """ :returns: `<short git hash>` if Git repository found """ try: po = subprocess.Popen( ['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'), cwd=os.path.dirname(fname)) return "-git" + po.stdout.read().strip() except: # trapping everything on purpose; git may not be installed or it # may not work properly return ''
Fix test for travis execution context
/*eslint-env mocha */ 'use strict'; const assert = require('assert'); const icli = require('../../packages/cli/src/bin/myrmex'); const showStdout = !!process.env.MYRMEX_SHOW_STDOUT; describe('The "cheers" sub-command', () => { before(() => { process.chdir(__dirname); }); beforeEach(() => { return icli.init(); }); it('should display a beer', () => { icli.catchPrintStart(showStdout); return icli.parse('node script.js cheers'.split(' ')) .then(res => { const stdout = icli.catchPrintStop(); assert.ok(stdout.indexOf('language: ') > -1); assert.ok(stdout.indexOf('font: ') > -1); }); }); it('should allow to select a language and a font', () => { icli.catchPrintStart(showStdout); return icli.parse('node script.js cheers -l french -f Binary'.split(' ')) .then(res => { const stdout = icli.catchPrintStop(); assert.ok(stdout.indexOf('language: french') > -1); assert.ok(stdout.indexOf('font: Binary') > -1); // Disable assertion because of travis execution context // assert.ok(stdout.indexOf('01010011 01100001 01101110 01110100 01100101') > -1); }); }); });
/*eslint-env mocha */ 'use strict'; const assert = require('assert'); const icli = require('../../packages/cli/src/bin/myrmex'); const showStdout = !!process.env.MYRMEX_SHOW_STDOUT; describe('The "cheers" sub-command', () => { before(() => { process.chdir(__dirname); }); beforeEach(() => { return icli.init(); }); it('should display a beer', () => { icli.catchPrintStart(showStdout); return icli.parse('node script.js cheers'.split(' ')) .then(res => { const stdout = icli.catchPrintStop(); assert.ok(stdout.indexOf('language: ') > -1); assert.ok(stdout.indexOf('font: ') > -1); }); }); it('should allow to select a language and a font', () => { icli.catchPrintStart(showStdout); return icli.parse('node script.js cheers -l french -f Binary'.split(' ')) .then(res => { const stdout = icli.catchPrintStop(); assert.ok(stdout.indexOf('language: french') > -1); assert.ok(stdout.indexOf('font: Binary') > -1); assert.ok(stdout.indexOf('01010011 01100001 01101110 01110100 01100101') > -1); }); }); });
Allow synonyms longer than the answer can be (since we may take substrings)
package solver import "cryptics/utils" type transform func(string, int) map[string][]string var TRANSFORMS = map[int]transform{ LIT: func(x string, l int) map[string][]string { return map[string][]string{x: []string{}} }, NULL: func(x string, l int) map[string][]string { return map[string][]string{"": []string{}} }, FIRST: func(x string, l int) map[string][]string { return map[string][]string{string(x[0]): []string{}} }, SYN: func(x string, l int) map[string][]string { if syns, ok := (utils.SYNONYMS)[x]; ok { if l == 0 { panic("Got zero length") } result := map[string][]string{} for _, s := range syns { // if len(s) <= l { result[s] = []string{} // } } return result } return map[string][]string{} }}
package solver import "cryptics/utils" type transform func(string, int) map[string][]string var TRANSFORMS = map[int]transform{ LIT: func(x string, l int) map[string][]string { return map[string][]string{x: []string{}} }, NULL: func(x string, l int) map[string][]string { return map[string][]string{"": []string{}} }, FIRST: func(x string, l int) map[string][]string { return map[string][]string{string(x[0]): []string{}} }, SYN: func(x string, l int) map[string][]string { if syns, ok := (utils.SYNONYMS)[x]; ok { if l == 0 { panic("Got zero length") } result := map[string][]string{} for _, s := range syns { if len(s) <= l { result[s] = []string{} } } return result } return map[string][]string{} }}
Fix tmpdir fixture to remove all the sutff (normally it keeps the last 3, which is a lot).
import os.path import pytest @pytest.yield_fixture def tmpdir(request, tmpdir): try: yield tmpdir finally: tmpdir.remove(ignore_errors=True) def pytest_collection_modifyitems(items): for item in items: module_path = os.path.relpath( item.module.__file__, os.path.commonprefix([__file__, item.module.__file__]), ) module_root_dir = module_path.split(os.sep)[0] if module_root_dir == "functional": item.add_marker(pytest.mark.functional) elif module_root_dir == "unit": item.add_marker(pytest.mark.unit) else: raise RuntimeError( "Unknown test type (filename = {0})".format(module_path) )
import os.path import pytest def pytest_collection_modifyitems(items): for item in items: module_path = os.path.relpath( item.module.__file__, os.path.commonprefix([__file__, item.module.__file__]), ) module_root_dir = module_path.split(os.sep)[0] if module_root_dir == "functional": item.add_marker(pytest.mark.functional) elif module_root_dir == "unit": item.add_marker(pytest.mark.unit) else: raise RuntimeError( "Unknown test type (filename = {0})".format(module_path) )
Include file extension in returned filename
from flask import Flask, render_template, request, jsonify import os app = Flask(__name__) app.config.from_object('config.Debug') @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'GET': return render_template('upload.html') elif request.method == 'POST': file = request.files['file'] if file: filename = os.urandom(30).encode('hex') + '.' + file.filename.split('.')[-1] while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)): filename = os.urandom(30).encode('hex') file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return jsonify(filename=filename) @app.route('/confirm/<filename>/<id>', methods=['POST']) def confirm(filename, id): return '' if __name__ == "__main__": app.run()
from flask import Flask, render_template, request, jsonify import os app = Flask(__name__) app.config.from_object('config.Debug') @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'GET': return render_template('upload.html') elif request.method == 'POST': file = request.files['file'] if file: filename = os.urandom(30).encode('hex') while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)): filename = os.urandom(30).encode('hex') file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return jsonify(filename=filename) @app.route('/confirm/<filename>/<id>', methods=['POST']) def confirm(filename, id): return '' if __name__ == "__main__": app.run()
Fix for multiple tab highlighting
$(document).foundation(); function show(clickId) { var showdiv = document.getElementById(clickId); var tabUl = document.querySelector('.tabs'); var tabs = tabUl.querySelectorAll('.tab-title'); var tabcontentdivs = document.querySelector('.tabs-content'); var tabcontentpanels = tabcontentdivs.querySelectorAll('.content'); for (var j=0;j<tabcontentpanels.length;j++) { var tabClass = tabcontentpanels[j].className; if (tabcontentpanels[j].id == clickId) { if (tabClass.search("active")!=-1){ tabClass=tabClass + ' active'; tabs[j].className=tabs[j].className + ' active'; } } else { tabClass=tabClass.replace('active',""); tabs[j].className=tabs[j].className.replace('active',''); } } }
$(document).foundation(); function show(clickId) { var showdiv = document.getElementById(clickId); var tabUl = document.querySelector('.tabs'); var tabs = tabUl.querySelectorAll('.tab-title'); var tabcontentdivs = document.querySelector('.tabs-content'); var tabcontentpanels = tabcontentdivs.querySelectorAll('.content'); for (var j=0;j<tabcontentpanels.length;j++) { if (tabcontentpanels[j].id == clickId) { tabcontentpanels[j].className=tabcontentpanels[j].className + ' active'; tabs[j].className=tabs[j].className + ' active'; } else { tabcontentpanels[j].className=tabcontentpanels[j].className.replace('active',""); tabs[j].className=tabs[j].className.replace('active',''); } } }
Add public method for getting private hash part
<?php class Kwf_Util_Hash { public static function getPrivatePart() { $salt = Kwf_Cache_SimpleStatic::fetch('hashpp-'); if (!$salt) { if ($salt = Kwf_Config::getValue('hashPrivatePart')) { //defined in config, required if multiple webservers should share the same salt } else { $hashFile = 'cache/hashprivatepart'; if (!file_exists($hashFile)) { file_put_contents($hashFile, time().rand(100000, 1000000)); } $salt = file_get_contents($hashFile); Kwf_Cache_SimpleStatic::add('hashpp-', $salt); } } return $salt; } public static function hash($str) { return md5(self::getPrivatePart().$str); } }
<?php class Kwf_Util_Hash { public static function hash($str) { $salt = Kwf_Cache_SimpleStatic::fetch('hashpp-'); if (!$salt) { if ($salt = Kwf_Config::getValue('hashPrivatePart')) { //defined in config, required if multiple webservers should share the same salt } else { $hashFile = 'cache/hashprivatepart'; if (!file_exists($hashFile)) { file_put_contents($hashFile, time().rand(100000, 1000000)); } $salt = file_get_contents($hashFile); Kwf_Cache_SimpleStatic::add('hashpp-', $salt); } } return md5($salt.$str); } }
Set stroke width to 0
function WorldView(world, paper) { this.world = world; this.paper = paper; this.cellSize = 16; this.world.observe(this); } WorldView.prototype.paintLiveCell = function(cell) { this.paintCell(cell, "#222"); }; WorldView.prototype.paintDeadCell = function(cell) { this.paintCell(cell, "#fff"); }; WorldView.prototype.paintCell = function(cell, color) { var x = cell[0] * this.cellSize, y = cell[1] * this.cellSize, cellView = this.paper.rect(x, y, this.cellSize, this.cellSize); cellView.attr("fill", color); cellView.attr("stroke-width", 0); }; WorldView.prototype.notify = function(event) { if (event.eventName === "reviveCell") { this.paintLiveCell(event.cell); } else if (event.eventName === "killCell") { this.paintDeadCell(event.cell); } };
function WorldView(world, paper) { this.world = world; this.paper = paper; this.cellSize = 16; this.world.observe(this); } WorldView.prototype.paintLiveCell = function(cell) { this.paintCell(cell, "#222"); }; WorldView.prototype.paintDeadCell = function(cell) { this.paintCell(cell, "#fff"); }; WorldView.prototype.paintCell = function(cell, color) { var x = cell[0] * this.cellSize, y = cell[1] * this.cellSize, cellView = this.paper.rect(x, y, this.cellSize, this.cellSize); cellView.attr("fill", color); }; WorldView.prototype.notify = function(event) { if (event.eventName === "reviveCell") { this.paintLiveCell(event.cell); } else if (event.eventName === "killCell") { this.paintDeadCell(event.cell); } };
Remove reference in docs to removed function.
#! /usr/bin/env python """Functions on iterators, optimised for case when iterators are sorted. """ import itertools import iterators def partition_o(left_function, items): """Return a pair of iterators: left and right Items for which left_function returns a true value go into left. Items for which left_function returns a false value go into right. Items must be sorted such that left_function may be true for an initial set of items, but once an item is found such that left_function(item) is false, it will remain false for the rest of the items. In other words the following must hold: for all N where 0 <= N < (len(items) - 1) : not(func(item[n])) => not(func(item[n+1])) For example lambda x: x < 3 is a valid function for [1,2,3,4,5], but not for [1,3,4,2,5]. >>> (left, right) = partition_o(lambda x: x < 3, [-1, 0, 2, 3, 4, 5]) >>> list(left) [-1, 0, 2] >>> list(right) [3, 4, 5] """ left = itertools.takewhile(left_function, items) right = itertools.dropwhile(left_function, items) return left, right if __name__ == "__main__": import doctest doctest.testmod()
#! /usr/bin/env python """Functions on iterators, optimised for case when iterators are sorted. Note sift_o is hidden as _sift_o at the moment because it is broken. Please don't use it. Once fixed, I'll remove the leading underscore again. """ import itertools import iterators def partition_o(left_function, items): """Return a pair of iterators: left and right Items for which left_function returns a true value go into left. Items for which left_function returns a false value go into right. Items must be sorted such that left_function may be true for an initial set of items, but once an item is found such that left_function(item) is false, it will remain false for the rest of the items. In other words the following must hold: for all N where 0 <= N < (len(items) - 1) : not(func(item[n])) => not(func(item[n+1])) For example lambda x: x < 3 is a valid function for [1,2,3,4,5], but not for [1,3,4,2,5]. >>> (left, right) = partition_o(lambda x: x < 3, [-1, 0, 2, 3, 4, 5]) >>> list(left) [-1, 0, 2] >>> list(right) [3, 4, 5] """ left = itertools.takewhile(left_function, items) right = itertools.dropwhile(left_function, items) return left, right if __name__ == "__main__": import doctest doctest.testmod()
Make sure info.nick is always set
'use strict'; module.exports = function(config, ircbot) { ircbot.addListener('raw', function(message) { switch (message.command) { case 'rpl_whoisidle': ircbot._addWhoisData(message.args[1], 'signon', new Date(parseInt(message.args[3]) * 1000)); break; case '338': ircbot._addWhoisData(message.args[1], 'actual_host', message.args[2]); break; case '671': ircbot._addWhoisData(message.args[1], 'secure_connection', true); break; } }); ircbot.constructor.prototype.remoteWhois = function(nick, callback) { if (typeof callback === 'function') { var callbackWrapper = function(info) { let whoisNick = ''; try { whoisNick = info.nick.toLowerCase(); } catch (e) {} if (whoisNick == nick.toLowerCase()) { this.removeListener('whois', callbackWrapper); return callback.apply(this, arguments); } }; this.addListener('whois', callbackWrapper); } this.send('WHOIS', nick, nick); }; };
'use strict'; module.exports = function(config, ircbot) { ircbot.addListener('raw', function(message) { switch (message.command) { case 'rpl_whoisidle': ircbot._addWhoisData(message.args[1], 'signon', new Date(parseInt(message.args[3]) * 1000)); break; case '338': ircbot._addWhoisData(message.args[1], 'actual_host', message.args[2]); break; case '671': ircbot._addWhoisData(message.args[1], 'secure_connection', true); break; } }); ircbot.constructor.prototype.remoteWhois = function(nick, callback) { if (typeof callback === 'function') { var callbackWrapper = function(info) { if (info.nick.toLowerCase() == nick.toLowerCase()) { this.removeListener('whois', callbackWrapper); return callback.apply(this, arguments); } }; this.addListener('whois', callbackWrapper); } this.send('WHOIS', nick, nick); }; };
Use test server with methods
package dk.statsbiblioteket.doms.central.connectors.fedora.methods; import dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest; import dk.statsbiblioteket.doms.central.connectors.fedora.methods.generated.Method; import dk.statsbiblioteket.doms.webservices.authentication.Credentials; import java.util.List; import static org.junit.Assert.assertTrue; /** * Created with IntelliJ IDEA. * User: abr * Date: 9/13/12 * Time: 11:30 AM * To change this template use File | Settings | File Templates. */ public class MethodsImplTest { @org.junit.Test public void testGetMethods() throws Exception { MethodsImpl methods = new MethodsImpl(new FedoraRest(new Credentials("fedoraAdmin", "fedoraAdminPass"), "http://alhena:7880/fedora"),""); List<Method> methodList = methods.getStaticMethods("doms:ContentModel_VHSFile"); assertTrue("no methods!",methodList.size() > 0); } }
package dk.statsbiblioteket.doms.central.connectors.fedora.methods; import dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest; import dk.statsbiblioteket.doms.central.connectors.fedora.methods.generated.Method; import dk.statsbiblioteket.doms.webservices.authentication.Credentials; import java.util.List; import static org.junit.Assert.assertTrue; /** * Created with IntelliJ IDEA. * User: abr * Date: 9/13/12 * Time: 11:30 AM * To change this template use File | Settings | File Templates. */ public class MethodsImplTest { @org.junit.Test public void testGetMethods() throws Exception { MethodsImpl methods = new MethodsImpl(new FedoraRest(new Credentials("fedoraAdmin", "fedoraAdminPass"), "http://alhena:7780/fedora"),""); List<Method> methodList = methods.getStaticMethods("doms:ContentModel_VHSFile"); assertTrue("no methods!",methodList.size() > 0); } }
Allow Endpoint JMX export to be switched off
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.autoconfigure; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jmx.export.MBeanExporter; /** * {@link EnableAutoConfiguration Auto-configuration} to enable JMX export for * {@link Endpoint}s. * * @author Christian Dupuis */ @Configuration @ConditionalOnBean({ MBeanExporter.class }) @AutoConfigureAfter({ EndpointAutoConfiguration.class }) @ConditionalOnExpression("${endpoints.jmx.enabled:true}") class EndpointMBeanExportAutoConfiguration { @Bean public EndpointMBeanExporter endpointMBeanExporter() { // TODO add configuration for domain name return new EndpointMBeanExporter(); } }
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.autoconfigure; import org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jmx.export.MBeanExporter; @Configuration @ConditionalOnBean({ MBeanExporter.class }) @AutoConfigureAfter({ EndpointAutoConfiguration.class }) class EndpointMBeanExportAutoConfiguration { @Bean public EndpointMBeanExporter endpointMBeanExporter() { return new EndpointMBeanExporter(); } }
Set middleware setting according to Django version in test settings Django 1.10 introduced new-style middleware and the corresponding MIDDLEWARE setting and deprecated MIDDLEWARE_CLASSES. The latter is ignored on Django 2.
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command TEST_SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, 'ALLOWED_HOSTS': [ 'testserver', ], 'INSTALLED_APPS': [ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], 'PERMISSIONS': { 'allow_staff': False, }, 'ROOT_URLCONF': 'permissions.tests.urls', 'TEMPLATES': [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], 'TEST_RUNNER': 'django.test.runner.DiscoverRunner', } if django.VERSION < (1, 10): TEST_SETTINGS['MIDDLEWARE_CLASSES'] = [] else: TEST_SETTINGS['MIDDLEWARE'] = [] settings.configure(**TEST_SETTINGS) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ALLOWED_HOSTS=[ 'testserver', ], INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], MIDDLEWARE_CLASSES=[], PERMISSIONS={ 'allow_staff': False, }, ROOT_URLCONF='permissions.tests.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], TEST_RUNNER='django.test.runner.DiscoverRunner', ) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
Reset the handle when it is already defined Signed-off-by: Stéphane HULARD <a24f38cb8c57ec2778c80a9f0c151933508927e5@chstudio.fr>
<?php /** * This file is part of the bee4/transport package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright Bee4 2014 * @author Stephane HULARD <s.hulard@chstudio.fr> * @package Bee4\Transport\Handle */ namespace Bee4\Transport\Handle; use Bee4\Transport\Message\Request\AbstractRequest; /** * Handle factory * @package Bee4\Transport\Handle */ class HandleFactory { /** * List of already loaded handles * @var array */ private static $loaded = []; /** * Build the Handle instance based on the given request * @param AbstractRequest $request * @return HandleInterface */ public static function build( AbstractRequest $request ) { $name = get_class($request); if( !isset(self::$loaded[$name]) ) { self::$loaded[$name] = new CurlHandle(); } else { self::$loaded[$name]->reset(); } self::$loaded[$name]->addOptions($request->getOptions()); return self::$loaded[$name]; } }
<?php /** * This file is part of the bee4/transport package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright Bee4 2014 * @author Stephane HULARD <s.hulard@chstudio.fr> * @package Bee4\Transport\Handle */ namespace Bee4\Transport\Handle; use Bee4\Transport\Message\Request\AbstractRequest; /** * Handle factory * @package Bee4\Transport\Handle */ class HandleFactory { /** * List of already loaded handles * @var array */ private static $loaded = []; /** * Build the Handle instance based on the given request * @param AbstractRequest $request * @return HandleInterface */ public static function build( AbstractRequest $request ) { $name = get_class($request); if( !isset(self::$loaded[$name]) ) { self::$loaded[$name] = new CurlHandle(); } self::$loaded[$name]->addOptions($request->getOptions()); return self::$loaded[$name]; } }
Update unit tests to reflect new routing.
<?php class C00_Station_ProfileCest extends CestAbstract { /** * @before setupComplete * @before login */ public function editStationProfile(FunctionalTester $I) { $I->wantTo('View and edit a station profile.'); $station_id = $this->test_station->getId(); $I->amOnPage('/station/'.$station_id.'/profile'); $I->see('Functional Test Radio'); $I->wantTo('Edit a station profile.'); $I->click('.btn-float'); // Plus sign $I->seeCurrentUrlEquals('/station/'.$station_id.'/profile/edit'); $I->submitForm('.form', [ 'name' => 'Profile Update Test Radio', 'description' => 'Testing a profile update.', ]); $I->seeCurrentUrlEquals('/station/'.$station_id.'/profile'); $I->see('Profile Update Test Radio'); $I->see('Testing a profile update.'); } }
<?php class C00_Station_ProfileCest extends CestAbstract { /** * @before setupComplete * @before login */ public function editStationProfile(FunctionalTester $I) { $I->wantTo('View and edit a station profile.'); $station_id = $this->test_station->getId(); $I->amOnPage('/station/'.$station_id); $I->see('Functional Test Radio'); $I->wantTo('Edit a station profile.'); $I->click('.btn-float'); // Plus sign $I->seeCurrentUrlEquals('/station/'.$station_id.'/profile/edit'); $I->submitForm('.form', [ 'name' => 'Profile Update Test Radio', 'description' => 'Testing a profile update.', ]); $I->seeCurrentUrlEquals('/station/'.$station_id); $I->see('Profile Update Test Radio'); $I->see('Testing a profile update.'); } }
Fix wrong links when listing multiple apps
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var angular = require('angular'); module.exports = function ($state, $q) { 'ngInject'; var views = []; this.register = function (view) { views.push(view); }; this.getApplicationViews = function (application) { var applicationViews = []; views.forEach(function (view) { $q.when(!view.show || view.show(application)).then(function (result) { if (result) { var appView = angular.copy(view); appView.href = $state.href(view.state, { id: application.id }); applicationViews.push(appView); applicationViews.sort(function (v1, v2) { return (v1.order || 0) - (v2.order || 0); }); } }); }); return applicationViews; }; };
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; module.exports = function ($state, $q) { 'ngInject'; var views = []; this.register = function (view) { views.push(view); }; this.getApplicationViews = function (application) { var applicationViews = []; views.forEach(function (view) { $q.when(!view.show || view.show(application)).then(function (result) { if (result) { view.href = $state.href(view.state, { id: application.id }); applicationViews.push(view); applicationViews.sort(function (v1, v2) { return (v1.order || 0) - (v2.order || 0); }); } }); }); return applicationViews; }; };
Add skip for records where geometry is too large for ES to handle
var Transform = require('stream').Transform, geoJsonCenter = require('../../lib/geoJsonCenter'), mapper = new Transform({ objectMode: true }); mapper._write = function( data, enc, next ){ try { // Skip records where geometry is too large for ES to process if( data.geometry.coordinates.length > 1000 ){ throw new Error( 'SKIPPING RECORD - COORDS LENGTH" ' + data.geometry.coordinates.length ); } this.push({ _index: 'pelias', _type: 'locality', _id: data.properties.qs_loc_lc, data: { gn_id: data.properties.gs_gn_id || '', woe_id: data.properties.woe_id || '', boundaries: data.geometry, center_point: geoJsonCenter( data.geometry ), suggest: data.properties.qs_loc } }); } catch( e ) { console.error( e ); // console.log( JSON.stringify( data.geometry, null, 2 ) ); } next(); } module.exports = mapper;
var Transform = require('stream').Transform, geoJsonCenter = require('../../lib/geoJsonCenter'), mapper = new Transform({ objectMode: true }); mapper._write = function( data, enc, next ){ try { this.push({ _index: 'pelias', _type: 'locality', _id: data.properties.qs_loc_lc, data: { gn_id: data.properties.gs_gn_id || '', woe_id: data.properties.woe_id || '', boundaries: data.geometry, center_point: geoJsonCenter( data.geometry ), suggest: data.properties.qs_loc } }); } catch( e ) { console.error( e ); // console.log( JSON.stringify( data.geometry, null, 2 ) ); } next(); } module.exports = mapper;
Update regex and path resolution for test image files.
var path = require('path'); var fs = require('fs'); var mimetypes = { '.gif': 'image/gif', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.jpe': 'image/jpeg', '.png': 'image/png' }; var encode = function( filePath ) { return new Buffer(fs.readFileSync(filePath)).toString('base64'); }; module.exports = function( inputText, inputName, outputName ) { if (!inputText || !inputName) { return inputText; } var transformedText = inputText, regex = /url\((?:\\?['"])?([\w\/\\._-]*?)([\w-_]+\.\w{3,4})\\?['"]?\)/g, // capture group $1 (path) // capture group $2 (filename) found = inputText.match(regex); if (found) { transformedText = inputText.replace(regex, function( match, filePath, fileName ) { var fullPath = path.resolve('test/assets/' + filePath + fileName), prefix = 'data:' + mimetypes[path.extname(fileName.toLowerCase())] + ';base64,', falseFind = match.charAt === '#'; var encodedFile = encode(fullPath); return falseFind ? match : 'url(' + prefix + encodedFile + ')'; }); } return transformedText; };
var path = require('path'); var fs = require('fs'); var mimetypes = { '.gif': 'image/gif', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.jpe': 'image/jpeg', '.png': 'image/png', '.bmp': 'image/bmp' }; var encode = function( filePath ) { return new Buffer(fs.readFileSync(filePath)).toString('base64'); }; module.exports = function( inputText, inputName ) { var transformedText = inputText, regex = /url\((?:\\?['"])?(.*?)([\w-_]+\.\w{3,4})\\?['"]?\)/g, found = inputText.match(regex); if (found) { transformedText = inputText.replace(regex, function( match, cg1, cg2 ) { // cg1 = capture group $1 (path) // cg2 = capture group $2 (filename) var filePath = path.dirname(inputName) + '/' + (cg1 ? cg1 : '') + cg2, prefix = 'data:' + mimetypes[path.extname(cg2)] + ';base64,'; return 'url(' + prefix + encode(filePath) + ')'; }); } return transformedText; };
Include php tag after processing stub for generators
<?php namespace Layla\Module\Generators; use Illuminate\Support\Facades\Blade; class Generator { /** * The blueprint to use * * @var \Layla\Module\Blueprints\Blueprint */ protected $blueprint; /** * Location of the stub * * @var string */ protected $stub; /** * Create a new Generator instance * * @param Blueprint $blueprint */ public function __construct(Blueprint $blueprint) { $this->blueprint = $blueprint; } /** * Generate the file * * @return boolean Could we save it? */ public function generate() { $result = $this->generateString(); $destination = $this->blueprint->getDestination(); $pathInfo = pathinfo($destination); $directory = $pathInfo['dirname']; // try to make sure that the destination exists @mkdir($directory, 0755, true); // store the result return file_put_contents($destination, $result); } /** * Get the generated string * * @return string */ public function generateString() { $blueprint = $this->blueprint; $destination = $blueprint->getDestination(); $data = $blueprint->getAttributes(); $data = array_merge($data, compact('blueprint', 'destination')); return '<?php'.eval_blade(layla_module_stubs_path().$this->stub, $data); } }
<?php namespace Layla\Module\Generators; use Illuminate\Support\Facades\Blade; class Generator { /** * The blueprint to use * * @var \Layla\Module\Blueprints\Blueprint */ protected $blueprint; /** * Location of the stub * * @var string */ protected $stub; /** * Create a new Generator instance * * @param Blueprint $blueprint */ public function __construct(Blueprint $blueprint) { $this->blueprint = $blueprint; } /** * Generate the file * * @return boolean Could we save it? */ public function generate() { $result = $this->generateString(); $destination = $this->blueprint->getDestination(); $pathInfo = pathinfo($destination); $directory = $pathInfo['dirname']; // try to make sure that the destination exists @mkdir($directory, 0755, true); // store the result return file_put_contents($destination, $result); } /** * Get the generated string * * @return string */ public function generateString() { $blueprint = $this->blueprint; $destination = $blueprint->getDestination(); $data = $blueprint->getAttributes(); $data = array_merge($data, compact('blueprint', 'destination')); return eval_blade(layla_module_stubs_path().$this->stub, $data); } }
Add advanced svgo plugins option example Example : disable the straightCurve simplification for the convertPathData plugin.
'use strict'; module.exports = function (grunt) { grunt.initConfig({ svgmin: { compile: { files: { 'test/tmp/test.svg': 'test/fixtures/test.svg' } }, withconfig: { options: { plugins: [ {removeViewBox: false}, {convertPathData: { straightCurves:false }} // Advanced svgo plugin option ] }, files: { 'test/tmp/withconfig.svg': 'test/fixtures/test.svg' } }, multiple: { files: [{ expand:true, cwd: 'test/fixtures/', src: ['**/*.svg'], // Actual pattern(s) to match. dest: 'test/tmp/' }] } }, simplemocha: { test: { src: 'test/*.js' } }, clean: { test: ['test/tmp'] } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-simple-mocha'); grunt.registerTask('default', ['clean', 'svgmin', 'simplemocha', 'clean']); };
'use strict'; module.exports = function (grunt) { grunt.initConfig({ svgmin: { compile: { files: { 'test/tmp/test.svg': 'test/fixtures/test.svg' } }, withconfig: { options: { plugins: [{ removeViewBox: false }] }, files: { 'test/tmp/withconfig.svg': 'test/fixtures/test.svg' } }, multiple: { files: [{ expand:true, cwd: 'test/fixtures/', src: ['**/*.svg'], // Actual pattern(s) to match. dest: 'test/tmp/' }] } }, simplemocha: { test: { src: 'test/*.js' } }, clean: { test: ['test/tmp'] } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-simple-mocha'); grunt.registerTask('default', ['clean', 'svgmin', 'simplemocha', 'clean']); };
Fix errors due to quotes and parenthesis in reading
import requests from bs4 import BeautifulSoup from SenseCells.tts import tts # NDTV News fixed_url = 'http://profit.ndtv.com/news/latest/' news_headlines_list = [] news_details_list = [] for i in range(1, 2): changing_slug = '/page-' + str(i) url = fixed_url + changing_slug r = requests.get(url) data = r.text soup = BeautifulSoup(data, "html.parser") for news_headlines in soup.find_all('h2'): news_headlines_list.append(news_headlines.get_text()) del news_headlines_list[-2:] for news_details in soup.find_all('p', 'intro'): news_details_list.append(news_details.get_text()) news_headlines_list_small = [element.lower().replace("(", "").replace(")", "").replace("'", "") for element in news_headlines_list] news_details_list_small = [element.lower().replace("(", "").replace(")", "").replace("'", "") for element in news_details_list] news_dictionary = dict(zip(news_headlines_list_small, news_details_list_small)) def news_reader(): for key, value in news_dictionary.items(): tts('Headline, ' + key) tts('News, ' + value)
import json import requests from bs4 import BeautifulSoup from SenseCells.tts import tts # NDTV News fixed_url = 'http://profit.ndtv.com/news/latest/' news_headlines_list = [] news_details_list = [] for i in range(1, 2): changing_slug = '/page-' + str(i) url = fixed_url + changing_slug r = requests.get(url) data = r.text soup = BeautifulSoup(data, "html.parser") for news_headlines in soup.find_all('h2'): news_headlines_list.append(news_headlines.get_text()) del news_headlines_list[-2:] for news_details in soup.find_all('p', 'intro'): news_details_list.append(news_details.get_text()) news_headlines_list_small = [element.lower() for element in news_headlines_list] news_details_list_small = [element.lower() for element in news_details_list] news_dictionary = dict(zip(news_headlines_list_small, news_details_list_small)) def news_reader(): for key, value in news_dictionary.items(): tts('Headline, ' + key) tts('News, ' + value)
[PLAT-1734] Check for a null calc config and fail gracefully
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.volatility.surface; import java.util.Set; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.view.ViewCalculationConfiguration; import com.opengamma.financial.property.DefaultPropertyFunction; /** * Function to shift a volatility surface, implemented using properties and constraints. */ public class DefaultVolatilitySurfaceShiftFunction extends DefaultPropertyFunction { /** * Property to shift all volatility surfaces. */ protected static final String VOLATILITY_SURFACE_SHIFT = "VOLATILITY_SURFACE_" + VolatilitySurfaceShiftFunction.SHIFT; public DefaultVolatilitySurfaceShiftFunction() { super(ComputationTargetType.SECURITY, VolatilitySurfaceShiftFunction.SHIFT, ValueRequirementNames.VOLATILITY_SURFACE); } @Override protected Set<String> getDefaultValue(FunctionCompilationContext context, ComputationTarget target, ValueRequirement desiredValue) { final ViewCalculationConfiguration config = context.getViewCalculationConfiguration(); if (config != null) { return config.getDefaultProperties().getValues(VOLATILITY_SURFACE_SHIFT); } else { return null; } } }
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.volatility.surface; import java.util.Set; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.financial.property.DefaultPropertyFunction; /** * Function to shift a volatility surface, implemented using properties and constraints. */ public class DefaultVolatilitySurfaceShiftFunction extends DefaultPropertyFunction { /** * Property to shift all volatility surfaces. */ protected static final String VOLATILITY_SURFACE_SHIFT = "VOLATILITY_SURFACE_" + VolatilitySurfaceShiftFunction.SHIFT; public DefaultVolatilitySurfaceShiftFunction() { super(ComputationTargetType.SECURITY, VolatilitySurfaceShiftFunction.SHIFT, ValueRequirementNames.VOLATILITY_SURFACE); } @Override protected Set<String> getDefaultValue(FunctionCompilationContext context, ComputationTarget target, ValueRequirement desiredValue) { return context.getViewCalculationConfiguration().getDefaultProperties().getValues(VOLATILITY_SURFACE_SHIFT); } }
Test get and set next node
package com.mijecu25.dsa; import org.junit.Assert; import org.junit.Test; /** * This is the Node test class. * * @author Miguel Velez * @version 0.3 * */ public class TestNode { Node first = new Node(6, null); Node second = new Node("Dog", null); /** * Test the node constructor. */ @Test public void TestNodeConstructor() { // Check if they are the same class Assert.assertSame(Node.class, this.first.getClass()); // Check if they are the same class Assert.assertNotSame(String.class, this.first.getClass()); } /** * Test the get data method. */ @Test public void TestGetData() { // Checking if we get the same data back Assert.assertEquals(6, this.first.getData()); // Check if we do not get the same data back Assert.assertNotEquals(5, this.first.getData()); } /** * Test the get next method */ @Test public void TestSetGetNext() { // Set second as first's next first.setNext(second); // Check if the next node is the second node Assert.assertEquals(second, first.getNext()); // Check if that the next node of second is not first Assert.assertNotEquals(first, second.getNext()); } }
package com.mijecu25.dsa; import org.junit.Assert; import org.junit.Test; /** * This is the Node test class. * * @author Miguel Velez * @version 0.2.1 * */ public class TestNode { Node node = new Node(6, null); /** * Test the node constructor. */ @Test public void TestNodeConstructor() { // Check if they are the same class Assert.assertSame(Node.class, this.node.getClass()); // Check if they are the same class Assert.assertNotSame(String.class, this.node.getClass()); } /** * Test the get data method. */ @Test public void TestGetData() { // Checking if we get the same data back Assert.assertEquals(6, this.node.getData()); // Check if we do not get the same data back Assert.assertNotEquals(5, this.node.getData()); } }