text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use logging levels to suppress non-error output with --quiet on the CLI.
# -*- coding: utf-8 -*- import logging import os import argparse from markdoc.cli import commands from markdoc.cli.parser import parser from markdoc.config import Config, ConfigNotFound def main(cmd_args=None): """The main entry point for running the Markdoc CLI.""" if cmd_args is not None: args = parser.parse_args(cmd_args) else: args = parser.parse_args() if args.command != 'init': try: args.config = os.path.abspath(args.config) if os.path.isdir(args.config): config = Config.for_directory(args.config) elif os.path.isfile(args.config): config = Config.for_file(args.config) else: raise ConfigNotFound("Couldn't locate Markdoc config.") except ConfigNotFound, exc: parser.error(str(exc)) else: config = None if args.quiet: logging.getLogger('markdoc').setLevel(logging.ERROR) command = getattr(commands, args.command.replace('-', '_')) return command(config, args) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import os import argparse from markdoc.cli import commands from markdoc.cli.parser import parser from markdoc.config import Config, ConfigNotFound def main(cmd_args=None): """The main entry point for running the Markdoc CLI.""" if cmd_args is not None: args = parser.parse_args(cmd_args) else: args = parser.parse_args() if args.command != 'init': try: args.config = os.path.abspath(args.config) if os.path.isdir(args.config): config = Config.for_directory(args.config) elif os.path.isfile(args.config): config = Config.for_file(args.config) else: raise ConfigNotFound("Couldn't locate Markdoc config.") except ConfigNotFound, exc: parser.error(str(exc)) else: config = None command = getattr(commands, args.command.replace('-', '_')) return command(config, args) if __name__ == '__main__': main()
Fix Twisted requirement (I think?)
#!/usr/bin/env python2.6 try: from setuptools import setup except: from distutils.core import setup def getVersion(): import os packageSeedFile = os.path.join("lib", "_version.py") ns = {"__name__": __name__, } execfile(packageSeedFile, ns) return ns["version"] version = getVersion() setup( name = version.package, version = version.short(), description = "Pub Client and Service", long_description = "Pub key management service and client", author = "Oliver Gould", author_email = "ver@yahoo-inc.com", maintainer = "Oliver Gould", maintainer_email = "ver@yahoo-inc.com", requires = ["jersey", "Twisted", "pendrell>=0.3.0", ], packages = ["pub", "pub.cases", "pub.client", "twisted.plugins", ], scripts = ["bin/jget", "bin/pubc", ], package_dir = {"pub": "lib", }, package_data = {"twisted.plugins": ["pubs.py"], }, )
#!/usr/bin/env python2.6 try: from setuptools import setup except: from distutils.core import setup def getVersion(): import os packageSeedFile = os.path.join("lib", "_version.py") ns = {"__name__": __name__, } execfile(packageSeedFile, ns) return ns["version"] version = getVersion() setup( name = version.package, version = version.short(), description = "Pub Client and Service", long_description = "Pub key management service and client", author = "Oliver Gould", author_email = "ver@yahoo-inc.com", maintainer = "Oliver Gould", maintainer_email = "ver@yahoo-inc.com", requires = ["jersey", "twisted", "twisted.conch", "pendrell(>=0.2.0)", ], packages = ["pub", "pub.cases", "pub.client", "twisted.plugins", ], scripts = ["bin/jget", "bin/pubc", ], package_dir = {"pub": "lib", }, package_data = {"twisted.plugins": ["pubs.py"], }, )
Remove describe only test switch
/* jshint mocha: true */ 'use strict'; const assert = require('assert'); const gitter = require('../lib/gitter'); const jsonist = require('jsonist'); let nodes; let post = jsonist.post; beforeEach(function() { jsonist.post = function() {}; nodes = [ { name: 'foo', offline: true, },{ name: 'bar', offline: false, } ]; }); afterEach(function() { jsonist.post = post; }); describe('gitter', function() { it('posts nodes to gitter', function(done) { let i = 0; const level = ['error', 'success']; jsonist.post = function(url, data, opts, cb) { assert.equal(url, process.env.GITTER_WEBHOOK_URL); assert.equal(typeof data.message, 'string'); assert.equal(data.level, level[i++]); cb(null, { success: true }, {}); }; gitter.post(nodes, done); }); it('returns any errors', function(done) { jsonist.post = function(url, data, opts, cb) { cb(new Error('I am borked')); }; gitter.post(nodes, function(err) { assert(/I am borked/.test(err)); done(); }); }); });
/* jshint mocha: true */ 'use strict'; const assert = require('assert'); const gitter = require('../lib/gitter'); const jsonist = require('jsonist'); let nodes; let post = jsonist.post; beforeEach(function() { jsonist.post = function() {}; nodes = [ { name: 'foo', offline: true, },{ name: 'bar', offline: false, } ]; }); afterEach(function() { jsonist.post = post; }); describe.only('gitter', function() { it('posts nodes to gitter', function(done) { let i = 0; const level = ['error', 'success']; jsonist.post = function(url, data, opts, cb) { assert.equal(url, process.env.GITTER_WEBHOOK_URL); assert.equal(typeof data.message, 'string'); assert.equal(data.level, level[i++]); cb(null, { success: true }, {}); }; gitter.post(nodes, done); }); it('returns any errors', function(done) { jsonist.post = function(url, data, opts, cb) { cb(new Error('I am borked')); }; gitter.post(nodes, function(err) { assert(/I am borked/.test(err)); done(); }); }); });
Change another options log from info to debug
/** * Copyright 2013-2020 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see https://www.jhipster.tech/ * for more information. * * 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. */ const chalk = require('chalk'); const packageJson = require('../package.json'); const { logger, toString, getCommandOptions, doneFactory } = require('./utils'); const EnvironmentBuilder = require('./environment-builder'); const env = EnvironmentBuilder.createDefaultBuilder().getEnvironment(); const command = process.argv[2]; const options = getCommandOptions(packageJson, process.argv.slice(3)); logger.info(chalk.yellow(`Executing ${command} on ${process.cwd()}`)); logger.debug(chalk.yellow(`Options: ${toString(options)}`)); try { env.run(command, options, doneFactory()); } catch (e) { logger.error(e.message, e); process.exitCode = 1; }
/** * Copyright 2013-2020 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see https://www.jhipster.tech/ * for more information. * * 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. */ const chalk = require('chalk'); const packageJson = require('../package.json'); const { logger, toString, getCommandOptions, doneFactory } = require('./utils'); const EnvironmentBuilder = require('./environment-builder'); const env = EnvironmentBuilder.createDefaultBuilder().getEnvironment(); const command = process.argv[2]; const options = getCommandOptions(packageJson, process.argv.slice(3)); logger.info(chalk.yellow(`Executing ${command} on ${process.cwd()}`)); logger.info(chalk.yellow(`Options: ${toString(options)}`)); try { env.run(command, options, doneFactory()); } catch (e) { logger.error(e.message, e); process.exitCode = 1; }
Improve live region behaviour with JAWS / IE
define(['jquery'], function ($) { return { createLiveRegion: function() { var $liveRegionContainer = $('.live-region-container'); if ($liveRegionContainer.length === 0) { return $('<div class="visuallyhidden live-region-container" aria-live="assertive" role="alert"></div>').appendTo('body'); } else { return $liveRegionContainer; } }, /** * @param text - text to update with * @param {jQuery} [$liveRegionContainer] should be a container element with aria-live="assertive" */ updateLiveRegion: function(text, $liveRegionContainer) { if (!$liveRegionContainer || !$liveRegionContainer.length) { $liveRegionContainer = this.createLiveRegion(); } $liveRegionContainer .empty() .html(text); // using html instead of text seems to work better with JAWS } }; });
define(['jquery'], function ($) { return { createLiveRegion: function() { var $liveRegionContainer = $('.live-region-container'); if ($liveRegionContainer.length === 0) { return $('<div class="visuallyhidden live-region-container" aria-live="polite"></div>').appendTo('body'); } else { return $liveRegionContainer; } }, /** * @param text - text to update with * @param {jQuery} [$liveRegionContainer] should be a container element with aria-live="assertive" */ updateLiveRegion: function(text, $liveRegionContainer) { if (!$liveRegionContainer || !$liveRegionContainer.length) { $liveRegionContainer = this.createLiveRegion(); } $liveRegionContainer.empty(); $liveRegionContainer.text(text); } }; });
Fix bug where column the function was being called, rather than class
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.DateTime) author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relations" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) class User(Base): __tablename__ = "users" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) username = sqlalchemy.Column(sqlalchemy.String) password = sqlalchemy.Column(sqlalchemy.String) can_change_settings = sqlalchemy.Column(sqlalchemy.Boolean) can_write_posts = sqlalchemy.Column(sqlalchemy.Boolean) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.DateTime) author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relations" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) class User(Base): __tablename__ = "users" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) username = sqlalchemy.Column(sqlalchemy.String) password = sqlalchemy.Column(sqlalchemy.String) can_change_settings = sqlalchemy.column(sqlalchemy.Boolean) can_write_posts = sqlalchemy.column(sqlalchemy.Boolean) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
Add env browser for browser globals support
const baseRules = [ 'eslint:recommended', ].concat([ '../src/rules/ava', '../src/rules/best-practices', '../src/rules/errors', '../src/rules/es6', '../src/rules/imports', '../src/rules/jsdoc', '../src/rules/node', '../src/rules/react', '../src/rules/strict', '../src/rules/style', '../src/rules/variables', ].map(require.resolve)) module.exports = { parser: 'babel-eslint', env: { node: true, browser: true, }, extends: baseRules, parserOptions: { ecmaVersion: 7, sourceType: 'module', }, }
const baseRules = [ 'eslint:recommended', ].concat([ '../src/rules/ava', '../src/rules/best-practices', '../src/rules/errors', '../src/rules/es6', '../src/rules/imports', '../src/rules/jsdoc', '../src/rules/node', '../src/rules/react', '../src/rules/strict', '../src/rules/style', '../src/rules/variables', ].map(require.resolve)) module.exports = { parser: 'babel-eslint', env: { node: true }, extends: baseRules, parserOptions: { ecmaVersion: 7, sourceType: 'module', } }
Implement both classes in the wp facade
<?php if ( ! function_exists( 'whip_wp_check_versions' ) ) { /** * Facade to quickly check if version requirements are met. * * @param array $requirements The requirements to check. */ function whip_wp_check_versions( $requirements ) { // Only show for admin users. if ( ! is_array( $requirements ) ) { return; } $config = include dirname( __FILE__ ) . '/../configs/default.php'; $checker = new Whip_RequirementsChecker( $config ); $dismisser = new Whip_WPMessageDismisser(); $dismisser->listen(); $dismissedOption = $dismisser->getDismissed(); if ( $dismissedOption ) { $requirementsFilter = new Whip_RequirementsFilter( time() + MONTH_IN_SECONDS, $requirements ); $requirements = $requirementsFilter->filter( $dismissedOption ); } foreach ( $requirements as $component => $versionComparison ) { $checker->addRequirement( Whip_VersionRequirement::fromCompareString( $component, $versionComparison ) ); } $checker->check(); if ( ! $checker->hasMessages() ) { return; } $presenter = new Whip_WPMessagePresenter( $checker->getMostRecentMessage() ); $presenter->register_hooks(); } }
<?php if ( ! function_exists( 'whip_wp_check_versions' ) ) { /** * Facade to quickly check if version requirements are met. * * @param array $requirements The requirements to check. */ function whip_wp_check_versions( $requirements ) { // Only show for admin users. if ( ! is_array( $requirements ) ) { return; } $config = include dirname( __FILE__ ) . '/../configs/default.php'; $checker = new Whip_RequirementsChecker( $config ); foreach ( $requirements as $component => $versionComparison ) { $checker->addRequirement( Whip_VersionRequirement::fromCompareString( $component, $versionComparison ) ); } $checker->check(); if ( ! $checker->hasMessages() ) { return; } $presenter = new Whip_WPMessagePresenter( $checker->getMostRecentMessage() ); $presenter->register_hooks(); } }
Fix up webcam texture now that it works
package com.haxademic.app.haxmapper.textures; import com.haxademic.core.app.P; import com.haxademic.core.debug.DebugUtil; import processing.video.Capture; public class TextureWebCam extends BaseTexture { protected Capture _webCam; public TextureWebCam( int width, int height ) { super(); buildGraphics( width, height ); initWebCam(); } void initWebCam() { String[] cameras = Capture.list(); if (cameras.length == 0) { DebugUtil.printErr("Couldn't find a webcam"); } else { _webCam = new Capture(P.p, cameras[6]); _webCam.start(); } } public void updateDraw() { if( _texture != null && _webCam != null && _webCam.available() == true ) { _webCam.read(); _texture.image( _webCam.get(), 0, 0, _texture.width, _texture.height ); } } }
package com.haxademic.app.haxmapper.textures; import processing.opengl.PShader; import processing.video.Capture; import com.haxademic.core.app.P; import com.haxademic.core.debug.DebugUtil; import com.haxademic.core.system.FileUtil; public class TextureWebCam extends BaseTexture { protected Capture _webCam; protected PShader _threshold; public TextureWebCam() { super(); initWebCam(); _threshold = P.p.loadShader( FileUtil.getHaxademicDataPath() + "shaders/filters/threshold.glsl"); } void initWebCam() { String[] cameras = Capture.list(); if (cameras.length == 0) { DebugUtil.printErr("Couldn't find a webcam"); buildGraphics(100, 100); } else { _webCam = new Capture(P.p, cameras[6]); _webCam.start(); buildGraphics(100, 100); } } public void updateDraw() { if( _texture != null && _webCam != null && _webCam.available() == true ) { if( _texture.width != _webCam.width && _webCam.width > 100 ) { buildGraphics( _webCam.width, _webCam.height ); } _webCam.read(); if( _texture != null ) { _texture.image( _webCam.get(), 0, 0 ); _texture.filter( _threshold ); } } else { _texture.clear(); } } }
Add utm metadata to sharing link for tracking
import { connect } from 'react-redux' import ModalShare from '../components/ModalShare' import { showHideModal } from '../actions' import { withRouter } from 'react-router' import { BASE_HREF } from '../constants/AppConstants' const mapStateToProps = (state, ownProps) => { let queryState = Object.assign({}, state.query) delete queryState.isFetching const encodedJSON = encodeURIComponent(JSON.stringify(queryState)) const shareLink = BASE_HREF + ownProps.location.pathname + '?q=' + encodedJSON + '&utm_source=explorer&utm_medium=share_modal' return { showModal: state.ui.modals.share, shareLink } } const mapDispatchToProps = (dispatch, ownProps) => ( { showHideModal: () => dispatch(showHideModal('share')) } ) export default withRouter(connect( mapStateToProps, mapDispatchToProps )(ModalShare))
import { connect } from 'react-redux' import ModalShare from '../components/ModalShare' import { showHideModal } from '../actions' import { withRouter } from 'react-router' import { BASE_HREF } from '../constants/AppConstants' const mapStateToProps = (state, ownProps) => { let queryState = Object.assign({}, state.query) delete queryState.isFetching const encodedJSON = encodeURIComponent(JSON.stringify(queryState)) const shareLink = BASE_HREF + ownProps.location.pathname + '?q=' + encodedJSON return { showModal: state.ui.modals.share, shareLink } } const mapDispatchToProps = (dispatch, ownProps) => ( { showHideModal: () => dispatch(showHideModal('share')) } ) export default withRouter(connect( mapStateToProps, mapDispatchToProps )(ModalShare))
Implement __getattr__ to reduce code
class SpaceAge(object): YEARS = {"on_earth": 1, "on_mercury": 0.2408467, "on_venus": 0.61519726, "on_mars": 1.8808158, "on_jupiter": 11.862615, "on_saturn": 29.447498, "on_uranus": 84.016846, "on_neptune": 164.79132} def __init__(self, seconds): self.seconds = seconds @property def years(self): return self.seconds/31557600 def __getattr__(self, on_planet): if on_planet in SpaceAge.YEARS: return lambda: round(self.years/SpaceAge.YEARS[on_planet], 2) else: raise AttributeError
class SpaceAge(object): def __init__(self, seconds): self.seconds = seconds @property def years(self): return self.seconds/31557600 def on_earth(self): return round(self.years, 2) def on_mercury(self): return round(self.years/0.2408467, 2) def on_venus(self): return round(self.years/0.6151976, 2) def on_mars(self): return round(self.years/1.8808158, 2) def on_jupiter(self): return round(self.years/11.862615, 2) def on_saturn(self): return round(self.years/29.447498, 2) def on_uranus(self): return round(self.years/84.016846, 2) def on_neptune(self): return round(self.years/164.79132, 2)
Use specific version of Ionic Keyboard plugin
#!/usr/bin/env node //this hook installs all your plugins var pluginlist = [ "https://github.com/driftyco/ionic-plugins-keyboard.git#v1.0.4", "cordova-plugin-vibration", "cordova-plugin-media", "https://github.com/apache/cordova-plugin-splashscreen.git", "https://github.com/extendedmind/Calendar-PhoneGap-Plugin.git", "https://github.com/extendedmind/cordova-plugin-local-notifications", "https://github.com/leohenning/KeepScreenOnPlugin", "https://github.com/extendedmind/cordova-webintent", "cordova-plugin-device", "cordova-plugin-whitelist" ]; // no need to configure below var fs = require('fs'); var path = require('path'); var sys = require('sys') var exec = require('child_process').exec; function puts(error, stdout, stderr) { sys.puts(stdout) } pluginlist.forEach(function(plug) { exec("cordova plugin add " + plug, puts); });
#!/usr/bin/env node //this hook installs all your plugins var pluginlist = [ "https://github.com/driftyco/ionic-plugins-keyboard.git", "cordova-plugin-vibration", "cordova-plugin-media", "https://github.com/apache/cordova-plugin-splashscreen.git", "https://github.com/extendedmind/Calendar-PhoneGap-Plugin.git", "https://github.com/extendedmind/cordova-plugin-local-notifications", "https://github.com/leohenning/KeepScreenOnPlugin", "https://github.com/extendedmind/cordova-webintent", "cordova-plugin-device", "cordova-plugin-whitelist" ]; // no need to configure below var fs = require('fs'); var path = require('path'); var sys = require('sys') var exec = require('child_process').exec; function puts(error, stdout, stderr) { sys.puts(stdout) } pluginlist.forEach(function(plug) { exec("cordova plugin add " + plug, puts); });
NXP-11577: Fix Sonar Major violation: Interface Is Type
/* * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Olivier Grisel <ogrisel@nuxeo.com> * Antoine Taillefer <ataillefer@nuxeo.com> */ package org.nuxeo.drive.service; import java.io.Serializable; public final class NuxeoDriveEvents { public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot"; public static final String ROOT_REGISTERED = "rootRegistered"; public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot"; public static final String ROOT_UNREGISTERED = "rootUnregistered"; public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName"; public static final Serializable EVENT_CATEGORY = "NuxeoDrive"; public static final String DELETED_EVENT = "deleted"; }
/* * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Olivier Grisel <ogrisel@nuxeo.com> * Antoine Taillefer <ataillefer@nuxeo.com> */ package org.nuxeo.drive.service; import java.io.Serializable; public interface NuxeoDriveEvents { String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot"; String ROOT_REGISTERED = "rootRegistered"; String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot"; String ROOT_UNREGISTERED = "rootUnregistered"; String IMPACTED_USERNAME_PROPERTY = "impactedUserName"; Serializable EVENT_CATEGORY = "NuxeoDrive"; String DELETED_EVENT = "deleted"; }
Fix timeline tabs to work on mozilla (for instead of forEach to nodelist)
var tabs = document.querySelectorAll('.tab'); var allPanels = document.querySelectorAll(".schedule"); function activateTab(tab) { //remove active de todas as outras tabs for (i = 0; i < tabs.length; ++i) { tabs[i].classList.remove('active'); } //adiciona active em t tab.classList.add('active'); } function openCourse(item, day) { for(var i=0;i<allPanels.length;i++){ allPanels[i].style.display = 'none'; } document.getElementById(day).style.display = 'block'; activateTab(item); } function initMap() { var myLatlng = {lat: -23.482069, lng: -47.425131}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: myLatlng, scrollwheel: false, }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: 'Click to zoom' }); map.addListener('center_changed', function() { // 3 seconds after the center of the map has changed, pan back to the // marker. window.setTimeout(function() { map.panTo(marker.getPosition()); }, 3000); }); marker.addListener('click', function() { map.setZoom(8); map.setCenter(marker.getPosition()); }); }
var tabs = document.querySelectorAll('.tab'); var allPanels = document.querySelectorAll(".schedule"); function activateTab(tab) { //remove active de todas as outras tabs tabs.forEach(function(tab) { tab.classList.remove('active'); }); //adiciona active em t tab.classList.add('active'); } function openCourse(item, day) { for(var i=0;i<allPanels.length;i++){ allPanels[i].style.display = 'none'; } document.getElementById(day).style.display = 'block'; activateTab(item); } function initMap() { var myLatlng = {lat: -23.482069, lng: -47.425131}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: myLatlng, scrollwheel: false, }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: 'Click to zoom' }); map.addListener('center_changed', function() { // 3 seconds after the center of the map has changed, pan back to the // marker. window.setTimeout(function() { map.panTo(marker.getPosition()); }, 3000); }); marker.addListener('click', function() { map.setZoom(8); map.setCenter(marker.getPosition()); }); }
Change test_v24 to the correct item.
var assert = require("assert"); var parseApk = require(".."); describe("APK V24", function () { var output = null; before(function (done) { parseApk(__dirname + "/samples/test_v24.apk", function (err, out) { if (err) { return done(err); } output = out; done(); }); }); it("Parses correctly", function () { assert.notEqual(null, output); }); it("Starts with a manifest tag", function () { assert.equal(output.manifest.length, 1); }); it("Has a package name", function () { assert.equal(output.manifest[0]["@package"], "com.idotools.bookstore"); }); it("Has a package version", function () { assert.equal(output.manifest[0]["@platformBuildVersionCode"], "24"); }); it("Has an application tag", function () { var manifest = output.manifest[0]; assert.equal(manifest.application.length, 1); }); });
var assert = require("assert"); var parseApk = require(".."); describe("APK V24", function () { var output = null; before(function (done) { parseApk(__dirname + "/samples/test_v24.apk", function (err, out) { if (err) { return done(err); } output = out; done(); }); }); it("Parses correctly", function () { assert.notEqual(null, output); }); it("Starts with a manifest tag", function () { assert.equal(output.manifest.length, 1); }); it("Has a package name", function () { assert.equal(output.manifest[0]["@package"], "org.rubenv.testapk"); }); it("Has a package version", function () { assert.equal(output.manifest[0]["@platformBuildVersionCode"], "21"); }); it("Has an application tag", function () { var manifest = output.manifest[0]; assert.equal(manifest.application.length, 1); }); });
Add current time to output messages.
var chalk = require('chalk'); var options = require('./options'); var Promise = require('promise'); function say(message, type) { var shouldEmit = true; var headerBg; type = type || 'error'; switch (type) { case 'write': if (!options['dry-run']) { say.writeCount += 1; } case 'success': headerBg = 'bgGreen'; break; case 'debug': shouldEmit = options['debug']; headerBg = 'bgBlue'; break; case 'info': shouldEmit = !options['quiet']; headerBg = 'bgCyan'; break; case 'error': say.errCount += 1; case 'failure': default: headerBg = 'bgRed'; break; } if (shouldEmit) { console.log(chalk[headerBg].gray.bold(type.toUpperCase()) + chalk.gray.bold('\t' + ('0' + (new Date()).toLocaleTimeString()).slice(-11)) + chalk.white.bold(' ' + message)); } } say.errCount = 0; say.writeCount = 0; module.exports = say;
var chalk = require('chalk'); var options = require('./options'); var Promise = require('promise'); function say(message, type) { var shouldEmit = true; var headerBg; type = type || 'error'; switch (type) { case 'write': if (!options['dry-run']) { say.writeCount += 1; } case 'success': headerBg = 'bgGreen'; break; case 'debug': shouldEmit = options['debug']; headerBg = 'bgBlue'; break; case 'info': shouldEmit = !options['quiet']; headerBg = 'bgCyan'; break; case 'error': say.errCount += 1; case 'failure': default: headerBg = 'bgRed'; break; } if (shouldEmit) { console.log(chalk[headerBg].gray.bold(type.toUpperCase()) + chalk.white.bold('\t' + message)); } } say.errCount = 0; say.writeCount = 0; module.exports = say;
Save file in correct folder
from update import * from plot_and_save import * from Parameters.parametersA3 import n, n_t, n0 animate = False # animate the wave in the string upon completion plot = False # plot the waveform and frequency spectrum on the piano bridge write_file = True # write the waveform on the bridge to a .wav file filename = "./Notes/pianoA3.wav" # calculate matrices A, B = calculate_AB() C = calculate_C() # initialize eta and u eta = update_eta(init=True) u = u_old = 1.*np.zeros(n) ims = [] u_bridge = np.array([]) for i in range(n_t): u_bridge = np.append(u_bridge, u[-1]) if i%10==0 and animate: ims.append([u]) if eta[1] >= 0.: # eta[0]: force = calculate_force(eta[1], u[n0]) u, u_old = update_displacement(u, u_old, A, B, C, force) eta = update_eta(eta, force[n0]) else: u, u_old = update_displacement(u, u_old, A, B) # animate, plot and save if animate: animate_string(ims) if plot: plot_u_bridge(u_bridge) plot_frequency(u_bridge) if write_file: save_to_wav(u_bridge, filename)
from update import * from plot_and_save import * from Parameters.parametersA3 import n, n_t, n0 animate = False # animate the wave in the string upon completion plot = False # plot the waveform and frequency spectrum on the piano bridge write_file = True # write the waveform on the bridge to a .wav file filename = "pianoA3.wav" # calculate matrices A, B = calculate_AB() C = calculate_C() # initialize eta and u eta = update_eta(init=True) u = u_old = 1.*np.zeros(n) ims = [] u_bridge = np.array([]) for i in range(n_t): u_bridge = np.append(u_bridge, u[-1]) if i%10==0 and animate: ims.append([u]) if eta[1] >= 0.: # eta[0]: force = calculate_force(eta[1], u[n0]) u, u_old = update_displacement(u, u_old, A, B, C, force) eta = update_eta(eta, force[n0]) else: u, u_old = update_displacement(u, u_old, A, B) # animate, plot and save if animate: animate_string(ims) if plot: plot_u_bridge(u_bridge) plot_frequency(u_bridge) if write_file: save_to_wav(u_bridge, filename)
Handle when the user presses cancel on the permission prompt.
package com.jakewharton.telecine; import android.app.Activity; import android.content.Intent; import android.media.projection.MediaProjectionManager; import android.os.Bundle; import butterknife.ButterKnife; import butterknife.OnClick; import timber.log.Timber; public final class TelecineActivity extends Activity { private static final int CREATE_SCREEN_CAPTURE = 4242; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); } @OnClick(R.id.launch) void onLaunchClicked() { Timber.d("Attempting to acquire permission to screen capture."); MediaProjectionManager manager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE); Intent intent = manager.createScreenCaptureIntent(); startActivityForResult(intent, CREATE_SCREEN_CAPTURE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CREATE_SCREEN_CAPTURE: if (resultCode == 0) { Timber.d("Failed to acquire permission to screen capture."); } else { Timber.d("Acquired permission to screen capture. Starting service."); startService(TelecineService.newIntent(this, resultCode, data)); } break; default: super.onActivityResult(requestCode, resultCode, data); } } }
package com.jakewharton.telecine; import android.app.Activity; import android.content.Intent; import android.media.projection.MediaProjectionManager; import android.os.Bundle; import butterknife.ButterKnife; import butterknife.OnClick; import timber.log.Timber; public final class TelecineActivity extends Activity { private static final int CREATE_SCREEN_CAPTURE = 4242; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); } @OnClick(R.id.launch) void onLaunchClicked() { Timber.d("Attempting to acquire permission to screen capture."); MediaProjectionManager manager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE); Intent intent = manager.createScreenCaptureIntent(); startActivityForResult(intent, CREATE_SCREEN_CAPTURE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CREATE_SCREEN_CAPTURE: Timber.d("Acquired permission to screen capture. Starting service."); startService(TelecineService.newIntent(this, resultCode, data)); break; default: super.onActivityResult(requestCode, resultCode, data); } } }
Add documentation on wait parameter
import 'babel-polyfill'; import meow from 'meow'; import logSymbols from 'log-symbols'; import parseURL from './lib/parse-url'; import checkURL from './lib/check-url'; const cli = meow(` Example $ is-js-error example.com ${logSymbols.success} OK $ is-js-error example.com --wait 3000 ${logSymbols.success} OK Options --help, Display this help --version, Display the version number --wait [ms], Wait for a given period before reporting no error. `); if (cli.input.length === 0) { console.error('Specify a URL'); process.exit(1); } const url = parseURL(cli.input[0]); const maxWait = Math.max(cli.flags.wait, 1000); checkURL(url, maxWait, (err, results) => { if (err) { console.log(`${logSymbols.warning} ${err}`); process.exit(1); } else { const hasError = results[1]; console.log(hasError ? `${logSymbols.error} KO` : `${logSymbols.success} OK`); process.exit(hasError ? 2 : 0); } });
import 'babel-polyfill'; import meow from 'meow'; import logSymbols from 'log-symbols'; import parseURL from './lib/parse-url'; import checkURL from './lib/check-url'; const cli = meow(` Example $ is-js-error example.com ${logSymbols.success} OK `); if (cli.input.length === 0) { console.error('Specify a URL'); process.exit(1); } const url = parseURL(cli.input[0]); const maxWait = Math.max(cli.flags.wait || cli.flags.w, 1000); checkURL(url, maxWait, (err, results) => { if (err) { console.log(`${logSymbols.warning} ${err}`); process.exit(1); } else { const hasError = results[1]; console.log(hasError ? `${logSymbols.error} KO` : `${logSymbols.success} OK`); process.exit(hasError ? 2 : 0); } });
FIX: Use new resource loading syntax for javascript SilverStripe 4 vendormodule types make use of an 'expose' composer directive to allow assets they provide to be accessed by a web request. Previously the javascript for the iFrame resizing business tried to load from a static path that no longer exists (referenced inside PHP), which caused a fatal error. This has been fixed along with making the conditional code for enforcing a protocol on the page's request a bit more readable & easily digestable to developers.
<?php namespace SilverStripe\IFrame; use SilverStripe\CMS\Controllers\ContentController; use SilverStripe\Control\Director; use SilverStripe\View\Requirements; class IFramePageController extends ContentController { protected function init() { parent::init(); $currentProtocol = Director::protocol(); $desiredProtocol = $this->ForceProtocol; if ($desiredProtocol && $currentProtocol !== $desiredProtocol) { $enforcedLocation = preg_replace( "#^${currentProtocol}#", $desiredProtocol, $this->AbsoluteLink() ); return $this->redirect($enforcedLocation); } if ($this->IFrameURL) { Requirements::javascript('silverstripe/iframe: javascript/iframe_page.js'); } } }
<?php namespace SilverStripe\IFrame; use SilverStripe\CMS\Controllers\ContentController; use SilverStripe\Control\Director; use SilverStripe\View\Requirements; class IFramePageController extends ContentController { protected function init() { parent::init(); if ($this->ForceProtocol) { if ($this->ForceProtocol == 'http://' && Director::protocol() != 'http://') { return $this->redirect(preg_replace('#https://#', 'http://', $this->AbsoluteLink())); } elseif ($this->ForceProtocol == 'https://' && Director::protocol() != 'https://') { return $this->redirect(preg_replace('#http://#', 'https://', $this->AbsoluteLink())); } } if ($this->IFrameURL) { Requirements::javascript('iframe/javascript/iframe_page.js'); } } }
Remove false docstring from common cog.
from collections import OrderedDict import threading from joku.bot import Jokusoramame class _CogMeta(type): def __prepare__(*args, **kwargs): # Use an OrderedDict for the class body. return OrderedDict() class Cog(metaclass=_CogMeta): def __init__(self, bot: Jokusoramame): self._bot = bot self.logger = self.bot.logger @property def bot(self) -> 'Jokusoramame': """ :return: The bot instance associated with this cog. """ return self._bot @classmethod def setup(cls, bot: Jokusoramame): bot.add_cog(cls(bot))
from collections import OrderedDict import threading from joku.bot import Jokusoramame class _CogMeta(type): def __prepare__(*args, **kwargs): # Use an OrderedDict for the class body. return OrderedDict() class Cog(metaclass=_CogMeta): """ A common class for all cogs. This makes the class body ordered, and provides a `local` which stores thread-local data. This makes the cogs semi thread-safe. """ def __init__(self, bot: Jokusoramame): self._bot = bot self.logger = self.bot.logger @property def bot(self) -> 'Jokusoramame': """ :return: The bot instance associated with this cog. """ return self._bot @classmethod def setup(cls, bot: Jokusoramame): bot.add_cog(cls(bot))
Add message to webpage repo trigger Should fix triggering builds on the webpage repo even when the most recent commit message skip the CI build. Also should make it easier to identify builds started by this trigger. [ci skip] [skip ci]
""" Trigger the conda-forge.github.io Travis job to restart. """ import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers["Accept"] = "application/json" headers["Travis-API-Version"] = "3" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, json={ "request": { "branch": "master", "message": "Triggering build from staged-recipes", } }, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io')
""" Trigger the conda-forge.github.io Travis job to restart. """ import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers["Accept"] = "application/json" headers["Travis-API-Version"] = "3" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, json={"request": {"branch": "master"}}, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io')
Fix benchmark test listener comment
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.oxauth.load.benchmark; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; /** * @author Yuriy Movchan * @version 0.1, 03/17/2015 */ public class BenchmarkTestListener implements ITestListener { @Override public void onTestStart(ITestResult result) { } @Override public void onTestSuccess(ITestResult result) { } @Override public void onTestFailure(ITestResult result) { } @Override public void onTestSkipped(ITestResult result) { } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { } @Override public void onStart(ITestContext context) { System.out.println("Test '" + context.getName() + "' started ..."); } @Override public void onFinish(ITestContext context) { final long takes = (context.getEndDate().getTime() - context.getStartDate().getTime()) / 1000; System.out.println("Test '" + context.getName() + "' finished in " + takes + " seconds"); } }
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.oxauth.load.benchmark; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; /** * @author Yuriy Movchan * @version 0.1, 03/17/2015 */ public class BenchmarkTestListener implements ITestListener { @Override public void onTestStart(ITestResult result) { } @Override public void onTestSuccess(ITestResult result) { } @Override public void onTestFailure(ITestResult result) { } @Override public void onTestSkipped(ITestResult result) { } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { } @Override public void onStart(ITestContext context) { System.out.println("Test '" + context.getName() + "' started ..."); } @Override public void onFinish(ITestContext context) { final long takes = (context.getEndDate().getTime() - context.getStartDate().getTime()) / 1000; System.out.println("Suite '" + context.getName() + "' finished in " + takes + " seconds"); } }
Add watch of test files to gulp
'use strict'; var gulp = require('gulp'), browserify = require('browserify'), transform = require('vinyl-transform'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), jasmine = require('gulp-jasmine'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', ['test']); gulp.watch('./spec/**/*.js', ['test']); }); gulp.task('build', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./src/js/bowler.js') .pipe(browserified) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/js')); }); gulp.task('test', ['build'], function () { return gulp.src('./spec/**/*.js') .pipe(jasmine()); });
'use strict'; var gulp = require('gulp'), browserify = require('browserify'), transform = require('vinyl-transform'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), jasmine = require('gulp-jasmine'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', ['test']); }); gulp.task('build', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./src/js/bowler.js') .pipe(browserified) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/js')); }); gulp.task('test', ['build'], function () { return gulp.src('./spec/**/*.js') .pipe(jasmine()); });
Use sinon.createSandbox instead of sinon.sandbox.create, if available Avoids a deprecation warning in Sinon 5+
(function(){ function mochaSinon(sinon){ if (typeof beforeEach !== "function") { throw "mocha-sinon relies on mocha having been loaded."; } beforeEach(function() { if (null == this.sinon) { if (sinon.createSandbox) { // Sinon 2+ (sinon.sandbox.create triggers a deprecation warning in Sinon 5) this.sinon = sinon.createSandbox(); } else { this.sinon = sinon.sandbox.create(); } } else { this.sinon.restore(); } }); } (function(plugin){ if ( typeof window === "object" && typeof window.sinon === "object" ) { plugin(window.sinon); } else if (typeof require === "function") { var sinon = require('sinon'); module.exports = function () { plugin(sinon); }; plugin(sinon); } else { throw "We could not find sinon through a supported module loading technique. Pull requests are welcome!"; } })(mochaSinon); })();
(function(){ function mochaSinon(sinon){ if (typeof beforeEach !== "function") { throw "mocha-sinon relies on mocha having been loaded."; } beforeEach(function() { if (null == this.sinon) { this.sinon = sinon.sandbox.create(); } else { this.sinon.restore(); } }); } (function(plugin){ if ( typeof window === "object" && typeof window.sinon === "object" ) { plugin(window.sinon); } else if (typeof require === "function") { var sinon = require('sinon'); module.exports = function () { plugin(sinon); }; plugin(sinon); } else { throw "We could not find sinon through a supported module loading technique. Pull requests are welcome!"; } })(mochaSinon); })();
Correct author list, add OCA
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Sale Payment Method - Automatic Worflow (link module)', 'version': '1.0', 'author': 'Camptocamp,Akretion,Odoo Community Association (OCA)', 'license': 'AGPL-3', 'category': 'Generic Modules/Others', 'depends': ['sale_payment_method', 'sale_automatic_workflow'], 'website': 'http://www.camptocamp.com', 'data': ['view/sale_order_view.xml', 'view/payment_method_view.xml', ], 'test': [], 'installable': True, 'auto_install': True, }
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Sale Payment Method - Automatic Worflow (link module)', 'version': '1.0', 'author': ['Camptocamp', 'Akretion'], 'license': 'AGPL-3', 'category': 'Generic Modules/Others', 'depends': ['sale_payment_method', 'sale_automatic_workflow'], 'website': 'http://www.camptocamp.com', 'data': ['view/sale_order_view.xml', 'view/payment_method_view.xml', ], 'test': [], 'installable': True, 'auto_install': True, }
Replace Function.prototype.bind polyfill with one that works for the latest version of Phantomjs
// using react's Function.prototype.bind polyfill for phantomjs // https://github.com/facebook/react/blob/master/src/test/phantomjs-shims.js (function() { var Ap = Array.prototype; var slice = Ap.slice; var Fp = Function.prototype; if (!Fp.bind) { // PhantomJS doesn't support Function.prototype.bind natively, so // polyfill it whenever this module is required. Fp.bind = function(context) { var func = this; var args = slice.call(arguments, 1); function bound() { var invokedAsConstructor = func.prototype && (this instanceof func); return func.apply( // Ignore the context parameter when invoking the bound function // as a constructor. Note that this includes not only constructor // invocations using the new keyword but also calls to base class // constructors such as BaseClass.call(this, ...) or super(...). !invokedAsConstructor && context || this, args.concat(slice.call(arguments)) ); } // The bound function must share the .prototype of the unbound // function so that any object created by one constructor will count // as an instance of both constructors. bound.prototype = func.prototype; return bound; }; } })();
(function() { /** * Function.bind for ECMAScript 5 Support * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind */ if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } })();
Remove warning when a call agent is not present
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ function getCallStatusText (agent) { if (agent == undefined) { return ""; } switch(agent.callStatus) { case CallAgent.CallStatusNoCall: if (agent.error) { return qsTr("Error"); } else { return qsTr("No Call"); } break; case CallAgent.CallStatusIncomingCall: return qsTr("Incoming"); break; case CallAgent.CallStatusConnecting: return qsTr("Connecting"); break; case CallAgent.CallStatusRinging: return qsTr("Ringing"); break; case CallAgent.CallStatusTalking: // Qt has no way to get the time separator return Qt.formatTime(window.callAgent.elapsedTime(), "h:mm:ss"); break; case CallAgent.CallStatusHeld: return qsTr("On Hold"); break; case CallAgent.CallStatusHangingUp: return qsTr("Hanging up"); break; default: return qsTr("Unknown"); } }
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ function getCallStatusText (agent) { switch(agent.callStatus) { case CallAgent.CallStatusNoCall: if (agent.error) { return qsTr("Error"); } else { return qsTr("No Call"); } break; case CallAgent.CallStatusIncomingCall: return qsTr("Incoming"); break; case CallAgent.CallStatusConnecting: return qsTr("Connecting"); break; case CallAgent.CallStatusRinging: return qsTr("Ringing"); break; case CallAgent.CallStatusTalking: // Qt has no way to get the time separator return Qt.formatTime(window.callAgent.elapsedTime(), "h:mm:ss"); break; case CallAgent.CallStatusHeld: return qsTr("On Hold"); break; case CallAgent.CallStatusHangingUp: return qsTr("Hanging up"); break; default: return qsTr("Unknown"); } }
Make this a subclass of Thread. git-svn-id: becfadaebdf67c7884f0d18099f2460615305e2e@969 c76caeb1-94fd-44dd-870f-0c9d92034fc1
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.util.*; import java.io.*; import java.net.*; /** * A special-purpose thread used by Resolvers (both SimpleResolver and * ExtendedResolver) to perform asynchronous queries. * * @author Brian Wellington */ class ResolveThread extends Thread { private Message query; private Object id; private ResolverListener listener; private Resolver res; /** Creates a new ResolveThread */ public ResolveThread(Resolver res, Message query, Object id, ResolverListener listener) { this.res = res; this.query = query; this.id = id; this.listener = listener; } /** * Performs the query, and executes the callback. */ public void run() { try { Message response = res.send(query); listener.receiveMessage(id, response); } catch (Exception e) { listener.handleException(id, e); } } }
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.util.*; import java.io.*; import java.net.*; /** * A special-purpose thread used by Resolvers (both SimpleResolver and * ExtendedResolver) to perform asynchronous queries. * * @author Brian Wellington */ class ResolveThread implements Runnable { private Message query; private Object id; private ResolverListener listener; private Resolver res; /** Creates a new ResolveThread */ public ResolveThread(Resolver res, Message query, Object id, ResolverListener listener) { this.res = res; this.query = query; this.id = id; this.listener = listener; } /** * Performs the query, and executes the callback. */ public void run() { try { Message response = res.send(query); listener.receiveMessage(id, response); } catch (Exception e) { listener.handleException(id, e); } } }
Update GDAXProductTicker obj name from bitstampTicker to gdaxTicker Looks to be a copy paste mistake. Updated the name to reference gdax as opposed to bitstamp in this gdax example.
package org.knowm.xchange.examples.gdax; import java.io.IOException; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeFactory; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.gdax.GDAXExchange; import org.knowm.xchange.gdax.dto.marketdata.GDAXProductTicker; import org.knowm.xchange.gdax.service.GDAXMarketDataServiceRaw; import org.knowm.xchange.service.marketdata.MarketDataService; public class GDAXTickerDemo { public static void main(String[] args) throws IOException { Exchange exchange = ExchangeFactory.INSTANCE.createExchange(GDAXExchange.class.getName()); MarketDataService marketDataService = exchange.getMarketDataService(); generic(marketDataService); raw((GDAXMarketDataServiceRaw) marketDataService); } private static void generic(MarketDataService marketDataService) throws IOException { Ticker ticker = marketDataService.getTicker(CurrencyPair.BTC_USD); System.out.println(ticker.toString()); } private static void raw(GDAXMarketDataServiceRaw marketDataService) throws IOException { GDAXProductTicker gdaxTicker = marketDataService.getCoinbaseExProductTicker(CurrencyPair.BTC_USD); System.out.println(gdaxTicker.toString()); } }
package org.knowm.xchange.examples.gdax; import java.io.IOException; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeFactory; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.gdax.GDAXExchange; import org.knowm.xchange.gdax.dto.marketdata.GDAXProductTicker; import org.knowm.xchange.gdax.service.GDAXMarketDataServiceRaw; import org.knowm.xchange.service.marketdata.MarketDataService; public class GDAXTickerDemo { public static void main(String[] args) throws IOException { Exchange exchange = ExchangeFactory.INSTANCE.createExchange(GDAXExchange.class.getName()); MarketDataService marketDataService = exchange.getMarketDataService(); generic(marketDataService); raw((GDAXMarketDataServiceRaw) marketDataService); } private static void generic(MarketDataService marketDataService) throws IOException { Ticker ticker = marketDataService.getTicker(CurrencyPair.BTC_USD); System.out.println(ticker.toString()); } private static void raw(GDAXMarketDataServiceRaw marketDataService) throws IOException { GDAXProductTicker bitstampTicker = marketDataService.getCoinbaseExProductTicker(CurrencyPair.BTC_USD); System.out.println(bitstampTicker.toString()); } }
Add team ID to provider keys
package oauth import ( "github.com/skygeario/skygear-server/pkg/auth/dependency/principal" "github.com/skygeario/skygear-server/pkg/core/config" ) type GetByProviderOptions struct { ProviderType string ProviderKeys map[string]interface{} ProviderUserID string } type GetByUserOptions struct { ProviderType string ProviderKeys map[string]interface{} UserID string } type Provider interface { principal.Provider GetPrincipalByProvider(options GetByProviderOptions) (*Principal, error) GetPrincipalByUser(options GetByUserOptions) (*Principal, error) CreatePrincipal(principal *Principal) error UpdatePrincipal(principal *Principal) error DeletePrincipal(principal *Principal) error } func ProviderKeysFromProviderConfig(c config.OAuthProviderConfiguration) map[string]interface{} { m := map[string]interface{}{} if c.Tenant != "" { m["tenant"] = c.Tenant } if c.TeamID != "" { m["team_id"] = c.TeamID } return m }
package oauth import ( "github.com/skygeario/skygear-server/pkg/auth/dependency/principal" "github.com/skygeario/skygear-server/pkg/core/config" ) type GetByProviderOptions struct { ProviderType string ProviderKeys map[string]interface{} ProviderUserID string } type GetByUserOptions struct { ProviderType string ProviderKeys map[string]interface{} UserID string } type Provider interface { principal.Provider GetPrincipalByProvider(options GetByProviderOptions) (*Principal, error) GetPrincipalByUser(options GetByUserOptions) (*Principal, error) CreatePrincipal(principal *Principal) error UpdatePrincipal(principal *Principal) error DeletePrincipal(principal *Principal) error } func ProviderKeysFromProviderConfig(c config.OAuthProviderConfiguration) map[string]interface{} { m := map[string]interface{}{} if c.Tenant != "" { m["tenant"] = c.Tenant } return m }
Correct attribute name (spelling mistake) OPEN - task 32: Add "Create Item" functionalities http://github.com/DevOpsDistilled/OpERP/issues/issue/32
package devopsdistilled.operp.server.data.entity.items; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import devopsdistilled.operp.server.data.entity.Entiti; @Entity public class Manufacturer extends Entiti implements Serializable { private static final long serialVersionUID = 3771480832066400289L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long manufacturerId; private String manufacturerName; @OneToMany(mappedBy = "manufacturer") private List<Brand> brands; public Long getManufacturerId() { return manufacturerId; } public void setManufacturerId(Long manufacturerId) { this.manufacturerId = manufacturerId; } public String getManufacturerName() { return manufacturerName; } public void setManufacturerName(String manufactuerName) { this.manufacturerName = manufactuerName; } public List<Brand> getBrands() { return brands; } public void setBrands(List<Brand> brands) { this.brands = brands; } }
package devopsdistilled.operp.server.data.entity.items; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import devopsdistilled.operp.server.data.entity.Entiti; @Entity public class Manufacturer extends Entiti implements Serializable { private static final long serialVersionUID = 3771480832066400289L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long manufacturerId; private String manufactuerName; @OneToMany(mappedBy = "manufacturer") private List<Brand> brands; public Long getManufacturerId() { return manufacturerId; } public void setManufacturerId(Long manufacturerId) { this.manufacturerId = manufacturerId; } public String getManufactuerName() { return manufactuerName; } public void setManufactuerName(String manufactuerName) { this.manufactuerName = manufactuerName; } public List<Brand> getBrands() { return brands; } public void setBrands(List<Brand> brands) { this.brands = brands; } }
Stop hacking hash salt, we haz Lando now!
<?php /** * Load services definition file. */ $settings['container_yamls'][] = __DIR__ . '/services.yml'; /** * Include the Pantheon-specific settings file. * * n.b. The settings.pantheon.php file makes some changes * that affect all envrionments that this site * exists in. Always include this file, even in * a local development environment, to ensure that * the site settings remain consistent. */ include __DIR__ . "/settings.pantheon.php"; /** * Place the config directory outside of the Drupal root. */ $config_directories = array( CONFIG_SYNC_DIRECTORY => dirname(DRUPAL_ROOT) . '/config', ); /** * If there is a local settings file, then include it */ $local_settings = __DIR__ . "/settings.local.php"; if (file_exists($local_settings)) { include $local_settings; } /** * Always install the 'standard' profile to stop the installer from * modifying settings.php. * * See: tests/installer-features/installer.feature */ $settings['install_profile'] = 'standard';
<?php /** * Load services definition file. */ $settings['container_yamls'][] = __DIR__ . '/services.yml'; /** * Include the Pantheon-specific settings file. * * n.b. The settings.pantheon.php file makes some changes * that affect all envrionments that this site * exists in. Always include this file, even in * a local development environment, to ensure that * the site settings remain consistent. */ include __DIR__ . "/settings.pantheon.php"; /** * Place the config directory outside of the Drupal root. */ $config_directories = array( CONFIG_SYNC_DIRECTORY => dirname(DRUPAL_ROOT) . '/config', ); /** * If there is a local settings file, then include it */ $local_settings = __DIR__ . "/settings.local.php"; if (file_exists($local_settings)) { include $local_settings; } /** * Always install the 'standard' profile to stop the installer from * modifying settings.php. * * See: tests/installer-features/installer.feature */ $settings['install_profile'] = 'standard'; // Hack to handle containers not supplying $_ENV vars to PHP if (!isset($settings['hash_salt']) && getenv('DRUPAL_HASH_SALT')) { $settings['hash_salt'] = getenv('DRUPAL_HASH_SALT'); }
Use a list for the style cycle so that subsequent calls to the plotting functions don't mix up the line styles.
import brewer2mpl from cycler import cycler N = 5 cmap = brewer2mpl.get_map('Set1', 'Qualitative', N, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) style_cycle = list(color_cycle + marker_cycle + markersize_cycle)[:N] cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) style_cycle_fig7 = list(color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)[:N]
import brewer2mpl import itertools from cycler import cycler cmap = brewer2mpl.get_map('Set1', 'Qualitative', 5, reverse=False) color_cycle = cycler('color', cmap.hex_colors) marker_cycle = cycler('marker', ['s', '^', 'o', 'D', 'v']) markersize_cycle = cycler('markersize', [10, 12, 11, 10, 12]) style_cycle = itertools.cycle(color_cycle + marker_cycle + markersize_cycle) cmap = brewer2mpl.get_map('Set1', 'Qualitative', 3, reverse=False) color_cycle = cycler('color', ['black', '#88CCDD', '#c73027']) marker_cycle = cycler('marker', [' ', ' ', ' ']) markersize_cycle = cycler('markersize', [8, 8, 8]) fillstyle_cycle = cycler('fillstyle', ['full', 'full', 'full']) linestyle_cycle = cycler('linestyle', ['dashed', 'solid', 'solid']) linewidth_cycle = cycler('linewidth', [2, 2.25, 2]) style_cycle_fig7 = (color_cycle + marker_cycle + markersize_cycle + fillstyle_cycle + linestyle_cycle + linewidth_cycle)
Edit search function to only return modules that are mapped to the exact NUS module code entered by user
import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; Meteor.publish('modules', function(PUField, regionField, search) { check(search, Match.OneOf(String, null, undefined)); check(regionField, Match.OneOf(String, null, undefined)); check(PUField, Match.OneOf(String, null, undefined)); let query = {}; const projection = { limit: 10, sort: [['PrevMatch', 'desc'], ['Similarity', 'desc']] }; // sort in descending order according to Similarity field if (search) { let regex = new RegExp(`^`+search+`$`, 'i'); //search for PU modules that are mapped exactly to the NUS module code entered by user if (PUField) { query['UniversityName'] = PUField; } if (regionField) { query['Region'] = regionField; } query['NUSModuleCode'] = regex; projection.limit = 100; } return Modules.find(query, projection); });
import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; Meteor.publish('modules', function(PUField, regionField, search) { check(search, Match.OneOf(String, null, undefined)); check(regionField, Match.OneOf(String, null, undefined)); check(PUField, Match.OneOf(String, null, undefined)); let query = {}; const projection = { limit: 10, sort: [['PrevMatch', 'desc'], ['Similarity', 'desc']] }; // sort in descending order according to Similarity field if (search) { let regex = new RegExp(search, 'i'); if (PUField) { query['UniversityName'] = PUField; } if (regionField) { query['Region'] = regionField; } query['NUSModuleCode'] = regex; projection.limit = 100; } return Modules.find(query, projection); });
Fix use of wrong setting for organizations Implements nci-agency/anet#448
import Model from 'components/Model' import Settings from 'Settings' export default class Organization extends Model { static resourceName = 'Organization' static listName = 'organizationList' static TYPE = { ADVISOR_ORG: 'ADVISOR_ORG', PRINCIPAL_ORG: 'PRINCIPAL_ORG' } static schema = { shortName: '', longName: '', identificationCode: null, type: '', parentOrg: null, childrenOrgs: [], approvalSteps: [], positions: [], tasks: [] } isAdvisorOrg() { return this.type === Organization.TYPE.ADVISOR_ORG } static humanNameOfType(type) { if (type === Organization.TYPE.PRINCIPAL_ORG) { return Settings.fields.principal.org.name } else { return Settings.fields.advisor.org.name } // TODO do not assume that if not of type TYPE.PRINCIPAL_ORG it is an advisor } humanNameOfType(type) { return Organization.humanNameOfType(this.type) } toString() { return this.shortName || this.longName || this.identificationCode } }
import Model from 'components/Model' import Settings from 'Settings' export default class Organization extends Model { static resourceName = 'Organization' static listName = 'organizationList' static TYPE = { ADVISOR_ORG: 'ADVISOR_ORG', PRINCIPAL_ORG: 'PRINCIPAL_ORG' } static schema = { shortName: '', longName: '', identificationCode: null, type: '', parentOrg: null, childrenOrgs: [], approvalSteps: [], positions: [], tasks: [] } isAdvisorOrg() { return this.type === Organization.TYPE.ADVISOR_ORG } static humanNameOfType(type) { if (type === Organization.TYPE.PRINCIPAL_ORG) { return Settings.fields.advisor.org.name } else { return Settings.fields.advisor.org.name } // TODO do not assume that if not of type TYPE.PRINCIPAL_ORG it is an advisor } humanNameOfType(type) { return Organization.humanNameOfType(this.type) } toString() { return this.shortName || this.longName || this.identificationCode } }
Remove the boilerplate comment now that we have more tests.
import { moduleFor, test } from 'ember-qunit'; moduleFor('adapter:github-release', 'Unit | Adapter | github release', { // Specify the other units that are required for this test. // needs: ['serializer:foo'] }); test('it exists', function(assert) { let adapter = this.subject(); assert.ok(adapter); }); test('it builds the URL for the releases query correctly', function(assert) { let adapter = this.subject(); const host = adapter.get('host'); const repo = 'jimmay5469/old-hash'; assert.equal(adapter.buildURL('github-release', null, null, 'query', { repo: repo }), `${host}/repos/${repo}/releases`); }); test('it builds the URL for a specific release query correctly', function(assert) { let adapter = this.subject(); const host = adapter.get('host'); const repo = 'jimmay5469/old-hash'; const release = 1; assert.equal( adapter.buildURL('github-release', null, null, 'queryRecord', { repo: repo, releaseId: release }), `${host}/repos/${repo}/releases/${release}` ); });
import { moduleFor, test } from 'ember-qunit'; moduleFor('adapter:github-release', 'Unit | Adapter | github release', { // Specify the other units that are required for this test. // needs: ['serializer:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { let adapter = this.subject(); assert.ok(adapter); }); test('it builds the URL for the releases query correctly', function(assert) { let adapter = this.subject(); const host = adapter.get('host'); const repo = 'jimmay5469/old-hash'; assert.equal(adapter.buildURL('github-release', null, null, 'query', { repo: repo }), `${host}/repos/${repo}/releases`); }); test('it builds the URL for a specific release query correctly', function(assert) { let adapter = this.subject(); const host = adapter.get('host'); const repo = 'jimmay5469/old-hash'; const release = 1; assert.equal( adapter.buildURL('github-release', null, null, 'queryRecord', { repo: repo, releaseId: release }), `${host}/repos/${repo}/releases/${release}` ); });
Switch from goblin to ginkgo for testing
package main import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "errors" "testing" ) func Test(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Run") } var _ = Describe("Run", func() { extensionError := errors.New("run could not determine how to run this file because it does not have a known extension") Describe(".command_for_file", func() { Context("when a filename is given with a known extension", func() { It("should be a valid command", func() { command, err := commandForFile("hello.rb") Expect(command).To(Equal("ruby hello.rb")) Expect(err).To(BeNil()) }) }) Context("when a filename is given without a known extension", func() { It("should return an error", func() { _, err := commandForFile("hello.unknown") Expect(err).To(Equal(extensionError)) }) }) Context("when a filename is given without any extension", func() { It("should return an error", func() { _, err := commandForFile("hello") Expect(err).To(Equal(extensionError)) }) }) }) })
package main import ( . "github.com/franela/goblin" "errors" "testing" ) func Test(t *testing.T) { g := Goblin(t) g.Describe("Run", func() { extensionError := errors.New("run could not determine how to run this file because it does not have a known extension") g.Describe(".command_for_file", func() { g.Describe("when a filename is given with a known extension", func() { g.It("should be a valid command", func() { command, err := commandForFile("hello.rb") g.Assert(command).Equal("ruby hello.rb") g.Assert(err).Equal(nil) }) }) g.Describe("when a filename is given without a known extension", func() { g.It("should return an error", func() { _, err := commandForFile("hello.unknown") g.Assert(err).Equal(extensionError) }) }) g.Describe("when a filename is given without any extension", func() { g.It("should return an error", func() { _, err := commandForFile("hello") g.Assert(err).Equal(extensionError) }) }) }) }) }
Create Datafield in Magento ignores Default Value Create DataField in Magento ignores Visibility
define(['jquery'], function($){ "use strict"; /** * Initializer * @param url */ function init(url) { $('#connector_data_mapping_dynamic_datafield_datafield_button').click(function () { var name = $('#connector_data_mapping_dynamic_datafield_datafield_name').val(); var type = $('#connector_data_mapping_dynamic_datafield_datafield_type').val(); var d_default = $('#connector_data_mapping_dynamic_datafield_datafield_default').val(); var access = $('#connector_data_mapping_dynamic_datafield_datafield_access').val(); if(name && type && access) { $.post(url, {name: name, type: type, default: d_default, visibility: access}, function () { window.location.reload(); }); } }); } /** * Export/return dataFields * @param dataFields */ return function(dataFields) { init(dataFields.url); }; });
define(['jquery'], function($){ "use strict"; /** * Initializer * @param url */ function init(url) { $('#connector_data_mapping_dynamic_datafield_datafield_button').click(function () { var name = $('#connector_data_mapping_dynamic_datafield_datafield_name').val(); var type = $('#connector_data_mapping_dynamic_datafield_datafield_type').val(); var d_default = $('#connector_data_mapping_dynamic_datafield_datafield_default').val(); var access = $('#connector_data_mapping_dynamic_datafield_datafield_access').val(); if(name && type && access) { $.post(url, {name: name, type: type, deafult: d_default, visiblity: access}, function () { window.location.reload(); }); } }); } /** * Export/return dataFields * @param dataFields */ return function(dataFields) { init(dataFields.url); }; });
DOC: Add docstring to test functions
from pim.commands.init import _defaults, _make_package from pim.commands.install import install from pim.commands.uninstall import uninstall from click.testing import CliRunner def _create_test_package(): """Helper function to create a test package""" d = _defaults() d['description'] = 'test package' _make_package(d, True) return d def test_install_and_uninstall(): """Round trip the install/uninstall functionality""" pkg_to_install = 'nose' runner = CliRunner() with runner.isolated_filesystem(): d = _create_test_package() result = runner.invoke(install, ['-g', pkg_to_install]) # _install([pkg_to_install], globally=True) with open('requirements.txt', 'r') as f: lines = f.readlines() assert pkg_to_install in lines result = runner.invoke(uninstall, ['-g', pkg_to_install]) with open('requirements.txt', 'r') as f: lines = f.readlines() assert pkg_to_install not in lines
from pim.commands.init import _defaults, _make_package from pim.commands.install import install from pim.commands.uninstall import uninstall from click.testing import CliRunner def _create_test_package(): d = _defaults() d['description'] = 'test package' _make_package(d, True) return d def test_install_and_uninstall(): pkg_to_install = 'nose' runner = CliRunner() with runner.isolated_filesystem(): d = _create_test_package() result = runner.invoke(install, ['-g', pkg_to_install]) # _install([pkg_to_install], globally=True) with open('requirements.txt', 'r') as f: lines = f.readlines() assert pkg_to_install in lines result = runner.invoke(uninstall, ['-g', pkg_to_install]) with open('requirements.txt', 'r') as f: lines = f.readlines() assert pkg_to_install not in lines
Fix height of photo in profile picture edit page
<? require_once('php/classes/member.php'); $profileEdited = new Member($_GET['member']); if (!$currentUser->isAdmin() || !$profileEdited->exists()) { $profileEdited = $currentUser; } ?><div class="row"> <div class="large-12 columns"> <h1>Edit Profile Picture: <?=$profileEdited->rcsid()?></h1> <p>This picture is displayed publicly on the "About Us" page:</p> <img class="editing" src="<?=$profileEdited->photoURL()?>" alt="<?=$profileEdited->fullName()?>"> <p>The new image must be a JPEG (*.jpg) file smaller than 1 MB.</p> <form enctype="multipart/form-data" action="post.php" method="post"> <input type="hidden" name="rcsid" value="<?=$profileEdited->rcsid()?>"> <input type="hidden" name="MAX_FILE_SIZE" value="1048576"> <div class="row"> <div class="medium-8 columns"> <input name="new_profile_photo" type="file"> <button type="submit" name="action" value="profile_photo_edit">Upload</button> </div> </div> </form> </div> </div>
<? require_once('php/classes/member.php'); $profileEdited = new Member($_GET['member']); if (!$currentUser->isAdmin() || !$profileEdited->exists()) { $profileEdited = $currentUser; } ?><div class="row"> <div class="large-12 columns"> <h1>Edit Profile Picture: <?=$profileEdited->rcsid()?></h1> <p>This picture is displayed publicly on the "About Us" page:</p> <img src="<?=$profileEdited->photoURL()?>" alt="<?=$profileEdited->fullName()?>"> <p>The new image must be a JPEG (*.jpg) file smaller than 1 MB.</p> <form enctype="multipart/form-data" action="post.php" method="post"> <input type="hidden" name="rcsid" value="<?=$profileEdited->rcsid()?>"> <input type="hidden" name="MAX_FILE_SIZE" value="1048576"> <div class="row"> <div class="medium-8 columns"> <input name="new_profile_photo" type="file"> <button type="submit" name="action" value="profile_photo_edit">Upload</button> </div> </div> </form> </div> </div>
Move a global style and add my correct email address.
import React from "react"; import styled from "styled-components"; import Link from "gatsby-link"; import PictureFrame from "../components/PictureFrame"; import Social from "../components/Social"; const StyledHome = styled.div` display: flex; flex-direction: column; align-items: flex-start; `; export default () => ( <StyledHome className="container"> <h1>Hello!</h1> <p> I'm a <strong>web developer</strong> employed as the{" "} <strong>chief technologist</strong> at a digital marketing agency. Currently I work primarily with React and Node but over the years I have acquired proficiency in many technologies. </p> <p> Besides building my own companies, I've also produced things for many brands, Fortune 500 and small companies or individuals alike. Need a hand with an upcoming project? Learn a bit more{" "} <Link to="/about-me">about me</Link> and then consider{" "} <a href="mailto:antoniwan@gmail.com?subject=Let's work together!"> working with me </a>. </p> <p> Thanks for visiting!<br /> <strong>Antonio Rodríguez</strong> </p> <hr /> <Social /> </StyledHome> );
import React from "react"; import styled from "styled-components"; import Link from "gatsby-link"; import PictureFrame from "../components/PictureFrame"; import Social from "../components/Social"; const StyledHome = styled.div` display: flex; flex-direction: column; align-items: flex-start; hr { width: 100%; } `; export default () => ( <StyledHome className="container"> <h1>Hello!</h1> <p> I'm a <strong>web developer</strong> employed as the{" "} <strong>chief technologist</strong> at a digital marketing agency. Currently I work primarily with React and Node but over the years I have acquired proficiency in many technologies. </p> <p> Besides building my own companies, I've also produced things for many brands, Fortune 500 and small companies or individuals alike. Need a hand with an upcoming project? Learn a bit more{" "} <Link to="/about-me">about me</Link> and then consider{" "} <a href="mailto:hello@antoniorodriguez.us">working with me</a>. </p> <p> Thanks for visiting!<br /> <strong>Antonio Rodríguez</strong> </p> <hr /> <Social /> </StyledHome> );
Update indentation of variable assigment
var util = require('util'), gulp = require('gulp'), colors = require('gulp/node_modules/gulp-util').colors, jshint = require('gulp-jshint'), jscs = require('gulp-jscs'), map = require('gulp-jshint/node_modules/map-stream'), jshintErrors = [] ; gulp.task('lint', function() { return gulp.src([__filename, './index.js', './lib/**/*.js', './test/**/test_*.js']) .pipe(jshint()) .pipe(map(function (file, cb) { if (file.jshint && !file.jshint.success) { jshintErrors.push.apply(jshintErrors, file.jshint.results); } cb(null, file); })) .pipe(jscs(__dirname + '/.jscs.json')); }); gulp.task('default', ['lint'], function() { if (jshintErrors.length) { console.error(jshintErrors.map(function(error) { return util.format( '[%s] %s in (%s:%d)\n', colors.green('gulp-jshint'), colors.red(error.error.reason), error.file, error.error.line ); }).join('')); process.exit(1); } });
var util = require('util'), gulp = require('gulp'), colors = require('gulp/node_modules/gulp-util').colors, jshint = require('gulp-jshint'), jscs = require('gulp-jscs'), map = require('gulp-jshint/node_modules/map-stream'), jshintErrors = [] ; gulp.task('lint', function() { return gulp.src([__filename, './index.js', './lib/**/*.js', './test/**/test_*.js']) .pipe(jshint()) .pipe(map(function (file, cb) { if (file.jshint && !file.jshint.success) { jshintErrors.push.apply(jshintErrors, file.jshint.results); } cb(null, file); })) .pipe(jscs(__dirname + '/.jscs.json')); }); gulp.task('default', ['lint'], function() { if (jshintErrors.length) { console.error(jshintErrors.map(function(error) { return util.format( '[%s] %s in (%s:%d)\n', colors.green('gulp-jshint'), colors.red(error.error.reason), error.file, error.error.line ); }).join('')); process.exit(1); } });
Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
import chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == stock def test_i_filter_random_words_not_in_lexicon(): u"""Assert that if all words are not in lexicon the default is returned.""" bot = chatbot_brain.Chatbot() words = ["moose", "bear", "eagle"] lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert the returned word is in the lexicon and is not a stop char.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == u"What a funny thing to say!" # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
Extend task list to a nested view
define([ 'Backbone', //Collection 'app/collections/tasks', //View 'app/views/taskItemView', //Template 'text!templates/project-page/taskItemTemplate.html', ], function( Backbone, //Collection Tasks, //View taskItemView, //Template itemTemplate ){ var TaskController = Backbone.View.extend({ template: _.template(itemTemplate), initialize: function(){ this.collection = new Tasks(this.options.projectId); this.collection.bind('reset', this.render, this); this.collection.bind('search', this.searchResult, this); }, searchResult: function(result){ this.$el.html(''); var template = this.template; var $list = this.$el; var title; _.each(result, function(model){ title = model.get('title'); if(title){ $list.append(template({title: model.get('title')})); } }); }, render: function(){ this.$el.html(''); var template = this.template; var $list = this.$el; var task; _.each(this.collection.models, function(model){ task = new taskItemView({ model: model }); $list.append(task.el); }); } }); return TaskController; });
define([ 'Backbone', //Collection 'app/collections/tasks', //Template 'text!templates/project-page/taskItemTemplate.html', ], function( Backbone, //Collection Tasks, //Template itemTemplate ){ var TaskController = Backbone.View.extend({ template: _.template(itemTemplate), initialize: function(){ this.collection = new Tasks(this.options.projectId); this.collection.bind('reset', this.render, this); this.collection.bind('search', this.searchResult, this); }, searchResult: function(result){ this.$el.html(''); var template = this.template; var $list = this.$el; var title; _.each(result, function(model){ title = model.get('title'); if(title){ $list.append(template({title: model.get('title')})); } }); }, render: function(){ this.$el.html(''); var template = this.template; var $list = this.$el; _.each(this.collection.models, function(model){ $list.append(template({title: model.get('title')})); }); } }); return TaskController; });
Change action properties to be protected so it will serialize
<?php declare(strict_types=1); namespace LotGD\Core; /** * A representation of an action the user can take to affect the game * state. An encapsulation of a navigation menu option. */ class Action { protected $id; protected $destinationSceneId; /** * Construct a new action with the specified Scene as its destination. * @param int $destinationSceneId */ public function __construct(int $destinationSceneId) { $this->id = bin2hex(random_bytes(8)); $this->destinationSceneId = $destinationSceneId; } /** * Returns the unique, automatically generated identifier for this action. * Use this ID to refer to this action when calling Game::takeAction(). * @return string */ public function getId(): string { return $this->id; } /** * Return the database ID of the destination scene, where the user will * go if they take this action. * @return string */ public function getDestinationSceneId(): int { return $this->destinationSceneId; } }
<?php declare(strict_types=1); namespace LotGD\Core; /** * A representation of an action the user can take to affect the game * state. An encapsulation of a navigation menu option. */ class Action { private $id; private $destinationSceneId; /** * Construct a new action with the specified Scene as its destination. * @param int $destinationSceneId */ public function __construct(int $destinationSceneId) { $this->id = bin2hex(random_bytes(8)); $this->destinationSceneId = $destinationSceneId; } /** * Returns the unique, automatically generated identifier for this action. * Use this ID to refer to this action when calling Game::takeAction(). * @return string */ public function getId(): string { return $this->id; } /** * Return the database ID of the destination scene, where the user will * go if they take this action. * @return string */ public function getDestinationSceneId(): int { return $this->destinationSceneId; } }
Fix fatal when matching null values in needle
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object|Function} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { if (typeof needle === 'function') { return needle(haystack); } var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && needle[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object|Function} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { if (typeof needle === 'function') { return needle(haystack); } var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
Fix layout rendering errors after login
(function() { function showLoading(ionicLoading, text) { ionicLoading.show({ template: text, noBackdrop: true, duration: 2000 }); } angular.module("proBebe.controllers") .controller("AuthCtrl", function($scope, $ionicLoading, $state, $window, Constants, authentication, storage) { $scope.login_info = {}; $scope.signUp = function() { $window.open(Constants.SIGN_UP_URL, '_system'); }; $scope.signIn = function() { var authPromise = authentication.authenticate($scope.login_info.email, $scope.login_info.password); $ionicLoading.show({ templateUrl: 'templates/loading.html' }); return authPromise.then(function(result) { if (result) { showLoading($ionicLoading, "Autenticado com sucesso"); $state.go('messages'); location.reload(); } else { showLoading($ionicLoading, "Credenciais inválidas"); } }).catch(function(error) { showLoading($ionicLoading, "Ocorreu um erro na autenticação"); }); }; $scope.signOut = function() { authentication.signOut(); storage.clear(); $state.go('signin'); }; }); })();
(function() { function showLoading(ionicLoading, text) { ionicLoading.show({ template: text, noBackdrop: true, duration: 2000 }); } angular.module("proBebe.controllers") .controller("AuthCtrl", function($scope, $ionicLoading, $state, $window, Constants, authentication, storage) { $scope.login_info = {}; $scope.signUp = function() { $window.open(Constants.SIGN_UP_URL, '_system'); }; $scope.signIn = function() { var authPromise = authentication.authenticate($scope.login_info.email, $scope.login_info.password); $ionicLoading.show({ templateUrl: 'templates/loading.html' }); return authPromise.then(function(result) { if (result) { showLoading($ionicLoading, "Autenticado com sucesso"); $state.go('messages'); } else { showLoading($ionicLoading, "Credenciais inválidas"); } }).catch(function(error) { showLoading($ionicLoading, "Ocorreu um erro na autenticação"); }); }; $scope.signOut = function() { authentication.signOut(); storage.clear(); $state.go('signin'); }; }); })();
[CFG] Put shutter control entirely in the user's hands
from ophyd.controls.area_detector import (AreaDetectorFileStoreHDF5, AreaDetectorFileStoreTIFF, AreaDetectorFileStoreTIFFSquashing) # from shutter import sh1 #shctl1 = EpicsSignal('XF:28IDC-ES:1{Det:PE1}cam1:ShutterMode', name='shctl1') shctl1 = EpicsSignal('XF:28IDC-ES:1{Sh:Exp}Cmd-Cmd', name='shctl1') pe1 = AreaDetectorFileStoreTIFFSquashing( 'XF:28IDC-ES:1{Det:PE1}', name='pe1', stats=[], ioc_file_path = 'H:/pe1_data', file_path = '/home/xf28id1/pe1_data', # shutter=shctl1, # shutter_val=(1, 0) ) # Dan and Sanjit commented this out in June. #shctl2 = EpicsSignal('XF:28IDC-ES:1{Det:PE2}cam1:ShutterMode', name='shctl2') #pe2 = AreaDetectorFileStoreTIFFSquashing( # 'XF:28IDC-ES:1{Det:PE2}', # name='pe2', # stats=[], # ioc_file_path = 'G:/pe2_data', # file_path = '/home/xf28id1/pe2_data', # shutter=shctl2, # shutter_val=(1,0))
from ophyd.controls.area_detector import (AreaDetectorFileStoreHDF5, AreaDetectorFileStoreTIFF, AreaDetectorFileStoreTIFFSquashing) # from shutter import sh1 shctl1 = EpicsSignal('XF:28IDC-ES:1{Det:PE1}cam1:ShutterMode', name='shctl1') pe1 = AreaDetectorFileStoreTIFFSquashing( 'XF:28IDC-ES:1{Det:PE1}', name='pe1', stats=[], ioc_file_path = 'H:/pe1_data', file_path = '/home/xf28id1/pe1_data', shutter=shctl1, shutter_val=(1, 0) ) # Dan and Sanjit commented this out in June. #shctl2 = EpicsSignal('XF:28IDC-ES:1{Det:PE2}cam1:ShutterMode', name='shctl2') #pe2 = AreaDetectorFileStoreTIFFSquashing( # 'XF:28IDC-ES:1{Det:PE2}', # name='pe2', # stats=[], # ioc_file_path = 'G:/pe2_data', # file_path = '/home/xf28id1/pe2_data', # shutter=shctl2, # shutter_val=(1,0))
[ChopBox] Fix indentation and arrange imports from shortest tolongest
<?php namespace ChopBox\Http\Controllers; use ChopBox\helpers\PostChop; use Illuminate\Support\Facades\Auth; use ChopBox\Http\Requests\ChopsFormRequest; use Illuminate\Support\Facades\Input as Input; class ChopsController extends Controller { /** * Store posted chops * * @param Request $request * * @return Response Redirect to homepage view */ public function store(ChopsFormRequest $request, PostChop $post) { $user = Auth::user(); $images = Input::file('image'); $chopsId = $post->saveChops($user, $request); if (! is_null($images[0])) { $shortened_url = $post->uploadImages($images); $post->saveUploads($user, $images, $shortened_url, $chopsId); } return redirect()->action('HomeController@index'); } }
<?php namespace ChopBox\Http\Controllers; use ChopBox\helpers\PostChop; use ChopBox\Http\Requests\ChopsFormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input as Input; class ChopsController extends Controller { /** * Store posted chops * * @param Request $request * * @return Response Redirect to homepage view */ public function store(ChopsFormRequest $request, PostChop $post) { $user = Auth::user(); $images = Input::file('image'); $chopsId = $post->saveChops($user, $request); if (! is_null($images[0])) { $shortened_url = $post->uploadImages($images); $post->saveUploads($user, $images, $shortened_url, $chopsId); } return redirect()->action('HomeController@index'); } }
Add user serialized to ServiceSerializer
from rest_framework import serializers from .models import Service, Category, ServicePhoto from semillas_backend.users.serializers import UserSerializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'photo', 'order') class ServicePhotoSerializer(serializers.ModelSerializer): """ """ class Meta: model = ServicePhoto fields = ('id', 'photo') class ServiceSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from semillas_backend.users.serializers import UserSerializer JSONRenderer().render(UserSerializer(user_instance).data) """ category = CategorySerializer() photos = ServicePhotoSerializer(many=True) author = UserSerializer() class Meta: model = Service fields = ('id', 'title', 'date', 'description', 'author', 'category', 'photos')
from rest_framework import serializers from .models import Service, Category, ServicePhoto class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'photo', 'order') class ServicePhotoSerializer(serializers.ModelSerializer): """ """ class Meta: model = ServicePhoto fields = ('id', 'photo') class ServiceSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from semillas_backend.users.serializers import UserSerializer JSONRenderer().render(UserSerializer(user_instance).data) """ category = CategorySerializer() photos = ServicePhotoSerializer(many=True) class Meta: model = Service fields = ('id', 'title', 'date', 'description', 'category', 'photos')
Increase timeouts for the python test.
# Copyright 2019 DeepMind Technologies Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for open_spiel.python.referee.""" import os import pyspiel from absl.testing import absltest class RefereeTest(absltest.TestCase): def test_playing_tournament(self): base = os.path.dirname(__file__) + "/../../higc/bots" ref = pyspiel.Referee( "kuhn_poker", [f"{base}/random_bot_py.sh", f"{base}/random_bot_cpp.sh"], settings=pyspiel.TournamentSettings(timeout_ready=2000, timeout_start=2000) ) results = ref.play_tournament(num_matches=1) self.assertEqual(len(results.matches), 1) if __name__ == "__main__": absltest.main()
# Copyright 2019 DeepMind Technologies Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for open_spiel.python.referee.""" import os import pyspiel from absl.testing import absltest class RefereeTest(absltest.TestCase): def test_playing_tournament(self): base = os.path.dirname(__file__) + "/../../higc/bots" ref = pyspiel.Referee("kuhn_poker", [f"{base}/random_bot_py.sh", f"{base}/random_bot_cpp.sh"]) results = ref.play_tournament(num_matches=1) self.assertEqual(len(results.matches), 1) if __name__ == "__main__": absltest.main()
Add test for verifying etcd server used under test is the correct version [#98993568]
package store_test import ( "io/ioutil" "net/http" "os" "os/signal" "testing" "github.com/cloudfoundry/storeadapter/storerunner/etcdstorerunner" . "github.com/onsi/ginkgo" "github.com/onsi/ginkgo/config" . "github.com/onsi/gomega" ) var ( etcdRunner *etcdstorerunner.ETCDClusterRunner etcdVersion = "2.1.0" ) func TestStore(t *testing.T) { registerSignalHandler() RegisterFailHandler(Fail) etcdRunner = etcdstorerunner.NewETCDClusterRunner(5001+config.GinkgoConfig.ParallelNode, 1) etcdRunner.Start() RunSpecs(t, "Store Suite") etcdRunner.Stop() } var _ = BeforeSuite(func() { Expect(len(etcdRunner.NodeURLS())).Should(BeNumerically(">=", 1)) etcdVersionUrl := etcdRunner.NodeURLS()[0] + "/version" resp, err := http.Get(etcdVersionUrl) Expect(err).ToNot(HaveOccurred()) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(string(body)).To(ContainSubstring(etcdVersion)) }) var _ = BeforeEach(func() { etcdRunner.Reset() }) func registerSignalHandler() { go func() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) select { case <-c: etcdRunner.Stop() os.Exit(0) } }() }
package store_test import ( . "github.com/onsi/ginkgo" "github.com/onsi/ginkgo/config" . "github.com/onsi/gomega" "github.com/cloudfoundry/storeadapter/storerunner/etcdstorerunner" "os" "os/signal" "testing" ) var etcdRunner *etcdstorerunner.ETCDClusterRunner func TestStore(t *testing.T) { registerSignalHandler() RegisterFailHandler(Fail) etcdRunner = etcdstorerunner.NewETCDClusterRunner(5001+config.GinkgoConfig.ParallelNode, 1) etcdRunner.Start() RunSpecs(t, "Store Suite") etcdRunner.Stop() } var _ = BeforeEach(func() { etcdRunner.Reset() }) func registerSignalHandler() { go func() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) select { case <-c: etcdRunner.Stop() os.Exit(0) } }() }
Update resource name in breadcrumbs if it has been changed (WAL-347)
export const resourceBreadcrumbs = { template: '<breadcrumbs items="$ctrl.items" active-item="$ctrl.activeItem"/>', bindings: { resource: '<' }, controller: class ResourceBreadcrumbsController { constructor(ResourceBreadcrumbsService) { this.ResourceBreadcrumbsService = ResourceBreadcrumbsService; } $onInit() { this.items = [ { label: 'Project dashboard', state: 'project.details', params: { uuid: this.resource.project_uuid } }, ...this.ResourceBreadcrumbsService.get(this.resource), ]; this.activeItem = this.resource.name; } $doCheck() { if (this.activeItem !== this.resource.name) { this.activeItem = this.resource.name; } } } };
export const resourceBreadcrumbs = { template: '<breadcrumbs items="$ctrl.items" active-item="$ctrl.activeItem"/>', bindings: { resource: '<' }, controller: class ResourceBreadcrumbsController { constructor(ResourceBreadcrumbsService) { this.ResourceBreadcrumbsService = ResourceBreadcrumbsService; } $onInit() { this.items = [ { label: 'Project dashboard', state: 'project.details', params: { uuid: this.resource.project_uuid } }, ...this.ResourceBreadcrumbsService.get(this.resource), ]; this.activeItem = this.resource.name; } } };
Use fileinput instead of sed.
from __future__ import print_function import argparse import fileinput import sys from plumbum import local from pre_commit_hooks.util import entry def _fix_file(filename): for line in fileinput.input([filename], inplace=True): print(line.rstrip()) @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) _fix_file(bad_whitespace_file) return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace())
from __future__ import print_function import argparse import sys from plumbum import local from pre_commit_hooks.util import entry @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) local['sed']['-i', '-e', 's/[[:space:]]*$//', bad_whitespace_file]() return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace())
Make -app parameter work again.
#!/usr/bin/php -q <?php /** * Command-line code generation utility to automate programmer chores. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2012, Cake Software Foundation, Inc. * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Console * @since CakePHP(tm) v 1.2.0.5012 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $root = dirname(dirname(dirname(__DIR__))); $loaded = false; $appIndex = array_search('-app', $argv); if ($appIndex !== false) { $loaded = true; $dir = $argv[$appIndex + 1]; require $dir . '/Config/bootstrap.php'; } // Default app directory layout if (!$loaded && file_exists($root . '/App/Config/bootstrap.php')) { require $root . '/App/Config/bootstrap.php'; } unset($root, $loaded, $appIndex, $dir); return Cake\Console\ShellDispatcher::run($argv);
#!/usr/bin/php -q <?php /** * Command-line code generation utility to automate programmer chores. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2012, Cake Software Foundation, Inc. * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Console * @since CakePHP(tm) v 1.2.0.5012 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $root = dirname(dirname(dirname(__DIR__))); // Default app directory layout if (file_exists($root . '/App/Config/bootstrap.php')) { require $root . '/App/Config/bootstrap.php'; } // TODO read ARGV for -app flag, and bootstrap that application. return Cake\Console\ShellDispatcher::run($argv);
Fix sqlite plugin javadoc typo.
/* * 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.jdbi.v3.sqlite3; import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.core.spi.JdbiPlugin; import java.net.URL; /** * Jdbi plugin for SQLite. */ public class SQLitePlugin implements JdbiPlugin { @Override public void customizeJdbi(Jdbi jdbi) { jdbi.registerArgument(new URLArgumentFactory()); jdbi.registerColumnMapper(new URLColumnMapper()); } }
/* * 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.jdbi.v3.sqlite3; import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.core.spi.JdbiPlugin; import java.net.URL; /** * Jdbc plugin for SQLite */ public class SQLitePlugin implements JdbiPlugin { @Override public void customizeJdbi(Jdbi jdbi) { jdbi.registerArgument(new URLArgumentFactory()); jdbi.registerColumnMapper(new URLColumnMapper()); } }
Fix expected error message in test. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@168220 91177308-0d34-0410-b5e6-96231b3b80d8
"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python error raised while importing module: I do not want to be imported']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
"""Check that we handle an ImportError in a special way when command script importing files.""" import os, sys, time import unittest2 import lldb from lldbtest import * class Rdar12586188TestCase(TestBase): mydir = os.path.join("functionalities", "command_script", "import", "rdar-12586188") @python_api_test def test_rdar12586188_command(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.run_test() def setUp(self): # Call super's setUp(). TestBase.setUp(self) def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" self.expect("command script import ./fail12586188.py --allow-reload", error=True, substrs = ['error: module importing failed: I do not want to be imported']) self.expect("command script import ./fail212586188.py --allow-reload", error=True, substrs = ['error: module importing failed: Python raised an error while importing module']) if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
Add helpful logging to app stop handler To mirror similar logging in the desire app handler [#107962562] Signed-off-by: Kira Combs <327dac51f3a5158dc1dbf428a088e367dce1ec10@pivotal.io>
package handlers import ( "net/http" "github.com/cloudfoundry-incubator/bbs" "github.com/cloudfoundry-incubator/bbs/models" "github.com/pivotal-golang/lager" ) type StopAppHandler struct { bbsClient bbs.Client logger lager.Logger } func NewStopAppHandler(logger lager.Logger, bbsClient bbs.Client) *StopAppHandler { return &StopAppHandler{ logger: logger, bbsClient: bbsClient, } } func (h *StopAppHandler) StopApp(resp http.ResponseWriter, req *http.Request) { processGuid := req.FormValue(":process_guid") logger := h.logger.Session("stop-app", lager.Data{"process-guid": processGuid}) if processGuid == "" { logger.Error("missing-process-guid", missingParameterErr) resp.WriteHeader(http.StatusBadRequest) return } logger.Info("stop-request-from-cc", lager.Data{"processGuid": processGuid}) err := h.bbsClient.RemoveDesiredLRP(processGuid) if err != nil { logger.Error("failed-to-delete-desired-lrp", err) bbsError := models.ConvertError(err) if bbsError.Type == models.Error_ResourceNotFound { resp.WriteHeader(http.StatusNotFound) return } resp.WriteHeader(http.StatusServiceUnavailable) return } resp.WriteHeader(http.StatusAccepted) }
package handlers import ( "net/http" "github.com/cloudfoundry-incubator/bbs" "github.com/cloudfoundry-incubator/bbs/models" "github.com/pivotal-golang/lager" ) type StopAppHandler struct { bbsClient bbs.Client logger lager.Logger } func NewStopAppHandler(logger lager.Logger, bbsClient bbs.Client) *StopAppHandler { return &StopAppHandler{ logger: logger, bbsClient: bbsClient, } } func (h *StopAppHandler) StopApp(resp http.ResponseWriter, req *http.Request) { processGuid := req.FormValue(":process_guid") logger := h.logger.Session("stop-app", lager.Data{"process-guid": processGuid}) if processGuid == "" { logger.Error("missing-process-guid", missingParameterErr) resp.WriteHeader(http.StatusBadRequest) return } err := h.bbsClient.RemoveDesiredLRP(processGuid) if err != nil { logger.Error("failed-to-delete-desired-lrp", err) bbsError := models.ConvertError(err) if bbsError.Type == models.Error_ResourceNotFound { resp.WriteHeader(http.StatusNotFound) return } resp.WriteHeader(http.StatusServiceUnavailable) return } resp.WriteHeader(http.StatusAccepted) }
Fix a second infinite loop
// @flow export default function (el: HTMLTextAreaElement, headToCursor: string, cursorToTail: ?string) { const curr = el.value, // strA + strB1 + strC next = headToCursor + (cursorToTail || ''), // strA + strB2 + strC activeElement = document.activeElement; // Calculate length of strA and strC let aLength = 0, cLength = 0; while (aLength < curr.length && aLength < next.length && curr[aLength] === next[aLength]) { aLength++; } while (curr.length - cLength - 1 >= 0 && next.length - cLength - 1 >= 0 && curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) { cLength++; } aLength = Math.min(aLength, Math.min(curr.length, next.length) - cLength); // Select strB1 el.setSelectionRange(aLength, curr.length - cLength); // Get strB2 const strB2 = next.substring(aLength, next.length - cLength); // Replace strB1 with strB2 el.focus(); if (!document.execCommand('insertText', false, strB2)) { // Document.execCommand returns false if the command is not supported. // Firefox and IE returns false in this case. el.value = next; } // Move cursor to the end of headToCursor el.setSelectionRange(headToCursor.length, headToCursor.length); activeElement && activeElement.focus(); return el; }
// @flow export default function (el: HTMLTextAreaElement, headToCursor: string, cursorToTail: ?string) { const curr = el.value, // strA + strB1 + strC next = headToCursor + (cursorToTail || ''), // strA + strB2 + strC activeElement = document.activeElement; // Calculate length of strA and strC let aLength = 0, cLength = 0; while (aLength < curr.length && aLength < next.length && curr[aLength] === next[aLength]) { aLength++; } while (curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) { cLength++; } aLength = Math.min(aLength, Math.min(curr.length, next.length) - cLength); // Select strB1 el.setSelectionRange(aLength, curr.length - cLength); // Get strB2 const strB2 = next.substring(aLength, next.length - cLength); // Replace strB1 with strB2 el.focus(); if (!document.execCommand('insertText', false, strB2)) { // Document.execCommand returns false if the command is not supported. // Firefox and IE returns false in this case. el.value = next; } // Move cursor to the end of headToCursor el.setSelectionRange(headToCursor.length, headToCursor.length); activeElement && activeElement.focus(); return el; }
Use local variable to store monkey-patch state
var isPatched = false; if (isPatched) return console.log('already patched'); function addColor(string, name) { var colors = { green: ['\x1B[32m', '\x1B[39m'], red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'], yellow: ['\x1B[33m', '\x1B[39m'] } return colors[name][0] + string + colors[name][1]; } function getColorName(methodName) { switch (methodName) { case 'error': return 'red'; case 'warn': return 'yellow'; default: return 'green'; } } ['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) { var baseConsoleMethod = console[method]; var slice = Array.prototype.slice; var color = getColorName(method); var messageType = method.toUpperCase(); var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout'; console[method] = function() { var date = (new Date()).toISOString(); var args = slice.call(arguments); if (process[output].isTTY) messageType = addColor(messageType, color); process[output].write('[' + date + '] ' + messageType + ' '); return baseConsoleMethod.apply(console, args); } }); isPatched = true;
if (console._isPatched) return; function addColor(string, name) { var colors = { green: ['\x1B[32m', '\x1B[39m'], red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'], yellow: ['\x1B[33m', '\x1B[39m'] } return colors[name][0] + string + colors[name][1]; } function getColorName(methodName) { switch (methodName) { case 'error': return 'red'; case 'warn': return 'yellow'; default: return 'green'; } } ['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) { var baseConsoleMethod = console[method]; var slice = Array.prototype.slice; var color = getColorName(method); var messageType = method.toUpperCase(); var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout'; console[method] = function() { var date = (new Date()).toISOString(); var args = slice.call(arguments); if (process[output].isTTY) messageType = addColor(messageType, color); process[output].write('[' + date + '] ' + messageType + ' '); return baseConsoleMethod.apply(console, args); } }); console._isPatched = true;
[Bugfix] Remove typo in method name "getEntityByValueAndClass"
<?php namespace Sle\TYPO3\Extbase\Domain\Utility; use TYPO3\CMS\Core\Utility\GeneralUtility; /** * Class EntityUtility * * @package Sle\TYPO3\Extbase\Domain\Utility * @author Steve Lenz <kontakt@steve-lenz.de> * @copyright (c) 2015, Steve Lenz */ class EntityUtility { /** * @param mixed $value * @param string $fullQualifiedClassName - e.g. \\My\\App\\Entity * @return mixed */ public static function getEntityByValueAndClass($value, $fullQualifiedClassName) { if (is_a($value, $fullQualifiedClassName)) { return $value; } else { $om = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager'); $repo = $om->get($fullQualifiedClassName . 'Repository'); $entity = $repo->findByUid($value); return $entity; } } }
<?php namespace Sle\TYPO3\Extbase\Domain\Utility; use TYPO3\CMS\Core\Utility\GeneralUtility; /** * Class EntityUtility * * @package Sle\TYPO3\Extbase\Domain\Utility * @author Steve Lenz <kontakt@steve-lenz.de> * @copyright (c) 2015, Steve Lenz */ class EntityUtility { /** * @param mixed $value * @param string $fullQualifiedClassName - e.g. \\My\\App\\Entity * @return mixed */ public static function getEntityByValueAdnClass($value, $fullQualifiedClassName) { if (is_a($value, $fullQualifiedClassName)) { return $value; } else { $om = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager'); $repo = $om->get($fullQualifiedClassName . 'Repository'); $entity = $repo->findByUid($value); return $entity; } } }
[bbagent] Make and signal process group on *nix. This should enable bootstrapper-based builds to cancel correctly. R=chanli, yiwzhang Change-Id: I786a527a1023c58d79805aaf19fac5d7cd085886 Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-go/+/3340242 Auto-Submit: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org> Reviewed-by: Yiwei Zhang <50b2a565e2e78c292794832469a30ce5abc9959c@google.com> Commit-Queue: Yiwei Zhang <50b2a565e2e78c292794832469a30ce5abc9959c@google.com>
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build !windows package invoke import ( "os/exec" "syscall" "go.chromium.org/luci/common/errors" ) func setSysProcAttr(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} } func (s *Subprocess) terminate() error { if err := syscall.Kill(-s.cmd.Process.Pid, syscall.SIGTERM); err != nil { return errors.Annotate(err, "send SIGTERM").Err() } return nil }
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build !windows package invoke import ( "os/exec" "syscall" "go.chromium.org/luci/common/errors" ) func setSysProcAttr(_ *exec.Cmd) {} func (s *Subprocess) terminate() error { if err := s.cmd.Process.Signal(syscall.SIGTERM); err != nil { return errors.Annotate(err, "send SIGTERM").Err() } return nil }
Fix optional inspection in 3.9
from typing import Tuple, Union def inspect_optional_typing(annotation) -> Tuple[bool, type]: # seems like at some point internal behavior on typing Union changed # https://bugs.launchpad.net/ubuntu/+source/python3.5/+bug/1650202 if "Union" not in str(annotation) and "Optional" not in str(annotation): return False, type(None) if hasattr(annotation, '__origin__'): is_union = annotation.__origin__ == Union else: is_union = issubclass(annotation, Union) if not is_union: return False, type(None) if hasattr(annotation, '__args__'): union_params = annotation.__args__ else: union_params = annotation.__union_params__ is_optional = len(union_params) == 2 and isinstance(None, union_params[1]) return is_optional, union_params[0]
from typing import Tuple, Union def inspect_optional_typing(annotation) -> Tuple[bool, type]: # seems like at some point internal behavior on typing Union changed # https://bugs.launchpad.net/ubuntu/+source/python3.5/+bug/1650202 if "Union" not in str(annotation): return False, type(None) if hasattr(annotation, '__origin__'): is_union = annotation.__origin__ == Union else: is_union = issubclass(annotation, Union) if not is_union: return False, type(None) if hasattr(annotation, '__args__'): union_params = annotation.__args__ else: union_params = annotation.__union_params__ is_optional = len(union_params) == 2 and isinstance(None, union_params[1]) return is_optional, union_params[0]
Use array for search columns
<?php namespace WP_CLI\Fetchers; use WP_User; /** * Fetch a WordPress user based on one of its attributes. */ class User extends Base { /** * The message to display when an item is not found. * * @var string */ protected $msg = "Invalid user ID, email or login: '%s'"; /** * Get a user object by one of its identifying attributes. * * @param string $arg The raw CLI argument. * @return WP_User|false The item if found; false otherwise. */ public function get( $arg ) { if ( is_numeric( $arg ) ) { $users = get_users( [ 'include' => [ (int) $arg ] ] ); } elseif ( is_email( $arg ) ) { $users = get_users( [ 'search' => $arg, 'search_columns' => [ 'user_email' ], ] ); // Logins can be emails. if ( ! $user ) { $users = get_users( [ 'login' => $arg ] ); } } else { $users = get_users( [ 'login' => $arg ] ); } return is_array( $users ) ? $users[0] : false; } }
<?php namespace WP_CLI\Fetchers; use WP_User; /** * Fetch a WordPress user based on one of its attributes. */ class User extends Base { /** * The message to display when an item is not found. * * @var string */ protected $msg = "Invalid user ID, email or login: '%s'"; /** * Get a user object by one of its identifying attributes. * * @param string $arg The raw CLI argument. * @return WP_User|false The item if found; false otherwise. */ public function get( $arg ) { if ( is_numeric( $arg ) ) { $users = get_users( [ 'include' => [ (int) $arg ] ] ); } elseif ( is_email( $arg ) ) { $users = get_users( [ 'search' => $arg, 'search_columns' => 'user_email', ] ); // Logins can be emails. if ( ! $user ) { $users = get_users( [ 'login' => $arg ] ); } } else { $users = get_users( [ 'login' => $arg ] ); } return is_array( $users ) ? $users[0] : false; } }
Fix AmplitudeLimiter > to >= for expected behavour
""".""" class AmplitudeLimiter(object): """.""" def __init__(self, f, *args, **kwargs): """If thereareno decorator args the function tobe decorated is passed to the constructor.""" # print(f) # print(*args) # print(**kwargs) # print("Inside __init__()") self.f = f def __call__(self, f, *args, **kwargs): """The __call__ method is not called until the decorated function is called.""" # print(f) print(*args) # print(**kwargs) # print("Inside __call__()") setpoint = float(*args) if setpoint >= f.amplimit: f.log.warn( "Amplimit ({}) reached with setpoint ({}) on {}" .format(f.amplimit, setpoint, f.instrument)) else: self.f(f, *args) # print("After self.f(*args)")
""".""" class AmplitudeLimiter(object): """.""" def __init__(self, f, *args, **kwargs): """If thereareno decorator args the function tobe decorated is passed to the constructor.""" # print(f) # print(*args) # print(**kwargs) # print("Inside __init__()") self.f = f def __call__(self, f, *args, **kwargs): """The __call__ method is not called until the decorated function is called.""" # print(f) print(*args) # print(**kwargs) # print("Inside __call__()") setpoint = float(*args) if setpoint > f.amplimit: f.log.warn( "Amplimit ({}) reached with setpoint ({}) on {}" .format(f.amplimit, setpoint, f.instrument)) else: self.f(f, *args) # print("After self.f(*args)")
Fix scenario rendering when no param matched.
(function($){ var SEL = { list : "neo-rails-scenarios-list", open : "neo-rails-scenarios-list-open" }; var url_param = function(name){ var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); return results !== null && results[1]; }; $(function(){ $("."+SEL.list).each(function(){ var ui = $(this); ui.on("click", "h2", function(evt){ ui.toggleClass(SEL.open); }); var active_scenario = url_param("scenario"); if (active_scenario){ ui.addClass(SEL.open); }; }); }) })(jQuery);
(function($){ var SEL = { list : "neo-rails-scenarios-list", open : "neo-rails-scenarios-list-open" }; var url_param = function(name){ var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); return results[1] || null; }; $(function(){ $("."+SEL.list).each(function(){ var ui = $(this); ui.on("click", "h2", function(evt){ ui.toggleClass(SEL.open); }); var active_scenario = url_param("scenario"); if(active_scenario !== null){ ui.addClass(SEL.open); }; }); }) })(jQuery);
Fix import error caught by new version of isort (4.2.8)
"""Patch ReSDK resources with analysis methods.""" from __future__ import absolute_import, division, print_function, unicode_literals from resdk.analysis.alignment import bowtie2, hisat2 from resdk.analysis.chip_seq import macs, rose2 from resdk.analysis.expressions import cuffnorm, cuffquant from resdk.analysis.plots import bamliquidator, bamplot from resdk.resources import Collection, Relation, Sample Collection.run_bamliquidator = bamliquidator Collection.run_bamplot = bamplot Collection.run_bowtie2 = bowtie2 Collection.run_cuffnorm = cuffnorm Collection.run_cuffquant = cuffquant Collection.run_hisat2 = hisat2 Collection.run_macs = macs Collection.run_rose2 = rose2 Relation.run_bamliquidator = bamliquidator Relation.run_bamplot = bamplot Relation.run_bowtie2 = bowtie2 Relation.run_cuffnorm = cuffnorm Relation.run_cuffquant = cuffquant Relation.run_hisat2 = hisat2 Relation.run_macs = macs Relation.run_rose2 = rose2 Sample.run_bowtie2 = bowtie2 Sample.run_cuffquant = cuffquant Sample.run_hisat2 = hisat2 Sample.run_macs = macs Sample.run_rose2 = rose2
"""Patch ReSDK resources with analysis methods.""" from __future__ import absolute_import, division, print_function, unicode_literals from resdk.analysis.alignment import bowtie2, hisat2 from resdk.analysis.chip_seq import macs, rose2 from resdk.analysis.expressions import cuffnorm, cuffquant from resdk.analysis.plots import bamliquidator, bamplot from resdk.resources import Collection, Relation, Sample Collection.run_bamliquidator = bamliquidator Collection.run_bamplot = bamplot Collection.run_bowtie2 = bowtie2 Collection.run_cuffnorm = cuffnorm Collection.run_cuffquant = cuffquant Collection.run_hisat2 = hisat2 Collection.run_macs = macs Collection.run_rose2 = rose2 Relation.run_bamliquidator = bamliquidator Relation.run_bamplot = bamplot Relation.run_bowtie2 = bowtie2 Relation.run_cuffnorm = cuffnorm Relation.run_cuffquant = cuffquant Relation.run_hisat2 = hisat2 Relation.run_macs = macs Relation.run_rose2 = rose2 Sample.run_bowtie2 = bowtie2 Sample.run_cuffquant = cuffquant Sample.run_hisat2 = hisat2 Sample.run_macs = macs Sample.run_rose2 = rose2
Fix how to calculate ws URL from baseapi URL
/* jshint camelcase:false */ Polymer('nn-annotable', { ready: function(){ this.baseapi = this.baseapi || window.location.origin; this.tokens = this.baseapi.split('://'); this.wsurl = (this.tokens.shift() === 'https' ? 'wss' : 'ws') + '://' + this.tokens.shift(); this.domain = window.location.hostname; this.connect = (this.connect !== undefined) ? this.connect : true; this.comments = []; }, attached: function(){ if(!this.nid){ throw 'Attribute missing: nid'; } this.$.websocket.addEventListener('message', this.updateComments.bind(this)); this.$.get_comments.go(); }, populateComments: function(evt){ this.comments = evt.detail.response; }, updateComments: function(evt){ this.comments.push(evt.detail); }, newComment: function(evt){ this.message = ''; evt.preventDefault(); if(!this.author || !this.text){ this.message = 'completa tutti i campi'; return; } this.$.new_comment.go(); }, resetForm: function(){ this.author = this.text = ''; } });
/* jshint camelcase:false */ Polymer('nn-annotable', { ready: function(){ this.baseapi = this.baseapi || window.location.origin; this.tokens = this.baseapi.split('://'); this.wsurl = this.tokens.shift() === 'https' ? 'wss' : 'ws' + '://' + this.tokens.shift(); this.domain = window.location.hostname; this.connect = (this.connect !== undefined) ? this.connect : true; this.comments = []; }, attached: function(){ if(!this.nid){ throw 'Attribute missing: nid'; } this.$.websocket.addEventListener('message', this.updateComments.bind(this)); this.$.get_comments.go(); }, populateComments: function(evt){ this.comments = evt.detail.response; }, updateComments: function(evt){ this.comments.push(evt.detail); }, newComment: function(evt){ this.message = ''; evt.preventDefault(); if(!this.author || !this.text){ this.message = 'completa tutti i campi'; return; } this.$.new_comment.go(); }, resetForm: function(){ this.author = this.text = ''; } });
Add a new invariant check: check blackholes *or* loops
from sts.invariant_checker import InvariantChecker import sys def bail_on_connectivity(simulation): result = InvariantChecker.python_check_connectivity(simulation) if not result: print "Connectivity established - bailing out" sys.exit(0) return [] def check_for_loops_or_connectivity(simulation): result = InvariantChecker.check_loops(simulation) if result: return result return bail_on_connectivity(simulation) def check_for_loops_blackholes_or_connectivity(simulation): for check in [InvariantChecker.check_loops, InvariantChecker.check_blackholes]: result = check(simulation) if result: return result return bail_on_connectivity(simulation) # Note: make sure to add new custom invariant checks to this dictionary! name_to_invariant_check = { "check_for_loops_or_connectivity" : check_for_loops_or_connectivity, "check_for_loops_blackholes_or_connectivity" : check_for_loops_blackholes_or_connectivity, "InvariantChecker.check_liveness" : InvariantChecker.check_liveness, "InvariantChecker.check_loops" : InvariantChecker.check_loops, "InvariantChecker.python_check_connectivity" : InvariantChecker.python_check_connectivity, "InvariantChecker.check_connectivity" : InvariantChecker.check_connectivity, "InvariantChecker.check_blackholes" : InvariantChecker.check_blackholes, "InvariantChecker.check_correspondence" : InvariantChecker.check_correspondence, }
from sts.invariant_checker import InvariantChecker def check_for_loops_or_connectivity(simulation): from sts.invariant_checker import InvariantChecker result = InvariantChecker.check_loops(simulation) if result: return result result = InvariantChecker.python_check_connectivity(simulation) if not result: print "Connectivity established - bailing out" import sys sys.exit(0) return [] # Note: make sure to add new custom invariant checks to this dictionary! name_to_invariant_check = { "check_for_loops_or_connectivity" : check_for_loops_or_connectivity, "InvariantChecker.check_liveness" : InvariantChecker.check_liveness, "InvariantChecker.check_loops" : InvariantChecker.check_loops, "InvariantChecker.python_check_connectivity" : InvariantChecker.python_check_connectivity, "InvariantChecker.check_connectivity" : InvariantChecker.check_connectivity, "InvariantChecker.check_blackholes" : InvariantChecker.check_blackholes, "InvariantChecker.check_correspondence" : InvariantChecker.check_correspondence, }
Change helper, add additional support traits
<?php namespace Aedart\Testing\Laravel\Traits; use Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication; use Illuminate\Foundation\Testing\Concerns\InteractsWithConsole; use Illuminate\Foundation\Testing\Concerns\InteractsWithContainer; use Illuminate\Foundation\Testing\Concerns\InteractsWithDatabase; use Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling; use Illuminate\Foundation\Testing\Concerns\InteractsWithSession; use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests; use Illuminate\Foundation\Testing\Concerns\MocksApplicationServices; use Orchestra\Testbench\Traits\WithFactories; use Orchestra\Testbench\Traits\WithLaravelMigrations; use Orchestra\Testbench\Traits\WithLoadMigrationsFrom; /** * Trait Test Helper * * @see \Aedart\Testing\Laravel\Contracts\TestCase * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Testing\Laravel\Traits */ trait TestHelperTrait { use ApplicationInitiatorTrait; use InteractsWithContainer; use MakesHttpRequests; use InteractsWithAuthentication; use InteractsWithConsole; use InteractsWithExceptionHandling; use InteractsWithDatabase; use InteractsWithSession; use MocksApplicationServices; use WithFactories; use WithLaravelMigrations; use WithLoadMigrationsFrom; }
<?php namespace Aedart\Testing\Laravel\Traits; use Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication; use Illuminate\Foundation\Testing\Concerns\InteractsWithConsole; use Illuminate\Foundation\Testing\Concerns\InteractsWithContainer; use Illuminate\Foundation\Testing\Concerns\InteractsWithDatabase; use Illuminate\Foundation\Testing\Concerns\InteractsWithSession; use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests; use Illuminate\Foundation\Testing\Concerns\MocksApplicationServices; use Orchestra\Testbench\Traits\WithFactories; /** * Trait Test Helper * * @see \Aedart\Testing\Laravel\Interfaces\ITestHelper * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Testing\Laravel\Traits */ trait TestHelperTrait { use ApplicationInitiatorTrait; use InteractsWithContainer; use MakesHttpRequests; use InteractsWithAuthentication; use InteractsWithConsole; use InteractsWithDatabase; use InteractsWithSession; use MocksApplicationServices; use WithFactories; }
Remove extraneous parent reference from Footer
/* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT @license. */ /** A Footer is a generic class that only defines a default tag `tfoot` and number of required parameters in the initializer. @abstract @class Backgrid.Footer @extends Backbone.View */ var Footer = Backgrid.Footer = Backbone.View.extend({ /** @property */ tagName: "tfoot", /** Initializer. @param {Object} options @param {*} options.parent The parent view class of this footer. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Collection} options.collection @throws {TypeError} If options.columns or options.collection is undefined. */ initialize: function (options) { Backgrid.requireOptions(options, ["columns", "collection"]); this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Backgrid.Columns(this.columns); } } });
/* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT @license. */ /** A Footer is a generic class that only defines a default tag `tfoot` and number of required parameters in the initializer. @abstract @class Backgrid.Footer @extends Backbone.View */ var Footer = Backgrid.Footer = Backbone.View.extend({ /** @property */ tagName: "tfoot", /** Initializer. @param {Object} options @param {*} options.parent The parent view class of this footer. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Collection} options.collection @throws {TypeError} If options.columns or options.collection is undefined. */ initialize: function (options) { Backgrid.requireOptions(options, ["columns", "collection"]); this.parent = options.parent; this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Backgrid.Columns(this.columns); } } });
Modify the interfaces listing view to filter only the port on the mgt network DHC-1512 Change-Id: If7e5aebf7cfd7e87df0dea8cd749764c142f1676 Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
from django.utils.translation import ugettext_lazy as _ # noqa from horizon import exceptions from openstack_dashboard import api def get_interfaces_data(self): try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) # Note(rods): Filter off the port on the mgt network ports = [api.quantum.Port(p) for p in router.ports if p['device_owner'] != 'network:router_management'] except Exception: ports = [] msg = _( 'Port list can not be retrieved for router ID %s' % self.kwargs.get('router_id') ) exceptions.handle(self.request, msg) for p in ports: p.set_id_as_name_if_empty() return ports
from django.utils.translation import ugettext_lazy as _ # noqa from horizon import exceptions from openstack_dashboard import api def get_interfaces_data(self): try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) # Note(rods): Right now we are listing, for both normal and # admin users, all the ports on the user's networks # the router is associated with. We may want in the # future show the ports on the mgt and the external # networks for the admin users. ports = [api.quantum.Port(p) for p in router.ports if p['device_owner'] == 'network:router_interface'] except Exception: ports = [] msg = _( 'Port list can not be retrieved for router ID %s' % self.kwargs.get('router_id') ) exceptions.handle(self.request, msg) for p in ports: p.set_id_as_name_if_empty() return ports
Return error from search string
package main import ( "bytes" "errors" "fmt" "log" "net/http" "strings" ) const baseURL = "https://api.github.com/search/repositories" type Query struct { Q string Lang string Limit int } func escapeSearch(s string) string { return strings.Replace(s, " ", "+", -1) } func searchString(q Query) (string, error) { var buffer bytes.Buffer buffer.WriteString(baseURL) fmt.Println(q) if q.Q == "" { return "", errors.New("You must enter a search query") } query := fmt.Sprintf("?q=%s", escapeSearch(q.Q)) buffer.WriteString(query) // return fmt.Sprintf("%s?q=%s+language:assembly&sort=stars&order=desc", baseURL, q) return buffer.String(), nil } func requestSearch(url string, client http.Client) (r *http.Response, e error) { res, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal(err) } res.Header.Set("Accept", "application/vnd.github.preview") return client.Do(res) } func main() { fmt.Println(searchString(Query{"foo bar", "", 0})) }
package main import ( "bytes" "fmt" "log" "net/http" "strings" ) const baseURL = "https://api.github.com/search/repositories" type Query struct { Q string Lang string Limit int } func escapeSearch(s string) string { return strings.Replace(s, " ", "+", -1) } func searchString(q Query) string { var buffer bytes.Buffer buffer.WriteString(baseURL) fmt.Println(q) if q.Q == "" { log.Fatal("You must enter a search query") } query := fmt.Sprintf("?q=%s", escapeSearch(q.Q)) buffer.WriteString(query) // return fmt.Sprintf("%s?q=%s+language:assembly&sort=stars&order=desc", baseURL, q) return buffer.String() } func requestSearch(url string, client http.Client) (r *http.Response, e error) { res, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal(err) } res.Header.Set("Accept", "application/vnd.github.preview") return client.Do(res) } func main() { fmt.Println(searchString(Query{"foo bar", "", 0})) }
Fix test, editor instance is required
# -*- coding: utf-8 -*- """ This is a simple test script to that is meant to be run by Travis CI to ensure everything works properly foreach bindings on each supported python version (3.2, 3.3, 3.4). It runs a QApplication and shows a QPythonCodeEdit for 500ms. """ import sys from PyQt4 import QtCore, QtGui from pyqode.core import client from pyqode.python.editor import QPythonCodeEdit import logging logging.basicConfig(level=True) def leave(): app = QtGui.QApplication.instance() app.exit(0) def test_editor(): app = QtGui.QApplication(sys.argv) editor = QPythonCodeEdit() editor.show() editor.start_server() editor.open_file(__file__) QtCore.QTimer.singleShot(500, leave) app.exec_() client.stop_server(editor) del editor del app
# -*- coding: utf-8 -*- """ This is a simple test script to that is meant to be run by Travis CI to ensure everything works properly foreach bindings on each supported python version (3.2, 3.3, 3.4). It runs a QApplication and shows a QPythonCodeEdit for 500ms. """ import sys from PyQt4 import QtCore, QtGui from pyqode.core import client from pyqode.python.editor import QPythonCodeEdit import logging logging.basicConfig(level=True) def leave(): app = QtGui.QApplication.instance() app.exit(0) def test_editor(): app = QtGui.QApplication(sys.argv) editor = QPythonCodeEdit() editor.show() editor.start_server() editor.open_file(__file__) QtCore.QTimer.singleShot(500, leave) app.exec_() client.stop_server() del editor del app
Support Circle fill in SVG
/* This acts as both a way to normalize attribute names, but also acts as a white list for the supported properties. */ export default { 'circle': { 'radius': 'r', 'x': 'cx', 'y': 'cy', 'fill': 'fill', 'stroke': 'stroke', 'stroke-width': 'stroke-width' }, 'group': { 'transform': 'transform' }, 'rect': { 'x': 'x', 'y': 'y', 'height': 'height', 'width': 'width', 'fill': 'fill', 'stroke': 'stroke', 'stroke-width': 'stroke-width' }, 'line': { 'x1': 'x1', 'x2': 'x2', 'y1': 'y1', 'y2': 'y2', 'stroke': 'stroke', 'stroke-width': 'stroke-width' }, 'path': { 'd': 'd', 'stroke': 'stroke', 'stroke-width': 'stroke-width', 'fill': 'fill' }, 'text': { 'x': 'x', 'y': 'y' } };
/* This acts as both a way to normalize attribute names, but also acts as a white list for the supported properties. */ export default { 'circle': { 'radius': 'r', 'x': 'cx', 'y': 'cy' }, 'group': { 'transform': 'transform' }, 'rect': { 'x': 'x', 'y': 'y', 'height': 'height', 'width': 'width', 'fill': 'fill', 'stroke': 'stroke', 'stroke-width': 'stroke-width' }, 'line': { 'x1': 'x1', 'x2': 'x2', 'y1': 'y1', 'y2': 'y2', 'stroke': 'stroke', 'stroke-width': 'stroke-width' }, 'path': { 'd': 'd', 'stroke': 'stroke', 'stroke-width': 'stroke-width', 'fill': 'fill' }, 'text': { 'x': 'x', 'y': 'y' } };
Fix Javadoc first sentence ending with a period
package com.easternedgerobotics.rov.event.io; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.FastInput; import com.esotericsoftware.kryo.io.FastOutput; import com.esotericsoftware.kryo.io.Output; /** * The KryoSerializer class serializes and deserializes Java objects * using <a href="https://github.com/EsotericSoftware/kryo">Kryo</a>. * <p> * This class is not thread safe because Kryo is not thread safe. */ public class KryoSerializer implements Serializer { /** * The Kryo instance. */ private final Kryo kryo; public KryoSerializer() { kryo = new Kryo(); } @Override public byte[] serialize(final Object value) { final Output output = new FastOutput(16, 1024); kryo.writeClassAndObject(output, value); return output.toBytes(); } @Override public Object deserialize(final byte[] bytes) { return kryo.readClassAndObject(new FastInput(bytes)); } }
package com.easternedgerobotics.rov.event.io; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.FastInput; import com.esotericsoftware.kryo.io.FastOutput; import com.esotericsoftware.kryo.io.Output; /** * The KryoSerializer class serializes and deserializes Java objects * using <a href="https://github.com/EsotericSoftware/kryo">Kryo</a>. * <p> * This class is not thread safe because Kryo is not thread safe. */ public class KryoSerializer implements Serializer { /** * The Kryo instance */ private final Kryo kryo; public KryoSerializer() { kryo = new Kryo(); } @Override public byte[] serialize(final Object value) { final Output output = new FastOutput(16, 1024); kryo.writeClassAndObject(output, value); return output.toBytes(); } @Override public Object deserialize(final byte[] bytes) { return kryo.readClassAndObject(new FastInput(bytes)); } }
Support locales into the component
import { translate } from './translator' var Vue var data = { lang: { value: '' }, locales: {} } class Locale { constructor (locales, lang = 'en') { if (!Locale.installed) { throw new Error( 'Please install the VueLocale with Vue.use() before creating an instance.' ) } data.lang.value = lang data.locales = locales Vue.util.defineReactive({}, null, data.lang) Vue.prototype.$lang = function (path, repls) { // search for the path 'locally' return translate(this.$options.locales, data.lang.value, path, repls) // search for the path 'globally' || translate(data.locales, data.lang.value, path, repls) // if the path does not exist, return the path || path } Vue.prototype.$lang.change = this.change.bind(this) } change (lang) { if (data.lang.value === lang) return data.lang.value = lang } } Locale.installed = false Locale.install = (vue) => { Vue = vue Locale.installed = true } export default Locale
import { translate } from './translator' var Vue var data = { lang: { value: '' }, locales: {} } class Locale { constructor (locales, lang = 'en') { if (!Locale.installed) { throw new Error( 'Please install the VueLocale with Vue.use() before creating an instance.' ) } data.lang.value = lang data.locales = locales Vue.util.defineReactive({}, null, data.lang) Vue.prototype.$lang = function (path, repls) { return translate(data.locales, data.lang.value, path, repls) || path } Vue.prototype.$lang.change = this.change.bind(this) } change (lang) { if (data.lang.value === lang) return data.lang.value = lang } } Locale.installed = false Locale.install = (vue) => { Vue = vue Locale.installed = true } export default Locale
Fix for asset log incorrectly using soft deletes
<?php class Actionlog extends Eloquent { protected $table = 'asset_logs'; public $timestamps = false; public function assetlog() { return $this->belongsTo('Asset','asset_id')->withTrashed(); } public function licenselog() { return $this->belongsTo('License','asset_id'); } public function adminlog() { return $this->belongsTo('User','user_id'); } public function userlog() { return $this->belongsTo('User','checkedout_to')->withTrashed(); } /** * Get the parent category name */ public function logaction($actiontype) { $this->action_type = $actiontype; if($this->save()) { return true; } else { return false; } } }
<?php class Actionlog extends Eloquent { use SoftDeletingTrait; protected $dates = ['deleted_at']; protected $table = 'asset_logs'; public $timestamps = false; public function assetlog() { return $this->belongsTo('Asset','asset_id')->withTrashed(); } public function licenselog() { return $this->belongsTo('License','asset_id'); } public function adminlog() { return $this->belongsTo('User','user_id'); } public function userlog() { return $this->belongsTo('User','checkedout_to')->withTrashed(); } /** * Get the parent category name */ public function logaction($actiontype) { $this->action_type = $actiontype; if($this->save()) { return true; } else { return false; } } }
Correct token sale banner timezone.
'use strict' import {Component} from 'react' import {Link} from 'react-router' import Countdown from 'react-countdown-now'; import CountdownTimer from './CountdownTimer' const registrationEndDate = "Wednesday, November 15 2017 15:00:00 EST" class Alert extends Component { constructor(props) { super(props) } render() { return ( <a href="http://blockstack.com" target="_blank" className="alert alert-primary alert-dismissible fade show text-center text-white" role="alert" style={{ marginBottom: '0', display: "block", paddingBottom: '21px' }}> <div> <button type="button" className="close close-primary d-none d-sm-block" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <span className="" style={{ marginLeft: "26px" }}>Blockstack Token Main Sale Starts - Thu, Nov 16 at 11AM EDT</span> </div> </a> ) } } export default Alert
'use strict' import {Component} from 'react' import {Link} from 'react-router' import Countdown from 'react-countdown-now'; import CountdownTimer from './CountdownTimer' const registrationEndDate = "Wednesday, November 15 2017 15:00:00 EST" class Alert extends Component { constructor(props) { super(props) } render() { return ( <a href="http://blockstack.com" target="_blank" className="alert alert-primary alert-dismissible fade show text-center text-white" role="alert" style={{ marginBottom: '0', display: "block", paddingBottom: '21px' }}> <div> <button type="button" className="close close-primary d-none d-sm-block" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <span className="" style={{ marginLeft: "26px" }}>Blockstack Token Main Sale Starts - Thu, Nov 16 at 11AM EST</span> </div> </a> ) } } export default Alert
Fix the issue on Xs or Os problem.
def checkio(array): if (array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]) and array[0][0] != '.': return array[0][0] if (array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]) and array[1][1] != '.': return array[1][1] if (array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]) and array[2][2] != '.' : return array[2][2] return "D" if __name__ == '__main__': assert checkio([ "X.O", "XX.", "XOO"]) == "X", "Xs wins" assert checkio([ "OO.", "XOX", "XOX"]) == "O", "Os wins" assert checkio([ "OOX", "XXO", "OXX"]) == "D", "Draw" assert checkio([ "...", "XXO", "XXO" ]) == "D", "Draw"
def checkio(array): if array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]: return array[0][0] if array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]: return array[1][1] if array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]: return array[2][2] return "D" if __name__ == '__main__': assert checkio([ "X.O", "XX.", "XOO"]) == "X", "Xs wins" assert checkio([ "OO.", "XOX", "XOX"]) == "O", "Os wins" assert checkio([ "OOX", "XXO", "OXX"]) == "D", "Draw"
Change the static copy command so it works with new layout.
from django.core.management.base import NoArgsCommand import os import shutil class Command(NoArgsCommand): help = "Copy the satchmo static directory and files to the local project." def handle_noargs(self, **options): import satchmo_store static_src = os.path.join(satchmo_store.__path__[0],'../../static') static_dest = os.path.join(os.getcwd(), 'static') if os.path.exists(static_dest): print "Static directory exists. You must manually copy the files you need." else: shutil.copytree(static_src, static_dest) for root, dirs, files in os.walk(static_dest): if '.svn' in dirs: shutil.rmtree(os.path.join(root,'.svn'), True) print "Copied %s to %s" % (static_src, static_dest)
from django.core.management.base import NoArgsCommand import os import shutil class Command(NoArgsCommand): help = "Copy the satchmo static directory and files to the local project." def handle_noargs(self, **options): import satchmo_store static_src = os.path.join(satchmo_store.__path__[0],'static') static_dest = os.path.join(os.getcwd(), 'static') if os.path.exists(static_dest): print "Static directory exists. You must manually copy the files you need." else: shutil.copytree(static_src, static_dest) for root, dirs, files in os.walk(static_dest): if '.svn' in dirs: shutil.rmtree(os.path.join(root,'.svn'), True) print "Copied %s to %s" % (static_src, static_dest)
Update test to work with current jquery-ui
# Copyright (c) 2012 gocept gmbh & co. kg # See also LICENSE.txt import zeit.content.article.testing class Preview(zeit.content.article.testing.SeleniumTestCase): def test_selected_tab_is_stored_across_reload(self): self.open('/repository/online/2007/01/Somalia') s = self.selenium selected_tab = 'css=#preview-tabs .ui-tabs-active' s.waitForElementPresent(selected_tab) s.waitForText(selected_tab, 'iPad') s.click('css=#preview-tabs a:contains("Desktop")') s.waitForText(selected_tab, 'Desktop') s.refresh() s.waitForElementPresent(selected_tab) s.waitForText(selected_tab, 'Desktop')
# Copyright (c) 2012 gocept gmbh & co. kg # See also LICENSE.txt import zeit.content.article.testing class Preview(zeit.content.article.testing.SeleniumTestCase): def test_selected_tab_is_stored_across_reload(self): self.open('/repository/online/2007/01/Somalia') s = self.selenium selected_tab = 'css=#preview-tabs .ui-tabs-selected' s.waitForElementPresent(selected_tab) s.assertText(selected_tab, 'iPad') s.click('css=#preview-tabs a:contains("Desktop")') s.waitForText(selected_tab, 'Desktop') s.refresh() s.waitForElementPresent(selected_tab) s.assertText(selected_tab, 'Desktop')
Exclude QuickFilesNodes that don't have contributors
import logging import sys from django.db import transaction from django.db.models import F, Count from website.app import setup_django setup_django() from osf.models import QuickFilesNode from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(): dry = '--dry' in sys.argv if not dry: # If we're not running in dry mode log everything to a file script_utils.add_file_logger(logger, __file__) with transaction.atomic(): qs = QuickFilesNode.objects.exclude(_contributors=F('creator')).annotate(contrib_count=Count('_contributors')).exclude(contrib_count=0) logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count())) for node in qs: bad_contrib = node._contributors.get() logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id)) node.contributor_set.filter(user=bad_contrib).update(user=node.creator) node.save() if dry: raise Exception('Abort Transaction - Dry Run') print('Done') if __name__ == '__main__': main()
import logging import sys from django.db import transaction from django.db.models import F from website.app import setup_django setup_django() from osf.models import QuickFilesNode from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(): dry = '--dry' in sys.argv if not dry: # If we're not running in dry mode log everything to a file script_utils.add_file_logger(logger, __file__) with transaction.atomic(): qs = QuickFilesNode.objects.exclude(_contributors=F('creator')) logger.info('Found {} quickfiles nodes with mismatched creator and _contributors'.format(qs.count())) for node in qs: # There should only be one contributor, will error if this assumption is false bad_contrib = node._contributors.get() logger.info('Fixing {} (quickfiles node): Replacing {} (bad contributor) with {} (creator)'.format(node._id, bad_contrib._id, node.creator._id)) node.contributor_set.filter(user=bad_contrib).update(user=node.creator) node.save() if dry: raise Exception('Abort Transaction - Dry Run') print('Done') if __name__ == '__main__': main()
Check if not hasOwnProperty when copying Java prototype to Vue object
/** * This object provides methods to integrate Java in Vue.JS world * @author Adrien Baron */ window.vueGwt = { createVueInstance: function (vueComponentDefinition) { return new Vue(vueComponentDefinition); }, createInstanceForVueClass: function (extendedVueClass) { return new extendedVueClass(); } }; Vue.use(function (Vue) { Vue.mixin({ created: function () { if (!this.$options.vuegwt$javaComponentInstance) return; // This is required for GWT type checking to work var jciProto = this.$options.vuegwt$javaComponentInstance.__proto__; for (var protoProp in jciProto) { if (jciProto.hasOwnProperty(protoProp) && !this.hasOwnProperty(protoProp)) { this[protoProp] = jciProto[protoProp]; } } } }) });
/** * This object provides methods to integrate Java in Vue.JS world * @author Adrien Baron */ window.vueGwt = { createVueInstance: function (vueComponentDefinition) { return new Vue(vueComponentDefinition); }, createInstanceForVueClass: function (extendedVueClass) { return new extendedVueClass(); } }; Vue.use(function (Vue) { Vue.mixin({ created: function () { if (!this.$options.vuegwt$javaComponentInstance) return; // This is required for GWT type checking to work var jciProto = this.$options.vuegwt$javaComponentInstance.__proto__; for (var protoProp in jciProto) { if (jciProto.hasOwnProperty(protoProp) && !this[protoProp]) { this[protoProp] = jciProto[protoProp]; } } } }) });
Update testcases with proper casing
import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( '.molecule/ansible_inventory').get_hosts('all') desktop_file_location = "/root/.local/share/applications/rubymine-2017.2.desktop" def test_desktop_file_exists(File): f = File(desktop_file_location) assert f.exists assert f.is_file def test_desktop_file_contains_fullpath(File): f = File(desktop_file_location) assert f.contains("/root/Tools/RubyMine-2017.2/bin/rubymine.png") assert f.contains("/root/Tools/RubyMine-2017.2/bin/rubymine.sh") def test_desktop_file_contains_right_name(File): f = File(desktop_file_location) assert f.contains("RubyMine 2017.2") def test_start_file_exists(File): f = File('/root/Tools/RubyMine-2017.2/bin/rubymine.sh') assert f.exists assert f.is_file
import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( '.molecule/ansible_inventory').get_hosts('all') desktop_file_location = "/root/.local/share/applications/rubymine-2017.2.desktop" def test_desktop_file_exists(File): f = File(desktop_file_location) assert f.exists assert f.is_file def test_desktop_file_contains_fullpath(File): f = File(desktop_file_location) assert f.contains("/root/Tools/RubyMine-2017.2/bin/rubymine.png") assert f.contains("/root/Tools/RubyMine-2017.2/bin/rubymine.sh") def test_desktop_file_contains_right_name(File): f = File(desktop_file_location) assert f.contains("rubymine 2017.2") def test_start_file_exists(File): f = File('/root/Tools/RubyMine-2017.2/bin/rubymine.sh') assert f.exists assert f.is_file
Allow creation of expired tokens
import jsrsasign from 'jsrsasign'; @registerDynamicValueClass class JsonWebTokenDynamicValue { static identifier = 'de.choffmeister.PawExtensions.JsonWebTokenDynamicValue'; static title = 'Json Web Token'; static help = 'https://github.com/choffmeister/Paw-JsonWebTokenDynamicValue'; static inputs = [ DynamicValueInput('isExpired', 'Expired', 'Checkbox'), DynamicValueInput('payload', 'Payload', 'JSON'), DynamicValueInput('signatureSecret', 'Secret', 'SecureValue'), DynamicValueInput('signatureSecretIsBase64', 'Secret is Base64', 'Checkbox') ]; evaluate() { const now = Math.floor((new Date()).getTime() / 1000); const oneHour = 60 * 60; const header = { typ: 'JWT', alg: 'HS256' }; const payload = { ...this.payload, exp: !this.isExpired ? now + oneHour : now - oneHour, iat: !this.isExpired ? now : now - 2*oneHour }; const secret = this.signatureSecretIsBase64 ? {b64: jsrsasign.b64utob64(this.signatureSecret)} : this.signatureSecret; return jsrsasign.jws.JWS.sign(null, header, payload, secret); } }
import jsrsasign from 'jsrsasign'; @registerDynamicValueClass class JsonWebTokenDynamicValue { static identifier = 'de.choffmeister.PawExtensions.JsonWebTokenDynamicValue'; static title = 'Json Web Token'; static help = 'https://github.com/choffmeister/Paw-JsonWebTokenDynamicValue'; static inputs = [ DynamicValueInput('signatureSecret', 'Secret', 'SecureValue'), DynamicValueInput('signatureSecretIsBase64', 'Secret is Base64', 'Checkbox'), DynamicValueInput('payload', 'Payload', 'JSON') ]; evaluate() { const now = Math.floor((new Date()).getTime() / 1000); const header = { typ: 'JWT', alg: 'HS256' }; const payload = { ...this.payload, exp: now + (60 * 60 * 24 * 7), iat: now }; const secret = this.signatureSecretIsBase64 ? {b64: jsrsasign.b64utob64(this.signatureSecret)} : this.signatureSecret; return jsrsasign.jws.JWS.sign(null, header, payload, secret); } }
Refresh after tab selection changed. Refresh after tab selection changed.
 $(document).ready(function () { $('#userTree').jstree({ 'core': { 'data': { 'url': '/Authorisation/GetTree?tab=' + $(this).attr('href'), 'data': function (node) { return { 'id': node.id }; } } } }); $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { localStorage.setItem('activeTab', $(this).attr('href')); $('#userTree').jstree(true).settings.core.url = '/Authorisation/GetTree?tab=' + $(this).attr('href'); $('#userTree').jstree(true).refresh(); }); var activeTab = localStorage.getItem('activeTab'); if (activeTab) { $('[href="' + activeTab + '"]').tab('show'); } });
 $(document).ready(function () { $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { localStorage.setItem('activeTab', $(this).attr('href')); alert($(this).attr('href')); $('#userTree').jstree({ 'core': { 'data': { 'url': '/Authorisation/GetTree?' + $(this).attr('href'), 'data': function (node) { return { 'id': node.id }; } } } }); }); var activeTab = localStorage.getItem('activeTab'); if (activeTab) { $('[href="' + activeTab + '"]').tab('show'); alert("test 2"); } });
Patch missing method on cgi package
from operator import itemgetter from itertools import chain from typing import List import cgi from urllib.parse import parse_qs from ...utils.py3_hook import with_hook with with_hook(): from arcrest import Catalog import numpy as np cgi.parse_qs = parse_qs def get_layers(service): layers = service.layers return { layer.name: layer for layer in layers } def mend_extent(extent): extent.wkid = extent.spatialReference.wkid return extent def get_data(requested_layers: List[str]): catalog = Catalog('http://services.ga.gov.au/site_7/rest/services') service = catalog['NM_Transport_Infrastructure'] layers = get_layers(service) return chain.from_iterable( layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent)) for layer in requested_layers ) def get_paths(request_layers: List[str]) -> np.array: paths = get_data(request_layers) paths = map(itemgetter('geometry'), paths) paths = chain.from_iterable( geometry.paths for geometry in paths if hasattr(geometry, 'paths') ) return np.array([ tuple( (part.x, part.y) for part in path ) for path in paths ])
from operator import itemgetter from itertools import chain from typing import List from ...utils.py3_hook import with_hook with with_hook(): from arcrest import Catalog import numpy as np def get_layers(service): layers = service.layers return { layer.name: layer for layer in layers } def mend_extent(extent): extent.wkid = extent.spatialReference.wkid return extent def get_data(requested_layers: List[str]): catalog = Catalog('http://services.ga.gov.au/site_7/rest/services') service = catalog['NM_Transport_Infrastructure'] layers = get_layers(service) return chain.from_iterable( layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent)) for layer in requested_layers ) def get_paths(request_layers: List[str]) -> np.array: paths = get_data(request_layers) paths = map(itemgetter('geometry'), paths) paths = chain.from_iterable( geometry.paths for geometry in paths if hasattr(geometry, 'paths') ) return np.array([ tuple( (part.x, part.y) for part in path ) for path in paths ])
Reduce direct dependencies on environ
from werkzeug.wrappers import Request from lexington.util.di import depends_on @depends_on(['environ']) def get_request(environ): return Request(environ) @depends_on(['request']) def get_method(request): return request.method @depends_on(['request']) def get_path(request): return request.path @depends_on(['request']) def get_query_string(request): return request.query_string @depends_on(['request']) def get_query(request): return request.args def register_all(dependencies): dependant_functions = { 'request': get_request, 'method': get_method, 'path': get_path, 'query_string': get_query_string, 'query': get_query, } for name, dependant in dependant_functions.items(): dependencies.register_dependant(name, dependant)
from urllib import parse from werkzeug.wrappers import Request from lexington.util.di import depends_on @depends_on(['environ']) def get_request(environ): return Request(environ) # TODO: clean up all of these... @depends_on(['environ']) def get_method(environ): return environ['REQUEST_METHOD'] @depends_on(['environ']) def get_path(environ): return environ['PATH_INFO'] @depends_on(['environ']) def get_query_string(environ): return environ['QUERY_STRING'] @depends_on(['query_string']) def get_query(query_string): return parse.parse_qs(query_string) def register_all(dependencies): dependant_functions = { 'request': get_request, 'method': get_method, 'path': get_path, 'query_string': get_query_string, 'query': get_query, } for name, dependant in dependant_functions.items(): dependencies.register_dependant(name, dependant)
Make dart master pull stable from 1.7 Review URL: https://codereview.chromium.org/638823002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292365 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.7', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.6', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Convert text columns to varchar for mysql
"""empty message Revision ID: 4093ccb6d914 Revises: None Create Date: 2014-04-30 22:02:09.991428 """ # revision identifiers, used by Alembic. revision = '4093ccb6d914' down_revision = None from alembic import op import sqlalchemy as sa from datetime import datetime def upgrade(): op.create_table('gallery', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Text(), nullable=False), sa.Column('folder', sa.types.VARCHAR(length=255), nullable=False), sa.Column('share_code', sa.Text(), nullable=False), sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow), sa.Column('created', sa.DateTime(timezone=True), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('folder') ) op.create_table('user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.types.VARCHAR(length=255), nullable=False), sa.Column('password', sa.Text(), nullable=False), sa.Column('role', sa.Text(), nullable=False, server_default="user"), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) def downgrade(): op.drop_table('user') op.drop_table('gallery')
"""empty message Revision ID: 4093ccb6d914 Revises: None Create Date: 2014-04-30 22:02:09.991428 """ # revision identifiers, used by Alembic. revision = '4093ccb6d914' down_revision = None from alembic import op import sqlalchemy as sa from datetime import datetime def upgrade(): op.create_table('gallery', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Text(), nullable=False), sa.Column('folder', sa.Text(length=255), nullable=False), sa.Column('share_code', sa.Text(), nullable=False), sa.Column('modified', sa.DateTime(timezone=True), default=datetime.utcnow), sa.Column('created', sa.DateTime(timezone=True), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('folder') ) op.create_table('user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Text(length=255), nullable=False), sa.Column('password', sa.Text(), nullable=False), sa.Column('role', sa.Text(), nullable=False, server_default="user"), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) def downgrade(): op.drop_table('user') op.drop_table('gallery')
Add $ function to module level-editor
'use strict'; function $(id) { return document.getElementById(id); } function checkKey(e) { e = e || window.event; /*let dir = keyToDirection(e.keyCode); if (dir.direction != ''){ currentLevel.pig.tryMove(dir); // ++globalSteps; // $('steps-output').innerHTML = globalSteps; } */ // its 'q' for 'quit' from editing wolf's trajectory if (e.keyCode == 81) editor.finishWolf(); } var currentLevel; var editor; function showField() { let el = $('mainDiv'); while (el.firstChild) { el.removeChild(el.firstChild); } $('mainDiv').appendChild(currentLevel.field.table) initialDraw(); } window.onload = function(){ let f = new Field(5, 5); let p = new Pig(Point(0, 0)); currentLevel = new Level(f, p, []); showField(); editor = new Editor(currentLevel); $('buttonCompleteRedraw').onclick = editor.completeFieldRedraw(); document.onkeydown = checkKey; } function generateField() { let height = $('fieldlHeight').value; let width = $('fieldWidth').value; let background = $('fieldBackground').value; currentLevel.field = new Field(height, width, background); editor.makeFieldCellsClickable(); showField(); }
'use strict'; function checkKey(e) { e = e || window.event; /*let dir = keyToDirection(e.keyCode); if (dir.direction != ''){ currentLevel.pig.tryMove(dir); // ++globalSteps; // $('steps-output').innerHTML = globalSteps; } */ // its 'q' for 'quit' from editing wolf's trajectory if (e.keyCode == 81) editor.finishWolf(); } var currentLevel; var editor; function showField() { let el = $('mainDiv'); while (el.firstChild) { el.removeChild(el.firstChild); } $('mainDiv').appendChild(currentLevel.field.table) initialDraw(); } window.onload = function(){ let f = new Field(5, 5); let p = new Pig(Point(0, 0)); currentLevel = new Level(f, p, []); showField(); editor = new Editor(currentLevel); $('buttonCompleteRedraw').onclick = editor.completeFieldRedraw(); document.onkeydown = checkKey; } function generateField() { let height = $('fieldlHeight').value; let width = $('fieldWidth').value; let background = $('fieldBackground').value; currentLevel.field = new Field(height, width, background); editor.makeFieldCellsClickable(); showField(); }
[Units] Add type hint to calculate function
import operator from pyparsing import Forward, Group, Literal, nums, Suppress, Word expression_stack = [] def push_first(tokens): expression_stack.append(tokens[0]) """ atom :: '0'..'9'+ | '(' expression ')' term :: atom [ ('*' | '/') atom ]* expression :: term [ ('+' | '-') term ]* """ expression = Forward() atom = (Word(nums)).setParseAction(push_first) | Group(Suppress('(') + expression + Suppress(')')) term = atom + ((Literal('*') | Literal('/')) + atom).setParseAction(push_first)[...] expression <<= term + ((Literal('+') | Literal('-')) + term).setParseAction(push_first)[...] operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv } def evaluate_stack(stack): token = stack.pop() if token in "+-*/": # Operands are pushed onto the stack in reverse order operand_2 = evaluate_stack(stack) operand_1 = evaluate_stack(stack) return operations[token](operand_1, operand_2) else: return int(token) def calculate(input_string: str): expression_stack.clear() expression.parseString(input_string, parseAll=True) # can raise pyparsing.ParseException return evaluate_stack(expression_stack) # can raise ZeroDivisionError
import operator from pyparsing import Forward, Group, Literal, nums, Suppress, Word expression_stack = [] def push_first(tokens): expression_stack.append(tokens[0]) """ atom :: '0'..'9'+ | '(' expression ')' term :: atom [ ('*' | '/') atom ]* expression :: term [ ('+' | '-') term ]* """ expression = Forward() atom = (Word(nums)).setParseAction(push_first) | Group(Suppress('(') + expression + Suppress(')')) term = atom + ((Literal('*') | Literal('/')) + atom).setParseAction(push_first)[...] expression <<= term + ((Literal('+') | Literal('-')) + term).setParseAction(push_first)[...] operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv } def evaluate_stack(stack): token = stack.pop() if token in "+-*/": # Operands are pushed onto the stack in reverse order operand_2 = evaluate_stack(stack) operand_1 = evaluate_stack(stack) return operations[token](operand_1, operand_2) else: return int(token) def calculate(input_string): expression_stack.clear() expression.parseString(input_string, parseAll=True) # can raise pyparsing.ParseException return evaluate_stack(expression_stack) # can raise ZeroDivisionError
FIX: Use README.markdown instead of README.md
/** * Module dependencies */ var markdown = require('./../htmlifiers/markdown'), fs = require('fs'), step = require('step'), cheerio = require('cheerio'); /** * Build a html piece from the README.md of the module in `cwd` * @param {string} cwd - current working directory * @param {Function} callback - */ module.exports = function(cwd,callback){ var path = cwd + '/README.md'; step( function search(){ fs.stat(path,this); }, function retrieve(err,stats){ if(err){ console.warn('the README.md cannot be found!'); // Bypass the callback chains callback(); }else{ fs.readFile(path,'utf8',this); } }, function htmlify(err,file){ var readme = markdown.htmlify(file); var $ = cheerio.load(readme); $('h1>p').remove(); $('h1').remove(); return '<section id="readme">' + $.html() + '</section>'; }, callback ); };
/** * Module dependencies */ var markdown = require('./../htmlifiers/markdown'), fs = require('fs'), step = require('step'), cheerio = require('cheerio'); /** * Build a html piece from the README.md of the module in `cwd` * @param {string} cwd - current working directory * @param {Function} callback - */ module.exports = function(cwd,callback){ var path = cwd + '/README.markdown'; step( function search(){ fs.stat(path,this); }, function retrieve(err,stats){ if(err){ console.warn('the README.md cannot be found!'); // Bypass the callback chains callback(); }else{ fs.readFile(path,'utf8',this); } }, function htmlify(err,file){ var readme = markdown.htmlify(file); var $ = cheerio.load(readme); $('h1>p').remove(); $('h1').remove(); return '<section id="readme">' + $.html() + '</section>'; }, callback ); };
Add system.out for each file converted
package uk.org.taverna.scufl2.wfdesc; import java.io.File; import java.io.IOException; import javax.xml.bind.JAXBException; import uk.org.taverna.scufl2.api.container.WorkflowBundle; import uk.org.taverna.scufl2.api.io.ReaderException; import uk.org.taverna.scufl2.api.io.WorkflowBundleIO; import uk.org.taverna.scufl2.api.io.WriterException; public class ConvertToWfdesc { public static void main(String[] args) throws JAXBException, IOException, ReaderException, WriterException { WorkflowBundleIO io = new WorkflowBundleIO(); for (String filepath : args) { File original = new File(filepath); String filename = original.getName(); filename = filename.replaceFirst("\\..*", "") + ".wfdesc.ttl"; File wfdesc = new File(original.getParentFile(), filename); WorkflowBundle wfBundle = io.readBundle(original, null); io.writeBundle(wfBundle, wfdesc, "text/vnd.wf4ever.wfdesc+turtle"); System.out.println("Converted " + original.getPath() + " to " + wfdesc.getPath()); } } }
package uk.org.taverna.scufl2.wfdesc; import java.io.File; import java.io.IOException; import javax.xml.bind.JAXBException; import uk.org.taverna.scufl2.api.container.WorkflowBundle; import uk.org.taverna.scufl2.api.io.ReaderException; import uk.org.taverna.scufl2.api.io.WorkflowBundleIO; import uk.org.taverna.scufl2.api.io.WriterException; public class ConvertToWfdesc { public static void main(String[] args) throws JAXBException, IOException, ReaderException, WriterException { WorkflowBundleIO io = new WorkflowBundleIO(); for (String filepath : args) { File original = new File(filepath); String filename = original.getName(); filename = filename.replaceFirst("\\..*", "") + ".wfdesc.ttl"; File wfdesc = new File(original.getParentFile(), filename); WorkflowBundle wfBundle = io.readBundle(original, null); io.writeBundle(wfBundle, wfdesc, "text/vnd.wf4ever.wfdesc+turtle"); } } }
Set the default port to 3001 so it doesn't conflict with the default 3000 of express-rest-api-example.
var compression = require("compression"); var express = require("express"); var handlebars = require("express-handlebars"); // Initialize Express var app = express(); // Treat "/foo" and "/Foo" as different URLs app.set("case sensitive routing", true); // Treat "/foo" and "/foo/" as different URLs app.set("strict routing", true); // Default to port 3001 app.set("port", process.env.PORT || 3001); // Compress all requests app.use(compression()); // Set Handlebars as the default template language app.engine("handlebars", handlebars({ defaultLayout: "main" })); app.set("view engine", "handlebars"); // Serve static contents from the public directory app.use(express.static(__dirname + "/public")); // Handle 404 errors app.use(function(req, res) { res.type("text/plain"); res.status(404); res.send("404 - Not Found"); }); // Handle 500 errors app.use(function(err, req, res, next) { console.error(err.stack); res.type("text/plain"); res.status(500); res.send("500 - Server Error"); }); app.listen(app.get("port"), function() { console.log("Express started on http://localhost:" + app.get("port") + "; press Ctrl-C to terminate."); });
var compression = require("compression"); var express = require("express"); var handlebars = require("express-handlebars"); // Initialize Express var app = express(); // Treat "/foo" and "/Foo" as different URLs app.set("case sensitive routing", true); // Treat "/foo" and "/foo/" as different URLs app.set("strict routing", true); // Default to port 3000 app.set("port", process.env.PORT || 3000); // Compress all requests app.use(compression()); // Set Handlebars as the default template language app.engine("handlebars", handlebars({ defaultLayout: "main" })); app.set("view engine", "handlebars"); // Serve static contents from the public directory app.use(express.static(__dirname + "/public")); // Handle 404 errors app.use(function(req, res) { res.type("text/plain"); res.status(404); res.send("404 - Not Found"); }); // Handle 500 errors app.use(function(err, req, res, next) { console.error(err.stack); res.type("text/plain"); res.status(500); res.send("500 - Server Error"); }); app.listen(app.get("port"), function() { console.log("Express started on http://localhost:" + app.get("port") + "; press Ctrl-C to terminate."); });
Add a package argument to import_symbol.
import importlib def import_symbol(typename, package=None): """Import a module or typename within a module from its name.""" try: return importlib.import_module(typename, package=package) except ImportError as e: parts = typename.split('.') if len(parts) > 1: typename = parts.pop() # Call import_module recursively. namespace = import_symbol('.'.join(parts), package=package) try: return getattr(namespace, typename) except AttributeError: pass raise e except: raise def make_object(*args, typename, package=None, **kwds): """Make an object from a symbol.""" return import_symbol(typename, package)(*args, **kwds)
import importlib def import_symbol(typename): """Import a module or typename within a module from its name.""" try: return importlib.import_module(typename) except ImportError as e: parts = typename.split('.') if len(parts) > 1: typename = parts.pop() # Call import_module recursively. namespace = import_symbol('.'.join(parts)) try: return getattr(namespace, typename) except AttributeError: pass raise e except: raise def make_object(*args, typename, **kwds): """Make an object from a symbol.""" return import_symbol(typename)(*args, **kwds)
Use six for python 2/3 bytes
from six import BytesIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_schedules.sync_schedule') def test_schedule_sync_called(self, sync_task): """ The sync schedules management command should call the sync schedule task for every schedule. """ utils.disable_signals() schedule = Schedule.objects.create() utils.enable_signals() out = BytesIO() call_command('sync_schedules', stdout=out) sync_task.assert_called_once_with(str(schedule.id)) self.assertIn(str(schedule.id), out.getvalue()) self.assertIn('Synchronised 1 schedule/s', out.getvalue())
from io import BytesIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_schedules.sync_schedule') def test_schedule_sync_called(self, sync_task): """ The sync schedules management command should call the sync schedule task for every schedule. """ utils.disable_signals() schedule = Schedule.objects.create() utils.enable_signals() out = BytesIO() call_command('sync_schedules', stdout=out) sync_task.assert_called_once_with(str(schedule.id)) self.assertIn(str(schedule.id), out.getvalue()) self.assertIn('Synchronised 1 schedule/s', out.getvalue())
Fix bug where id were not stored
const low = require("lowdb"); const Parser = require('../controllers/parser'); const Requester = require('../controllers/requester'); const TIME_SECOND = 1000; const TIME_MIN = 60 * TIME_SECOND; const TIME_HOUR = 60 * TIME_MIN; var updateLoop = function updateLoop(functionToRun) { functionToRun(); setTimeout(updateLoop, 5 * TIME_MIN, functionToRun); } var TaskRunner = { init: function() { updateModuleIds(); // Initialise app // obtains ids // announcements, forum, webcast, files }, run: function() { updateLoop(Parser.getAnnouncements); } }; var updateModuleIds = function updateModuleIds() { // Obtain data from IVLE Requester.requestJson("Modules", { "Duration": "0", "IncludeAllInfo": "false" }).then( filterModuleIds, function(error) { console.error(error); } ); function filterModuleIds(data) { const userDb = low('./data/userdb.json'); let modulesArray = data["Results"]; let modules = {}; modulesArray.forEach(function(moduleObj, index, array) { userDb.set(`modules.${moduleObj["ID"]}`, {}).value(); }); } } module.exports = TaskRunner;
const low = require("lowdb"); const userDb = low('./data/userdb.json'); const dataDb = low('./data/datadb.json'); const Requester = require('../controllers/requester'); const Parser = require('../controllers/parser'); const TIME_SECOND = 1000; const TIME_MIN = 60 * TIME_SECOND; const TIME_HOUR = 60 * TIME_MIN; var updateLoop = function updateLoop(functionToRun) { functionToRun(); setTimeout(updateLoop, 5 * TIME_MIN, functionToRun); } var TaskRunner = { init: function() { updateModuleIds(); // Initialise app // obtains ids // announcements, forum, webcast, files }, run: function() { updateLoop(Parser.getAnnouncements); } }; var updateModuleIds = function updateModuleIds() { // Obtain data from IVLE Requester.requestJson("Modules", { "Duration": "0", "IncludeAllInfo": "false" }).then( function(data) { let modulesObj = filterModuleIds(data); storeModuleIds(modulesObj); }, function(error) { console.error(error); } ); function filterModuleIds(data) { let modulesArray = data["Results"]; let modulesObj = {}; modulesArray.forEach(function(moduleObj, index, array) { let moduleId = moduleObj["ID"]; modulesObj[moduleId] = {}; }); return modulesObj; } function storeModuleIds(modulesObj) { userDb.set("modules", modulesObj); } } module.exports = TaskRunner;