text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Revert "Another attempt to fix the RTD build." This reverts commit 43807c085493962ca0f79105b64b3be8ddc6fc39. References #25
from setuptools import setup, find_packages from os.path import dirname, abspath HERE = abspath(dirname(__file__)) VERSION = open(HERE + '/puresnmp/version.txt').read().strip() setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open(HERE + "/README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
from setuptools import setup, find_packages VERSION = '1.1.4' setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open("README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
Use callback instead of sync
'use strict' const grunt = require('gruntfile-api') const fs = require('fs') const path = require('path') const spawn = require('child_process').spawn global.processes = {} exports.getTasks = function () { return new Promise(function (resolve, reject) { fs.readFile(path.join(window.localStorage.getItem('current'), 'Gruntfile.js'), function (err, gruntfile) { if (err) return resolve([]) grunt.init(gruntfile) let tasks = JSON.parse(grunt.getJsonTasks()) let taskList = [] for (let task in tasks) { taskList.push(task) } return resolve(taskList) }) }) } exports.runTask = function (task, cb) { // Stop task if running if (global.processes[task]) { global.processes[task].kill() return } let dir = window.localStorage.getItem('current') var command = spawn('grunt', [task], {cwd: dir}) // Save global.processes[task] = command cb() // Remove when done command.on('close', function () { delete global.processes[task] cb() }) }
'use strict' const grunt = require('gruntfile-api') const fs = require('fs') const path = require('path') const spawn = require('child_process').spawn global.processes = {} exports.getTasks = function () { return new Promise(function (resolve, reject) { const gruntfile = fs.readFileSync(path.join(window.localStorage.getItem('current'), 'Gruntfile.js')) grunt.init(gruntfile) let tasks = JSON.parse(grunt.getJsonTasks()) let taskList = [] for (let task in tasks) { taskList.push(task) } return resolve(taskList) }) } exports.runTask = function (task, cb) { // Stop task if running if (global.processes[task]) { global.processes[task].kill() return } let dir = window.localStorage.getItem('current') var command = spawn('grunt', [task], {cwd: dir}) // Save global.processes[task] = command cb() // Remove when done command.on('close', function () { delete global.processes[task] cb() }) }
Fix syntax of a migration
"""add a flag for review active Revision ID: 4d45dd3d8ce5 Revises: 49d09b3d2801 Create Date: 2014-02-26 16:29:54.507710 """ # revision identifiers, used by Alembic. revision = '4d45dd3d8ce5' down_revision = '49d09b3d2801' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column( 'violations', sa.Column('review_is_active', sa.Integer, nullable=False, server_default='1') ) connection = op.get_bind() connection.execute('''UPDATE violations SET review_is_active = 0 WHERE review_id IN (SELECT id FROM reviews WHERE is_active = 0)''') op.create_index( 'idx_key_domain_review_active', 'violations', ['key_id', 'domain_id', 'review_is_active']) def downgrade(): op.drop_index('idx_key_domain_review_active', 'violations') op.drop_column('violations', 'review_is_active')
"""add a flag for review active Revision ID: 4d45dd3d8ce5 Revises: 49d09b3d2801 Create Date: 2014-02-26 16:29:54.507710 """ # revision identifiers, used by Alembic. revision = '4d45dd3d8ce5' down_revision = '49d09b3d2801' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column( 'violations', sa.Column('review_is_active', sa.Integer, nullable=False, server_default='1') ) connection = op.get_bind() connection.execute('''UPDATE violations SET review_is_active = 0 WHERE review_id IN (SELECT id FROM reviews WHERE is_active = 0)''') op.create_index( 'idx_key_domain_review_active', 'violations', ['key_id', 'domain_id', 'review_is_active']) def downgrade(): op.drop_index('idx_key_domain_review_active', 'violations'), op.drop_column('violations', 'review_is_active')
Fix for scalable option bug, pointed out by Jason Smith. git-svn-id: 27e0aca8c7a52a9ae65dfba2e16879604119af8c@465 93a4e39c-3214-0410-bb16-828d8e3bcd0f
<?php # $Id$ # Retrieves and parses the XML output from gmond. Results stored # in global variables: $clusters, $hosts, $hosts_down, $metrics. # Assumes you have already called get_context.php. # if (! Gmetad($ganglia_ip, $ganglia_port) ) { print "<H4>There was an error collecting ganglia data ". "($ganglia_ip:$ganglia_port): $error</H4>\n"; exit; } # If we have no child data sources, assume something is wrong. if (!count($grid) and !count($cluster)) { print "<H4>Ganglia cannot find a data source. Is gmond running?</H4>"; exit; } # If we only have one cluster source, suppress MetaCluster output. if (count($grid) == 2 and $context=="meta") { # Lets look for one cluster (the other is our grid). foreach($grid as $source) if ($source[CLUSTER]) { $standalone = 1; $context = "cluster"; # Need to refresh data with new context. Gmetad($ganglia_ip, $ganglia_port); $clustername = $source[NAME]; } } ?>
<?php # $Id$ # Retrieves and parses the XML output from gmond. Results stored # in global variables: $clusters, $hosts, $hosts_down, $metrics. # Assumes you have already called get_context.php. # if (! Gmetad($ganglia_ip, $ganglia_port) ) { print "<H4>There was an error collecting ganglia data ". "($ganglia_ip:$ganglia_port): $error</H4>\n"; exit; } # If we have no child data sources, assume something is wrong. if (!count($grid)) { print "<H4>Ganglia cannot find a data source. Is gmond running?</H4>"; exit; } # If we only have one cluster source, suppress MetaCluster output. if (count($grid) == 2 and $context=="meta") { # Lets look for one cluster (the other is our grid). foreach($grid as $source) if ($source[CLUSTER]) { $standalone = 1; $context = "cluster"; # Need to refresh data with new context. Gmetad($ganglia_ip, $ganglia_port); $clustername = $source[NAME]; } } ?>
Apply fix only when utils are broken
// Temporary fix for https://github.com/Gozala/test-commonjs/pull/8 'use strict'; var utils = require('test/utils') , instanceOf; try { if (utils.instanceOf) utils.instanceOf(Object.create(null), Date); } catch (e) { instanceOf = utils.instanceOf = function (value, Type) { var constructor, isConstructorNameSame, isConstructorSourceSame , isInstanceOf = value instanceof Type; if (!isInstanceOf && value) { constructor = value.constructor; isConstructorNameSame = constructor && (constructor.name === Type.name); isConstructorSourceSame = String(constructor) === String(Type); isInstanceOf = (isConstructorNameSame && isConstructorSourceSame) || instanceOf(Object.getPrototypeOf(value), Type); } return isInstanceOf; }; utils.isDate = function (value) { return utils.isObject(value) && instanceOf(value, Date); }; utils.isRegExp = function (value) { return instanceOf(value, RegExp); }; }
// Temporary fix for https://github.com/Gozala/test-commonjs/pull/8 'use strict'; var utils = require('test/utils') , instanceOf; instanceOf = utils.instanceOf = function (value, Type) { var constructor, isConstructorNameSame, isConstructorSourceSame , isInstanceOf = value instanceof Type; // If `instanceof` returned `false` we do ducktype check since `Type` may be // from a different sandbox. If a constructor of the `value` or a constructor // of the value"s prototype has same name and source we assume that it"s an // instance of the Type. if (!isInstanceOf && value) { constructor = value.constructor; isConstructorNameSame = constructor && (constructor.name === Type.name); isConstructorSourceSame = String(constructor) === String(Type); isInstanceOf = (isConstructorNameSame && isConstructorSourceSame) || instanceOf(Object.getPrototypeOf(value), Type); } return isInstanceOf; }; utils.isDate = function (value) { return utils.isObject(value) && instanceOf(value, Date); }; utils.isRegExp = function (value) { return instanceOf(value, RegExp); };
Allow to use custom model for Single Sender
<?php namespace Fenos\Notifynder\Senders; use Fenos\Notifynder\Contracts\SenderContract; use Fenos\Notifynder\Contracts\SenderManagerContract; use Fenos\Notifynder\Models\Notification; /** * Class SingleSender. */ class SingleSender implements SenderContract { /** * @var \Fenos\Notifynder\Builder\Notification */ protected $notification; /** * SingleSender constructor. * * @param array $notifications */ public function __construct(array $notifications) { $this->notification = array_values($notifications)[0]; } /** * Send the single notification. * * @param SenderManagerContract $sender * @return bool */ public function send(SenderManagerContract $sender) { $model = notifynder_config()->getNotificationModel(); $notification = new $model($this->notification); return $notification->save(); } }
<?php namespace Fenos\Notifynder\Senders; use Fenos\Notifynder\Contracts\SenderContract; use Fenos\Notifynder\Contracts\SenderManagerContract; use Fenos\Notifynder\Models\Notification; /** * Class SingleSender. */ class SingleSender implements SenderContract { /** * @var \Fenos\Notifynder\Builder\Notification */ protected $notification; /** * SingleSender constructor. * * @param array $notifications */ public function __construct(array $notifications) { $this->notification = array_values($notifications)[0]; } /** * Send the single notification. * * @param SenderManagerContract $sender * @return bool */ public function send(SenderManagerContract $sender) { $notification = new Notification($this->notification); return $notification->save(); } }
Fix mirage to only use default scenario when not testing
/* eslint global-require: off, import/no-mutable-exports: off */ import merge from 'lodash/merge'; import flow from 'lodash/flow'; const environment = process.env.NODE_ENV || 'test'; let start = () => {}; if (environment !== 'production') { const { default: Mirage, camelize } = require('@bigtest/mirage'); const { default: coreModules } = require('./index'); require('./force-fetch-polyfill'); start = (scenarioNames, options = {}) => { const { coreScenarios = {}, baseConfig: coreConfig, ...coreOpts } = coreModules; const { scenarios = {}, baseConfig = () => {}, ...opts } = options; const server = new Mirage(merge({ baseConfig: flow(coreConfig, baseConfig), environment }, coreOpts, opts)); // the default scenario is only used when not in test mode let defaultScenario; if (!scenarioNames && environment !== 'test') { defaultScenario = 'default'; } // mirage only loads a `default` scenario for us out of the box, // so instead of providing all scenarios we run specific scenarios // after the mirage server is initialized. [].concat(scenarioNames || defaultScenario).filter(Boolean).forEach(name => { const key = camelize(name); const scenario = scenarios[key] || coreScenarios[key]; if (scenario) scenario(server); }); return server; }; } export default start;
/* eslint global-require: off, import/no-mutable-exports: off */ import merge from 'lodash/merge'; import flow from 'lodash/flow'; const environment = process.env.NODE_ENV || 'test'; let start = () => {}; if (environment !== 'production') { const { default: Mirage, camelize } = require('@bigtest/mirage'); const { default: coreModules } = require('./index'); require('./force-fetch-polyfill'); start = (scenarioNames, options = {}) => { const { coreScenarios = {}, baseConfig: coreConfig, ...coreOpts } = coreModules; const { scenarios = {}, baseConfig = () => {}, ...opts } = options; const server = new Mirage(merge({ baseConfig: flow(coreConfig, baseConfig), environment }, coreOpts, opts)); // mirage only loads a `default` scenario for us out of the box, // so instead of providing all scenarios we run specific scenarios // after the mirage server is initialized. [].concat(scenarioNames || 'default').filter(Boolean).forEach(name => { const key = camelize(name); const scenario = scenarios[key] || coreScenarios[key]; if (scenario) scenario(server); }); return server; }; } export default start;
Add torpedo failure rate as an environment variable
package hu.bme.mit.spaceship; import java.util.Random; /** * Class storing and managing the torpedoes of a ship */ public class TorpedoStore { private double FAILURE_RATE = 0.0; private int torpedoCount = 0; private Random generator = new Random(); public TorpedoStore(int numberOfTorpedos){ this.torpedoCount = numberOfTorpedos; // update failure rate if it was specified in an environment variable String failureEnv = System.getenv("IVT_RATE"); if (failureEnv != null){ try { FAILURE_RATE = Double.parseDouble(failureEnv); } catch (NumberFormatException nfe) { FAILURE_RATE = 0.0; } } } public boolean fire(int numberOfTorpedos){ if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){ throw new IllegalArgumentException("numberOfTorpedos"); } boolean success = false; // simulate random overheating of the launcher bay which prevents firing double r = generator.nextDouble(); if (r >= FAILURE_RATE) { // successful firing this.torpedoCount -= numberOfTorpedos; success = true; } else { // simulated failure success = false; } return success; } public boolean isEmpty(){ return this.torpedoCount <= 0; } public int getTorpedoCount() { return this.torpedoCount; } }
package hu.bme.mit.spaceship; import java.util.Random; /** * Class storing and managing the torpedoes of a ship */ public class TorpedoStore { private int torpedoCount = 0; private Random generator = new Random(); public TorpedoStore(int numberOfTorpedos){ this.torpedoCount = numberOfTorpedos; } public boolean fire(int numberOfTorpedos){ if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){ throw new IllegalArgumentException("numberOfTorpedos"); } boolean success = false; //simulate random overheating of the launcher bay which prevents firing double r = generator.nextDouble(); if (r > 0.01) { // successful firing this.torpedoCount -= numberOfTorpedos; success = true; } else { // failure success = false; } return success; } public boolean isEmpty(){ return this.torpedoCount <= 0; } public int getTorpedoCount() { return this.torpedoCount; } }
Fix bug in focus measure
import cv2 import numpy def LAPV(img): """Implements the LAPV focus measure algorithm. :param img: the image the measure is applied to as a numpy matrix """ return numpy.std(cv2.Laplacian(img, cv2.CV_64F)) ** 2 def TENG(img): """Implements the TENG focus measure algorithm. :param img: the image the measure is applied to as a numpy matrix """ gaussianX = cv2.Sobel(img, cv2.CV_64F, 1, 0) gaussianY = cv2.Sobel(img, cv2.CV_64F, 1, 0) return numpy.mean(gaussianX * gaussianX + gaussianY * gaussianY) def LAPM(img): """Implements the LAPM focus measure algorithm. :param img: the image the measure is applied to as a numpy matrix """ kernel = numpy.array([-1, 2, -1]) laplacianX = numpy.abs(cv2.filter2D(img, -1, kernel)) laplacianY = numpy.abs(cv2.filter2D(img, -1, kernel.T)) return numpy.mean(laplacianX + laplacianY) def MLOG(img): """Implements the MLOG focus measure algorithm. :param img: the image the measure is applied to as a numpy matrix """ return numpy.max(cv2.convertScaleAbs(cv2.Laplacian(img, 3)))
import cv2 import numpy def LAPV(img): """Implements the LAPV focus measure algorithm. :param img: the image the measure is applied to as a numpy matrix """ return numpy.std(cv2.Laplacian(img, cv2.CV_64F)) ** 2 def TENG(img): """Implements the TENG focus measure algorithm. :param img: the image the measure is applied to as a numpy matrix """ gaussianX = cv2.Sobel(img, cv2.CV_64F, 1, 0, 1) gaussianY = cv2.Sobel(img, cv2.CV_64F, 1, 0, 1) return numpy.mean(gaussianX * gaussianX + gaussianY * gaussianY) def LAPM(img): """Implements the LAPM focus measure algorithm. :param img: the image the measure is applied to as a numpy matrix """ kernel = numpy.array([-1, 2, -1]) laplacianX = numpy.abs(cv2.filter2D(img, -1, kernel)) laplacianY = numpy.abs(cv2.filter2D(img, -1, kernel.T)) return numpy.mean(laplacianX + laplacianY) def MLOG(img): """Implements the MLOG focus measure algorithm. :param img: the image the measure is applied to as a numpy matrix """ return numpy.max(cv2.convertScaleAbs(cv2.Laplacian(img, 3)))
Update comment for passport creation
package co.inventorsoft.oop.basic.demo; import co.inventorsoft.oop.basic.model.Passport; import co.inventorsoft.oop.basic.model.Person; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; public class Main { public static void main(String[] args) { final Person martynBorodavka = new Person("Martyn", "Borodavka", LocalDateTime.of(LocalDate.of(1736, Month.JULY, 10), LocalTime.now())); /* * age calculation is reflective to current date but we don't care because of encapsulation */ printAge(martynBorodavka); martynBorodavka.setAge(-2); //we cannot change created person's age which is makes sense martynBorodavka.setPassport(new Passport()); //we cannot create passport object without required info /* * we can omit birth date for newborns but age is calculation right. But again we don't care. thanks for encapsulation */ final Person newBorn = new Person("Ivan", "Ivanenko"); printAge(newBorn); } private static String printAge(final Person person) { System.out.println(String.format("Martyn Borodavka is %d years old", person.getAge())); } }
package co.inventorsoft.oop.basic.demo; import co.inventorsoft.oop.basic.model.Passport; import co.inventorsoft.oop.basic.model.Person; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; public class Main { public static void main(String[] args) { final Person martynBorodavka = new Person("Martyn", "Borodavka", LocalDateTime.of(LocalDate.of(1736, Month.JULY, 10), LocalTime.now())); /* * age calculation is reflective to current date but we don't care because of encapsulation */ printAge(martynBorodavka); martynBorodavka.setAge(-2); //we cannot change created person's age which is makes sense martynBorodavka.setPassport(new Passport()); //we can create objects we are not responsible to create /* * we can omit birth date for newborns but age is calculation right. But again we don't care. thanks for encapsulation */ final Person newBorn = new Person("Ivan", "Ivanenko"); printAge(newBorn); } private static String printAge(final Person person) { System.out.println(String.format("Martyn Borodavka is %d years old", person.getAge())); } }
Stop shipping qy with python-moira Moira now provides with its own native qy.
#!/usr/bin/python from setuptools import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name="PyMoira", version="4.3.2", description="PyMoira - Python bindings for the Athena Moira library", author="Evan Broder", author_email="broder@mit.edu", license="MIT", py_modules=['moira'], ext_modules=[ Extension("_moira", ["_moira.pyx"], libraries=["moira", "krb5"]), Extension("mrclient", ["mrclient.pyx"], libraries=["mrclient", "moira"]), ], cmdclass= {"build_ext": build_ext} )
#!/usr/bin/python from setuptools import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name="PyMoira", version="4.3.1", description="PyMoira - Python bindings for the Athena Moira library", author="Evan Broder", author_email="broder@mit.edu", license="MIT", py_modules=['moira'], ext_modules=[ Extension("_moira", ["_moira.pyx"], libraries=["moira", "krb5"]), Extension("mrclient", ["mrclient.pyx"], libraries=["mrclient", "moira"]), ], scripts=['qy'], cmdclass= {"build_ext": build_ext} )
Abort migrations check if a version is present more than once list_migrations checks whether we have more than one branch in the list of migration versions. Since we've switched to a new revision naming convention, pull requests open at the same time are likely to use the same revision number when adding new migrations (ie if the current latest migration is '500' two pull requests adding a new one are both likely to use '510' for their revision id). When this happens, alembic excludes on of the migrations from the tree and doesn't consider it to be a multiple branches issue. Instead, it prints out a warning. In order to make sure the tests fail when this happens we transform the warning into an exception inside the list_migrations script. This is similar to running the python interpreter with `-W error`.
#!/usr/bin/env python # encoding: utf-8 from __future__ import print_function import sys import warnings from alembic.script import ScriptDirectory warnings.simplefilter('error') def detect_heads(migrations): heads = migrations.get_heads() return heads def version_history(migrations): version_history = [ (m.revision, m.doc) for m in migrations.walk_revisions() ] version_history.reverse() return version_history def main(migrations_path): migrations = ScriptDirectory(migrations_path) heads = detect_heads(migrations) if len(heads) > 1: print("Migrations directory has multiple heads due to branching: {}".format(heads), file=sys.stderr) sys.exit(1) for version in version_history(migrations): print("{:35} {}".format(*version)) if __name__ == '__main__': main('migrations/')
#!/usr/bin/env python # encoding: utf-8 from __future__ import print_function import sys from alembic.script import ScriptDirectory def detect_heads(migrations): heads = migrations.get_heads() return heads def version_history(migrations): version_history = [ (m.revision, m.doc) for m in migrations.walk_revisions() ] version_history.reverse() return version_history def main(migrations_path): migrations = ScriptDirectory(migrations_path) heads = detect_heads(migrations) if len(heads) > 1: print("Migrations directory has multiple heads due to branching: {}".format(heads), file=sys.stderr) sys.exit(1) for version in version_history(migrations): print("{:35} {}".format(*version)) if __name__ == '__main__': main('migrations/')
general: Add package handler to class map
<?php $Gcm__ = array( 'GatewayApiController'=>'controllers/GatewayApiController.php', 'ManagementApiController'=>'controllers/ManagementApiController.php', 'SpringApiController'=>'controllers/SpringApiController.php', 'CoreHandler'=>'handlers/CoreHandler.php', 'GatewayHandler'=>'handlers/GatewayHandler.php', 'ModuleHandler'=>'handlers/ModuleHandler.php', 'PackageHandler'=>'handlers/PackageHandler.php', 'ProtocolHandler'=>'handlers/ProtocolHandler.php', 'RequestHandler'=>'handlers/RequestHandler.php', 'SemanticVersion'=>'handlers/SemanticVersion.php', 'VersionHandler'=>'handlers/VersionHandler.php', 'ICoreHandler'=>'interfaces/ICoreHandler.php', 'IModuleHandler'=>'interfaces/IModuleHandler.php', 'IPackageHandler'=>'interfaces/IPackageHandler.php', 'ISystemUpdateDb'=>'interfaces/ISystemUpdateDb.php', 'IVersionHandler'=>'interfaces/IVersionHandler.php', 'NetspaceKvs'=>'models/NetspaceKvs.php', 'Resolution'=>'models/Resolution.php', 'SystemUpdateKvs'=>'models/SystemUpdateKvs.php', 'UpdateCheck'=>'updater/UpdateCheck.php', 'UpdateRunner'=>'updater/UpdateRunner.php', ); spl_autoload_register(function ($class) { global $Gcm__; if(!isset($Gcm__[$class])) return; include __DIR__.'/system/' . $Gcm__[$class]; });
<?php $Gcm__ = array( 'GatewayApiController'=>'controllers/GatewayApiController.php', 'ManagementApiController'=>'controllers/ManagementApiController.php', 'SpringApiController'=>'controllers/SpringApiController.php', 'CoreHandler'=>'handlers/CoreHandler.php', 'GatewayHandler'=>'handlers/GatewayHandler.php', 'ModuleHandler'=>'handlers/ModuleHandler.php', 'ProtocolHandler'=>'handlers/ProtocolHandler.php', 'RequestHandler'=>'handlers/RequestHandler.php', 'SemanticVersion'=>'handlers/SemanticVersion.php', 'VersionHandler'=>'handlers/VersionHandler.php', 'ICoreHandler'=>'interfaces/ICoreHandler.php', 'IModuleHandler'=>'interfaces/IModuleHandler.php', 'ISystemUpdateDb'=>'interfaces/ISystemUpdateDb.php', 'IVersionHandler'=>'interfaces/IVersionHandler.php', 'NetspaceKvs'=>'models/NetspaceKvs.php', 'Resolution'=>'models/Resolution.php', 'SystemUpdateKvs'=>'models/SystemUpdateKvs.php', 'UpdateCheck'=>'updater/UpdateCheck.php', 'UpdateRunner'=>'updater/UpdateRunner.php', ); spl_autoload_register(function ($class) { global $Gcm__; if(!isset($Gcm__[$class])) return; include __DIR__.'/system/' . $Gcm__[$class]; });
Update blood death knight for soft mitigation check split damage schools.
import CoreMitigationCheck from 'parser/shared/modules/MitigationCheck'; import SPELLS from 'common/SPELLS'; class MitigationCheck extends CoreMitigationCheck { constructor(...args) { super(...args); this.buffCheckPhysical = [ SPELLS.BONE_SHIELD.id, SPELLS.DANCING_RUNE_WEAPON_BUFF.id, ]; this.buffCheckMagical = [ SPELLS.ANTI_MAGIC_SHELL.id, ]; this.buffCheckPhysAndMag = [ SPELLS.BLOOD_SHIELD.id, SPELLS.VAMPIRIC_BLOOD.id, SPELLS.ICEBOUND_FORTITUDE.id, SPELLS.TOMBSTONE_TALENT.id, ]; } } export default MitigationCheck;
import CoreMitigationCheck from 'parser/shared/modules/MitigationCheck'; import SPELLS from 'common/SPELLS'; class MitigationCheck extends CoreMitigationCheck { constructor(...args){ super(...args); this.buffCheck = [SPELLS.BLOOD_SHIELD.id, SPELLS.BONE_SHIELD.id, SPELLS.ANTI_MAGIC_SHELL.id, SPELLS.VAMPIRIC_BLOOD.id, SPELLS.ICEBOUND_FORTITUDE.id, SPELLS.DANCING_RUNE_WEAPON_BUFF.id, SPELLS.TOMBSTONE_TALENT.id]; } } export default MitigationCheck;
Add new GetHatenaFeed func prototype
package main import ( "github.com/timakin/ts/loader" "github.com/codegangsta/cli" ) var Commands = []cli.Command{ commandAll, commandBiz, commandHack, } var commandAll = cli.Command{ Name: "pop", Usage: "", Description: ` `, Action: doAll, } var commandBiz = cli.Command{ Name: "biz", Usage: "", Description: ` `, Action: doBiz, } var commandHack = cli.Command{ Name: "hack", Usage: "", Description: ` `, Action: doHack, } func doAll(c *cli.Context) { hn := make(chan loader.ResultData) ph := make(chan loader.ResultData) re := make(chan loader.ResultData) go loader.GetHNFeed(hn) go loader.GetPHFeed(ph) go loader.GetRedditFeed(re) hnres := <- hn phres := <- ph reres := <- re var HNData loader.Feed = &hnres var PHData loader.Feed = &phres var REData loader.Feed = &reres HNData.Display() PHData.Display() REData.Display() } func doBiz(c *cli.Context) { } func doHack(c *cli.Context) { loader.GetHatenaFeed() }
package main import ( "github.com/timakin/ts/loader" "github.com/codegangsta/cli" ) var Commands = []cli.Command{ commandAll, commandBiz, commandHack, } var commandAll = cli.Command{ Name: "pop", Usage: "", Description: ` `, Action: doAll, } var commandBiz = cli.Command{ Name: "biz", Usage: "", Description: ` `, Action: doBiz, } var commandHack = cli.Command{ Name: "hack", Usage: "", Description: ` `, Action: doHack, } func doAll(c *cli.Context) { hn := make(chan loader.ResultData) ph := make(chan loader.ResultData) re := make(chan loader.ResultData) go loader.GetHNFeed(hn) go loader.GetPHFeed(ph) go loader.GetRedditFeed(re) hnres := <- hn phres := <- ph reres := <- re var HNData loader.Feed = &hnres var PHData loader.Feed = &phres var REData loader.Feed = &reres HNData.Display() PHData.Display() REData.Display() } func doBiz(c *cli.Context) { } func doHack(c *cli.Context) { }
Add rpm-build into environment setup message for CentOS Change-Id: I44bd14f2f3c3e76c24f5efd26a5ff6a545dcaf72 Implements: blueprint plugin-major-version-for-releases
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. header = '=' * 50 install_required_packages = """ Was not able to find required packages. If you use Ubuntu, run: # sudo apt-get install createrepo rpm dpkg-dev If you use CentOS, run: # yum install createrepo dpkg-devel rpm rpm-build """
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. header = '=' * 50 install_required_packages = """ Was not able to find required packages. If you use Ubuntu, run: # sudo apt-get install createrepo rpm dpkg-dev If you use CentOS, run: # yum install createrepo rpm dpkg-devel """
Print console messages by default in the emulator
import DefaultConfig from 'anyware/lib/game-logic/config/default-config'; import GAMES from 'anyware/lib/game-logic/constants/games'; class Config extends DefaultConfig { constructor() { super(); this.DEBUG.console = true; this.CLIENT_CONNECTION_OPTIONS = { protocol: "wss", username: "anyware", password: "anyware", host: "broker.shiftr.io" }; this.diskUrls = { disk0: 'images/disk0.png', disk1: 'images/disk1.png', disk2: 'images/disk2.png' }; this.projectionParameters = { scale: 1, translate: [0, 0], }; // this.GAMES_SEQUENCE = [ // GAMES.DISK, // GAMES.SIMON // ]; } // FIXME: Configure user colors here? How to communicate that to CSS? } export default new Config();
import DefaultConfig from 'anyware/lib/game-logic/config/default-config'; import GAMES from 'anyware/lib/game-logic/constants/games'; class Config extends DefaultConfig { constructor() { super(); this.CLIENT_CONNECTION_OPTIONS = { protocol: "wss", username: "anyware", password: "anyware", host: "broker.shiftr.io" }; this.diskUrls = { disk0: 'images/disk0.png', disk1: 'images/disk1.png', disk2: 'images/disk2.png' }; this.projectionParameters = { scale: 1, translate: [0, 0], }; // this.GAMES_SEQUENCE = [ // GAMES.DISK, // GAMES.SIMON // ]; } // FIXME: Configure user colors here? How to communicate that to CSS? } export default new Config();
Use new extension setup() API
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(GMusicExtension, self).get_config_schema() schema['username'] = config.String() schema['password'] = config.Secret() schema['deviceid'] = config.String(optional=True) return schema def setup(self, registry): from .actor import GMusicBackend registry.add('backend', GMusicBackend)
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(GMusicExtension, self).get_config_schema() schema['username'] = config.String() schema['password'] = config.Secret() schema['deviceid'] = config.String(optional=True) return schema def get_backend_classes(self): from .actor import GMusicBackend return [GMusicBackend]
Fix newline trimming in page renderer breaking GA tracking
</div> <footer><?=get_footer()?></footer> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script>if(!window.jQuery)document.write('\x3Cscript src="/js/jquery-2.1.4.min.js">\x3C/script>'); var REWRITE_REGEX = <?=str_replace('~','/',str_replace('/','\/',REWRITE_REGEX))?>i, SITE_TITLE = '<?=SITE_TITLE?>', PRINTABLE_ASCII_REGEX = '<?=PRINTABLE_ASCII_REGEX?>', DocReady = [];</script><? if (!isset($_SERVER['HTTP_DNT']) && !empty(GA_TRACKING_CODE) && !PERM('inspector')){ ?> <!-- We respect your privacy. Enable "Do Not Track" in your browser, and this tracking code will disappear. --> <script async src='https://www.google-analytics.com/analytics.js'></script> <script> /* http://nickcraver.com/blog/2015/03/24/optimization-considerations/ */ var ga=ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga('create','<?=GA_TRACKING_CODE?>','auto'); ga('require', 'displayfeatures'); ga('send','pageview'); </script> <? } if (isset($customJS)) foreach ($customJS as $js){ echo "<script src='$js'></script>\n"; } ?> </body> </html>
</div> <footer><?=get_footer()?></footer> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script>if(!window.jQuery)document.write('\x3Cscript src="/js/jquery-2.1.4.min.js">\x3C/script>'); var REWRITE_REGEX = <?=str_replace('~','/',str_replace('/','\/',REWRITE_REGEX))?>i, SITE_TITLE = '<?=SITE_TITLE?>', PRINTABLE_ASCII_REGEX = '<?=PRINTABLE_ASCII_REGEX?>', DocReady = [];</script><? if (!isset($_SERVER['HTTP_DNT']) && !empty(GA_TRACKING_CODE) && !PERM('inspector')){ ?> <!-- We respect your privacy. Enable "Do Not Track" in your browser, and this tracking code will disappear. --> <script async src='https://www.google-analytics.com/analytics.js'></script> <script> // http://nickcraver.com/blog/2015/03/24/optimization-considerations/ var ga=ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga('create','<?=GA_TRACKING_CODE?>','auto'); ga('require', 'displayfeatures'); ga('send','pageview'); </script> <? } if (isset($customJS)) foreach ($customJS as $js){ echo "<script src='$js'></script>\n"; } ?> </body> </html>
Use an ArrayDeque instead of LinkedList to store current rule execution context Array-based collections perform better than linked lists in general, as they don’t need to do memory allocation for each add/remove() call.
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.model.internal.registry; import org.gradle.api.Nullable; import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor; import java.util.ArrayDeque; import java.util.Deque; public class RuleContext { private static final ThreadLocal<Deque<ModelRuleDescriptor>> STACK = new ThreadLocal<Deque<ModelRuleDescriptor>>() { @Override protected Deque<ModelRuleDescriptor> initialValue() { return new ArrayDeque<ModelRuleDescriptor>(); } }; @Nullable public static ModelRuleDescriptor get() { return STACK.get().peek(); } public static void run(ModelRuleDescriptor descriptor, Runnable runnable) { STACK.get().push(descriptor); try { runnable.run(); } finally { STACK.get().pop(); } } }
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.model.internal.registry; import com.google.common.collect.Lists; import org.gradle.api.Nullable; import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor; import java.util.Deque; public class RuleContext { private static final ThreadLocal<Deque<ModelRuleDescriptor>> STACK = new ThreadLocal<Deque<ModelRuleDescriptor>>() { @Override protected Deque<ModelRuleDescriptor> initialValue() { return Lists.newLinkedList(); } }; @Nullable public static ModelRuleDescriptor get() { return STACK.get().peek(); } public static void run(ModelRuleDescriptor descriptor, Runnable runnable) { STACK.get().push(descriptor); try { runnable.run(); } finally { STACK.get().pop(); } } }
Use a promise chain to be sure that everything's built
#!/usr/bin/env node const fs = require('fs') const path = require('path') const handlebars = require('handlebars') const workingDir = process.cwd() const output = workingDir + '/dist' const tags = { greeting: 'Hello!' } try { const files = fs.readdirSync(workingDir + '/pages') } catch (err) { throw err } function compileFile (resolve) { var meta = path.parse(workingDir + '/pages/' + this) var fullPath = meta.dir + '/' + meta.base try { var content = fs.readFileSync(fullPath, 'utf8') } catch (err) { reject(err) } var template = handlebars.compile(content) var outputPath = output + '/' + meta.name + '.html' try { fs.writeFileSync(outputPath, template(tags)) } catch(err) { reject(err) } resolve() } const pages = files.reduce((promiseChain, file) => { return promiseChain.then(new Promise((resolve) => compileFile.apply(file))) }, Promise.resolve('Built!')) pages.then(function (info) { console.log(info) }, function (reason) { throw reason })
#!/usr/bin/env node const fs = require('fs') const path = require('path') const handlebars = require('handlebars') const workingDir = process.cwd() const output = workingDir + '/dist' const tags = { greeting: 'Hello!' } try { const files = fs.readdirSync(workingDir + '/pages') } catch (err) { throw err } files.forEach(function (file) { var meta = path.parse(workingDir + '/pages/' + file) var fullPath = meta.dir + '/' + meta.base fs.readFile(fullPath, 'utf8', function (err, content) { if (err) { throw err } var template = handlebars.compile(content) var outputPath = output + '/' + meta.name + '.html' try { fs.writeFileSync(outputPath, template(tags)) } catch(err) { throw err } }) })
Fix flake8 and missing sys module
import sys from setuptools.command.test import test as TestCommand from setuptools import setup from hbite import VERSION as version class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import tox errno = tox.cmdline(self.test_args) sys.exit(errno) install_requires = [ 'protobuf==2.5.0', 'protobuf-socket-rpc==1.3' ] test_requires = [ 'tox' ] setup( name='hbite', version=version, url='https://github.com/ravwojdyla/hbite', author='Rafal Wojdyla', author_email='ravwojdyla@gmail.com', description='A high-level Python library for Hadoop RPCs', packages=['hbite'], install_requires=install_requires, tests_require=test_requires, cmdclass={'test': Tox} )
from setuptools import setup from setuptools.command.test import test as TestCommand from setuptools import setup from hbite import VERSION as version class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import tox errno = tox.cmdline(self.test_args) sys.exit(errno) install_requires = [ 'protobuf==2.5.0', 'protobuf-socket-rpc==1.3' ] test_requires = [ 'tox' ] setup( name='hbite', version=version, url='https://github.com/ravwojdyla/hbite', author='Rafal Wojdyla', author_email='ravwojdyla@gmail.com', description='A high-level Python library for Hadoop RPCs', packages=['hbite'], install_requires=install_requires, tests_require=test_requires, cmdclass={'test': Tox} )
Remove my debugging statement... again
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * Gets the current guild and member counts. * * @param {CommandoClient} client - The Discord.JS-Commando Client object * @returns {object} - An object containing two properties, guilds and members, each representing the associated counts. */ exports.getGuildsAndMembers = client => { return client.guilds.reduce((acc, guild) => { acc.guilds += 1; acc.members += guild.members.array().length; return acc; }, { guilds: 0, members: 0, }); }; exports.setGame = client => { let { guilds, members } = this.getGuildsAndMembers(client); client.user.setGame(`${client.commandPrefix || client.options.commandPrefix}help | Serving ${members} members across ${guilds} guilds`); };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * Gets the current guild and member counts. * * @param {CommandoClient} client - The Discord.JS-Commando Client object * @returns {object} - An object containing two properties, guilds and members, each representing the associated counts. */ exports.getGuildsAndMembers = client => { return client.guilds.reduce((acc, guild) => { console.log(acc); acc.guilds += 1; acc.members += guild.members.array().length; return acc; }, { guilds: 0, members: 0, }); }; exports.setGame = client => { let { guilds, members } = this.getGuildsAndMembers(client); client.user.setGame(`${client.commandPrefix || client.options.commandPrefix}help | Serving ${members} members across ${guilds} guilds`); };
Add loading state to signup
import { connect } from 'react-redux' import { reduxForm } from 'redux-form' import { push } from 'react-router-redux' import { checkEmailAvailability, createUser } from '../../actions/users' import { EMAIL_REGEX } from '../../utils/regexes' import Signup from './Signup' function mapStateToProps (state, ownProps) { return {} } function mapDispatchToProps (dispatch, ownProps) { return { onSubmit (data) { return dispatch(createUser(data)) .then(() => dispatch(push('/'))) } } } function validate (values) { const errors = {} if (!values.name) { errors.name = 'Surely you must have a name.' } if (!values.email) { errors.email = 'You must provide an email.' } else if (!EMAIL_REGEX.test(values.email)) { errors.email = "This email address doesn't seem valid." } if (!values.password) { errors.password = 'You need a password. Make it good!' } return errors } function asyncValidate (object, dispatch) { return dispatch(checkEmailAvailability(object.email)).then((action) => { if (!action.payload.email_available) { /* eslint-disable no-throw-literal */ throw { email: 'This email is currently being used.' } } }) } export default connect( mapStateToProps, mapDispatchToProps )( reduxForm({ form: 'signup', validate, asyncValidate })(Signup) )
import { connect } from 'react-redux' import { reduxForm } from 'redux-form' import { push } from 'react-router-redux' import { checkEmailAvailability, createUser } from '../../actions/users' import { EMAIL_REGEX } from '../../utils/regexes' import Signup from './Signup' function mapStateToProps (state, ownProps) { return {} } function mapDispatchToProps (dispatch, ownProps) { return { onSubmit (data) { dispatch(createUser(data)) .then(() => dispatch(push('/'))) } } } function validate (values) { const errors = {} if (!values.name) { errors.name = 'Surely you must have a name.' } if (!values.email) { errors.email = 'You must provide an email.' } else if (!EMAIL_REGEX.test(values.email)) { errors.email = "This email address doesn't seem valid." } if (!values.password) { errors.password = 'You need a password. Make it good!' } return errors } function asyncValidate (object, dispatch) { return dispatch(checkEmailAvailability(object.email)).then((action) => { if (!action.payload.email_available) { /* eslint-disable no-throw-literal */ throw { email: 'This email is currently being used.' } } }) } export default connect( mapStateToProps, mapDispatchToProps )( reduxForm({ form: 'signup', validate, asyncValidate })(Signup) )
Use npm style variable declarations.
/** * Communicate back to the web app. */ var extensionRoot = (new File($.fileName)).parent + '/'; $.evalFile(extensionRoot + '/constants.js'); $.evalFile(extensionRoot + '/Json.js'); $.evalFile(extensionRoot + '/Saver.js'); function getSettingsPath() { return SP_SETTINGS_PATH; } function save(args) { var preset = Json.eval(args[0]) , s = new sp.Saver() ; return Json.encode(s.save(preset)); } function serializeUi(args) { var file = new File(SP_SETTINGS_PATH + 'ui.json') , collapsed = [] ; for (var i in args[0]) collapsed.push(args[0][i]); if (file.open('w')) { file.writeln(Json.encode({ collapsed: collapsed })); } }
/** * Communicate back to the web app. */ var extensionRoot = (new File($.fileName)).parent + '/'; $.evalFile(extensionRoot + '/constants.js'); $.evalFile(extensionRoot + '/Json.js'); $.evalFile(extensionRoot + '/Saver.js'); function getSettingsPath() { return SP_SETTINGS_PATH; } function save(args) { var preset, s; preset = Json.eval(args[0]); s = new sp.Saver(); return Json.encode(s.save(preset)); } function serializeUi(args) { var file, collapsed; file = new File(SP_SETTINGS_PATH + 'ui.json'); collapsed = []; for (i in args[0]) collapsed.push(args[0][i]); if (file.open('w')) { file.writeln(Json.encode({ collapsed: collapsed })); } }
Fix Menu reload after re-login This bug existed for ages. After re-login there always was this 'this.tr is undefined' error. Problem was that two menu objects where created and the one actually rendered was not set to Kwf.menu. That caused the reload for the wrong object.
Kwf.ViewportWithoutMenu = Ext2.extend(Ext2.Viewport, { layout: 'fit', mabySubmit: function(cb, options) { var ret = true; this.items.each(function(i) { if (i.mabySubmit && !i.mabySubmit(cb, options)) { ret = false; return false; //break each } }, this); return ret; } }); Kwf.Viewport = Ext2.extend(Kwf.ViewportWithoutMenu, { initComponent: function() { Kwf.menu = Ext2.ComponentMgr.create({ xtype: 'kwf.menu', region: 'north', height: 30 }); this.items.push(Kwf.menu); this.layout = 'border'; Kwf.Viewport.superclass.initComponent.call(this); } });
Kwf.ViewportWithoutMenu = Ext2.extend(Ext2.Viewport, { layout: 'fit', mabySubmit: function(cb, options) { var ret = true; this.items.each(function(i) { if (i.mabySubmit && !i.mabySubmit(cb, options)) { ret = false; return false; //break each } }, this); return ret; } }); Kwf.Viewport = Ext2.extend(Kwf.ViewportWithoutMenu, { initComponent: function() { Kwf.menu = Ext2.ComponentMgr.create({ xtype: 'kwf.menu', region: 'north', height: 30 }); this.items.push({ xtype: 'kwf.menu', region: 'north', height: 30 }); this.layout = 'border'; Kwf.Viewport.superclass.initComponent.call(this); } });
Change system.rate-limit to prioritize disk
""" sentry.options.defaults ~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function from sentry.options import register, FLAG_NOSTORE, FLAG_REQUIRED, FLAG_PRIORITIZE_DISK register('cache.backend', flags=FLAG_NOSTORE) register('cache.options', default={}, flags=FLAG_NOSTORE) register('system.admin-email', flags=FLAG_REQUIRED) register('system.databases', default={}, flags=FLAG_NOSTORE) register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0, type=int, flags=FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE) register('redis.options', default={}, flags=FLAG_NOSTORE) # Absolute URL to the sentry root directory. Should not include a trailing slash. register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK)
""" sentry.options.defaults ~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function from sentry.options import register, FLAG_NOSTORE, FLAG_REQUIRED, FLAG_PRIORITIZE_DISK register('cache.backend', flags=FLAG_NOSTORE) register('cache.options', default={}, flags=FLAG_NOSTORE) register('system.admin-email', flags=FLAG_REQUIRED) register('system.databases', default={}, flags=FLAG_NOSTORE) register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0, type=int) register('system.secret-key', flags=FLAG_NOSTORE) register('redis.options', default={}, flags=FLAG_NOSTORE) # Absolute URL to the sentry root directory. Should not include a trailing slash. register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK)
Make sure the filename is alphanumeric
# encoding: utf-8 from django.db import models import uuid import os def unique_file_name(instance, filename): path = 'benchmarkLogs/' name = str(uuid.uuid4().hex) + '.log' return os.path.join(path, name) class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.FileField(upload_to=unique_file_name) slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, self).delete(*args, **kwargs)
# encoding: utf-8 from django.db import models import uuid import os def unique_file_name(instance, filename): path = 'benchmarkLogs/' name = str(uuid.uuid4()) + '.log' return os.path.join(path, name) class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.FileField(upload_to=unique_file_name) slug = models.SlugField(max_length=50, blank=True) def __unicode__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, self).delete(*args, **kwargs)
[TASK] Rename repository method `add` to attach in order to not collide with extbase
<?php namespace DreadLabs\VantomasWebsite\SecretSanta\Pair; use DreadLabs\VantomasWebsite\SecretSanta\Donee\DoneeInterface; use DreadLabs\VantomasWebsite\SecretSanta\Donor\DonorInterface; interface RepositoryInterface { /** * Finds a pair for the given donor * * @param DonorInterface $donor * @return PairInterface */ public function findPairFor(DonorInterface $donor); /** * Determines if the given donor/donee pair is mutual * * @param DonorInterface $donor * @param DoneeInterface $donee * @return bool */ public function isPairMutually(DonorInterface $donor, DoneeInterface $donee); /** * Flags if the incoming donor / donee pair is already existing * * @param DonorInterface $donor * @param DoneeInterface $donee * @return bool */ public function isPairExisting(DonorInterface $donor, DoneeInterface $donee); /** * @param PairInterface $pair * @return void */ public function attach(PairInterface $pair); }
<?php namespace DreadLabs\VantomasWebsite\SecretSanta\Pair; use DreadLabs\VantomasWebsite\SecretSanta\Donee\DoneeInterface; use DreadLabs\VantomasWebsite\SecretSanta\Donor\DonorInterface; interface RepositoryInterface { /** * Finds a pair for the given donor * * @param DonorInterface $donor * @return PairInterface */ public function findPairFor(DonorInterface $donor); /** * Determines if the given donor/donee pair is mutual * * @param DonorInterface $donor * @param DoneeInterface $donee * @return bool */ public function isPairMutually(DonorInterface $donor, DoneeInterface $donee); /** * Flags if the incoming donor / donee pair is already existing * * @param DonorInterface $donor * @param DoneeInterface $donee * @return bool */ public function isPairExisting(DonorInterface $donor, DoneeInterface $donee); /** * @param PairInterface $pair * @return void */ public function add(PairInterface $pair); }
[FIX] Rollback 17710. Use of TR by default is necessary for now because default home page message uses it. A better solution is welcome. git-svn-id: 08a866106b41c57cec985b5deddde5835bf030d4@17711 b456876b-0849-0410-b77d-98878d47e9d5
<?php // $Id: /cvsroot/tikiwiki/tiki/lib/wiki-plugins/wikiplugin_trackerlist.php,v 1.40.2.12 2008-03-22 12:13:54 sylvieg Exp $ function wikiplugin_tr_help() { $help = tra("Translate a string"); $help .= "~np~{TR()}string{TR}~/np~"; return $help; } function wikiplugin_tr_info() { return array( 'name' => tra('Translate'), 'description' => tra('Translate a string using Tikiwiki translation table.'), 'prefs' => array( 'wikiplugin_tr' ), 'body' => tra('string'), 'params' => array( ), ); } function wikiplugin_tr($data) { $return = tra($data); return $return == '_HOMEPAGE_CONTENT_' ? tra($data, 'en') : $return; }
<?php // $Id: /cvsroot/tikiwiki/tiki/lib/wiki-plugins/wikiplugin_trackerlist.php,v 1.40.2.12 2008-03-22 12:13:54 sylvieg Exp $ function wikiplugin_tr_help() { $help = tra("Translate a string"); $help .= "~np~{TR()}string{TR}~/np~"; return $help; } function wikiplugin_tr_info() { return array( 'name' => tra('Translate'), 'description' => tra('Translate a string using Tikiwiki translation table.'), 'prefs' => array( 'feature_multilingual', 'wikiplugin_tr' ), 'body' => tra('string'), 'params' => array( ), ); } function wikiplugin_tr($data) { $return = tra($data); return $return == '_HOMEPAGE_CONTENT_' ? tra($data, 'en') : $return; }
Make executable before develop/install, print what is made executable, and also run the actual develop/install.
from setuptools import setup from setuptools.command.develop import develop from setuptools.command.install import install import os dependencies = [ 'requests~=2.7' ] class PostDevelopCommand(develop): def run(self): make_director_executable() develop.run(self) class PostInstallCommand(install): def run(self): make_director_executable() install.run(self) _DIRECTOR_DIR = os.path.join(os.path.dirname(__file__), 'eclipsegen', 'director') def make_director_executable(): director_path = os.path.join(_DIRECTOR_DIR, 'director') print("Making {} executable".format(director_path)) os.chmod(director_path, 0o744) director_bat_path = os.path.join(_DIRECTOR_DIR, 'director.bat') print("Making {} executable".format(director_bat_path)) os.chmod(director_bat_path, 0o744) setup( name='eclipsegen', version='0.4.2', description='Generate Eclipse instances in Python', url='http://github.com/Gohla/eclipsegen', author='Gabriel Konat', author_email='gabrielkonat@gmail.com', license='Apache 2.0', packages=['eclipsegen'], install_requires=dependencies, test_suite='nose.collector', tests_require=['nose>=1.3.7'] + dependencies, include_package_data=True, zip_safe=False, cmdclass={ 'install': PostInstallCommand, 'develop': PostDevelopCommand } )
from setuptools import setup from setuptools.command.develop import develop from setuptools.command.install import install import os dependencies = [ 'requests~=2.7' ] class PostDevelopCommand(develop): def run(self): make_director_executable() class PostInstallCommand(install): def run(self): make_director_executable() _DIRECTOR_DIR = os.path.join(os.path.dirname(__file__), 'eclipsegen', 'director') def make_director_executable(): print("Making director executable") os.chmod(os.path.join(_DIRECTOR_DIR, 'director'), 0o744) os.chmod(os.path.join(_DIRECTOR_DIR, 'director.bat'), 0o744) setup( name='eclipsegen', version='0.4.2', description='Generate Eclipse instances in Python', url='http://github.com/Gohla/eclipsegen', author='Gabriel Konat', author_email='gabrielkonat@gmail.com', license='Apache 2.0', packages=['eclipsegen'], install_requires=dependencies, test_suite='nose.collector', tests_require=['nose>=1.3.7'] + dependencies, include_package_data=True, zip_safe=False, cmdclass={ 'install': PostInstallCommand, 'develop': PostDevelopCommand } )
Fix two mistakes of method description Fix two mistakes of method description in processor.py Change-Id: I3434665b6d458937295b0563ea0cd0ee6aebaca1
# -*- coding: utf-8 -*- # Copyright 2014 Objectif Libre # # 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. # # @author: Stéphane Albert # from cloudkitty import service def main(): service.prepare_service() # NOTE(mc): This import is done here to ensure that the prepare_service() # function is called before any cfg option. By importing the orchestrator # file, the utils one is imported too, and then some cfg options are read # before the prepare_service(), making cfg.CONF returning default values # systematically. from cloudkitty import orchestrator processor = orchestrator.Orchestrator() try: processor.process() except KeyboardInterrupt: processor.terminate() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # Copyright 2014 Objectif Libre # # 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. # # @author: Stéphane Albert # from cloudkitty import service def main(): service.prepare_service() # NOTE(mc): This import is done here to ensure that the prepare_service() # fonction is called before any cfg option. By importing the orchestrator # file, the utils one is imported too, and then some cfg option are read # before the prepare_service(), making cfg.CONF returning default values # systematically. from cloudkitty import orchestrator processor = orchestrator.Orchestrator() try: processor.process() except KeyboardInterrupt: processor.terminate() if __name__ == '__main__': main()
Switch to using InteractiveInterpreter object instead of eval
import sys import code from diesel import Application, Pipe, until DEFAULT_PROMPT = '>>> ' def readcb(): from diesel.app import current_app print 'Diesel Console' cmd = '' prompt = DEFAULT_PROMPT interp = code.InteractiveInterpreter(locals={'app':current_app}) while 1: sys.stdout.write(prompt) sys.stdout.flush() input = yield until("\n") cmd += input if input.lstrip() == input or input == "\n": ret = code.compile_command(input) if ret: out = interp.runcode(ret) if out: print 'Out: %r' % out cmd = '' prompt = DEFAULT_PROMPT else: # Start of a block prompt = '... ' else: # Continued block prompt = '... ' a = Application() a.add_loop(Pipe(sys.stdin, readcb)) a.run()
import sys import code from diesel import Application, Pipe, until DEFAULT_PROMPT = '>>> ' def readcb(): print 'Diesel Console' cmd = '' prompt = DEFAULT_PROMPT while 1: sys.stdout.write(prompt) sys.stdout.flush() input = yield until("\n") cmd += input if input.lstrip() == input or input == "\n": ret = code.compile_command(input) if ret: out = eval(ret) if out: print 'Out: %r' % out cmd = '' prompt = DEFAULT_PROMPT else: # Start of a block prompt = '... ' else: # Continued block prompt = '... ' a = Application() a.add_loop(Pipe(sys.stdin, readcb)) a.run()
fix: Make event emitter from blank object - If a function is passed to jQuery, it calls it 🤷🏻‍♂️ - In hindsight, it is not needed to pass the object to jQuery - This fixes a weird bug explained here https://github.com/frappe/frappe/pull/6791
frappe.provide('frappe.utils'); /** * Simple EventEmitterMixin which uses jQuery's event system */ const EventEmitterMixin = { init() { this.jq = jQuery({}); }, trigger(evt, data) { !this.jq && this.init(); this.jq.trigger(evt, data); }, once(evt, handler) { !this.jq && this.init(); this.jq.one(evt, (e, data) => handler(data)); }, on(evt, handler) { !this.jq && this.init(); this.jq.bind(evt, (e, data) => handler(data)); }, off(evt, handler) { !this.jq && this.init(); this.jq.unbind(evt, (e, data) => handler(data)); } } frappe.utils.make_event_emitter = function(object) { Object.assign(object, EventEmitterMixin); return object; }; export default EventEmitterMixin;
frappe.provide('frappe.utils'); /** * Simple EventEmitterMixin which uses jQuery's event system */ const EventEmitterMixin = { init() { this.jq = jQuery(this); }, trigger(evt, data) { !this.jq && this.init(); this.jq.trigger(evt, data); }, once(evt, handler) { !this.jq && this.init(); this.jq.one(evt, (e, data) => handler(data)); }, on(evt, handler) { !this.jq && this.init(); this.jq.bind(evt, (e, data) => handler(data)); }, off(evt, handler) { !this.jq && this.init(); this.jq.unbind(evt, (e, data) => handler(data)); } } frappe.utils.make_event_emitter = function(object) { Object.assign(object, EventEmitterMixin); return object; }; export default EventEmitterMixin;
Fix the initial search migration There is no point in creating the model in this way, that's just not how it's used: instead we want to use the FTS4 extension from SQLite.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from ideascube.search.utils import create_index_table class CreateSearchModel(migrations.CreateModel): def database_forwards(self, *_): # Don't run the parent method, we create the table our own way create_index_table() class Migration(migrations.Migration): dependencies = [ ] operations = [ CreateSearchModel( name='Search', fields=[], options={ 'db_table': 'idx', 'managed': False, }, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import ideascube.search.models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Search', fields=[ ('rowid', models.IntegerField(serialize=False, primary_key=True)), ('model', models.CharField(max_length=64)), ('model_id', models.IntegerField()), ('public', models.BooleanField(default=True)), ('text', ideascube.search.models.SearchField()), ], options={ 'db_table': 'idx', 'managed': False, }, ), ]
Apply lint to easy client
var Http = require('http'); class EasyClient { constructor(options) { this.options = options; this.postData = options.data; } call(success) { var responseData = ''; var req = Http.request(this.options); if (this.postData) { req.write(this.postData); } req.on('response', function(response) { response.on('data', function(buffer) { responseData = responseData.concat(buffer.toString()); }); response.on('end', function(buffer) { if (buffer) { responseData = responseData.concat(buffer.toString()); } success({ headers: response.headers, body: responseData, status: response.statusCode }); }); }).end(); } } module.exports = EasyClient;
var Http = require('http'); class EasyClient { constructor(options) { this.options = options this.postData = options.data; } static get(options) { } call(success) { var responseData = '', client = this; var req = Http.request(this.options); if (this.postData) { req.write(this.postData); } req.on('response', function(response) { response.on('data', function(buffer) { responseData = responseData.concat(buffer.toString()); }); response.on('end', function(buffer) { if (buffer) { responseData = responseData.concat(buffer.toString()); } success({ headers: response.headers, body: responseData, status: response.statusCode }); }); }).end(); } } module.exports = EasyClient;
Clean up $pre parameter description
<?php /* * Layout functions */ // `is_currentfile` // // Checks for current file. Returns boolean. function is_currentfile($file) { if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) { return true; } } // `filecount` // // Counts number of files in a directory. `$dir` must be without a trailing // slash. function filecount($dir) { $i = 0; foreach (glob($dir . '/*') as $file) { if (!is_dir($file)) { $i++; } } echo $i; } // `feedparse` // // Parses RSS or Atom feed. // $pre => preformat feed contents, must be a boolean function feedparse($url, $pre = false) { $feed = fopen($url, 'r'); $data = stream_get_contents($feed); fclose($feed); if ($pre) { echo '<pre>'; } echo $data; if ($pre) { echo '</pre>'; } } // `selectrandom` // // Selects a random value from array. function selectrandom($array) { echo $array[array_rand($array)]; } // `undot` // // Removes dots from string. function undot($string) { echo str_replace('.', '', $string); }
<?php /* * Layout functions */ // `is_currentfile` // // Checks for current file. Returns boolean. function is_currentfile($file) { if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) { return true; } } // `filecount` // // Counts number of files in a directory. `$dir` must be without a trailing // slash. function filecount($dir) { $i = 0; foreach (glob($dir . '/*') as $file) { if (!is_dir($file)) { $i++; } } echo $i; } // `feedparse` // // Parses RSS or Atom feed. // $pre => preformat feed contents or no, must be a boolean function feedparse($url, $pre = false) { $feed = fopen($url, 'r'); $data = stream_get_contents($feed); fclose($feed); if ($pre) { echo '<pre>'; } echo $data; if ($pre) { echo '</pre>'; } } // `selectrandom` // // Selects a random value from array. function selectrandom($array) { echo $array[array_rand($array)]; } // `undot` // // Removes dots from string. function undot($string) { echo str_replace('.', '', $string); }
Add python versions to classifiers
import os from setuptools import setup, find_packages ROOT = os.path.abspath(os.path.dirname(__file__)) setup( name='Flask-Mobility', version='0.1', url='http://github.com/rehandalal/flask-mobility/', license='BSD', author='Rehan Dalal', author_email='rehan@meet-rehan.com', description='A Flask extension to simplify building mobile-friendly sites.', long_description=open(os.path.join(ROOT, 'README.rst')).read(), py_modules=['flask_mobility'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'setuptools', 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
import os from setuptools import setup, find_packages ROOT = os.path.abspath(os.path.dirname(__file__)) setup( name='Flask-Mobility', version='0.1', url='http://github.com/rehandalal/flask-mobility/', license='BSD', author='Rehan Dalal', author_email='rehan@meet-rehan.com', description='A Flask extension to simplify building mobile-friendly sites.', long_description=open(os.path.join(ROOT, 'README.rst')).read(), py_modules=['flask_mobility'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'setuptools', 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Refactor tests with `runTests()` helper `runTests()` will create and run tests given parser and mock data. Since the helper creates an `it()` block for each mock object key, this allows the tests to be DRY and clear. Also, debugging will be easier since the type of parser test being run is made explicit.
'use strict'; /** * Module dependencies. */ var assert = require('chai').assert; var mocks = require('./mocks/'); var htmlparser = require('htmlparser2'); /** * Helper that creates and runs tests based on mock data. * * @param {Function} parser - The parser. * @param {Object} mockObj - The mock object. */ function runTests(parser, mockObj) { Object.keys(mockObj).forEach(function(type) { it(type, function() { var data = mockObj[type]; assert.deepEqual(parser(data), htmlparser.parseDOM(data)); }) }); } /** * Tests for parser. */ describe('html-dom-parser', function() { // server describe('server parser', function() { var parser = require('../'); // should be equivalent to `htmlparser2.parseDOM()` runTests(parser, mocks.html); runTests(parser, mocks.svg); }); });
'use strict'; /** * Module dependencies. */ var assert = require('chai').assert; var mocks = require('./mocks/'); var htmlparser = require('htmlparser2'); /** * Tests for parser. */ describe('html-dom-parser', function() { describe('server parser', function() { var parser = require('../'); it('is equivalent to `htmlparser2.parseDOM()`', function() { // html Object.keys(mocks.html).forEach(function(type) { var html = mocks.html[type]; assert.deepEqual(parser(html), htmlparser.parseDOM(html)); }); // svg Object.keys(mocks.svg).forEach(function(type) { var svg = mocks.svg[type]; assert.deepEqual(parser(svg), htmlparser.parseDOM(svg)); }); }); }); });
Update REST API address in test
import requests from nose.plugins.attrib import attr @attr('webservice') def test_rest_api_responsive(): stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "FPLX": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}' url = 'http://indra-api-72031e2dfde08e09.elb.us-east-1.amazonaws.com:8000/' + \ 'assemblers/cyjs' res = requests.post(url, stmt_str) assert res.status_code == 200
import requests from nose.plugins.attrib import attr @attr('webservice') def test_rest_api_responsive(): stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "FPLX": "ERK"}, "name": "ERK"}], "evidence": [{"text": "MEK binds ERK", "source_api": "trips"}]}]}' url = 'http://ec2-54-88-146-250.compute-1.amazonaws.com:8080/' + \ 'assemblers/cyjs' res = requests.post(url, stmt_str) assert res.status_code == 200
Fix content height not being set on Safari
'use strict'; module.exports = [ '$rootScope', '$window', '$timeout', function FixContainerHeight($rootScope, $window, $timeout) { return { restrict: 'A', link: function($scope, el) { function setParentHeight() { var pel = el[0].parentNode; var h = el[0].offsetHeight; var ph = pel.style.minHeight; if ( h > 0 && h + 'px' !== ph ) { pel.style.minHeight = h + 'px'; } } // Wait for the content to be appended and set parent height function waitAndSet() { var i; var times = [0,200,400,700,1000,1500,2000]; var len = times.length; for ( i = 0; i < len; i++ ) { $timeout(setParentHeight,times[i]); } } $scope.$on('ass-page-data-applied', waitAndSet); $window.addEventListener('resize', setParentHeight); } }; } ];
'use strict'; module.exports = [ '$rootScope', '$window', '$timeout', function FixContainerHeight($rootScope, $window, $timeout) { return { restrict: 'A', link: function($scope, el) { function setParentHeight() { var pel = el[0].parentNode; var h = el[0].offsetHeight; if ( h ) { pel.style.minHeight = h + 'px'; } } function updateScope() { // Wait for the reflow and set parent height for ( var i = 0; i < 5; i++ ) { $timeout(setParentHeight,i*200); } } $scope.$on('ass-page-data-applied', updateScope); $window.addEventListener('resize', updateScope); } }; } ];
Remove bug in autorunner management in PHAR.
<?php namespace mageekguy\atoum; use mageekguy\atoum, mageekguy\atoum\scripts\phar ; if (extension_loaded('phar') === false) { throw new \runtimeException('Phar extension is mandatory to use this PHAR'); } define(__NAMESPACE__ . '\phar\name', 'mageekguy.atoum.phar'); \phar::mapPhar(atoum\phar\name); $versions = unserialize(file_get_contents('phar://' . atoum\phar\name . '/versions')); require_once 'phar://' . atoum\phar\name . '/' . $versions['current'] . '/classes/autoloader.php'; if (defined(__NAMESPACE__ . '\scripts\runner') === false) { define(__NAMESPACE__ . '\scripts\runner', __FILE__); } if (phar\stub::autorunIsEnabled() === false) { phar\stub::enableAutorun(constant(__NAMESPACE__ . '\scripts\runner')); } __HALT_COMPILER();
<?php namespace mageekguy\atoum; use mageekguy\atoum, mageekguy\atoum\scripts\phar ; if (extension_loaded('phar') === false) { throw new \runtimeException('Phar extension is mandatory to use this PHAR'); } define(__NAMESPACE__ . '\phar\name', 'mageekguy.atoum.phar'); \phar::mapPhar(atoum\phar\name); $versions = unserialize(file_get_contents('phar://' . atoum\phar\name . '/versions')); require_once 'phar://' . atoum\phar\name . '/' . $versions['current'] . '/classes/autoloader.php'; if (defined(__NAMESPACE__ . '\autorun') === false) { define(__NAMESPACE__ . '\autorun', true); phar\stub::autorun(__FILE__); } __HALT_COMPILER();
Add check to ensure truncate does not error - check if input exists before acting on it - silences thrown error - spirit of template filter, do nothing rather than fail if input is incorrect
/** * Return a truncated version of a string * @param {string} input * @param {integer} length * @param {boolean} killwords * @param {string} end * @return {string} */ PolymerExpressions.prototype.truncate = function (input, length, killwords, end) { var orig = input; length = length || 255; if(!input) { return; } if (input.length <= length) return input; if (killwords) { input = input.substring(0, length); } else { var idx = input.lastIndexOf(' ', length); if (idx === -1) { idx = length; } input = input.substring(0, idx); } input += (end !== undefined && end !== null) ? end : '...'; return input; };
/** * Return a truncated version of a string * @param {string} input * @param {integer} length * @param {boolean} killwords * @param {string} end * @return {string} */ PolymerExpressions.prototype.truncate = function (input, length, killwords, end) { var orig = input; length = length || 255; if (input.length <= length) return input; if (killwords) { input = input.substring(0, length); } else { var idx = input.lastIndexOf(' ', length); if (idx === -1) { idx = length; } input = input.substring(0, idx); } input += (end !== undefined && end !== null) ? end : '...'; return input; };
Remove debuging add needed header
package marogo import "sync" import "encoding/json" import "net/http" import "bytes" import "fmt" func MakeRequest(address string, method string, data interface{}, needsHeader bool) (*http.Response, error) { address = API_URL + address jsob, err := json.Marshal(data) fmt.Print("%v\n", string(jsob)) if err != nil { return nil, err } body := bytes.NewReader(jsob) request, err := http.NewRequest(method, address, body) if err != nil { return nil, err } if needsHeader { request.Header.Add("Content-Type", "application/json") } client := &http.Client{} response, err := client.Do(request) if err != nil { return nil, err } return response, nil } func MakeAsyncRequest(address string, method string, data interface{}, wg *sync.WaitGroup) (bool, error) { MakeRequest(address, method, data) wg.Done() return true, nil }
package marogo import "sync" import "encoding/json" import "net/http" import "bytes" import "fmt" func MakeRequest(address string, method string, data interface{}) (*http.Response, error) { address = API_URL + address jsob, err := json.Marshal(data) fmt.Print("%v\n", string(jsob)) if err != nil { return nil, err } body := bytes.NewReader(jsob) request, err := http.NewRequest(method, address, body) if err != nil { return nil, err } client := &http.Client{} response, err := client.Do(request) if err != nil { return nil, err } return response, nil } func MakeAsyncRequest(address string, method string, data interface{}, wg *sync.WaitGroup) (bool, error) { MakeRequest(address, method, data) wg.Done() return true, nil }
Update to specify content-type header
import requests from .resources.batches import Batches from .resources.jobs import Jobs DEFAULT_API_ROOT = 'http://app.spare5.com/partner/v2' class Spare5Client(object): def __init__(self, username, token, api_root=DEFAULT_API_ROOT): super(Spare5Client, self).__init__() self.api_root = api_root self.username = username self.token = token self.batches = Batches(self) def _make_request(self, verb, *args, **kwargs): kwargs.update({ 'auth': (self.username, self.token), 'headers': { 'content-type': 'application/json', }, }) response = requests.request(verb, *args, **kwargs) return response.json() def _get(self, url, **kwargs): return self._make_request('get', url, **kwargs) def _post(self, url, data, **kwargs): return self._make_request('post', url, data=data, **kwargs) def _put(self, url, data, **kwargs): return self._make_request('put', url, data=data, **kwargs) def _delete(self, url, **kwargs): return self._make_request('delete', url, **kwargs)
import requests from .resources.batches import Batches from .resources.jobs import Jobs DEFAULT_API_ROOT = 'http://app.spare5.com/partner/v2' class Spare5Client(object): def __init__(self, username, token, api_root=DEFAULT_API_ROOT): super(Spare5Client, self).__init__() self.api_root = api_root self.username = username self.token = token self.batches = Batches(self) def _make_request(self, verb, *args, **kwargs): kwargs.update({ 'auth': (self.username, self.token) }) response = requests.request(verb, *args, **kwargs) return response.json() def _get(self, url, **kwargs): return self._make_request('get', url, **kwargs) def _post(self, url, data, **kwargs): return self._make_request('post', url, data=data, **kwargs) def _put(self, url, data, **kwargs): return self._make_request('put', url, data=data, **kwargs) def _delete(self, url, **kwargs): return self._make_request('delete', url, **kwargs)
Update AsynchronousAction default values of min_workers to 0 and max_seconds_idle to 60
from bot.action.core.action import IntermediateAction from bot.multithreading.work import Work class AsynchronousAction(IntermediateAction): def __init__(self, name: str, min_workers: int = 0, max_workers: int = 4, max_seconds_idle: int = 60): super().__init__() self.name = name self.min_workers = min_workers self.max_workers = max_workers self.max_seconds_idle = max_seconds_idle self.worker_pool = None # initialized in post_setup where we have access to scheduler def post_setup(self): self.worker_pool = self.scheduler.new_worker_pool( self.name, self.min_workers, self.max_workers, self.max_seconds_idle ) def process(self, event): self.worker_pool.post(Work(lambda: self._continue(event), "asynchronous_action"))
from bot.action.core.action import IntermediateAction from bot.multithreading.work import Work class AsynchronousAction(IntermediateAction): def __init__(self, name: str, min_workers: int = 1, max_workers: int = 4, max_seconds_idle: int = 15): super().__init__() self.name = name self.min_workers = min_workers self.max_workers = max_workers self.max_seconds_idle = max_seconds_idle self.worker_pool = None # initialized in post_setup where we have access to scheduler def post_setup(self): self.worker_pool = self.scheduler.new_worker_pool( self.name, self.min_workers, self.max_workers, self.max_seconds_idle ) def process(self, event): self.worker_pool.post(Work(lambda: self._continue(event), "asynchronous_action"))
Apply markups from the outside in
'use strict'; module.exports = convert var serializeInline = require('./inline').serializeInline /** * convert(elem, s) performs the actual work of converting an element * into its abstract representation. * * @param {Element} elem * @param {Serialize} s */ function convert (elem, s) { var allMarkups = [], node = elem, markups, i while (node) { if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) { markups = serializeInline(node) for (i = 0; i < markups.length; i += 1) markups[i].start = s.length allMarkups.push(markups) node = node.firstChild continue } if (node.nodeType === Node.TEXT_NODE) s.text += node.data else if (node.nodeName === 'BR') s.text += '\n' while (!node.nextSibling && node !== elem) { markups = allMarkups.pop() for (i = 0; i < markups.length; i += 1) markups[i].end = s.length allMarkups.unshift(markups) node = node.parentNode } if (node === elem) break node = node.nextSibling } s.addMarkups(allMarkups.reduce(function (arr, markups) { return arr.concat(markups) }, [])) }
'use strict'; module.exports = convert var serializeInline = require('./inline').serializeInline /** * convert(elem, s) performs the actual work of converting an element * into its abstract representation. * * @param {Element} elem * @param {Serialize} s */ function convert (elem, s) { var node = elem, children = [], info, i while (node) { if (node.nodeType === Node.ELEMENT_NODE && node.firstChild) { info = serializeInline(node) for (i = 0; i < info.length; i += 1) info[i].start = s.length children.push(info) node = node.firstChild continue } if (node.nodeType === Node.TEXT_NODE) s.text += node.data else if (node.nodeName === 'BR') s.text += '\n' while (!node.nextSibling && node !== elem) { info = children.pop() for (i = 0; i < info.length; i += 1) info[i].end = s.length s.addMarkups(info) node = node.parentNode } if (node === elem) break node = node.nextSibling } }
Use POST for all methods requiring it in specs Added all missing methods from https://dev.twitter.com/docs/api/1.1 Also included some of the streaming methods which work with both GET and POST but accept arguments like "track" which can quickly require POST. (Closes #187 #145 #188)
''' This module is automatically generated using `update.py` .. data:: POST_ACTIONS List of twitter method names that require the use of POST ''' POST_ACTIONS = [ # Status Methods 'update', 'retweet', # Direct Message Methods 'new', # Account Methods 'update_profile_image', 'update_delivery_device', 'update_profile', 'update_profile_background_image', 'update_profile_colors', 'update_location', 'end_session', 'settings', 'update_profile_banner', 'remove_profile_banner', # Notification Methods 'leave', 'follow', # Status Methods, Block Methods, Direct Message Methods, # Friendship Methods, Favorite Methods 'destroy', 'destroy_all', # Block Methods, Friendship Methods, Favorite Methods 'create', 'create_all', # Users Methods 'lookup', 'report_spam', # Geo Methods 'place', # Streaming Methods 'filter', 'user', 'site', # OAuth Methods 'token', 'access_token', 'request_token', 'invalidate_token', ]
''' This module is automatically generated using `update.py` .. data:: POST_ACTIONS List of twitter method names that require the use of POST ''' POST_ACTIONS = [ # Status Methods 'update', 'retweet', # Direct Message Methods 'new', # Account Methods 'update_profile_image', 'update_delivery_device', 'update_profile', 'update_profile_background_image', 'update_profile_colors', 'update_location', 'end_session', # Notification Methods 'leave', 'follow', # Status Methods, Block Methods, Direct Message Methods, # Friendship Methods, Favorite Methods 'destroy', # Block Methods, Friendship Methods, Favorite Methods 'create', 'create_all', # Users Methods 'lookup', # Semantic Methods 'filter', # OAuth Methods 'token', ]
Support sources rather than source
<?php /** * mbp-logging-reports.php * * A producer to create reports based on logged data in mb-logging-api. */ use DoSomething\MBP_LoggingReports\MBP_LoggingReports_Users; date_default_timezone_set('America/New_York'); define('CONFIG_PATH', __DIR__ . '/messagebroker-config'); // Load up the Composer autoload magic require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/mbp-logging-reports.config.inc'; if (isset($_GET['source'])) { $source[0] = $_GET['source']; } elseif (isset($argv[1])) { $source[0] = $argv[1]; } // all else { $source = [ 'niche', 'afterschool' ]; } echo '------- mbp-logging-reports START: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL; try { // Kick off $mbpLoggingReport = new MBP_LoggingReports_Users(); // Gather digest message mailing list $mbpLoggingReport->report('runningMonth', $sources); } catch(Exception $e) { echo $e->getMessage(), PHP_EOL; } echo '------- mbp-logging-reports END: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;
<?php /** * mbp-logging-reports.php * * A producer to create reports based on logged data in mb-logging-api. */ use DoSomething\MBP_LoggingReports\MBP_LoggingReports_Users; date_default_timezone_set('America/New_York'); define('CONFIG_PATH', __DIR__ . '/messagebroker-config'); // Load up the Composer autoload magic require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/mbp-logging-reports.config.inc'; if (isset($_GET['source'])) { $source = $_GET['source']; } elseif (isset($argv[1])) { $source = $argv[1]; } else { $source = 'all'; } echo '------- mbp-logging-reports START: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL; try { // Kick off $mbpLoggingReport = new MBP_LoggingReports_Users(); // Gather digest message mailing list $mbpLoggingReport->report('runningMonth', $source); } catch(Exception $e) { echo $e->getMessage(), PHP_EOL; } echo '------- mbp-logging-reports END: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;
Fix indentation issues in javadoc code samples
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gcloud; /** * Implementation of this interface can persist their state and restore from it. * * <p> * A typical capture usage: * <pre> {@code * X restorableObj; // X instanceof Restorable<X> * RestorableState<X> state = restorableObj.capture(); * .. persist state * }</pre> * * A typical restore usage: * <pre> {@code * RestorableState<X> state = ... // read from persistence * X restorableObj = state.restore(); * ... * }</pre> * * @param <T> the restorable object's type */ public interface Restorable<T extends Restorable<T>> { /** * Captures the state of this object. * * @return a {@link RestorableState} instance that contains the state for this object and can * restore it afterwards. */ RestorableState<T> capture(); }
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gcloud; /** * Implementation of this interface can persist their state and restore from it. * * <p> * A typical capture usage: * <pre> {@code * X restorableObj; // X instanceof Restorable<X> * RestorableState<X> state = restorableObj.capture(); * .. persist state * }</pre> * * A typical restore usage: * <pre> {@code * RestorableState<X> state = ... // read from persistence * X restorableObj = state.restore(); * ... * }</pre> * * @param <T> the restorable object's type */ public interface Restorable<T extends Restorable<T>> { /** * Captures the state of this object. * * @return a {@link RestorableState} instance that contains the state for this object and can * restore it afterwards. */ RestorableState<T> capture(); }
Fix the github xhr interface
const github = require('./lib/github') const view = require('./lib/view') var feeds require('./lib/feeds') .then(res => feeds = res) module.exports = { '/api/github/xhr/{command}': (request, reply) => { github.xhr[request.params.command] ? github.xhr[request.params.command](reply) : reply.continue() }, '/api/view/xhr/{name}': (request, reply) => { view.xhr(request.params.name, request, reply) .then(js => { console.log(js) const response = reply(js) response.type('text/plain') }) .catch(e => console.error(e) && reply.continue()) }, '/feed/{type}.xml': (request, reply) => { if (request.params.type === 'atom') return reply(feeds[0]) if (request.params.type === 'rss') return reply(feeds[1]) reply.continue() }, '/{p*}': (request, reply) => { const response = reply.view('404') response.type('text/html') response.code(404) } }
const github = require('./lib/github') const view = require('./lib/view') var feeds require('./lib/feeds') .then(res => feeds = res) module.exports = { '/api/github/xhr/{command}': (request, reply) => { github.xhr[request.params.command] ? github[request.params.command](reply) : reply.continue() }, '/api/view/xhr/{name}': (request, reply) => { view.xhr(request.params.name, request, reply) .then(js => { console.log(js) const response = reply(js) response.type('text/plain') }) .catch(e => console.error(e) && reply.continue()) }, '/feed/{type}.xml': (request, reply) => { if (request.params.type === 'atom') return reply(feeds[0]) if (request.params.type === 'rss') return reply(feeds[1]) reply.continue() }, '/{p*}': (request, reply) => { const response = reply.view('404') response.type('text/html') response.code(404) } }
Fix check style issue exceeding no of chars in one line
package org.wso2.carbon.apimgt.core.configuration.models; import org.wso2.carbon.apimgt.core.util.APIMgtConstants; import org.wso2.carbon.config.annotation.Configuration; import org.wso2.carbon.config.annotation.Element; import java.util.Collections; import java.util.List; /** * Class to hold Environment configurations */ @Configuration(description = "Environment Configurations") public class EnvironmentConfigurations { @Element(description = "list of web clients (eg: 127.0.0.1:9292) to allow make requests" + "to current environment\n(use '" + APIMgtConstants.CORSAllowOriginConstants.ALLOW_ALL_ORIGINS + "' to allow any web client)") private List<String> allowedHosts = Collections.singletonList( APIMgtConstants.CORSAllowOriginConstants.ALLOW_ALL_ORIGINS); //Unique name for environment to set cookies by backend @Element(description = "current environment's label from the list of environments") private String environmentLabel = "Default"; public List<String> getAllowedHosts() { return allowedHosts; } public void setAllowedHosts(List<String> allowedHosts) { this.allowedHosts = allowedHosts; } public String getEnvironmentLabel() { return environmentLabel; } public void setEnvironmentLabel(String environmentLabel) { this.environmentLabel = environmentLabel; } }
package org.wso2.carbon.apimgt.core.configuration.models; import org.wso2.carbon.apimgt.core.util.APIMgtConstants; import org.wso2.carbon.config.annotation.Configuration; import org.wso2.carbon.config.annotation.Element; import java.util.Collections; import java.util.List; /** * Class to hold Environment configurations */ @Configuration(description = "Environment Configurations") public class EnvironmentConfigurations { @Element(description = "list of web clients (eg: 127.0.0.1:9292) allowed to make requests to the current environment\n" + "(use '" + APIMgtConstants.CORSAllowOriginConstants.ALLOW_ALL_ORIGINS + "' to allow any web client)") private List<String> allowedHosts = Collections.singletonList( APIMgtConstants.CORSAllowOriginConstants.ALLOW_ALL_ORIGINS); //Unique name for environment to set cookies by backend @Element(description = "current environment's label from the list of environments") private String environmentLabel = "Default"; public List<String> getAllowedHosts() { return allowedHosts; } public void setAllowedHosts(List<String> allowedHosts) { this.allowedHosts = allowedHosts; } public String getEnvironmentLabel() { return environmentLabel; } public void setEnvironmentLabel(String environmentLabel) { this.environmentLabel = environmentLabel; } }
Make sure we have both images and not just one of them before building
"""Handles all command line actions for Berth.""" import berth.build as build import berth.config as config import berth.utils as utils import click @click.command(help='Berth use Docker containers to build packages for you, based on a YAML configuration file.') @click.pass_context @click.version_option(prog_name='Berth') @click.argument('config_file', metavar='<CONFIG FILE>', type=click.File()) @click.option('-v', '--verbose', is_flag=True, help='Turn on verbose output.') @click.option('-d', '--debug', is_flag=True, help='Turn on debug output.') def main(context, config_file, verbose, debug): """Build a package.""" if debug: utils.set_log_level(2) elif verbose: utils.set_log_level(1) configuration = config.read(config_file) if not configuration: context.exit(1) if not config.verify(configuration): context.exit(1) if not utils.pull_image(configuration['build']['image']) or \ not utils.pull_image(configuration['package'].get('image', 'dockerfile/fpm')): context.exit(1) build.build(configuration) context.exit(0) if __name__ == '__main__': main() # pylint: disable = no-value-for-parameter
"""Handles all command line actions for Berth.""" import berth.build as build import berth.config as config import berth.utils as utils import click @click.command(help='Berth use Docker containers to build packages for you, based on a YAML configuration file.') @click.pass_context @click.version_option(prog_name='Berth') @click.argument('config_file', metavar='<CONFIG FILE>', type=click.File()) @click.option('-v', '--verbose', is_flag=True, help='Turn on verbose output.') @click.option('-d', '--debug', is_flag=True, help='Turn on debug output.') def main(context, config_file, verbose, debug): """Build a package.""" if debug: utils.set_log_level(2) elif verbose: utils.set_log_level(1) configuration = config.read(config_file) if not configuration: context.exit(1) if not config.verify(configuration): context.exit(1) if not utils.pull_image(configuration['build']['image']) and \ not utils.pull_image(configuration['package'].get('image', 'dockerfile/fpm')): context.exit(1) build.build(configuration) context.exit(0) if __name__ == '__main__': main() # pylint: disable = no-value-for-parameter
Fix render method for sfWidgetFormInputFileMulti
<?php /** * sfWidgetFormInputFileMulti represents an upload HTML input tag with multiple option. * * @package symfony * @subpackage widget * @author Vincent Chabot <vchabot@groupe-exp.com> * @version SVN: $Id$ */ class sfWidgetFormInputFileMulti extends sfWidgetFormInputFile { /** * Configures the current widget. * * @param array $options An array of options * @param array $attributes An array of default HTML attributes * * @see sfWidgetFormInput */ protected function configure($options = array(), $attributes = array()) { parent::configure($options, $attributes); $this->addOption('multiple', true); } /** * Renders the widget. * * @param string $name The element name * @param string $value The value displayed in this widget * @param array $attributes An array of HTML attributes to be merged with the default HTML attributes * @param array $errors An array of errors for the field * * @return string An HTML tag string * * @see sfWidgetForm */ public function render($name, $value = null, $attributes = array(), $errors = array()) { if ($this->getOption('multiple')) { $name .= '[]'; $attributes['multiple'] = $this->getOption('multiple'); } return parent::render($name, $value, $attributes, $errors); } }
<?php /** * sfWidgetFormInputFileMulti represents an upload HTML input tag with multiple option. * * @package symfony * @subpackage widget * @author Vincent Chabot <vchabot@groupe-exp.com> * @version SVN: $Id$ */ class sfWidgetFormInputFileMulti extends sfWidgetFormInputFile { /** * Configures the current widget. * * @param array $options An array of options * @param array $attributes An array of default HTML attributes * * @see sfWidgetFormInput */ protected function configure($options = array(), $attributes = array()) { parent::configure($options, $attributes); $this->addOption('multiple', true); } /** * Renders the widget. * * @param string $name The element name * @param string $value The value displayed in this widget * @param array $attributes An array of HTML attributes to be merged with the default HTML attributes * @param array $errors An array of errors for the field * * @return string An HTML tag string * * @see sfWidgetForm */ public function render($name, $value = null, $attributes = array(), $errors = array()) { $name .= $this->getOption('multiple') ? '[]' : ''; return $this->renderTag('input', array_merge(array('type' => $this->getOption('type'), 'name' => $name, 'value' => $value, 'multiple' => $this->getOption('multiple')), $attributes)); } }
Change fluent to eloquent to fix timestamps
<?php /** * Copyright (C) 2014 Ibrahim Yusuf <ibrahim7usuf@gmail.com>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. * */ class Activity extends Eloquent { function log($activity) { $act = new Activity; $act->message = $activity; $act->user_id = Auth::user()->id; $act->save(); } }
<?php /** * Copyright (C) 2014 Ibrahim Yusuf <ibrahim7usuf@gmail.com>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. * */ class Activity extends Eloquent { function log($activity) { DB::table('activities')->insert(array( 'message' => $activity, 'user_id' => Auth::user()->id )); } }
Return HTTP 403 when access is forbidden
<?php namespace Kanboard\Controller; use Kanboard\Core\Base; /** * Class AppController * * @package Kanboard\Controller * @author Frederic Guillot */ class AppController extends Base { /** * Forbidden page * * @access public * @param bool $withoutLayout * @param string $message */ public function accessForbidden($withoutLayout = false, $message = '') { if ($this->request->isAjax()) { $this->response->json(array('message' => $message ?: t('Access Forbidden')), 403); } else { $this->response->html($this->helper->layout->app('app/forbidden', array( 'title' => t('Access Forbidden'), 'no_layout' => $withoutLayout, )), 403); } } /** * Page not found * * @access public * @param boolean $withoutLayout */ public function notFound($withoutLayout = false) { $this->response->html($this->helper->layout->app('app/notfound', array( 'title' => t('Page not found'), 'no_layout' => $withoutLayout, ))); } }
<?php namespace Kanboard\Controller; use Kanboard\Core\Base; /** * Class AppController * * @package Kanboard\Controller * @author Frederic Guillot */ class AppController extends Base { /** * Forbidden page * * @access public * @param bool $withoutLayout * @param string $message */ public function accessForbidden($withoutLayout = false, $message = '') { if ($this->request->isAjax()) { $this->response->json(array('message' => $message ?: t('Access Forbidden')), 403); } else { $this->response->html($this->helper->layout->app('app/forbidden', array( 'title' => t('Access Forbidden'), 'no_layout' => $withoutLayout, ))); } } /** * Page not found * * @access public * @param boolean $withoutLayout */ public function notFound($withoutLayout = false) { $this->response->html($this->helper->layout->app('app/notfound', array( 'title' => t('Page not found'), 'no_layout' => $withoutLayout, ))); } }
Load only js files by default
/* eslint-disable global-require, import/no-dynamic-require */ import React, { Component, PropTypes } from 'react' export default class ComponentDoc extends Component { static propTypes = { path: PropTypes.string.isRequired, } state = { component: null, docs: null, } componentWillMount() { require.ensure([], () => { const docsContext = require.context('!!docs!../src', true, /^((?!test(\.js|$)).)*\.js$/) const componentContext = require.context('../src', true, /^((?!test(\.js|$)).)*\.js$/) this.setState({ component: componentContext(`./${this.props.path}.js`), docs: docsContext(`./${this.props.path}.js`), }) }) } render() { const { component, docs } = this.state const loaded = docs && component if (!loaded) { return <div>Loading...</div> } return ( <div> <h1>{component.displayName}</h1> <pre>{JSON.stringify(docs, null, 2)}</pre> </div> ) } }
/* eslint-disable global-require, import/no-dynamic-require */ import React, { Component, PropTypes } from 'react' export default class ComponentDoc extends Component { static propTypes = { path: PropTypes.string.isRequired, } state = { component: null, docs: null, } componentWillMount() { require.ensure([], () => { const docsContext = require.context('!!docs!../src', true, /^((?!test(\.js|$)|\.scss$).)*$/) const componentContext = require.context('../src', true, /^((?!test(\.js|$)|\.scss$).)*$/) this.setState({ component: componentContext(`./${this.props.path}`), docs: docsContext(`./${this.props.path}`), }) }) } render() { const { component, docs } = this.state const loaded = docs && component if (!loaded) { return <div>Loading...</div> } return ( <div> <h1>{component.displayName}</h1> <pre>{JSON.stringify(docs, null, 2)}</pre> </div> ) } }
Revert "GCW-1826 Disable scroll when menu is open" This reverts commit 18e774eb4e8a0033727c0a16e494ed04c60c8abb.
import Ember from 'ember'; export default Ember.Component.extend({ foundation: null, currentClassName: Ember.computed("className", function(){ return this.get("className") ? `.${this.get('className')}` : document; }), click() { Ember.run.later(function() { if($('.off-canvas-wrap.move-right')[0]) { $('html').css('overflow', 'hidden'); } else { $('html').css('overflow', 'auto'); } }, 100); }, didInsertElement() { var className = this.get("currentClassName"); var _this = this; this._super(); Ember.run.debounce(this, function(){ var clientHeight = $( window ).height(); $('.inner-wrap').css('min-height', clientHeight); }, 1000); Ember.run.scheduleOnce('afterRender', this, function(){ var initFoundation = Ember.$(className).foundation({ offcanvas: { close_on_click: true } }); _this.set("foundation", initFoundation); }); } // TODO: Breaks sometime on menu-bar // willDestroyElement() { // this.get("foundation").foundation("destroy"); // } });
import Ember from 'ember'; import config from '../config/environment'; export default Ember.Component.extend({ foundation: null, isMobileApp: config.cordova.enabled, currentClassName: Ember.computed("className", function(){ return this.get("className") ? `.${this.get('className')}` : document; }), click() { Ember.run.later(function() { let mobileApp = this.get("isMobileApp"); if($('.off-canvas-wrap.move-right')[0]) { mobileApp ? $('body').css('overflow', 'hidden') : $('html').css('overflow', 'hidden'); } else { mobileApp ? $('body').css('overflow', 'auto') : $('html').css('overflow', 'auto'); } }, 100); }, didInsertElement() { var className = this.get("currentClassName"); var _this = this; this._super(); Ember.run.debounce(this, function(){ var clientHeight = $( window ).height(); $('.inner-wrap').css('min-height', clientHeight); }, 1000); Ember.run.scheduleOnce('afterRender', this, function(){ var initFoundation = Ember.$(className).foundation({ offcanvas: { close_on_click: true } }); _this.set("foundation", initFoundation); }); } // TODO: Breaks sometime on menu-bar // willDestroyElement() { // this.get("foundation").foundation("destroy"); // } });
[Extensions] Add support for persistent callback listener This is going to be the base of the EventTarget implementation. It is important to remove the listener at some point otherwise the object will leak.
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var callback_listeners = {}; var callback_id = 0; var extension_object; function wrapCallback(args, callback) { if (callback) { var id = (callback_id++).toString(); callback_listeners[id] = callback; args.unshift(id); } else { // The function name and the callback ID are prepended before // the arguments. If there is no callback, an empty string is // should be used. This will be sorted out by the InternalInstance // message handler. args.unshift(""); } return id; } exports.setupInternalExtension = function(extension_obj) { if (extension_object != null) return; extension_object = extension_obj; extension_object.setMessageListener(function(msg) { var args = arguments[0]; var id = args.shift(); var listener = callback_listeners[id]; if (listener !== undefined) { if (!listener.apply(null, args)) delete callback_listeners[id]; } }); }; exports.postMessage = function(function_name, args, callback) { var id = wrapCallback(args, callback); args.unshift(function_name); extension_object.postMessage(args); return id; }; exports.removeCallback = function(id) { if (!id in callback_listeners) return; delete callback_listeners[id]; };
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var callback_listeners = {}; var callback_id = 0; var extension_object; function wrapCallback(args, callback) { if (callback) { var id = (callback_id++).toString(); callback_listeners[id] = callback; args.unshift(id); } else { // The function name and the callback ID are prepended before // the arguments. If there is no callback, an empty string is // should be used. This will be sorted out by the InternalInstance // message handler. args.unshift(""); } } exports.setupInternalExtension = function(extension_obj) { if (extension_object != null) return; extension_object = extension_obj; extension_object.setMessageListener(function(msg) { var args = arguments[0]; var id = args.shift(); var listener = callback_listeners[id]; if (listener !== undefined) { listener.apply(null, args); delete callback_listeners[id]; } }); }; exports.postMessage = function(function_name, args, callback) { wrapCallback(args, callback); args.unshift(function_name); extension_object.postMessage(args); };
Add missing email validation during initial setup
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from wtforms import BooleanField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import DataRequired, Email from indico.modules.auth.forms import LocalRegistrationForm from indico.util.i18n import _ from indico.web.forms.validators import UsedIfChecked from indico.web.forms.widgets import SwitchWidget class BootstrapForm(LocalRegistrationForm): first_name = StringField('First Name', [DataRequired()]) last_name = StringField('Last Name', [DataRequired()]) email = EmailField(_('Email address'), [DataRequired(), Email()]) affiliation = StringField('Affiliation', [DataRequired()]) enable_tracking = BooleanField('Join the community', widget=SwitchWidget()) contact_name = StringField('Contact Name', [UsedIfChecked('enable_tracking'), DataRequired()]) contact_email = EmailField('Contact Email Address', [UsedIfChecked('enable_tracking'), DataRequired(), Email()])
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from wtforms import BooleanField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import DataRequired, Email from indico.modules.auth.forms import LocalRegistrationForm from indico.util.i18n import _ from indico.web.forms.validators import UsedIfChecked from indico.web.forms.widgets import SwitchWidget class BootstrapForm(LocalRegistrationForm): first_name = StringField('First Name', [DataRequired()]) last_name = StringField('Last Name', [DataRequired()]) email = EmailField(_('Email address'), [DataRequired()]) affiliation = StringField('Affiliation', [DataRequired()]) enable_tracking = BooleanField('Join the community', widget=SwitchWidget()) contact_name = StringField('Contact Name', [UsedIfChecked('enable_tracking'), DataRequired()]) contact_email = EmailField('Contact Email Address', [UsedIfChecked('enable_tracking'), DataRequired(), Email()])
Fix wrong default behaviour for analytics opt out
<?php /** * Plugin to remove component which uses cookie when user has chosen to opt-out from cookies * * Needs to used in conjunction with Kwc_Statistics_CookieBeforePlugin * * @see Kwc_Statistics_Analytics_Component */ class Kwc_Statistics_CookieAfterPlugin extends Kwf_Component_Plugin_Abstract implements Kwf_Component_Plugin_Interface_ViewBeforeChildRender { public function processOutput($output, $renderer) { $pos = strpos($output, '{/kwcOptType}'); if ($pos) { $defaultOptValue = substr($output, 12, $pos - 12); if ( (!Kwf_Statistics::issetUserOptValue() && $defaultOptValue == Kwf_Statistics::OPT_IN) || Kwf_Statistics::getUserOptValue() == Kwf_Statistics::OPT_IN ) { return substr($output, $pos + 13); } } return ''; } }
<?php /** * Plugin to remove component which uses cookie when user has chosen to opt-out from cookies * * Needs to used in conjunction with Kwc_Statistics_CookieBeforePlugin * * @see Kwc_Statistics_Analytics_Component */ class Kwc_Statistics_CookieAfterPlugin extends Kwf_Component_Plugin_Abstract implements Kwf_Component_Plugin_Interface_ViewBeforeChildRender { public function processOutput($output, $renderer) { $pos = strpos($output, '{/kwcOptType}'); if ($pos) { $optType = substr($output, 12, $pos - 12); if ( (!Kwf_Statistics::issetUserOptValue() && $optType == Kwf_Statistics::OPT_OUT) || Kwf_Statistics::getUserOptValue() == Kwf_Statistics::OPT_IN ) { return substr($output, $pos + 13); } } return ''; } }
Check for DVD device for ripping queue processing
(function() { 'use strict'; var ripper = require('./Rip'), fs = require('fs'), encoder = require('./Encode'), ui = require('bull-ui/app')({ redis: { host: 'localhost', port: '6379' } }), Queue = require('bull'); ui.listen(1337, function() { console.log('bull-ui started listening on port', this.address().port); }); var ripQ = Queue('disc ripping'); var encodeQ = Queue('video encoding'); encodeQ.add({ type: './HandBrakeCLI', options: '-Z "High Profile" -O -q 21 --main-feature --min-duration 2000 -i /mnt/temp/RIP -o', destination: '/mnt/temp' }); ripQ.add({ destination: '/mnt/temp' }); encodeQ.process(function(job) { return encoder.encode(job); }); if(fs.existsSync('/dev/sr0')) { //if a DVD device exists, then we can process the Ripping queue ripQ.process(function(job) { return ripper.rip(job); }); } }());
(function() { 'use strict'; var ripper = require('./Rip'), encoder = require('./Encode'), ui = require('bull-ui/app')({ redis: { host: 'localhost', port: '6379' } }), Queue = require('bull'); ui.listen(1337, function() { console.log('bull-ui started listening on port', this.address().port); }); var ripQ = Queue('disc ripping'); var encodeQ = Queue('video encoding'); encodeQ.add({ type: './HandBrakeCLI', options: '-Z "High Profile" -O -q 21 --main-feature --min-duration 2000 -i /mnt/temp/RIP -o', destination: '/mnt/temp' }); ripQ.add({ destination: '/mnt/temp' }); encodeQ.process(function(job) { return encoder.encode(job); }); ripQ.process(function(job) { return ripper.rip(job); }); }());
Add docstring, change tables searched
#! /usr/bin/env python """ Calculate statistics for each study area, and prints results to stdout. All it prints is the number of blankspots, the number of v1 nodes, and the number of total nodes. Since I am no longer storing the blankspot information in the hist_point table itself, these stats are no longer very informative. If you are looking for statistics for each user, you want user_analysis.py """ import MapGardening import optparse usage = "usage: %prog [options]" p = optparse.OptionParser(usage) p.add_option('--place', '-p', default="all" ) options, arguments = p.parse_args() possible_tables = [ 'blankspots_1000_b', ] if options.place == "all": places = MapGardening.get_all_places() else: placename = options.place place = MapGardening.get_place(placename) places = {placename: place} MapGardening.init_logging() for placename in places.keys(): print "printing blankspot info for", placename MapGardening.init_db(places[placename]['dbname']) for table in possible_tables: nodetable = MapGardening.NodeTable(table) # Table may not exist, but object will still be created nodetable.get_blankspot_stats() MapGardening.disconnect_db()
#! /usr/bin/env python import MapGardening import optparse usage = "usage: %prog [options]" p = optparse.OptionParser(usage) p.add_option('--place', '-p', default="all" ) options, arguments = p.parse_args() possible_tables = [ 'hist_point', 'hist_point_250m', 'hist_point_500m', 'hist_point_1000m', 'hist_point_proximity', ] if options.place == "all": places = MapGardening.get_all_places() else: placename = options.place place = MapGardening.get_place(placename) places = {placename: place} MapGardening.init_logging() for placename in places.keys(): print "printing blankspot info for", placename MapGardening.init_db(places[placename]['dbname']) for table in possible_tables: nodetable = MapGardening.NodeTable(table) # Table may not exist, but object will still be created nodetable.get_blankspot_stats() MapGardening.disconnect_db()
Remove old style system callback, add function names for render() and debug() git-svn-id: fac99be8204c57f0935f741ea919b5bf0077cdf6@9403 688a9155-6ab5-4160-a077-9df41f55a9e9
import('helma.system', 'system'); system.addHostObject(org.helma.web.Response); /** * Render a skin to the response's buffer * @param skin * @param context * @param scope */ Response.prototype.render = function render(skin, context, scope) { var render = require('helma.skin').render; this.write(render(skin, context, scope)); } /** * Print a debug message to the rendered page. */ Response.prototype.debug = function debug() { var buffer = this.debugBuffer || new Buffer(); buffer.write("<div class=\"helma-debug-line\" style=\"background: yellow;"); buffer.write("color: black; border-top: 1px solid black;\">"); var length = arguments.length; for (var i = 0; i < length; i++) { buffer.write(arguments[i]); if (i < length - 1) { buffer.write(" "); } } buffer.writeln("</div>"); this.debugBuffer = buffer; return null; }; /** * Write the debug buffer to the response's main buffer. */ Response.prototype.flushDebug = function() { if (this.debugBuffer != null) { this.write(this.debugBuffer); this.debugBuffer.reset(); } return null; };
import('helma.system', 'system'); system.addHostObject(org.helma.web.Response); system.addCallback("onResponse", "debugFlusher", function(res) { if (res.status == 200 || res.status >= 400) { res.flushDebug(); } }) /** * Render a skin to the response's buffer * @param skin * @param context * @param scope */ Response.prototype.render = function(skin, context, scope) { var render = require('helma.skin').render; this.write(render(skin, context, scope)); } /** * Print a debug message to the rendered page. */ Response.prototype.debug = function() { var buffer = this.debugBuffer || new Buffer(); buffer.write("<div class=\"helma-debug-line\" style=\"background: yellow;"); buffer.write("color: black; border-top: 1px solid black;\">"); var length = arguments.length; for (var i = 0; i < length; i++) { buffer.write(arguments[i]); if (i < length - 1) { buffer.write(" "); } } buffer.writeln("</div>"); this.debugBuffer = buffer; return null; }; /** * Write the debug buffer to the response's main buffer. */ Response.prototype.flushDebug = function() { if (this.debugBuffer != null) { this.write(this.debugBuffer); this.debugBuffer.reset(); } return null; };
Simplify regex using non-greedy qualifier
import re # <a> followed by another <a> without any intervening </a>s # outer_link - partial outer element up to the inner link # inner_content - content of the inner_link link_inside_link_regex = re.compile( ur"(?P<outer_link><a ((?!</a>).)*)<a .*?>(?P<inner_content>.*?)</a>", re.IGNORECASE | re.DOTALL) def flatten_links(text): """ Fix <a> elements that have embedded <a> elements by replacing the internal <a> element with its content. """ while True: text, sub_count = link_inside_link_regex.subn( ur"\g<outer_link>\g<inner_content>", text) if sub_count == 0: return text
import re # <a> followed by another <a> without any intervening </a>s link_inside_link_regex = re.compile( ur"(?P<outer_link><a ((?!</a>).)*)(<a ((?!</a>).)*>" ur"(?P<internal_content>((?!</a>).)*)</a>)", re.IGNORECASE | re.DOTALL) def flatten_links(text): """ Fix <a> elements that have embedded <a> elements by replacing the internal <a> element with its content. Assumes that the text does not span multiple lines and that the <a> tags are lowercase. """ while True: text, sub_count = link_inside_link_regex.subn( ur"\g<outer_link>\g<internal_content>", text) if sub_count == 0: return text # Return only when no more subs possible
Add docstrings to rules unit tests
""" Tests for the rules module """ import unittest from src import rules class TestRules(unittest.TestCase): """ Tests for the rules module """ def test_good_value_1(self): """ Test a known good value""" rules_obj = rules.Rules() result = rules_obj.convertCharToInt('1') self.assertEqual(result, 1) def test_good_value_3(self): """ Test a known good value""" rules_obj = rules.Rules() result = rules_obj.convertCharToInt('3') self.assertEqual(result, 3) def test_upper_value_10(self): """ Test a value that should be too high""" rules_obj = rules.Rules() result = rules_obj.convertCharToInt('10') self.assertEqual(result, 0) def test_lower_value_5(self): """ Test a value that should be too low""" rules_obj = rules.Rules() result = rules_obj.convertCharToInt('-5') self.assertEqual(result, 0) def test_bad_value(self): """ Test a value that isn't an int""" rules_obj = rules.Rules(debug=True) result = rules_obj.convertCharToInt('qq') self.assertEqual(result, 0)
import unittest from src import rules class TestRules(unittest.TestCase): def test_good_value_1(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('1') self.assertEqual(result, 1) def test_good_value_3(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('3') self.assertEqual(result, 3) def test_upper_value_10(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('10') self.assertEqual(result, 0) def test_lower_value_5(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('-5') self.assertEqual(result, 0) def test_bad_value(self): rules_obj = rules.Rules() result = rules_obj.convertCharToInt('qq') self.assertEqual(result, 0)
Add collision detection for Obstacle
package com.pqbyte.coherence; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Array; public class CollisionListener implements ContactListener { private Array<Projectile> bulletsToBeRemoved; public CollisionListener(Array<Projectile> bulletsToBeRemoved) { this.bulletsToBeRemoved = bulletsToBeRemoved; } @Override public void beginContact(Contact contact) { Actor actorA = (Actor) contact.getFixtureA().getBody().getUserData(); Actor actorB = (Actor) contact.getFixtureB().getBody().getUserData(); if (actorA instanceof Projectile && (actorB instanceof Map || actorB instanceof Obstacle)) { bulletsToBeRemoved.add((Projectile) actorA); } else if (actorB instanceof Projectile && (actorA instanceof Map || actorA instanceof Obstacle)) { bulletsToBeRemoved.add((Projectile) actorB); } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } }
package com.pqbyte.coherence; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Array; public class CollisionListener implements ContactListener { private Array<Projectile> bulletsToBeRemoved; public CollisionListener(Array<Projectile> bulletsToBeRemoved) { this.bulletsToBeRemoved = bulletsToBeRemoved; } @Override public void beginContact(Contact contact) { Actor actorA = (Actor) contact.getFixtureA().getBody().getUserData(); Actor actorB = (Actor) contact.getFixtureB().getBody().getUserData(); if (actorA instanceof Projectile && actorB instanceof Map) { bulletsToBeRemoved.add((Projectile) actorA); } else if (actorB instanceof Projectile && actorA instanceof Map) { bulletsToBeRemoved.add((Projectile) actorB); } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } }
Rename Function Based on Feedback
import * as containers from "./container-view-builder"; import * as url from "url"; import { fetch } from "jsua"; export function linkViewBuilder(node) { var view = document.createElement("a"); if (node.base) { view.href = url.resolve(node.base, node.value.href); } else { view.href = node.value.href; } view.type = node.value.type; var followTimeout = tryGetFollowTimeout(node); if (followTimeout) { view.addEventListener("jsua-attach", function () { setTimeout(function () { view.click(); }, followTimeout); }); } view.addEventListener("click", function (evt) { evt.preventDefault(); evt.stopPropagation(); fetch(view.href, { origin: view }); }); return containers.buildChildViews(node) .then(function (childViews) { childViews.forEach(childView => view.appendChild(childView)); if (view.children.length === 0) { view.textContent = view.href; } return view; }); } function tryGetFollowTimeout(node) { console.log(node.value.follow); var follow = +node.value.follow; if (isNaN(follow)) follow = +node.spec.follow; if (isNaN(follow)) return; return follow < 10 ? 10 : follow; }
import * as containers from "./container-view-builder"; import * as url from "url"; import { fetch } from "jsua"; export function linkViewBuilder(node) { var view = document.createElement("a"); if (node.base) { view.href = url.resolve(node.base, node.value.href); } else { view.href = node.value.href; } view.type = node.value.type; var followTimeout = tryGetFollowTimeoutForFollowValue(node); if (followTimeout) { view.addEventListener("jsua-attach", function () { setTimeout(function () { view.click(); }, followTimeout); }); } view.addEventListener("click", function (evt) { evt.preventDefault(); evt.stopPropagation(); fetch(view.href, { origin: view }); }); return containers.buildChildViews(node) .then(function (childViews) { childViews.forEach(childView => view.appendChild(childView)); if (view.children.length === 0) { view.textContent = view.href; } return view; }); } function tryGetFollowTimeoutForFollowValue(node) { console.log(node.value.follow); var follow = +node.value.follow; if (isNaN(follow)) follow = +node.spec.follow; if (isNaN(follow)) return; return follow < 10 ? 10 : follow; }
Add .amr extension to supported audio files
package com.todoist.mediaparser; import com.todoist.mediaparser.util.StringUtils; class AudioFileParser extends MediaParser { // FIXME: .aac is only supported in Android 3.0+. // FIXME: .flac is only supported in Android 3.1+. private static final String[] EXTENSIONS = {".m4a", ".aac", ".amr", ".flac", ".mp3", ".mid", ".wav"}; AudioFileParser(String url) { super(url); } @Override protected boolean matches() { boolean matches = false; for(String extension : EXTENSIONS) matches |= StringUtils.endsWithIgnoreCase(mUrl, extension); return matches; } @Override public String getThumbnailUrl(int smallestSide) { return null; } @Override public String getUrl() { return mUrl; } @Override public Type getType() { return Type.AUDIO; } }
package com.todoist.mediaparser; import com.todoist.mediaparser.util.StringUtils; class AudioFileParser extends MediaParser { // FIXME: .aac is only supported in Android 3.0+. // FIXME: .flac is only supported in Android 3.1+. private static final String[] EXTENSIONS = {".m4a", ".aac", ".flac", ".mp3", ".mid", ".wav"}; AudioFileParser(String url) { super(url); } @Override protected boolean matches() { boolean matches = false; for(String extension : EXTENSIONS) matches |= StringUtils.endsWithIgnoreCase(mUrl, extension); return matches; } @Override public String getThumbnailUrl(int smallestSide) { return null; } @Override public String getUrl() { return mUrl; } @Override public Type getType() { return Type.AUDIO; } }
Check if we have tried, pause if we have
package com.nirima.jenkins.plugins.docker.utils; import com.nirima.docker.client.DockerException; import hudson.model.TaskListener; import hudson.slaves.ComputerLauncher; import hudson.slaves.DelegatingComputerLauncher; import hudson.slaves.SlaveComputer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class RetryingComputerLauncher extends DelegatingComputerLauncher { private static final Logger log = LoggerFactory.getLogger(RetryingComputerLauncher.class); /** * time (ms) to back off between retries? */ private final int pause = 5000; /** * Let us know when to pause the launch. */ private boolean hasTried = false; public RetryingComputerLauncher(ComputerLauncher delegate) { super(delegate); } @Override public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException { if (hasTried) { log.info("Launch failed, pausing before retry."); Thread.sleep(pause); } super.launch(computer, listener); hasTried = true; } }
package com.nirima.jenkins.plugins.docker.utils; import com.nirima.docker.client.DockerException; import hudson.model.TaskListener; import hudson.slaves.ComputerLauncher; import hudson.slaves.DelegatingComputerLauncher; import hudson.slaves.SlaveComputer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class RetryingComputerLauncher extends DelegatingComputerLauncher { private static final Logger log = LoggerFactory.getLogger(RetryingComputerLauncher.class); /** * How many times to retry the launch? */ private final int retries = 3; /** * time (ms) to back off between retries? */ private final int pause = 5000; public RetryingComputerLauncher(ComputerLauncher delegate) { super(delegate); } @Override public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException { for( int i=0;i<retries;i++) { try { super.launch(computer, listener); return; } catch(Exception ex) { log.info("Launch failed on attempt {}", i); } Thread.sleep(pause); } throw new IOException("SSH Launch failed"); } }
Fix sample event listener should call next
/* global assert */ module.exports = function(runner, options) { var called = {}; runner.on('setup', function (next) { console.log('called "setup"'); called.setup = true; next(null); }); runner.on('new client', function (client, next) { console.log('called "new client"'); called.newClient = true; next(null); }); runner.on('report', function (failures, next) { console.log('called "report"'); called.report = true; next(null, []); }); runner.on('done', function (failures, next) { console.log('called "done"'); assert(called.setup, 'should have called "setup" event'); assert(called.newClient, 'should have called "new client" event'); assert(called.report, 'should have called "report" event'); console.log('did call all events'); next(); }); };
/* global assert */ module.exports = function(runner, options) { var called = {}; runner.on('setup', function (next) { console.log('called "setup"'); called.setup = true; next(null); }); runner.on('new client', function (client, next) { console.log('called "new client"'); called.newClient = true; next(null); }); runner.on('report', function (failures, next) { console.log('called "report"'); called.report = true; next(null, []); }); runner.on('done', function (failures, next) { console.log('called "done"'); assert(called.setup, 'should have called "setup" event'); assert(called.newClient, 'should have called "new client" event'); assert(called.report, 'should have called "report" event'); console.log('did call all events'); }); };
Add new types of peripherals
import copy from ereuse_devicehub.resources.device.schema import Device from ereuse_devicehub.resources.device.settings import DeviceSubSettings class Peripheral(Device): type = { 'type': 'string', 'allowed': { 'Router', 'Switch', 'Printer', 'Scanner', 'MultifunctionPrinter', 'Terminal', 'HUB', 'SAI', 'Keyboard', 'Mouse', 'WirelessAccessPoint', 'LabelPrinter', 'Projector', 'VideoconferenceDevice', 'SoundDevice', 'Microphone', 'WirelessMicrophone', 'Scaler', 'VideoScaler', 'MemoryCardReader', 'Amplifier', 'AudioAmplifier' }, 'required': True } manufacturer = copy.copy(Device.manufacturer) manufacturer['required'] = True serialNumber = copy.copy(Device.serialNumber) serialNumber['required'] = True model = copy.copy(Device.model) model['required'] = True class PeripheralSettings(DeviceSubSettings): _schema = Peripheral
import copy from ereuse_devicehub.resources.device.schema import Device from ereuse_devicehub.resources.device.settings import DeviceSubSettings class Peripheral(Device): type = { 'type': 'string', 'allowed': {'Router', 'Switch', 'Printer', 'Scanner', 'MultifunctionPrinter', 'Terminal', 'HUB', 'SAI', 'Keyboard', 'Mouse', 'WirelessAccessPoint', 'LabelPrinter', 'Projector', 'VideoconferenceDevice'}, 'required': True } manufacturer = copy.copy(Device.manufacturer) manufacturer['required'] = True serialNumber = copy.copy(Device.serialNumber) serialNumber['required'] = True model = copy.copy(Device.model) model['required'] = True class PeripheralSettings(DeviceSubSettings): _schema = Peripheral
[bugfix] Reset redux value to defualt success.
import { NO_EXPANDED_ROUTES, REQUEST_ROUTES, REQUEST_EXPANDED_ROUTES, RECEIVE_EXPANDED_ROUTES, RECEIVE_ROUTES_LYFT, RECEIVE_ROUTES_UBER } from '../actions/types'; // Setting state to this default feels ghetto... probably a better way export default function(state={routes:{close:null,medium:null,far:null},message:null,received:false,success:true}, action) { switch (action.type) { case NO_EXPANDED_ROUTES: return Object.assign({}, state, { message: null, success: false }); case REQUEST_ROUTES: return { routes: {close:null,medium:null,far:null}, message: null, received: false, success: true } case REQUEST_EXPANDED_ROUTES: return Object.assign({}, state, { message: 'Searching for better routes...' }); case RECEIVE_EXPANDED_ROUTES: if (state.received) { return state; } return Object.assign({}, state, { routes: action.routes, message: null, received: true }); } return state; }
import { NO_EXPANDED_ROUTES, REQUEST_ROUTES, REQUEST_EXPANDED_ROUTES, RECEIVE_EXPANDED_ROUTES, RECEIVE_ROUTES_LYFT, RECEIVE_ROUTES_UBER } from '../actions/types'; // Setting state to this default feels ghetto... probably a better way export default function(state={routes:{close:null,medium:null,far:null},message:null,received:false,success:false}, action) { switch (action.type) { case NO_EXPANDED_ROUTES: return Object.assign({}, state, { message: null, success: false }); case REQUEST_ROUTES: return { routes: {close:null,medium:null,far:null}, message: null, received: false, success: true } case REQUEST_EXPANDED_ROUTES: return Object.assign({}, state, { message: 'Searching for better routes...' }); case RECEIVE_EXPANDED_ROUTES: if (state.received) { return state; } return Object.assign({}, state, { routes: action.routes, message: null, received: true }); } return state; }
Make verification required field optional
<?php namespace AppBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; class QualificationType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('verificationRequired', CheckboxType::class, [ 'required' => false ]) ; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\Qualification' )); } }
<?php namespace AppBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; class QualificationType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('verificationRequired', CheckboxType::class) ; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\Qualification' )); } }
Revert change, App must be nullable
<?php /** * Slim Framework (https://slimframework.com) * * @link https://github.com/slimphp/Slim * @copyright Copyright (c) 2011-2017 Josh Lockhart * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim; use Slim\Interfaces\RouteGroupInterface; /** * A collector for Routable objects with a common middleware stack * * @package Slim */ class RouteGroup extends Routable implements RouteGroupInterface { /** * Create a new RouteGroup * * @param string $pattern The pattern prefix for the group * @param callable $callable The group callable */ public function __construct($pattern, $callable) { $this->pattern = $pattern; $this->callable = $callable; } /** * Invoke the group to register any Routable objects within it. * * @param App $app The App to bind the callable to. */ public function __invoke(App $app = null) { // Resolve route callable $callable = $this->callable; if ($this->callableResolver) { $callable = $this->callableResolver->resolve($callable); } $callable($app); } }
<?php /** * Slim Framework (https://slimframework.com) * * @link https://github.com/slimphp/Slim * @copyright Copyright (c) 2011-2017 Josh Lockhart * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim; use Slim\Interfaces\RouteGroupInterface; /** * A collector for Routable objects with a common middleware stack * * @package Slim */ class RouteGroup extends Routable implements RouteGroupInterface { /** * Create a new RouteGroup * * @param string $pattern The pattern prefix for the group * @param callable $callable The group callable */ public function __construct($pattern, $callable) { $this->pattern = $pattern; $this->callable = $callable; } /** * Invoke the group to register any Routable objects within it. * * @param App $app The App to bind the callable to. */ public function __invoke(App $app) { // Resolve route callable $callable = $this->callable; if ($this->callableResolver) { $callable = $this->callableResolver->resolve($callable); } $callable($app); } }
Make sure to load the new mongo south adapter
from test_project.settings import * DATABASES['mongo'] = { 'ENGINE' : 'django_mongodb_engine', 'NAME' : 'mutant', 'OPTIONS': { 'OPERATIONS': { 'save' : {'safe' : True}, } } } SOUTH_DATABASE_ADAPTERS = {'mongo': 'django_mongodb_engine.south_adapter'} INSTALLED_APPS.extend(['django_mongodb_engine', 'djangotoolbox']) # FK and M2M are not supported for nonrel db so we make sure to avoid # loading mutant.contrib.related INSTALLED_APPS.remove('mutant.contrib.related') # But we can test the non rel fields INSTALLED_APPS.append('mutant.contrib.nonrel') DATABASE_ROUTERS = ( 'mongodb_router.MongoRouter', )
from test_project.settings import * DATABASES['mongo'] = { 'ENGINE' : 'django_mongodb_engine', 'NAME' : 'mutant', 'OPTIONS': { 'OPERATIONS': { 'save' : {'safe' : True}, } } } SOUTH_DATABASE_ADAPTERS = {'mongo': 'django_mongodb_engine.south'} INSTALLED_APPS.extend(['django_mongodb_engine', 'djangotoolbox']) # FK and M2M are not supported for nonrel db so we make sure to avoid # loading mutant.contrib.related INSTALLED_APPS.remove('mutant.contrib.related') # But we can test the non rel fields INSTALLED_APPS.append('mutant.contrib.nonrel') DATABASE_ROUTERS = ( 'mongodb_router.MongoRouter', )
Change Admin/Home controller parent to MY_Controller to get check_admin() method Signed-off-by: JWhy <6a9f7c06e789f829524fd1a3a38b8c7d794c3a1f@jwhy.de>
<?php class Home extends MY_Controller { public function index() { if($this->check_admin() === true){ $data['title'] = 'Admin Panel'; $this->load->view('general/header', $data); $this->load->view('admin/index', $data); $this->load->view('general/footer'); } } public function update_items() { if($this->check_admin() === true){ $this->config->load('craftshop'); $itemapi_cfg = $this->config->item('itemapi'); $this->load->library('itemapi', $itemapi_cfg); $this->load->model('minecraftitem_model', 'mcitems'); $data['urls'] = $this->itemapi->getUrls(); $data['update'] = $this->itemapi->getList(true); $updated = $this->mcitems->apply_update($data['update']->data->data); $data['updated'] = $updated; $data['title'] = 'Update Items'; $this->load->view('general/header', $data); $this->load->view('admin/update_items', $data); $this->load->view('general/footer'); } } } ?>
<?php class Home extends CI_Controller { public function index() { if($this->check_admin() === true){ $data['title'] = 'Admin Panel'; $this->load->view('general/header', $data); $this->load->view('admin/index', $data); $this->load->view('general/footer'); } } public function update_items() { if($this->check_admin() === true){ $this->config->load('craftshop'); $itemapi_cfg = $this->config->item('itemapi'); $this->load->library('itemapi', $itemapi_cfg); $this->load->model('minecraftitem_model', 'mcitems'); $data['urls'] = $this->itemapi->getUrls(); $data['update'] = $this->itemapi->getList(true); $updated = $this->mcitems->apply_update($data['update']->data->data); $data['updated'] = $updated; $data['title'] = 'Update Items'; $this->load->view('general/header', $data); $this->load->view('admin/update_items', $data); $this->load->view('general/footer'); } } } ?>
Fix a NPE plaguing tests that use the BlockingQueue transport.
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nokia.dempsy.messagetransport.blockingqueue; import java.util.concurrent.BlockingQueue; import com.nokia.dempsy.messagetransport.Destination; public class BlockingQueueDestination implements Destination { protected BlockingQueue<byte[]> queue = null; public BlockingQueueDestination(BlockingQueue<byte[]> queue) { this.queue = queue; } @Override public int hashCode() { return queue.hashCode(); } @Override public boolean equals(Object other) { return other == null ? false : queue.equals(((BlockingQueueDestination) other).queue); } }
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nokia.dempsy.messagetransport.blockingqueue; import java.util.concurrent.BlockingQueue; import com.nokia.dempsy.messagetransport.Destination; public class BlockingQueueDestination implements Destination { protected BlockingQueue<byte[]> queue = null; public BlockingQueueDestination(BlockingQueue<byte[]> queue) { this.queue = queue; } @Override public int hashCode() { return queue.hashCode(); } @Override public boolean equals(Object other) { return queue.equals(((BlockingQueueDestination) other).queue); } }
Repair check for correct status code on deploy.
var Request = require('./request') , Browser = require('./browser'); var Theme = function (session, blog, html) { this.session = session; this.blog = blog; this.html = html; } Theme.prototype = { save: function () { return this.session.create() .with(this) .then(this.get_customize_form) .then(this.get_form_key) .then(this.send_html) .then(this.handle_response); }, get_customize_form: function () { var request = new Request('customize/' + this.blog, { method: 'GET' }); return request.send(); }, get_form_key: function (response) { var browser = new Browser(response.body); return browser.value_of_element_with_id('form_key'); }, send_html: function (form_key) { var params = { 'user_form_key': form_key, 'custom_theme': this.html }; var request = new Request('customize_api/blog/' + this.blog, { method: 'POST', body: JSON.stringify(params) }); return request.send(); }, handle_response: function (response) { if (response.statusCode !== 200) { throw new Error('There was an error deploying your theme. ' + 'Please try again later.'); } return response; } } module.exports = Theme;
var Request = require('./request') , Browser = require('./browser'); var Theme = function (session, blog, html) { this.session = session; this.blog = blog; this.html = html; } Theme.prototype = { save: function () { return this.session.create() .with(this) .then(this.get_customize_form) .then(this.get_form_key) .then(this.send_html) .then(this.handle_response); }, get_customize_form: function () { var request = new Request('customize/' + this.blog, { method: 'GET' }); return request.send(); }, get_form_key: function (response) { var browser = new Browser(response.body); return browser.value_of_element_with_id('form_key'); }, send_html: function (form_key) { var params = { 'user_form_key': form_key, 'custom_theme': this.html }; var request = new Request('customize_api/blog/' + this.blog, { method: 'POST', body: JSON.stringify(params) }); return request.send(); }, handle_response: function (response) { if (response.code !== 200) { throw new Error('There was an error deploying your theme. ' + 'Please try again later.'); } return response; } } module.exports = Theme;
Clean up after science test
""" Scientific tests for SLCosmo package """ import matplotlib matplotlib.use('Agg') import os import unittest import desc.slcosmo class SLCosmoScienceTestCase(unittest.TestCase): def setUp(self): self.message = 'Testing SLCosmo - For Science!' self.Lets = desc.slcosmo.SLCosmo() def tearDown(self): "Clean up any mock data files created by the tests." for mock_file in self.Lets.mock_files: os.remove(mock_file) def test_round_trip(self): self.Lets.make_some_mock_data(Nlenses=10, Nsamples=20) self.Lets.draw_some_prior_samples(Npriorsamples=100) self.Lets.compute_the_joint_log_likelihood() self.Lets.report_the_inferred_cosmological_parameters() self.Lets.plot_the_inferred_cosmological_parameters() H0, sigma = self.Lets.estimate_H0() lower_limit = H0 - 3.0*sigma upper_limit = H0 + 3.0*sigma self.assertGreater(self.Lets.cosmotruth['H0'], lower_limit) self.assertLess(self.Lets.cosmotruth['H0'], upper_limit) if __name__ == '__main__': unittest.main()
""" Scientific tests for SLCosmo package """ import matplotlib matplotlib.use('Agg') import unittest import desc.slcosmo class SLCosmoScienceTestCase(unittest.TestCase): def setUp(self): self.message = 'Testing SLCosmo - For Science!' def tearDown(self): pass def test_round_trip(self): Lets = desc.slcosmo.SLCosmo() Lets.make_some_mock_data(Nlenses=10, Nsamples=20) Lets.draw_some_prior_samples(Npriorsamples=100) Lets.compute_the_joint_log_likelihood() Lets.report_the_inferred_cosmological_parameters() Lets.plot_the_inferred_cosmological_parameters() H0, sigma = Lets.estimate_H0() lower_limit = H0 - 3.0*sigma upper_limit = H0 + 3.0*sigma self.assertGreater(Lets.cosmotruth['H0'], lower_limit) self.assertLess(Lets.cosmotruth['H0'], upper_limit) if __name__ == '__main__': unittest.main()
Clean up plugin task file
/* * grunt-purifycss * https://github.com/purifycss/grunt-purify-css * * Copyright (c) 2015 Phoebe Li, Matthew Rourke, Kenny Tran * Licensed under the MIT license. */ 'use strict'; var glob = require('glob'); var purify = require('purify-css'); module.exports = function(grunt) { grunt.registerMultiTask('purifycss', 'Clean unnecessary CSS', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ }); var src = []; this.data.src.forEach(function(pathPattern) { var files = glob.sync(pathPattern); console.log("Source Files: ", files); src = src.concat(files); }); var styles = []; this.data.css.forEach(function(pathPattern) { var style = glob.sync(pathPattern); console.log("Style Files: ", style); styles = styles.concat(style); }); var pure = purify(src, styles, {write: false, info: true}); grunt.file.write(this.data.dest, pure); grunt.log.writeln('File "' + this.data.dest + '" created.'); }); };
/* * grunt-purifycss * https://github.com/purifycss/grunt-purify-css * * Copyright (c) 2015 Phoebe Li, Matthew Rourke, Kenny Tran * Licensed under the MIT license. */ 'use strict'; var glob = require('glob'); var purify = require('purify-css'); module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('purifycss', 'Clean unnecessary CSS', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ }); var src = []; this.data.src.forEach(function(pathPattern) { var files = glob.sync(pathPattern); console.log("glob files: ", files); src = src.concat(files); }); var styles = []; this.data.css.forEach(function(pathPattern) { var files = glob.sync(pathPattern); console.log("glob styles: ", files); styles = styles.concat(files); }) console.log(src); console.log(styles); var pure = purify(src, styles, {write: false, info: true}); grunt.file.write(this.data.dest, pure); grunt.log.writeln('File "' + this.data.dest + '" created.'); }); };
Use tagged template literal for chalk
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; let fatal = err => { console.error(`fatal: ${err}`); process.exit(1); }; process.argv.splice(0, 2); if (process.argv.length === 0) { fatal("No date string given"); }; let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (/Invalid Date/.test(parsedDate)) { fatal(`Could not parse ${date} into a valid date`); }; let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); let command = `GIT_COMMITTER_DATE="${dateString}" git commit --amend --date="${dateString}" --no-edit`; exec(command, (err, stdout, stderr) => { if (err) fatal("Could not modify the date of the previous commit"); console.log(chalk`\nModified previous commit:\n AUTHOR_DATE {grey ${dateString}}\n COMMITTER_DATE {grey ${dateString}}\n\nCommand executed:\n {bgWhite.black ${command}}\n`); });
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; let fatal = err => { console.error(`fatal: ${err}`); process.exit(1); }; process.argv.splice(0, 2); if (process.argv.length === 0) { fatal("No date string given"); }; let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (/Invalid Date/.test(parsedDate)) { fatal(`Could not parse ${date} into a valid date`); }; let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); let command = `GIT_COMMITTER_DATE="${dateString}" git commit --amend --date="${dateString}" --no-edit`; exec(command, (err, stdout, stderr) => { if (err) fatal("Could not modify the date of the previous commit"); console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); });
Make sure Django is required
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() setup( author="", author_email="", description="", name="pinax-{{ app_name }}", long_description=read("README.rst"), version="0.1", url="http://github.com/pinax/pinax-{{ app_name }}/", license="MIT", packages=find_packages(), package_data={ "{{ app_name }}": [] }, test_suite="runtests.runtests", install_requires=[ "Django>=1.8" ], tests_require=[ ], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False )
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() setup( author="", author_email="", description="", name="pinax-{{ app_name }}", long_description=read("README.rst"), version="0.1", url="http://github.com/pinax/pinax-{{ app_name }}/", license="MIT", packages=find_packages(), package_data={ "{{ app_name }}": [] }, test_suite="runtests.runtests", tests_require=[ ], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False )
Use 2 octets to indicate padding length.
// Copyright 2016 Martijn Croonen. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. package ece import ( "crypto/aes" "crypto/cipher" "encoding/binary" "errors" ) // Encrypt encrypts |plaintext| using AEAD_AES_GCM_128 with the keys in |keys| // adding |paddingLength| bytes of padding. func Encrypt(plaintext []byte, keys *EncryptionKeys, paddingLength int) ([]byte, error) { if paddingLength < 0 || paddingLength > 65535 { return nil, errors.New("Padding should be between 0 and 65535.") } aes, err := aes.NewCipher(keys.cek) if err != nil { return nil, err } aesgcm, err := cipher.NewGCM(aes) if err != nil { return nil, err } record := make([]byte, 2+paddingLength+len(plaintext)) binary.BigEndian.PutUint16(record, uint16(paddingLength)) copy(record[2+paddingLength:], plaintext) var auth []byte return aesgcm.Seal(nil, keys.nonce, record, auth), nil }
// Copyright 2016 Martijn Croonen. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. package ece import ( "crypto/aes" "crypto/cipher" "errors" ) // Encrypt encrypts |plaintext| using AEAD_AES_GCM_128 with the keys in |keys| // adding |paddingLength| bytes of padding. func Encrypt(plaintext []byte, keys *EncryptionKeys, paddingLength int) ([]byte, error) { if paddingLength < 0 || paddingLength > 255 { return nil, errors.New("Padding should be between 0 and 256.") } aes, err := aes.NewCipher(keys.cek) if err != nil { return nil, err } aesgcm, err := cipher.NewGCM(aes) if err != nil { return nil, err } record := make([]byte, 1+paddingLength+len(plaintext)) record[0] = byte(paddingLength) copy(record[1+paddingLength:], plaintext) var auth []byte return aesgcm.Seal(nil, keys.nonce, record, auth), nil }
Allow passing config as lazy-evaluated function
import fs from 'fs' import _ from 'lodash' import postcss from 'postcss' import cssnext from 'postcss-cssnext' import stylefmt from 'stylefmt' import defaultConfig from './defaultConfig' import mergeConfig from './util/mergeConfig' import addCustomMediaQueries from './lib/addCustomMediaQueries' import generateUtilities from './lib/generateUtilities' import substituteHoverableAtRules from './lib/substituteHoverableAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteBreakpointAtRules from './lib/substituteBreakpointAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' const plugin = postcss.plugin('tailwind', (options = {}) => { if (_.isFunction(options)) { options = options() } const config = mergeConfig(defaultConfig, options) return postcss([ addCustomMediaQueries(config), generateUtilities(config), substituteHoverableAtRules(config), substituteResponsiveAtRules(config), substituteBreakpointAtRules(config), substituteClassApplyAtRules(config), cssnext(), stylefmt, ]) }) module.exports = plugin
import fs from 'fs' import _ from 'lodash' import postcss from 'postcss' import cssnext from 'postcss-cssnext' import stylefmt from 'stylefmt' import defaultConfig from './defaultConfig' import mergeConfig from './util/mergeConfig' import addCustomMediaQueries from './lib/addCustomMediaQueries' import generateUtilities from './lib/generateUtilities' import substituteHoverableAtRules from './lib/substituteHoverableAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteBreakpointAtRules from './lib/substituteBreakpointAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' const plugin = postcss.plugin('tailwind', (options = {}) => { const config = mergeConfig(defaultConfig, options) return postcss([ addCustomMediaQueries(config), generateUtilities(config), substituteHoverableAtRules(config), substituteResponsiveAtRules(config), substituteBreakpointAtRules(config), substituteClassApplyAtRules(config), cssnext(), stylefmt, ]) }) module.exports = plugin
Fix off by one and string conversion
package fizzbuzz import ( "fmt" "log" ) func Generate(count int) ([]string, error) { if count <= 0 { return nil, fmt.Errorf("fizzbuzz: Negative fizzbuzz count provided") } fizzbuzz := make([]string, count) var output string for i := 1; i <= count; i++ { switch { case i%15 == 0: output = "FizzBuzz" case i%3 == 0: output = "Fizz" case i%5 == 0: output = "Buzz" default: output = fmt.Sprintf("%d", i) } fizzbuzz[i-1] = output } return fizzbuzz, nil } func Print(count int) { fizzbuzz, err := Generate(count) if err != nil { log.Fatal(err) } for _, entry := range fizzbuzz { fmt.Println(entry) } }
package fizzbuzz import ( "fmt" "log" ) func Generate(count int) ([]string, error) { if count <= 0 { return nil, fmt.Errorf("fizzbuzz: Negative fizzbuzz count provided") } fizzbuzz := make([]string, count) var output string for i := 1; i <= count; i++ { switch { case i%15 == 0: output = "FizzBuzz" case i%3 == 0: output = "Fizz" case i%5 == 0: output = "Buzz" default: output = string(i) } fizzbuzz[i] = output } return fizzbuzz, nil } func Print(count int) { fizzbuzz, err := Generate(count) if err != nil { log.Fatal(err) } for _, entry := range fizzbuzz { fmt.Println(entry) } }
Update Sparser script for phase3
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os import glob from indra import sparser base_folder = os.path.join(os.environ['HOME'], 'data/darpa/phase3_eval/sources/sparser-20170330') def get_file_names(base_dir): fnames = glob.glob(os.path.join(base_dir, '*.xml')) return fnames def get_file_stmts(fname): with open(fname, 'rb') as fh: print(fname) xml_bytes = fh.read() sp = sparser.process_xml(xml_bytes) if sp is None: print('ERROR: Could not process %s' % fname.split('/')[-1]) print('----') return [] return sp.statements def read_stmts(folder): fnames = get_file_names(folder) all_stmts = [] for fname in fnames: st = get_file_stmts(fname) all_stmts += st return all_stmts if __name__ == '__main__': stmts = read_stmts(base_folder)
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os import glob from indra import sparser base_folder = os.path.join(os.environ['HOME'], 'data/darpa/phase3_eval/sources/sparser-20170210') def get_file_names(base_dir): fnames = glob.glob(os.path.join(base_dir, '*.xml')) return fnames def get_file_stmts(fname): with open(fname, 'rb') as fh: xml_bytes = fh.read() xml_bytes = xml_bytes.replace(b'hmsid', b'pmid') sp = sparser.process_xml(xml_bytes) if sp is None: print('ERROR: Could not process %s' % fname.split('/')[-1]) print('----') return [] return sp.statements def read_stmts(folder): fnames = get_file_names(folder) all_stmts = [] for fname in fnames: st = get_file_stmts(fname) all_stmts += st return all_stmts if __name__ == '__main__': stmts = read_stmts(base_folder)
Fix wrong name for private field.
<?php namespace Predis\Options; class CustomOption extends Option { private $_validate, $_default; public function __construct(Array $options) { $validate = isset($options['validate']) ? $options['validate'] : 'parent::validate'; $default = isset($options['default']) ? $options['default'] : 'parent::getDefault'; if (!is_callable($validate) || !is_callable($default)) { throw new \InvalidArgumentException("Validate and default must be callable"); } $this->_validate = $validate; $this->_default = $default; } public function validate($value) { return call_user_func($this->_validate, $value); } public function getDefault() { return $this->validate(call_user_func($this->_default)); } }
<?php namespace Predis\Options; class CustomOption extends Option { private $__validate, $_default; public function __construct(Array $options) { $validate = isset($options['validate']) ? $options['validate'] : 'parent::validate'; $default = isset($options['default']) ? $options['default'] : 'parent::getDefault'; if (!is_callable($validate) || !is_callable($default)) { throw new \InvalidArgumentException("Validate and default must be callable"); } $this->_validate = $validate; $this->_default = $default; } public function validate($value) { return call_user_func($this->_validate, $value); } public function getDefault() { return $this->validate(call_user_func($this->_default)); } }
Add source to Article objects
'use strict'; var app = app || {}; (function (module) { let sourceArticles = {}; sourceArticles.all = []; sourceArticles.requestArticles = function (callback) { $.get('/news') .then(data => { sourceArticles.all = (JSON.parse(data).articles); sourceArticles.all.forEach(obj => obj.source = JSON.parse(data).source); }, err => console.error(err)) // .then(data => console.log(data), err => console.error(err)) .then(callback); }; // COMMENT: stretch goal: filtering by source or something else? // sourceArticles.with = attr => sourceArticles.all.filter( sourceArticle => sourceArticle[attr]); sourceArticles.requestArticles(loadArticles); function Article (sourceArticleData) { Object.keys(sourceArticleData).forEach(key => this[key] = sourceArticleData[key]); } function loadArticles() { Article.all = sourceArticles.all.map(obj => new Article(obj)); console.log('sourceArticles.all is', sourceArticles.all, 'Article.all is', Article.all); } module.sourceArticles = sourceArticles; }(app));
'use strict'; var app = app || {}; (function (module) { let sourceArticles = {}; sourceArticles.all = []; sourceArticles.requestArticles = function (callback) { console.log('requestArticles is listening'); $.get('/news') .then(data => sourceArticles.all = (JSON.parse(data).articles), err => console.error(err)) // .then(data => console.log(data), err => console.error(err)) .then(callback); }; // COMMENT: stretch goal: filtering by source or something else? // sourceArticles.with = attr => sourceArticles.all.filter( sourceArticle => sourceArticle[attr]); sourceArticles.requestArticles(loadArticles); function Article (sourceArticleData) { Object.keys(sourceArticleData).forEach(key => this[key] = sourceArticleData[key]); } function loadArticles() { Article.all = sourceArticles.all.map(obj => new Article(obj)); console.log('sourceArticles.all is', sourceArticles.all, 'Article.all is', Article.all); } module.sourceArticles = sourceArticles; }(app));
Use simple_tag instead of assignment_tag The assignment_tag is depraceted and in django-2.0 removed. Signed-off-by: Frantisek Lachman <bae095a6f6bdabf882218c81fdc3947ea1c10590@gmail.com>
from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.simple_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list)
from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.assignment_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list)
Update patch-level version number, upload to pypi
from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name="xonsh-apt-tabcomplete", version="0.1.6", license="BSD", url="https://github.com/DangerOnTheRanger/xonsh-apt-tabcomplete", download_url="https://github.com/DangerOnTheRanger/xonsh-apt-tabcomplete/tarball/v0.1.6", description="APT tabcomplete support for the Xonsh shell", long_description=long_description, author="Kermit Alexander II", author_email="tuxfreak@tuxfamily.org", packages=['xontrib'], package_dir={'xontrib': 'xontrib'}, package_data={'xontrib': ['*.xsh']}, zip_safe=False, classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "Environment :: Plugins", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: BSD License", "Operating System :: POSIX", "Programming Language :: Python" ] )
from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() setup( name="xonsh-apt-tabcomplete", version="0.1.3", license="BSD", url="https://github.com/DangerOnTheRanger/xonsh-apt-tabcomplete", download_url="https://github.com/DangerOnTheRanger/xonsh-apt-tabcomplete/tarball/v0.1.3", description="APT tabcomplete support for the Xonsh shell", long_description=long_description, author="Kermit Alexander II", author_email="tuxfreak@tuxfamily.org", packages=['xontrib'], package_dir={'xontrib': 'xontrib'}, package_data={'xontrib': ['*.xsh']}, zip_safe=False, classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "Environment :: Plugins", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: BSD License", "Operating System :: POSIX", "Programming Language :: Python" ] )
Fix a dumb mistake that broke the all-posts page
import moment from 'moment'; import { addCallback } from 'meteor/vulcan:core'; // Add 'after' and 'before' properties to terms which can be used to limit posts in time. function PostsAddBeforeAfterParameters (parameters, terms, apolloClient) { if (!parameters.selector.postedAt) { let postedAt = {}; if (terms.after) { postedAt.$gt = moment(terms.after).toDate(); } if (terms.before) { postedAt.$lt = moment(terms.before).toDate(); } if (!_.isEmpty(postedAt) && !terms.timeField) { parameters.selector.postedAt = postedAt; } else if (!_.isEmpty(postedAt)) { parameters.selector[terms.timeField] = postedAt; } } return parameters; } addCallback('posts.parameters', PostsAddBeforeAfterParameters);
import moment from 'moment'; import { addCallback } from 'meteor/vulcan:core'; // Add 'after' and 'before' properties to terms which can be used to limit posts in time. function PostsAddBeforeAfterParameters (parameters, terms, apolloClient) { if (parameters.selector.postedAt) { let postedAt = {}; if (terms.after) { postedAt.$gt = moment(terms.after).toDate(); } if (terms.before) { postedAt.$lt = moment(terms.before).toDate(); } if (!_.isEmpty(postedAt) && !terms.timeField) { parameters.selector.postedAt = postedAt; } else if (!_.isEmpty(postedAt)) { parameters.selector[terms.timeField] = postedAt; } } return parameters; } addCallback('posts.parameters', PostsAddBeforeAfterParameters);
Fix opencage reverse issue where it was using self.lcoation instead of just location
#!/usr/bin/python # coding: utf8 from __future__ import absolute_import import logging from geocoder.opencage import OpenCageResult, OpenCageQuery from geocoder.location import Location class OpenCageReverseResult(OpenCageResult): @property def ok(self): return bool(self.address) class OpenCageReverse(OpenCageQuery): """ OpenCage Geocoding Services =========================== OpenCage Geocoder simple, easy, and open geocoding for the entire world Our API combines multiple geocoding systems in the background. Each is optimized for different parts of the world and types of requests. We aggregate the best results from open data sources and algorithms so you don't have to. Each is optimized for different parts of the world and types of requests. API Reference ------------- https://geocoder.opencagedata.com/api """ provider = 'opencage' method = 'reverse' _URL = 'http://api.opencagedata.com/geocode/v1/json' _RESULT_CLASS = OpenCageReverseResult def _build_params(self, location, provider_key, **kwargs): location = Location(location) return { 'query': location, 'key': provider_key, } if __name__ == '__main__': logging.basicConfig(level=logging.INFO) g = OpenCageReverse([45.4049053, -75.7077965]) g.debug()
#!/usr/bin/python # coding: utf8 from __future__ import absolute_import import logging from geocoder.opencage import OpenCageResult, OpenCageQuery from geocoder.location import Location class OpenCageReverseResult(OpenCageResult): @property def ok(self): return bool(self.address) class OpenCageReverse(OpenCageQuery): """ OpenCage Geocoding Services =========================== OpenCage Geocoder simple, easy, and open geocoding for the entire world Our API combines multiple geocoding systems in the background. Each is optimized for different parts of the world and types of requests. We aggregate the best results from open data sources and algorithms so you don't have to. Each is optimized for different parts of the world and types of requests. API Reference ------------- https://geocoder.opencagedata.com/api """ provider = 'opencage' method = 'reverse' _URL = 'http://api.opencagedata.com/geocode/v1/json' _RESULT_CLASS = OpenCageReverseResult def _build_params(self, location, provider_key, **kwargs): location = Location(location) return { 'query': self.location, 'key': provider_key, } if __name__ == '__main__': logging.basicConfig(level=logging.INFO) g = OpenCageReverse([45.4049053, -75.7077965]) g.debug()
Print process.env to debug Travis
import React from 'react'; import { mount } from 'enzyme'; import { createStore } from 'redux'; import Phone from '../dev-server/Phone'; import App from '../dev-server/containers/App'; import brandConfig from '../dev-server/brandConfig'; import version from '../dev-server/version'; import prefix from '../dev-server/prefix'; import state from './state.json'; console.info(process.env); const apiConfig = { appKey: process.env.appKey, appSecret: process.env.appSecret, server: process.env.server, }; export const getPhone = async () => { const phone = new Phone({ apiConfig, brandConfig, prefix, appVersion: version, }); if (window.authData === null) { await phone.client.service.platform().login({ username: process.env.username, extension: process.env.extension, password: process.env.password }); window.authData = phone.client.service.platform().auth().data(); } else { phone.client.service.platform().auth().setData(window.authData); } state.storage.status = 'module-initializing'; const store = createStore(phone.reducer, state); phone.setStore(store); return phone; }; export const getWrapper = async () => { const phone = await getPhone(); return mount(<App phone={phone} />); }; export const getState = wrapper => wrapper.props().phone.store.getState(); export const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
import React from 'react'; import { mount } from 'enzyme'; import { createStore } from 'redux'; import Phone from '../dev-server/Phone'; import App from '../dev-server/containers/App'; import brandConfig from '../dev-server/brandConfig'; import version from '../dev-server/version'; import prefix from '../dev-server/prefix'; import state from './state.json'; const apiConfig = { appKey: process.env.appKey, appSecret: process.env.appSecret, server: process.env.server, }; export const getPhone = async () => { const phone = new Phone({ apiConfig, brandConfig, prefix, appVersion: version, }); if (window.authData === null) { await phone.client.service.platform().login({ username: process.env.username, extension: process.env.extension, password: process.env.password }); window.authData = phone.client.service.platform().auth().data(); } else { phone.client.service.platform().auth().setData(window.authData); } state.storage.status = 'module-initializing'; const store = createStore(phone.reducer, state); phone.setStore(store); return phone; }; export const getWrapper = async () => { const phone = await getPhone(); return mount(<App phone={phone} />); }; export const getState = wrapper => wrapper.props().phone.store.getState(); export const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
Add completion message to module:validate command
<?php declare(strict_types=1); namespace LotGD\Core\Console\Command; use LotGD\Core\Bootstrap; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ModuleValidateCommand extends Command { protected function configure() { $this->setName('module:validate') ->setDescription('Validate installed modules'); } protected function execute(InputInterface $input, OutputInterface $output) { $g = Bootstrap::createGame(); $results = $g->getModuleManager()->validate(); if (count($results) > 0) { foreach ($results as $r) { $output->writeln($r); } return 1; } else { $output->writeln("<info>LotGD modules validated</info>"); return 0; } } }
<?php declare(strict_types=1); namespace LotGD\Core\Console\Command; use LotGD\Core\Bootstrap; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ModuleValidateCommand extends Command { protected function configure() { $this->setName('module:validate') ->setDescription('Validate installed modules'); } protected function execute(InputInterface $input, OutputInterface $output) { $g = Bootstrap::createGame(); $results = $g->getModuleManager()->validate(); if (count($results) > 0) { foreach ($results as $r) { $output->writeln($r); } return 1; } else { return 0; } } }
Remove downloaded file before updating counter
#!/usr/bin/env python3 import ftplib import gzip import os import sys host = 'ftp.ncdc.noaa.gov' base = '/pub/data/noaa' retries = 3 ftp = ftplib.FTP(host) ftp.login() for line in sys.stdin: (year, filename) = line.strip().split() for i in range(retries): sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year, filename, i + 1, retries)) try: ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write) except ftplib.all_errors as error: sys.stderr.write('%s\n' % error) continue count = 0 for record in gzip.open(filename, 'rb'): print('%s\t%s' % (year, record.decode('ISO-8859-1').strip())) count += 1 os.remove(filename) sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count)) break else: ftp.quit() sys.exit(1) ftp.quit()
#!/usr/bin/env python3 import ftplib import gzip import os import sys host = 'ftp.ncdc.noaa.gov' base = '/pub/data/noaa' retries = 3 ftp = ftplib.FTP(host) ftp.login() for line in sys.stdin: (year, filename) = line.strip().split() for i in range(retries): sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year, filename, i + 1, retries)) try: ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write) except ftplib.all_errors as error: sys.stderr.write('%s\n' % error) continue count = 0 for record in gzip.open(filename, 'rb'): print('%s\t%s' % (year, record.decode('ISO-8859-1').strip())) count += 1 sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count)) os.remove(filename) break else: ftp.quit() sys.exit(1) ftp.quit()
Fix girder_work script bug: PEP 263 is not compatible with exec
############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import os import sys # Worker-defined inputs originalFile = globals()['originalFile'] segmentation_helpersPath = globals()['segmentation_helpersPath'] segmentation_helpersDirPath = os.path.dirname(segmentation_helpersPath) if segmentation_helpersDirPath not in sys.path: sys.path.append(segmentation_helpersDirPath) from segmentation_helpers.scikit import ScikitSegmentationHelper # noqa with open(originalFile, 'rb') as originalFileStream: # Scikit-Image is ~70ms faster at decoding image data originalImageData = ScikitSegmentationHelper.loadImage(originalFileStream) superpixelsData = ScikitSegmentationHelper.superpixels(originalImageData) superpixelsEncodedStream = ScikitSegmentationHelper.writeImage( superpixelsData, 'png') superpixelsEncodedBytes = superpixelsEncodedStream.getvalue()
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import os import sys # Worker-defined inputs originalFile = globals()['originalFile'] segmentation_helpersPath = globals()['segmentation_helpersPath'] segmentation_helpersDirPath = os.path.dirname(segmentation_helpersPath) if segmentation_helpersDirPath not in sys.path: sys.path.append(segmentation_helpersDirPath) from segmentation_helpers.scikit import ScikitSegmentationHelper # noqa with open(originalFile, 'rb') as originalFileStream: # Scikit-Image is ~70ms faster at decoding image data originalImageData = ScikitSegmentationHelper.loadImage(originalFileStream) superpixelsData = ScikitSegmentationHelper.superpixels(originalImageData) superpixelsEncodedStream = ScikitSegmentationHelper.writeImage( superpixelsData, 'png') superpixelsEncodedBytes = superpixelsEncodedStream.getvalue()
Add save_config for brocade VDX
"""Support for Brocade NOS/VDX.""" from __future__ import unicode_literals import time from netmiko.cisco_base_connection import CiscoSSHConnection class BrocadeNosSSH(CiscoSSHConnection): """Support for Brocade NOS/VDX.""" def enable(self, *args, **kwargs): """No enable mode on Brocade VDX.""" pass def exit_enable_mode(self, *args, **kwargs): """No enable mode on Brocade VDX.""" pass def special_login_handler(self, delay_factor=1): """Adding a delay after login.""" delay_factor = self.select_delay_factor(delay_factor) self.write_channel(self.RETURN) time.sleep(1 * delay_factor) def save_config(self): """Save Config for Brocade VDX.""" self.send_command('copy running-config startup-config', '[Y/N]') self.send_command('y')
"""Support for Brocade NOS/VDX.""" from __future__ import unicode_literals import time from netmiko.cisco_base_connection import CiscoSSHConnection class BrocadeNosSSH(CiscoSSHConnection): """Support for Brocade NOS/VDX.""" def enable(self, *args, **kwargs): """No enable mode on Brocade VDX.""" pass def exit_enable_mode(self, *args, **kwargs): """No enable mode on Brocade VDX.""" pass def special_login_handler(self, delay_factor=1): """Adding a delay after login.""" delay_factor = self.select_delay_factor(delay_factor) self.write_channel(self.RETURN) time.sleep(1 * delay_factor)
Change the order of the update matchday menu
(function() { 'use strict'; angular .module('app.matchday') .controller('UpdateRankMatchday', UpdateRankMatchday); function UpdateRankMatchday(initData, $scope, $rootScope, $modal) { $rootScope.$broadcast('state-btn', 'updaterank'); $rootScope.$broadcast('show-phase-nav', false); var vm = this; vm.currWeek = null; vm.maxWeek = 0; vm.currWeek = 0; vm.modalInstance = null; vm.openModal = openModal; vm.closeModal = closeModal; vm.doUpdateRank = doUpdateRank; activate(); function activate(){ vm.maxWeek = initData.matchdayModelView.week.weekNumber - 1; vm.maxWeek = parseInt(vm.maxWeek); vm.currWeek = vm.maxWeek; } function doUpdateRank() { vm.modalInstance.dismiss('cancel'); } function closeModal() { vm.modalInstance.dismiss('cancel'); } function openModal() { vm.modalInstance = $modal.open({ templateUrl: 'editScore.html', size: 'sm', scope: $scope }); } } })();
(function() { 'use strict'; angular .module('app.matchday') .controller('UpdateRankMatchday', UpdateRankMatchday); function UpdateRankMatchday(initData, $scope, $rootScope, $modal) { $rootScope.$broadcast('state-btn', 'updaterank'); $rootScope.$broadcast('show-phase-nav', false); var vm = this; vm.currWeek = null; vm.maxWeek = 0; vm.currWeek = 0; vm.modalInstance = null; vm.openModal = openModal; vm.closeModal = closeModal; vm.doUpdateRank = doUpdateRank; activate(); function activate(){ vm.maxWeek = initData.matchdayModelView.week.weekNumber; vm.maxWeek = parseInt(vm.maxWeek); vm.currWeek = vm.maxWeek; } function doUpdateRank() { vm.modalInstance.dismiss('cancel'); } function closeModal() { vm.modalInstance.dismiss('cancel'); } function openModal() { vm.modalInstance = $modal.open({ templateUrl: 'editScore.html', size: 'sm', scope: $scope }); } } })();
Make $routePattern default value null
<?php namespace Juy\ActiveMenu; /** * Class Active * * @package Juy\Providers */ class Active { /** * Current matched route * * @var Route */ protected $currentRouteName; /** * Active constructor * * @param $currentRouteName */ public function __construct($currentRouteName) { $this->currentRouteName = $currentRouteName; } /** * Active route name * If route matches given route (or array of routes) return active class * * @param $routePattern * * @return string */ public function route($routePattern = null) { // Convert to array if (!is_array($routePattern)) { $routePattern = explode(' ', $routePattern); } // Check the current route name // https://laravel.com/docs/5.3/helpers#method-str-is foreach ((array) $routePattern as $i) { if (str_is($i, $this->currentRouteName)) { return config('activemenu.class'); } } } }
<?php namespace Juy\ActiveMenu; /** * Class Active * * @package Juy\Providers */ class Active { /** * Current matched route * * @var Route */ protected $currentRouteName; /** * Active constructor * * @param $currentRouteName */ public function __construct($currentRouteName) { $this->currentRouteName = $currentRouteName; } /** * Active route name * If route matches given route (or array of routes) return active class * * @param $routePattern * * @return string */ public function route($routePattern = '') { // Convert to array if (!is_array($routePattern)) { $routePattern = explode(' ', $routePattern); } // Check the current route name // https://laravel.com/docs/5.3/helpers#method-str-is foreach ((array) $routePattern as $i) { if (str_is($i, $this->currentRouteName)) { return config('activemenu.class'); } } } }