hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
ce267eb673ffe290fec4b210f625b162b117a1a5
diff --git a/src/cli/config/abe-config.js b/src/cli/config/abe-config.js index <HASH>..<HASH> 100755 --- a/src/cli/config/abe-config.js +++ b/src/cli/config/abe-config.js @@ -98,7 +98,7 @@ var config = { siteUrl: false, sitePort: false, redis: { - enable: true, + enable: false, port: '6379', host:'127.0.0.1' }
Redis made necessary in cluster mode: Abe has become a stateful app
abecms_abecms
train
a5d2af855fc0f331ce365bdbf18e6653faf17bea
diff --git a/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php b/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php index <HASH>..<HASH> 100644 --- a/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php +++ b/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php @@ -128,9 +128,7 @@ class DoctrineMongoDBMappingsPass extends RegisterMappingsPass */ public static function createAnnotationMappingDriver(array $namespaces, array $directories, array $managerParameters, $enabledParameter = false, array $aliasMap = array()) { - $arguments = array(new Reference('doctrine_mongodb.odm.metadata.annotation_reader'), $directories); - $locator = new Definition('Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator', $arguments); - $driver = new Definition('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', array($locator)); + $driver = new Definition('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver', array(new Reference('annotation_reader'), $directories)); return new DoctrineMongoDBMappingsPass($driver, $namespaces, $managerParameters, $enabledParameter, $aliasMap); }
Fix annotation driver mapping pass to correctly instantiate and pass the annotation driver.
doctrine_DoctrineMongoDBBundle
train
17704ac9a87b52dd10d30472d2304954053893c6
diff --git a/fluent_dashboard/appsettings.py b/fluent_dashboard/appsettings.py index <HASH>..<HASH> 100644 --- a/fluent_dashboard/appsettings.py +++ b/fluent_dashboard/appsettings.py @@ -103,4 +103,4 @@ if not FLUENT_DASHBOARD_CMS_PAGE_MODEL: elif 'feincms' in settings.INSTALLED_APPS: FLUENT_DASHBOARD_CMS_PAGE_MODEL = ('page', 'page') elif 'fluent_pages' in settings.INSTALLED_APPS: - FLUENT_DASHBOARD_CMS_PAGE_MODEL = ('fluent_pages', 'urlnode') + FLUENT_DASHBOARD_CMS_PAGE_MODEL = ('fluent_pages', 'page') diff --git a/fluent_dashboard/items.py b/fluent_dashboard/items.py index <HASH>..<HASH> 100644 --- a/fluent_dashboard/items.py +++ b/fluent_dashboard/items.py @@ -10,7 +10,7 @@ from django.utils.translation import ugettext as _ from fluent_dashboard.appgroups import sort_cms_models import re -RE_CHANGE_URL = re.compile("([^_]+)_([^_]+)_change") +RE_CHANGE_URL = re.compile("(.+)_([^_]+)_change") class CmsModelList(items.ModelList): @@ -114,5 +114,3 @@ class ReturnToSiteItem(items.MenuItem): return model_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: return None - - return None
Fix compatibility with fluent_pages; an _ in the appname. Also using 'page' proxy model to access the urlnode structure, so revert to 'page' again.
django-fluent_django-fluent-dashboard
train
db217920012c6763df858ea5360243bc2eaa1fc0
diff --git a/lib/filewatcher.js b/lib/filewatcher.js index <HASH>..<HASH> 100644 --- a/lib/filewatcher.js +++ b/lib/filewatcher.js @@ -14,6 +14,7 @@ FileWatcher.prototype = { for (var path in this.fileInfo){ var info = this.fileInfo[path] info.watcher.close() + fs.unwatchFile(path) } this.fileInfo = {} this.emit('clear') @@ -50,8 +51,16 @@ FileWatcher.prototype = { if (err) return var fileInfo = self.getFileInfo(file) fileInfo.lastModTime = +stats.mtime - fileInfo.watcher = fs.watch(file, function(evt){ - self.onAccess(evt, file) + fileInfo.watcher = fs.watch( + file + , function(evt){ + self.onAccess(evt, file) + } + ) + fs.watchFile(file, function(curr, prev){ + if (curr.mtime !== prev.mtime){ + self.onAccess('change', file) + } }) }) })
Fallback to using fs.watchFile for filewatcher so that vi users can have autorun, be it less responsive.
testem_testem
train
d39d703d101ace744348a57aa708165222457b1f
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -13,8 +13,11 @@ var through = require('through2'), var PLUGIN_NAME = 'gulp-symlink'; +/** + * Wrapper to log when debug === true + * it's basically a console.log + */ var log = function() { - if(debug === true) { console.log.apply(console, [].slice.call(arguments)); return console.log; @@ -24,9 +27,15 @@ var log = function() { }; +/** + * Error wrapper - this is called in the through context + * @param {Error} error The error + * @return {Function} cb The through callback + */ var errored = function(error, cb) { this.emit('error', new PluginError(PLUGIN_NAME, error)); - //Push the file so that the stream is piped to the next task + //Push the file so that the stream is piped to the next task even if it has errored + //might be discussed this.push(this.source); return cb(); }; @@ -35,15 +44,13 @@ var symlinker = function(destination, resolver, options) { if(typeof resolver === 'object') { options = resolver; - resolver = 'absolute'; + resolver = 'relative'; } options = typeof options === 'object' ? options : {}; options.force = options.force === undefined ? false : options.force; - //pass the debug value to the through obj -// debug = this.debug; - + //Handling array of destinations, this test is because "instance of" isn't safe if( Object.prototype.toString.call( destination ) === '[object Array]' ) { //copy array because we'll shift values var destinations = destination.slice(); @@ -59,7 +66,8 @@ var symlinker = function(destination, resolver, options) { symlink = destinations !== undefined ? destinations.shift() : symlink; //if destination is a function pass the source to it - symlink = typeof destination === 'function' ? destination(source) : destination; + if(symlink === undefined) + symlink = typeof destination === 'function' ? destination(source) : destination; //if symlink is still undefined there is a problem! if (symlink === undefined) { @@ -69,7 +77,6 @@ var symlinker = function(destination, resolver, options) { // Convert the destination path to a new vinyl instance symlink = symlink instanceof File ? symlink : new File({ path: symlink }); - log('Before resolving')('Source: %s – dest: %s', source.path, symlink.path); symlink.directory = path.dirname(symlink.path); //this is the parent directory of the symlink @@ -78,9 +85,8 @@ var symlinker = function(destination, resolver, options) { if(resolver === 'relative' || options.relative === true) { source.resolved = path.relative(symlink.directory, source.path); } else { - //resolve from the symlink directory the absolute path from the source. It need to be from the current working directory to handle relative sources - source.resolved = path.resolve(symlink.directory, path.join(source.cwd, source.path.replace(source.cwd, ''))); - //maybe this could be done better like p.resolve(source.cwd, source.path) ? + //resolve the absolute path from the source. It need to be from the current working directory to handle relative sources + source.resolved = path.resolve(source.cwd, source.path); } log('After resolving')(source.resolved + ' in ' + symlink.path);
Improvements Handle Array of destinations Better absolute resolving Comments
ben-eb_gulp-symlink
train
20473dab36e88fca4f7826a61346a4e3a043f1ac
diff --git a/core/src/main/java/hudson/model/Slave.java b/core/src/main/java/hudson/model/Slave.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/model/Slave.java +++ b/core/src/main/java/hudson/model/Slave.java @@ -62,7 +62,6 @@ import jenkins.model.Jenkins; import jenkins.slaves.WorkspaceLocator; import org.apache.commons.io.IOUtils; -import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; @@ -134,7 +133,6 @@ public abstract class Slave extends Node implements Serializable { */ private String userId; - @DataBoundConstructor public Slave(String name, String nodeDescription, String remoteFS, String numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy, List<? extends NodeProperty<?>> nodeProperties) throws FormException, IOException { this(name,nodeDescription,remoteFS,Util.tryParseNumber(numExecutors, 1).intValue(),mode,labelString,launcher,retentionStrategy, nodeProperties); diff --git a/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java b/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java +++ b/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java @@ -5,7 +5,6 @@ import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; -import org.kohsuke.stapler.DataBoundConstructor; import java.text.ParseException; import java.util.logging.Logger; @@ -21,7 +20,6 @@ public abstract class AbstractDiskSpaceMonitor extends NodeMonitor { */ public final String freeSpaceThreshold; - @DataBoundConstructor public AbstractDiskSpaceMonitor(String threshold) throws ParseException { this.freeSpaceThreshold = threshold; DiskSpace.parse(threshold); // make sure it parses
@DataBoundConstructor makes no sense on an abstract class. (cherry picked from commit <I>d8b<I>ea<I>e0cda6dbc<I>b<I>c<I>)
jenkinsci_jenkins
train
1bb0573015e81af1e245dad7999c3fb16b530a10
diff --git a/vm/src/lib.js b/vm/src/lib.js index <HASH>..<HASH> 100644 --- a/vm/src/lib.js +++ b/vm/src/lib.js @@ -389,7 +389,7 @@ var shine = shine || {}; require: function (modname) { var thread, - packageLib = shine.lib['package'], + packageLib = this._globals['package'], running = shine.Coroutine._running._func._instance, vm = this, module,
Cached modules no longer stored statically and should be dumped with VM.
gamesys_moonshine
train
ad0accb97a7c422fea40778ec44dc87808c595cf
diff --git a/reflect-helpers.js b/reflect-helpers.js index <HASH>..<HASH> 100644 --- a/reflect-helpers.js +++ b/reflect-helpers.js @@ -294,10 +294,13 @@ */ _R.getObjectPrototype = function getObjectPrototype(what) { - if (typeof what !== 'object' || typeof what !== 'function' || what == null) { + if (typeof what !== 'object' && typeof what !== 'function') { return null; } - if (Object.getPrototypeOf) { + else if (what === null || what === undefined) { + return null; + } + else if (Object.getPrototypeOf) { return Object.getPrototypeOf(what); } else if (( {}).__proto__) { return what.__proto__;
Typo - OR instead of AND. xD
Ginden_reflect-helpers
train
6b9236d2d51fc329c17e5ab5aee0d806a1a40829
diff --git a/src/main/java/water/Model.java b/src/main/java/water/Model.java index <HASH>..<HASH> 100644 --- a/src/main/java/water/Model.java +++ b/src/main/java/water/Model.java @@ -308,6 +308,7 @@ public abstract class Model extends Iced { SB fileContextSB = new SB(); // preserve file context String modelName = JCodeGen.toJavaId(_selfKey.toString()); // HEADER + sb.p("import java.util.Map;").nl().nl(); sb.p("// AUTOGENERATED BY H2O at ").p(new Date().toString()).nl(); sb.p("// ").p(H2O.getBuildVersion().toString()).nl(); sb.p("//").nl(); @@ -322,7 +323,7 @@ public abstract class Model extends Iced { sb.p("//").nl(); sb.p("// (Note: Try java argument -XX:+PrintCompilation to show runtime JIT compiler behavior.)").nl(); sb.nl(); - sb.p("class ").p(modelName).p(" extends water.genmodel.GeneratedModel {").nl(); // or extends GenerateModel + sb.p("public class ").p(modelName).p(" extends water.genmodel.GeneratedModel {").nl(); // or extends GenerateModel toJavaInit(sb).nl(); toJavaNAMES(sb); toJavaNCLASSES(sb); @@ -419,7 +420,7 @@ public abstract class Model extends Iced { " // Takes a HashMap mapping column names to doubles. Looks up the column\n"+ " // names needed by the model, and places the doubles into the data array in\n"+ " // the order needed by the model. Missing columns use NaN.\n"+ - " double[] map( java.util.HashMap row, double data[] ) {\n"+ + " double[] map( Map<String, Double> row, double data[] ) {\n"+ " for( int i=0; i<NAMES.length-1; i++ ) {\n"+ " Double d = (Double)row.get(NAMES[i]);\n"+ " data[i] = d==null ? Double.NaN : d;\n"+ @@ -429,19 +430,19 @@ public abstract class Model extends Iced { private static final String TOJAVA_PREDICT_MAP = "\n"+ " // Does the mapping lookup for every row, no allocation\n"+ - " float[] predict( java.util.HashMap row, double data[], float preds[] ) {\n"+ + " float[] predict( Map<String, Double> row, double data[], float preds[] ) {\n"+ " return predict(map(row,data),preds);\n"+ " }\n"; private static final String TOJAVA_PREDICT_MAP_ALLOC1 = "\n"+ " // Allocates a double[] for every row\n"+ - " float[] predict( java.util.HashMap row, float preds[] ) {\n"+ + " float[] predict( Map<String, Double> row, float preds[] ) {\n"+ " return predict(map(row,new double[NAMES.length]),preds);\n"+ " }\n"; private static final String TOJAVA_PREDICT_MAP_ALLOC2 = "\n"+ " // Allocates a double[] and a float[] for every row\n"+ - " float[] predict( java.util.HashMap row ) {\n"+ + " float[] predict( Map<String, Double> row ) {\n"+ " return predict(map(row,new double[NAMES.length]),new float[NCLASSES+1]);\n"+ " }\n";
#<I>: Changed generated classes to be public. Modified map and predict methods to use Map<String, Double> instead of HashMap.
h2oai_h2o-2
train
7a26480b7f97254fc4f68db7722657d64526984d
diff --git a/galpy/potential.py b/galpy/potential.py index <HASH>..<HASH> 100644 --- a/galpy/potential.py +++ b/galpy/potential.py @@ -1,6 +1,4 @@ import warnings -from galpy.util import galpyWarning -warnings.warn("A major change in versions > 1.1 is that all galpy.potential functions and methods take the potential as the first argument; previously methods such as evaluatePotentials, evaluateDensities, etc. would be called with (R,z,Pot), now they are called as (Pot,R,z) for greater consistency across the codebase",galpyWarning) from galpy.potential_src import Potential from galpy.potential_src import planarPotential from galpy.potential_src import linearPotential
remove warning about changed arguments for potential functions
jobovy_galpy
train
390f87eaa82d065beba5d8d3e3391f95c77fb62c
diff --git a/cli/valet.php b/cli/valet.php index <HASH>..<HASH> 100755 --- a/cli/valet.php +++ b/cli/valet.php @@ -518,7 +518,7 @@ You might also want to investigate your global Composer configs. Helpful command return info("Valet is already using {$linkedVersion}."); } - info("Found '{$site}' specifying version: {$phpVersion}"); + info("Found '{$site}/.valetphprc' specifying version: {$phpVersion}"); } PhpFpm::useVersion($phpVersion, $force);
Update cli/valet.php
laravel_valet
train
ef03b753d4185d0a82980b7522c58866f2a4bc87
diff --git a/lib/cli.js b/lib/cli.js index <HASH>..<HASH> 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -56,11 +56,15 @@ var resolveTransition = function(transition) { }; var saveUserAsset = function(type, file) { - // ... + var assetName = path.basename(file, '.css') + , assetPath = path.join(regDir, type, name + '.css') + , assetContents = fs.readFileSync(file, 'utf8').toString(); + fs.writeFileSync(assetPath, assetContents, 'utf8'); } var rmUserAsset = function(type, name) { - // ... + var assetPath = path.join(regDir, type, name + '.css'); + fs.unlinkSync(assetPath); } var optsFromProgramArgs = function(program) {
partial: Add internal functions for saving/deleting assets
jtrussell_bedecked
train
bebe6825e05c318cd4d7d8bc00931c8f09e042d2
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java @@ -199,6 +199,8 @@ public class ORecordLazySet implements Set<OIdentifiable>, ORecordLazyMultiValue // ADD IN TEMP LIST if (newItems == null) newItems = new IdentityHashMap<ORecord<?>, Object>(); + else if (newItems.containsKey(record)) + return false; newItems.put(record, NEWMAP_VALUE); setDirty(); return true; diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordTrackedSet.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordTrackedSet.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordTrackedSet.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordTrackedSet.java @@ -50,6 +50,9 @@ public class ORecordTrackedSet extends AbstractCollection<OIdentifiable> impleme } public boolean add(final OIdentifiable e) { + if (map.containsKey(e)) + return false; + map.put(e, ENTRY_REMOVAL); setDirty(); @@ -66,7 +69,6 @@ public class ORecordTrackedSet extends AbstractCollection<OIdentifiable> impleme public boolean remove(Object o) { final Object old = map.remove(o); if (old != null) { - if (o instanceof ODocument) ((ODocument) o).removeOwner(this); diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/OTrackedMap.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/OTrackedMap.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/OTrackedMap.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/OTrackedMap.java @@ -40,8 +40,13 @@ public class OTrackedMap<T> extends LinkedHashMap<Object, T> implements ORecordE iSourceRecord.setDirty(); } + @SuppressWarnings("unchecked") @Override public T put(final Object iKey, final T iValue) { + Object oldValue = super.get(iKey); + if (oldValue != null && oldValue == iValue) + return (T) oldValue; + setDirty(); return super.put(iKey, iValue); } @@ -60,7 +65,6 @@ public class OTrackedMap<T> extends LinkedHashMap<Object, T> implements ORecordE @Override public void putAll(Map<? extends Object, ? extends T> m) { - setDirty(); super.putAll(m); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java @@ -216,7 +216,7 @@ public class ODocument extends ORecordSchemaAwareAbstract<Object> implements Ite cloned._fieldTypes = new HashMap<String, OType>(_fieldTypes); cloned._fieldOriginalValues = null; - cloned._dirty = _dirty; + cloned._dirty = _dirty; // LEAVE IT AS LAST TO AVOID SOMETHING SET THE FLAG TO TRUE return cloned; }
Checked on add/put/remove of multivalue types if dirty flag is really necessary.
orientechnologies_orientdb
train
08f3f30994d37f6f44acfac801f82fc43127fc78
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -305,9 +305,18 @@ module ActiveRecord def reverse_sql_order(order_query) order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty? - order_query.join(', ').split(',').collect do |s| - s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC') - end + order_query.map do |o| + case o + when Arel::Nodes::Ordering + o.reverse + when String, Symbol + o.to_s.split(',').collect do |s| + s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC') + end + else + o + end + end.flatten end def array_of_strings?(o) diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -145,6 +145,18 @@ class RelationTest < ActiveRecord::TestCase assert_equal topics(:first).title, topics.first.title end + + def test_finding_with_arel_order + topics = Topic.order(Topic.arel_table[:id].asc) + assert_equal 4, topics.to_a.size + assert_equal topics(:first).title, topics.first.title + end + + def test_finding_last_with_arel_order + topics = Topic.order(Topic.arel_table[:id].asc) + assert_equal topics(:fourth).title, topics.last.title + end + def test_finding_with_order_concatenated topics = Topic.order('author_name').order('title') assert_equal 4, topics.to_a.size
Support reversal of ARel orderings in reverse_sql_order
rails_rails
train
e6ffd987a3bd359fdb3246a90027706543489039
diff --git a/agent/grpc/resolver/resolver.go b/agent/grpc/resolver/resolver.go index <HASH>..<HASH> 100644 --- a/agent/grpc/resolver/resolver.go +++ b/agent/grpc/resolver/resolver.go @@ -5,6 +5,7 @@ import ( "math/rand" "strings" "sync" + "time" "github.com/hashicorp/consul/agent/metadata" "google.golang.org/grpc/resolver" @@ -59,6 +60,7 @@ func NewServerResolverBuilder(cfg Config) *ServerResolverBuilder { // Rebalance shuffles the server list for resolvers in all datacenters. func (s *ServerResolverBuilder) NewRebalancer(dc string) func() { + shuffler := rand.New(rand.NewSource(time.Now().UnixNano())) return func() { s.lock.RLock() defer s.lock.RUnlock() @@ -70,8 +72,7 @@ func (s *ServerResolverBuilder) NewRebalancer(dc string) func() { // Shuffle the list of addresses using the last list given to the resolver. resolver.addrLock.Lock() addrs := resolver.addrs - // TODO: seed this rand, so it is a little more random-like - rand.Shuffle(len(addrs), func(i, j int) { + shuffler.Shuffle(len(addrs), func(i, j int) { addrs[i], addrs[j] = addrs[j], addrs[i] }) // Pass the shuffled list to the resolver.
agent/grpc: seed the rand for shuffling servers
hashicorp_consul
train
d34092d1a004552f26c055143a3aef5936bf99d0
diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "autohost", - "version": "0.1.29", + "version": "0.1.30", "description": "Resource-driven http server", "main": "src/autohost.js", "author": "Alex Robson", @@ -8,6 +8,10 @@ { "name": "Scott Walters", "url": "http://github.com/LeankitScott" + }, + { + "name": "Jim Cowart", + "url": "http://github.com/ifandelse" } ], "license": "MIT License - http://opensource.org/licenses/MIT", @@ -28,11 +32,11 @@ "gaze": "~0.6.4" }, "devDependencies": { - "autohost-riak-auth": "~0.0.4", + "autohost-riak-auth": "~0.0.22", "configya": "~0.0.3", "gulp": "~3.5.6", "gulp-mocha": "~0.4.1", "passport-http": "~0.2.2", "processhost": "~0.1.6" } -} +} \ No newline at end of file diff --git a/src/_autohost/public/js/main.js b/src/_autohost/public/js/main.js index <HASH>..<HASH> 100644 --- a/src/_autohost/public/js/main.js +++ b/src/_autohost/public/js/main.js @@ -43,7 +43,7 @@ require( [ 'jsx!resource/main', 'socketio' ], - function($, React, Bootstrap, Home, io) { + function($, React, Bootstrap, Home, io) { var app = window.app = {}; window.React = React; var socket = window.socket = io.connect( '/' ); diff --git a/src/autohost.js b/src/autohost.js index <HASH>..<HASH> 100644 --- a/src/autohost.js +++ b/src/autohost.js @@ -87,6 +87,7 @@ module.exports = function( config ) { context: req.context, data: req.body || {}, path: req.url, + cookies: req.cookies, headers: req.headers, params: {}, files: req.files, @@ -147,6 +148,7 @@ module.exports = function( config ) { data: message.data || message, headers: message.headers || [], socket: socket, + cookies: socket.cookies, user: socket.user, path: message.topic, reply: function( envelope ) { diff --git a/src/resource.js b/src/resource.js index <HASH>..<HASH> 100644 --- a/src/resource.js +++ b/src/resource.js @@ -26,7 +26,8 @@ module.exports = function( Host ) { Host.prototype.loadModule = function( resourcePath ) { try { - delete require.cache[ resourcePath ]; + var key = path.resolve( resourcePath ); + delete require.cache[ key ]; var mod = require( resourcePath )( this ); if( mod && mod.name ) { this.processResource( this.config.apiPrefix, mod, path.dirname( resourcePath ) ); diff --git a/src/socketio.js b/src/socketio.js index <HASH>..<HASH> 100644 --- a/src/socketio.js +++ b/src/socketio.js @@ -57,7 +57,7 @@ module.exports = function( Host ) { id: handshake.id || handshake.user || 'anonymous', name: handshake.user || 'anonymous' }; - + socket.cookies = handshake.request.cookies; if( this.authorizer ) { this.authorizer.getUserRoles( socket.user, function( err, roles ) { if ( err ) { @@ -94,4 +94,4 @@ module.exports = function( Host ) { this.io = io; } }; -}; +}; \ No newline at end of file diff --git a/src/websockets.js b/src/websockets.js index <HASH>..<HASH> 100644 --- a/src/websockets.js +++ b/src/websockets.js @@ -16,6 +16,8 @@ module.exports = function( Host ) { name: user || 'anonymous' }; + socket.cookies = request.cookies; + if( this.authorizer ) { this.authorizer.getUserRoles( socket.user, function( err, roles ) { if ( err ) {
Add .cookies property to envelope for sockets and http requests. Update autohost-riak-auth dependency to working version. Add @ifandelse to contributors list.
LeanKit-Labs_autohost
train
e5056fa3e033d5939f3099cd501d719b60e773f3
diff --git a/lib/ronin/platform/overlay.rb b/lib/ronin/platform/overlay.rb index <HASH>..<HASH> 100644 --- a/lib/ronin/platform/overlay.rb +++ b/lib/ronin/platform/overlay.rb @@ -354,6 +354,8 @@ module Ronin # @return [Overlay] # The updated overlay. # + # @since 0.4.0 + # def update!(&block) # only update if we have a repository @repository.update(self.uri) if @repository @@ -381,6 +383,8 @@ module Ronin # @return [Overlay] # The deleted overlay. # + # @since 0.4.0 + # def uninstall!(&block) FileUtils.rm_rf(self.path) unless self.local? diff --git a/lib/ronin/platform/overlay_cache.rb b/lib/ronin/platform/overlay_cache.rb index <HASH>..<HASH> 100644 --- a/lib/ronin/platform/overlay_cache.rb +++ b/lib/ronin/platform/overlay_cache.rb @@ -263,17 +263,19 @@ module Ronin # @return [Overlay] # The newly added overlay. # + # @raise [OverlayCache] + # The specified overlay has already been cached. + # # @example - # cache.add(overlay) + # cache.add!(overlay) # # => #<Ronin::Platform::Overlay: ...> # # @example - # cache.add(overlay) do |cache| + # cache.add!(overlay) do |cache| # puts "Overlay #{overlay} added" # end # - # @raise [OverlayCache] - # The specified overlay has already been cached. + # @since 0.4.0 # def add!(overlay,&block) name = overlay.name.to_s @@ -300,14 +302,16 @@ module Ronin # Each updated overlay in the cache. # # @example - # update + # update! # # => #<Ronin::Platform::OverlayCache: ...> # # @example - # update do |overlay| + # update! do |overlay| # puts "#{overaly} is updated" # end # + # @since 0.4.0 + # def update!(&block) overlays.each do |overlay| # de-activate the overlay @@ -343,14 +347,16 @@ module Ronin # @return [nil] # # @example - # cache.uninstall('hello_word') + # cache.uninstall!('hello_word') # # => #<Ronin::Platform::Overlay: ...> # # @example - # cache.uninstall('hello_word') do |overlay| + # cache.uninstall!('hello_word') do |overlay| # puts "Overlay #{overlay} uninstalled" # end # + # @since 0.4.0 + # def uninstall!(name,&block) name = name.to_s diff --git a/lib/ronin/platform/platform.rb b/lib/ronin/platform/platform.rb index <HASH>..<HASH> 100644 --- a/lib/ronin/platform/platform.rb +++ b/lib/ronin/platform/platform.rb @@ -27,6 +27,8 @@ require 'extlib' module Ronin module Platform # + # The currently loaded Overlays. + # # @return [OverlayCache] # The current overlay cache. If no overlay cache is present, the # default overlay will be loaded. @@ -67,6 +69,8 @@ module Ronin # @raise [OverlayNotFound] # The `:path` option did not represent a valid directory. # + # @since 0.4.0 + # def Platform.add!(options={},&block) Platform.overlays.add!(Overlay.create!(options),&block) end @@ -98,6 +102,8 @@ module Ronin # @raise [ArgumentError] # The `:uri` option must be specified. # + # @since 0.4.0 + # def Platform.install!(options={},&block) Platform.overlays.add!(Overlay.install(options),&block) end @@ -111,6 +117,8 @@ module Ronin # # @return [nil] # + # @since 0.4.0 + # def Platform.update!(&block) Platform.overlays.update!() @@ -135,6 +143,8 @@ module Ronin # The overlay with the specified name could not be found in the # overlay cache. # + # @since 0.4.0 + # def Platform.uninstall!(name,&block) Platform.overlays.uninstall!(name)
Updated documentation for renamed methods.
ronin-ruby_ronin
train
f2b95e80a874937a051e8bb088874e422c704cdf
diff --git a/flatpack/src/main/java/net/sf/flatpack/DataSet.java b/flatpack/src/main/java/net/sf/flatpack/DataSet.java index <HASH>..<HASH> 100644 --- a/flatpack/src/main/java/net/sf/flatpack/DataSet.java +++ b/flatpack/src/main/java/net/sf/flatpack/DataSet.java @@ -36,7 +36,6 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; -import java.util.NoSuchElementException; import java.util.Properties; import net.sf.flatpack.ordering.OrderBy; diff --git a/flatpack/src/main/java/net/sf/flatpack/ParserFactory.java b/flatpack/src/main/java/net/sf/flatpack/ParserFactory.java index <HASH>..<HASH> 100644 --- a/flatpack/src/main/java/net/sf/flatpack/ParserFactory.java +++ b/flatpack/src/main/java/net/sf/flatpack/ParserFactory.java @@ -244,7 +244,8 @@ public interface ParserFactory { * The File can be wrapped in a "new FileReader(File)" * @return PZParser */ - Parser newDelimitedParser(final File pzmapXML, final File dataSource, final char delimiter, final char qualifier, final boolean ignoreFirstRecord); + Parser newDelimitedParser(final File pzmapXML, final File dataSource, final char delimiter, final char qualifier, + final boolean ignoreFirstRecord); /** * Constructs a new DataSet using the PZMAP XML file layout method. This is diff --git a/flatpack/src/main/java/net/sf/flatpack/util/FPStringUtils.java b/flatpack/src/main/java/net/sf/flatpack/util/FPStringUtils.java index <HASH>..<HASH> 100644 --- a/flatpack/src/main/java/net/sf/flatpack/util/FPStringUtils.java +++ b/flatpack/src/main/java/net/sf/flatpack/util/FPStringUtils.java @@ -5,7 +5,11 @@ package net.sf.flatpack.util; * * @author Jakarta Commons */ -public class FPStringUtils { +public final class FPStringUtils { + private FPStringUtils() { + + } + /** * <p>Checks if a String is whitespace, empty ("") or null.</p> * diff --git a/flatpack/src/main/java/net/sf/flatpack/xml/XMLRecordElement.java b/flatpack/src/main/java/net/sf/flatpack/xml/XMLRecordElement.java index <HASH>..<HASH> 100644 --- a/flatpack/src/main/java/net/sf/flatpack/xml/XMLRecordElement.java +++ b/flatpack/src/main/java/net/sf/flatpack/xml/XMLRecordElement.java @@ -113,13 +113,13 @@ public class XMLRecordElement { } /** - * @param columns + * @param columnsToUse * The columns to set. * @param p * PZParser being used. Can be null. */ - public void setColumns(final List columns, final Parser p) { - this.columns = columns; + public void setColumns(final List columnsToUse, final Parser p) { + this.columns = columnsToUse; this.columnIndex = ParserUtils.buidColumnIndexMap(columns, p); }
Fix a few PMD and Checkstyle warnings. Former-commit-id: e7b2cfd2d<I>c<I>ac<I>f<I>a5f3c0cb8ea<I>
Appendium_flatpack
train
b1894bd98a9fd73f3b08af009858e07f8bcd09ab
diff --git a/openquake/calculators/event_based_risk.py b/openquake/calculators/event_based_risk.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/event_based_risk.py +++ b/openquake/calculators/event_based_risk.py @@ -381,7 +381,7 @@ class EventBasedRiskCalculator(event_based.EventBasedCalculator): """ logging.info('Processing {:_d} rows of gmf_data'.format(len(eids))) ct = self.oqparam.concurrent_tasks or 1 - E = len(eids) / ct + E = int(len(numpy.unique(eids)) / ct) K = self.param['K'] names = {'loss', 'variance'} for sec_loss in self.param['sec_losses']:
Small fix in log_info [ci skip]
gem_oq-engine
train
bd8661e8fafd5f80ce12fa966b9f8e990b7d7714
diff --git a/daemon/logger/jsonfilelog/jsonfilelog.go b/daemon/logger/jsonfilelog/jsonfilelog.go index <HASH>..<HASH> 100644 --- a/daemon/logger/jsonfilelog/jsonfilelog.go +++ b/daemon/logger/jsonfilelog/jsonfilelog.go @@ -3,6 +3,7 @@ package jsonfilelog import ( "bytes" "os" + "sync" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/pkg/jsonlog" @@ -12,7 +13,8 @@ import ( // JSON objects to file type JSONFileLogger struct { buf *bytes.Buffer - f *os.File // store for closing + f *os.File // store for closing + mu sync.Mutex // protects buffer } // New creates new JSONFileLogger which writes to filename @@ -29,13 +31,20 @@ func New(filename string) (logger.Logger, error) { // Log converts logger.Message to jsonlog.JSONLog and serializes it to file func (l *JSONFileLogger) Log(msg *logger.Message) error { + l.mu.Lock() + defer l.mu.Unlock() err := (&jsonlog.JSONLog{Log: string(msg.Line) + "\n", Stream: msg.Source, Created: msg.Timestamp}).MarshalJSONBuf(l.buf) if err != nil { return err } l.buf.WriteByte('\n') _, err = l.buf.WriteTo(l.f) - return err + if err != nil { + // this buffer is screwed, replace it with another to avoid races + l.buf = bytes.NewBuffer(nil) + return err + } + return nil } // Close closes underlying file
Protect jsonfilelog writes with mutex
containers_storage
train
3da7d2460cfe6787ef0fcf1a93438440eae2532a
diff --git a/QUANTAXIS/QAARP/QAAccount.py b/QUANTAXIS/QAARP/QAAccount.py index <HASH>..<HASH> 100755 --- a/QUANTAXIS/QAARP/QAAccount.py +++ b/QUANTAXIS/QAARP/QAAccount.py @@ -97,7 +97,7 @@ class QA_Account(QA_Worker): def __init__(self, strategy_name=None, user_cookie=None, portfolio_cookie=None, account_cookie=None, market_type=MARKET_TYPE.STOCK_CN, frequence=FREQUENCE.DAY, broker=BROKER_TYPE.BACKETEST, - init_hold={}, init_cash=1000000, commission_coeff=0.00025, tax_coeff=0.0015, + init_hold={}, init_cash=1000000, commission_coeff=0.00025, tax_coeff=0.001, margin_level=False, allow_t0=False, allow_sellopen=False, running_environment=RUNNING_ENVIRONMENT.BACKETEST): """
#update tax_coeff
QUANTAXIS_QUANTAXIS
train
446e918e1474dd9647caf83b488b0cef35c3327d
diff --git a/num2words/__init__.py b/num2words/__init__.py index <HASH>..<HASH> 100644 --- a/num2words/__init__.py +++ b/num2words/__init__.py @@ -96,6 +96,8 @@ def num2words(number, ordinal=False, lang='en', to='cardinal', **kwargs): if lang not in CONVERTER_CLASSES: raise NotImplementedError() converter = CONVERTER_CLASSES[lang] + if isinstance(number, str): + number = converter.str_to_number(number) # backwards compatible if ordinal: return converter.to_ordinal(number) diff --git a/num2words/base.py b/num2words/base.py index <HASH>..<HASH> 100644 --- a/num2words/base.py +++ b/num2words/base.py @@ -96,6 +96,9 @@ class Num2Word_Base(object): return '%s ' % self.negword, num_str[1:] return '', num_str + def str_to_number(self, value): + return Decimal(value) + def to_cardinal(self, value): try: assert int(value) == value diff --git a/tests/test_cli.py b/tests/test_cli.py index <HASH>..<HASH> 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -72,7 +72,7 @@ class CliTestCase(unittest.TestCase): self.assertEqual(output.return_code, 0) self.assertEqual( output.out.strip(), - "one hundred and fifty point zero" + "one hundred and fifty" ) def test_cli_with_lang(self): @@ -82,7 +82,7 @@ class CliTestCase(unittest.TestCase): self.assertEqual(output.return_code, 0) self.assertEqual( output.out.strip(), - "ciento cincuenta punto cero" + "ciento cincuenta" ) def test_cli_with_lang_to(self):
Convert strings to Decimal values Punt string handling to python Decimal object, this correctly represents both integers and floats (except with regards to trailing zeros) Change command line tests to reflect handling of ints
savoirfairelinux_num2words
train
c341629060f5392ba0d86f0ea5a9f4df3072e6f1
diff --git a/java/server/src/org/openqa/grid/common/RegistrationRequest.java b/java/server/src/org/openqa/grid/common/RegistrationRequest.java index <HASH>..<HASH> 100644 --- a/java/server/src/org/openqa/grid/common/RegistrationRequest.java +++ b/java/server/src/org/openqa/grid/common/RegistrationRequest.java @@ -494,7 +494,7 @@ public class RegistrationRequest { * * @param resource */ - private void loadFromJSON(String resource) { + public void loadFromJSON(String resource) { try { JSONObject base = JSONConfigurationUtils.loadJSON(resource);
francoisReynaud: making method public to be able to configure a node programatically from a json config file. r<I>
SeleniumHQ_selenium
train
5387137387af672016bc83685d74bebc9ea27e3e
diff --git a/spyderlib/plugins/__init__.py b/spyderlib/plugins/__init__.py index <HASH>..<HASH> 100644 --- a/spyderlib/plugins/__init__.py +++ b/spyderlib/plugins/__init__.py @@ -46,6 +46,7 @@ class SpyderPluginMixin(object): FEATURES = QDockWidget.DockWidgetClosable | \ QDockWidget.DockWidgetFloatable | \ QDockWidget.DockWidgetMovable + DISABLE_ACTIONS_WHEN_HIDDEN = True def __init__(self, main): """Bind widget to a QMainWindow instance""" super(SpyderPluginMixin, self).__init__() @@ -98,8 +99,9 @@ class SpyderPluginMixin(object): if widget is not None: widget.setFocus() visible = self.dockwidget.isVisible() or self.ismaximized - toggle_actions(self.menu_actions, visible) - toggle_actions(self.toolbar_actions, visible) + if self.DISABLE_ACTIONS_WHEN_HIDDEN: + toggle_actions(self.menu_actions, visible) + toggle_actions(self.toolbar_actions, visible) if visible: self.refresh_plugin() #XXX Is it a good idea? diff --git a/spyderlib/plugins/editor.py b/spyderlib/plugins/editor.py index <HASH>..<HASH> 100644 --- a/spyderlib/plugins/editor.py +++ b/spyderlib/plugins/editor.py @@ -54,6 +54,7 @@ class Editor(SpyderPluginWidget): ID = 'editor' TEMPFILE_PATH = get_conf_path('.temp.py') TEMPLATE_PATH = get_conf_path('template.py') + DISABLE_ACTIONS_WHEN_HIDDEN = False # SpyderPluginWidget class attribute def __init__(self, parent, ignore_last_opened_files=False): # Creating template if it doesn't already exist if not osp.isfile(self.TEMPLATE_PATH):
SpyderPluginMixin: added class attribute 'DISABLE_ACTIONS_WHEN_HIDDEN' -> fixes Editor behaviour wrt to new windows
spyder-ide_spyder
train
4d88a95d6730383624570f8730aa203a56caadc3
diff --git a/integration/build/build_test.go b/integration/build/build_test.go index <HASH>..<HASH> 100644 --- a/integration/build/build_test.go +++ b/integration/build/build_test.go @@ -25,7 +25,7 @@ import ( func TestBuildWithRemoveAndForceRemove(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME") defer setupTest(t)() - t.Parallel() + cases := []struct { name string dockerfile string diff --git a/integration/container/update_linux_test.go b/integration/container/update_linux_test.go index <HASH>..<HASH> 100644 --- a/integration/container/update_linux_test.go +++ b/integration/container/update_linux_test.go @@ -67,8 +67,6 @@ func TestUpdateMemory(t *testing.T) { } func TestUpdateCPUQuota(t *testing.T) { - t.Parallel() - defer setupTest(t)() client := request.NewAPIClient(t) ctx := context.Background()
Don't mix t.Parallel() wth environment.ProtectAll() `testEnv` is a package-level variable, so protecting / restoring `testEnv` in parallel will result in "concurrent map write" errors. This patch removes `t.Parallel()` from tests that use this functionality (through `defer setupTest(t)()`). Note that _subtests_ can still be run in parallel, as the defer will be called after all subtests have completed.
moby_moby
train
5d0fdcc7e2aa37aaa2733476f840f42b926cd006
diff --git a/lib/telos/device.rb b/lib/telos/device.rb index <HASH>..<HASH> 100644 --- a/lib/telos/device.rb +++ b/lib/telos/device.rb @@ -61,5 +61,9 @@ module Telos end Thread.pass # Make sure the reader thread starts end + + def stop_reader_thread + @reader_thread.terminate if @reader_thread + end end end \ No newline at end of file
Actually add the stop_reader_thread method
Q-music_ruby-telos
train
b2e3a494b0e6a75b1caea32a17f41fc7d4799321
diff --git a/benchmark/document-suite.js b/benchmark/document-suite.js index <HASH>..<HASH> 100644 --- a/benchmark/document-suite.js +++ b/benchmark/document-suite.js @@ -1,7 +1,5 @@ "use strict"; const Benchmark = require("benchmark"); -const extend = require("xtend"); -const shallowClone = extend; const jsdomBenchmark = require("./jsdom-benchmark"); // jsdom might be an empty object if omitted by browserify @@ -57,14 +55,15 @@ function benchmarkFunctions(document, options) { module.exports = function documentSuite(optionsArg) { const options = typeof optionsArg === "function" ? { fn: optionsArg } : - shallowClone(optionsArg); + Object.assign({}, optionsArg); // default to async because that is required for defer:true const suite = options.suite || new Benchmark.Suite({ async: true }); delete options.suite; // do not pass to `Benchmark` if (nativeDoc) { - const newOptions = extend( + const newOptions = Object.assign( + {}, options, benchmarkFunctions(nativeDoc, options), { jsdomDocumentImplementation: "native" } @@ -75,7 +74,8 @@ module.exports = function documentSuite(optionsArg) { } if (jsdomDoc) { - const newOptions = extend( + const newOptions = Object.assign( + {}, options, benchmarkFunctions(jsdomDoc, options), { jsdomDocumentImplementation: "jsdom" } diff --git a/benchmark/jsdom-benchmark.js b/benchmark/jsdom-benchmark.js index <HASH>..<HASH> 100644 --- a/benchmark/jsdom-benchmark.js +++ b/benchmark/jsdom-benchmark.js @@ -1,11 +1,11 @@ "use strict"; const Benchmark = require("benchmark"); -const extend = require("xtend"); function noop() {} module.exports = function jsdomBenchmark(optionsArg) { - const options = extend( + const options = Object.assign( + {}, typeof optionsArg === "function" ? { fn: optionsArg } : optionsArg, { jsdomSetup: optionsArg.setup || noop, diff --git a/lib/jsdom.js b/lib/jsdom.js index <HASH>..<HASH> 100644 --- a/lib/jsdom.js +++ b/lib/jsdom.js @@ -5,7 +5,6 @@ const fs = require("fs"); const path = require("path"); -const xtend = require("xtend/mutable"); // TODO replace with Object.assign when io.js support is dropped. const CookieJar = require("tough-cookie").CookieJar; const toFileUrl = require("./jsdom/utils").toFileUrl; @@ -315,7 +314,7 @@ function getConfigFromArguments(args) { if (Array.isArray(arg)) { config.scripts = arg; } else { - xtend(config, arg); + Object.assign(config, arg); } break; } diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -31,8 +31,7 @@ "webidl-conversions": "^2.0.0", "whatwg-url-compat": "~0.6.5", "xml-name-validator": ">= 2.0.1 < 3.0.0", - "xmlhttprequest": ">= 1.6.0 < 2.0.0", - "xtend": "^4.0.0" + "xmlhttprequest": ">= 1.6.0 < 2.0.0" }, "devDependencies": { "benchmark": "1.0.0", diff --git a/test/browser-runner.js b/test/browser-runner.js index <HASH>..<HASH> 100644 --- a/test/browser-runner.js +++ b/test/browser-runner.js @@ -13,7 +13,6 @@ var runnerDisplay = require('./browser-display'); var portfinder = Q.denodeify(require('portfinder').getPort); var installSelenium = Q.denodeify(require('selenium-standalone').install); var startSeleniumCb = require('selenium-standalone').start; -var xtend = require('xtend/mutable'); var wd = require('wd'); var browser; @@ -142,7 +141,7 @@ function run() { function startSelenium(options) { return Q.promise(function (resolve) { - var newOptions = xtend({ spawnCb: resolve }, options); + var newOptions = Object.assign({ spawnCb: resolve }, options); startSeleniumCb(newOptions, function (err) { if (err) { reject(err);
Remove xtend dependency in favor of Object.assign
jsdom_jsdom
train
066ab17c79696d17916c50aecccff09fb7e07bd6
diff --git a/salt/version.py b/salt/version.py index <HASH>..<HASH> 100644 --- a/salt/version.py +++ b/salt/version.py @@ -1,2 +1,2 @@ -__version_info__ = (0, 9, 7) +__version_info__ = (0, 9, 8, 'pre') __version__ = '.'.join(map(str, __version_info__))
Make the release <I>.pre
saltstack_salt
train
e605fe105429cd7ee7c3e457f57c5df40356e8c7
diff --git a/src/test/java/net/mindengine/galen/tests/selenium/GalenSeleniumTest.java b/src/test/java/net/mindengine/galen/tests/selenium/GalenSeleniumTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/net/mindengine/galen/tests/selenium/GalenSeleniumTest.java +++ b/src/test/java/net/mindengine/galen/tests/selenium/GalenSeleniumTest.java @@ -114,9 +114,42 @@ public class GalenSeleniumTest { assertThat("Errors should be empty", errors.size(), is(0)); } + @Test + public void givesErrors_whenValidating_incorrectWebSite() throws Exception { + openDriverForBadPage(); + + PageSpec pageSpec = new PageSpecReader().read(getClass().getResourceAsStream("/html/page.spec")); + + driver.manage().window().setSize(new Dimension(400, 1000)); + + SeleniumPage page = new SeleniumPage(driver); + + TestValidationListener validationListener = new TestValidationListener(); + List<PageSection> pageSections = pageSpec.findSections("mobile"); + + assertThat("Filtered sections size should be", pageSections.size(), is(2)); + + SectionValidation sectionValidation = new SectionValidation(pageSections, new PageValidation(page, pageSpec), validationListener); + List<ValidationError> errors = sectionValidation.check(); + + assertThat("Invokations should", validationListener.getInvokations(), is("<o header>\n" + + "<SpecHeight header>\n" + + "<e><msg>\"header\" height is 140px which is not in range of 150 to 170px</msg></e>\n" + + "<o menu-item-home>\n" + + "<SpecHorizontally menu-item-home>\n" + + "<o menu-item-rss>\n" + + "<SpecHorizontally menu-item-rss>\n" + + "<SpecNear menu-item-rss>\n" + )); + assertThat("Errors should be empty", errors.size(), is(1)); + } + + private void openDriverForBadPage() { + driver.get("file://" + getClass().getResource("/html/page1.html").getPath()); + } + private void openDriverForNicePage() { - String path = "file://" + getClass().getResource("/html/page-nice.html").getPath(); - driver.get(path); + driver.get("file://" + getClass().getResource("/html/page-nice.html").getPath()); } } diff --git a/src/test/java/net/mindengine/galen/tests/specs/reader/PageSpecsReaderTest.java b/src/test/java/net/mindengine/galen/tests/specs/reader/PageSpecsReaderTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/net/mindengine/galen/tests/specs/reader/PageSpecsReaderTest.java +++ b/src/test/java/net/mindengine/galen/tests/specs/reader/PageSpecsReaderTest.java @@ -195,8 +195,6 @@ public class PageSpecsReaderTest { assertThat(exception.getSpecLine(), is(7)); } - //TODO write some negative tests for testing errors in page specs - private PageSpecReaderException expectExceptionFromReading(String file) throws IOException { try {
Added negative test for selenium tests
galenframework_galen
train
fbf899e8229ffe8bc0f261a335fa6d48ffb44797
diff --git a/app/models/spree/gateway/adyen_hpp.rb b/app/models/spree/gateway/adyen_hpp.rb index <HASH>..<HASH> 100644 --- a/app/models/spree/gateway/adyen_hpp.rb +++ b/app/models/spree/gateway/adyen_hpp.rb @@ -51,12 +51,12 @@ module Spree ActiveMerchant::Billing::Response.new(true, 'successful hpp payment') end - def capture(amount, source, currency:, **_opts) + def capture(amount, psp_reference, currency:, **_opts) value = { currency: currency, value: amount } handle_response( - provider.capture_payment(source.psp_reference, value), - source.psp_reference) + provider.capture_payment(psp_reference, value), + psp_reference) end # According to Spree Processing class API the response object should respond diff --git a/lib/spree/adyen/payment.rb b/lib/spree/adyen/payment.rb index <HASH>..<HASH> 100644 --- a/lib/spree/adyen/payment.rb +++ b/lib/spree/adyen/payment.rb @@ -7,7 +7,7 @@ module Spree::Adyen::Payment started_processing! # success state must remain as processing, it will change to completed # once the notification is received - gateway_action(source, :capture, :started_processing) + gateway_action(response_code, :capture, :started_processing) end def adyen_hpp_refund! diff --git a/spec/models/spree/gateway/adyen_hpp_spec.rb b/spec/models/spree/gateway/adyen_hpp_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/spree/gateway/adyen_hpp_spec.rb +++ b/spec/models/spree/gateway/adyen_hpp_spec.rb @@ -7,7 +7,7 @@ module Spree describe ".capture" do subject do - gateway.capture(2000, hpp_source, currency: "CAD") + gateway.capture(2000, hpp_source.psp_reference, currency: "CAD") end let(:response) do
Capture should take in the response code not source Changing this so it's more inline with how capture! works - it passes the response code and not the source as the first arg.
StemboltHQ_solidus-adyen
train
31bdd9647c70da3ec06b7cc96fb8ad4157f3ae20
diff --git a/Summarize.java b/Summarize.java index <HASH>..<HASH> 100644 --- a/Summarize.java +++ b/Summarize.java @@ -62,8 +62,8 @@ import hadooptrunk.TotalOrderPartitioner; import fi.tkk.ics.hadoop.bam.BAMInputFormat; import fi.tkk.ics.hadoop.bam.BAMRecordReader; -import fi.tkk.ics.hadoop.bam.customsamtools.BlockCompressedOutputStream; -import fi.tkk.ics.hadoop.bam.customsamtools.SAMRecord; +import fi.tkk.ics.hadoop.bam.custom.samtools.BlockCompressedOutputStream; +import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord; public final class Summarize extends Configured implements Tool { public static void main(String[] args) throws Exception {
Fix imports for hadoop-bam reorganization.
HadoopGenomics_Hadoop-BAM
train
2c0958a50cbfbdc0d4a8b7ed6b32635738488ddd
diff --git a/src/geshi.php b/src/geshi.php index <HASH>..<HASH> 100644 --- a/src/geshi.php +++ b/src/geshi.php @@ -1970,6 +1970,11 @@ class GeSHi { * @since 1.0.8 */ protected function build_parse_cache() { + // check whether language_data is available + if (empty($this->language_data)) { + return false; + } + // cache symbol regexp //As this is a costy operation, we avoid doing it for multiple groups ... //Instead we perform it for all symbols at once. @@ -2151,7 +2156,7 @@ class GeSHi { * * @since 1.0.0 */ - public function parse_code () { + public function parse_code() { // Start the timer $start_time = microtime(); @@ -2159,6 +2164,11 @@ class GeSHi { $code = str_replace("\r\n", "\n", $this->source); $code = str_replace("\r", "\n", $code); + // check whether language_data is available + if (empty($this->language_data)) { + $this->error = GESHI_ERROR_NO_SUCH_LANG; + } + // Firstly, if there is an error, we won't highlight if ($this->error) { //Escape the source for output
fix: prevent error with no language set
GeSHi_geshi-1.0
train
3d00ca09b9baf3482c17a23936ef836ea3fad3f2
diff --git a/sanic/response.py b/sanic/response.py index <HASH>..<HASH> 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -1,6 +1,12 @@ import ujson -STATUS_CODES = { +COMMON_STATUS_CODES = { + 200: b'OK', + 400: b'Bad Request', + 404: b'Not Found', + 500: b'Internal Server Error', +} +ALL_STATUS_CODES = { 100: b'Continue', 101: b'Switching Protocols', 102: b'Processing', @@ -89,6 +95,13 @@ class HTTPResponse: b'%b: %b\r\n' % (name.encode(), value.encode('utf-8')) for name, value in self.headers.items() ) + + # Try to pull from the common codes first + # Speeds up response rate 6% over pulling from all + status = COMMON_STATUS_CODES.get(self.status) + if not status: + status = ALL_STATUS_CODES.get(self.status) + return (b'HTTP/%b %d %b\r\n' b'Content-Type: %b\r\n' b'Content-Length: %d\r\n' @@ -97,7 +110,7 @@ class HTTPResponse: b'%b') % ( version.encode(), self.status, - STATUS_CODES.get(self.status, b'FAIL'), + status, self.content_type.encode(), len(self.body), b'keep-alive' if keep_alive else b'close',
Added fast lookup dict for common response codes
huge-success_sanic
train
7c2c6d834bf1ac3bd00991601fa1d57e3427b4dc
diff --git a/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/golang/GolangGenerator.java b/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/golang/GolangGenerator.java index <HASH>..<HASH> 100644 --- a/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/golang/GolangGenerator.java +++ b/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/golang/GolangGenerator.java @@ -568,7 +568,6 @@ public class GolangGenerator implements CodeGenerator init.append("\treturn\n}\n"); } - // Newer messages and groups can add extra properties before the variable // length elements (groups and varData). We read past the difference // between the message's blockLength and our (older) schema's blockLength diff --git a/sbe-tool/src/main/java/uk/co/real_logic/sbe/ir/Encoding.java b/sbe-tool/src/main/java/uk/co/real_logic/sbe/ir/Encoding.java index <HASH>..<HASH> 100644 --- a/sbe-tool/src/main/java/uk/co/real_logic/sbe/ir/Encoding.java +++ b/sbe-tool/src/main/java/uk/co/real_logic/sbe/ir/Encoding.java @@ -213,7 +213,6 @@ public class Encoding return primitiveType.minValue(); } - /** * The most applicable max value for the encoded type. *
[Java] Fix extra empty line
real-logic_simple-binary-encoding
train
5de62dfb031365c587dd2adb113ac50e8304df94
diff --git a/lib/nform/builder.rb b/lib/nform/builder.rb index <HASH>..<HASH> 100644 --- a/lib/nform/builder.rb +++ b/lib/nform/builder.rb @@ -122,7 +122,7 @@ module NForm def detect_object_name(o) if o.is_a?(Symbol) o.to_s - elsif o.respond_to?(:name) + elsif o.is_a?(Class) o.name elsif o.respond_to?(:object_name) o.object_name
Be more explicit when detecting class name so object instances that happen to have a name method don't lead to nutty object and collection names
burlesona_nform
train
8595fe6a35a729e749fc81db5bbc8bf58e8257b6
diff --git a/cmd/helm/search_hub.go b/cmd/helm/search_hub.go index <HASH>..<HASH> 100644 --- a/cmd/helm/search_hub.go +++ b/cmd/helm/search_hub.go @@ -50,7 +50,7 @@ func newSearchHubCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "hub [keyword]", - Short: "search for a keyword in charts", + Short: "search for charts in the Helm Hub or an instance of Monocular", Long: searchHubDesc, RunE: func(cmd *cobra.Command, args []string) error { return o.run(out, args) @@ -59,7 +59,7 @@ func newSearchHubCmd(out io.Writer) *cobra.Command { f := cmd.Flags() f.StringVar(&o.searchEndpoint, "endpoint", "https://hub.helm.sh", "monocular instance to query for charts") - f.UintVar(&o.maxColWidth, "maxColumnWidth", 50, "maximum column width for output table") + f.UintVar(&o.maxColWidth, "max-col-width", 50, "maximum column width for output table") return cmd } diff --git a/cmd/helm/search_repo.go b/cmd/helm/search_repo.go index <HASH>..<HASH> 100644 --- a/cmd/helm/search_repo.go +++ b/cmd/helm/search_repo.go @@ -54,7 +54,7 @@ func newSearchRepoCmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "repo [keyword]", - Short: "search for a keyword in charts", + Short: "search repositories for a keyword in charts", Long: searchRepoDesc, RunE: func(cmd *cobra.Command, args []string) error { return o.run(out, args) @@ -65,7 +65,7 @@ func newSearchRepoCmd(out io.Writer) *cobra.Command { f.BoolVarP(&o.regexp, "regexp", "r", false, "use regular expressions for searching repositories you have added") f.BoolVarP(&o.versions, "versions", "l", false, "show the long listing, with each version of each chart on its own line, for repositories you have added") f.StringVar(&o.version, "version", "", "search using semantic versioning constraints on repositories you have added") - f.UintVar(&o.maxColWidth, "maxColumnWidth", 50, "maximum column width for output table") + f.UintVar(&o.maxColWidth, "max-col-width", 50, "maximum column width for output table") return cmd }
Updating the search language and flags for consistency
helm_helm
train
b6564bbb871e3b86794872de04cd8c9913b9a72a
diff --git a/arcana/version_.py b/arcana/version_.py index <HASH>..<HASH> 100644 --- a/arcana/version_.py +++ b/arcana/version_.py @@ -1 +1 @@ -__version__ = '0.2.5' +__version__ = '0.2.6'
upped version to <I>
MonashBI_arcana
train
070b4b1c215f0f4d24884248c5b0bf5524a42064
diff --git a/framework/core/js/src/forum/compat.js b/framework/core/js/src/forum/compat.js index <HASH>..<HASH> 100644 --- a/framework/core/js/src/forum/compat.js +++ b/framework/core/js/src/forum/compat.js @@ -9,6 +9,10 @@ import DiscussionControls from './utils/DiscussionControls'; import alertEmailConfirmation from './utils/alertEmailConfirmation'; import UserControls from './utils/UserControls'; import Pane from './utils/Pane'; +import DiscussionListState from './state/DiscussionListState'; +import GlobalSearchState from './states/GlobalSearchState'; +import NotificationListState from './states/NotificationListState'; +import SearchState from './states/SearchState'; import DiscussionPage from './components/DiscussionPage'; import LogInModal from './components/LogInModal'; import ComposerBody from './components/ComposerBody'; @@ -77,6 +81,10 @@ export default Object.assign(compat, { 'utils/alertEmailConfirmation': alertEmailConfirmation, 'utils/UserControls': UserControls, 'utils/Pane': Pane, + 'states/DiscussionListState': DiscussionListState, + 'states/GlobalSearchState': GlobalSearchState, + 'states/NotificationListState': NotificationListState, + 'states/SearchState': SearchState, 'components/DiscussionPage': DiscussionPage, 'components/LogInModal': LogInModal, 'components/ComposerBody': ComposerBody,
Expose state classes via compat This way, they can be extended by extensions.
flarum_core
train
3177e6742f617504195b82b9a01e3832d87e16be
diff --git a/test/support/coerceable_test_sqlserver.rb b/test/support/coerceable_test_sqlserver.rb index <HASH>..<HASH> 100644 --- a/test/support/coerceable_test_sqlserver.rb +++ b/test/support/coerceable_test_sqlserver.rb @@ -11,17 +11,13 @@ module ARTest module ClassMethods - def coerce_tests(*methods) + def coerce_tests!(*methods) methods.each do |method| self.coerced_tests.push(method) coerced_test_warning(method) end end - def coerce_test!(method) - coerced_test_warning(method) - end - def coerce_all_tests! once = false instance_methods(false).each do |method| @@ -32,14 +28,11 @@ module ARTest STDOUT.puts "Info: Undefined all tests: #{self.name}" end - def method_added(method) - coerced_test_warning(method) if coerced_tests.include?(method.to_sym) - end - private def coerced_test_warning(method) - result = undef_method(method) rescue nil + method = instance_methods(false).detect { |m| m =~ method } if method.is_a?(Regexp) + result = undef_method(method) if method && method_defined?(method) STDOUT.puts "Info: Undefined coerced test: #{self.name}##{method}" unless result.blank? end
Allow coerced tests to be a Regexp.
rails-sqlserver_activerecord-sqlserver-adapter
train
7eda0d037951e653aeefa9b7c437df0d9b2fefb6
diff --git a/tests/test_connection.py b/tests/test_connection.py index <HASH>..<HASH> 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -76,3 +76,31 @@ class TestConnection(object): @raises(xcffib.XcffibException) def test_wait_for_nonexistent_request(self): self.conn.wait_for_reply(10) + + def test_create_window_wire(self): + expected = '\x00\x08\x00\x00\x00\x00 \x00J\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01\x00\x00\x00\x01\x00!\x00\x00\x00\x02\x08\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00' + + def fake_send(opcode, data, cookie=None, reply=None): + return data + + self.xproto.send_request = fake_send + + wid = self.conn.generate_id() + default_screen = self.conn.setup.roots[self.conn.pref_screen] + encoded = self.xproto.CreateWindow( + default_screen.root_depth, + wid, + default_screen.root, + 0, 0, 1, 1, # xywh + 0, + xcffib.xproto.WindowClass.InputOutput, + default_screen.root_visual, + xcffib.xproto.CW.BackPixel | xcffib.xproto.CW.EventMask, + [ + default_screen.black_pixel, + xcffib.xproto.EventMask.StructureNotify + ] + ) + + actual = bytes(encoded.getvalue()) + assert actual == expected
Add wire packing test for CreateWindow
tych0_xcffib
train
f6dd36d14402382d0e37f458328f8d6c4b9fb34b
diff --git a/resources/js/controllers/fields/radiobutton_controller.js b/resources/js/controllers/fields/radiobutton_controller.js index <HASH>..<HASH> 100644 --- a/resources/js/controllers/fields/radiobutton_controller.js +++ b/resources/js/controllers/fields/radiobutton_controller.js @@ -8,7 +8,10 @@ export default class extends Controller { event.target.offsetParent.querySelectorAll('input').forEach((input) => { input.removeAttribute('checked'); }); - + event.target.offsetParent.querySelectorAll('label').forEach((label) => { + label.classList.remove('active'); + }); + event.target.classList.add('active'); event.target.setAttribute('checked', 'checked'); event.target.dispatchEvent(new Event("change")); }
:bug: fixed display of the active radio button (#<I>)
orchidsoftware_platform
train
48d44221a9868bc853a036e64f272ef2a0b6540a
diff --git a/cmd/minikube/cmd/start.go b/cmd/minikube/cmd/start.go index <HASH>..<HASH> 100644 --- a/cmd/minikube/cmd/start.go +++ b/cmd/minikube/cmd/start.go @@ -252,7 +252,9 @@ func provisionWithDriver(cmd *cobra.Command, ds registry.DriverState, existing * validateFlags(cmd, driverName) validateUser(driverName) - validateDockerStorageDriver(driverName) + if driverName == oci.Docker { + validateDockerStorageDriver(driverName) + } // Download & update the driver, even in --download-only mode if !viper.GetBool(dryRun) {
Don't validate Docker storage driver for Podman For podman, "overlay" and "overlay2" are the same
kubernetes_minikube
train
a432b3d466132e446e2c452a9012bb576cf9f361
diff --git a/examples/run_squad.py b/examples/run_squad.py index <HASH>..<HASH> 100644 --- a/examples/run_squad.py +++ b/examples/run_squad.py @@ -234,10 +234,11 @@ def main(): train_sampler = RandomSampler(train_data) else: train_sampler = DistributedSampler(train_data) + train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size) num_train_optimization_steps = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs - if args.local_rank != -1: - num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size() + # if args.local_rank != -1: + # num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size() # Prepare optimizer param_optimizer = list(model.named_parameters())
distributed traing t_total
huggingface_pytorch-pretrained-BERT
train
72f9bcce98b85be9eae91b2e3d3786b2828a9b6e
diff --git a/tests/RollbarTest.php b/tests/RollbarTest.php index <HASH>..<HASH> 100644 --- a/tests/RollbarTest.php +++ b/tests/RollbarTest.php @@ -27,19 +27,6 @@ class RollbarTest extends BaseRollbarTest Rollbar::destroy(); } - public function testProfileInit() - { - $acceptable = 0.005; - $start = microtime(true); - Rollbar::init(self::$simpleConfig); - $finish = microtime(true); - $performance = $finish - $start; - $this->assertTrue( - $performance < $acceptable, - "Execution time of Rollbar::init ($performance sec) exceeded acceptable threshold of $acceptable sec." - ); - } - public function testInitWithConfig() { Rollbar::init(self::$simpleConfig);
<I>: fix prefix_unary_operator error on hhvm
rollbar_rollbar-php
train
6b7bc3dca22bdcd40c6eaf0edbfc8eb965c0733d
diff --git a/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/AbstractESContentIndexClientIteratorSource.java b/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/AbstractESContentIndexClientIteratorSource.java index <HASH>..<HASH> 100644 --- a/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/AbstractESContentIndexClientIteratorSource.java +++ b/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/AbstractESContentIndexClientIteratorSource.java @@ -33,5 +33,15 @@ public abstract class AbstractESContentIndexClientIteratorSource<T> implements I this.space = space; } - public abstract Collection<T> getNext(); + protected abstract Collection<T> getNextImpl(); + + public final Collection<T> getNext() { + Collection<T> collection = getNextImpl(); + if(collection.size() > 0) { + pageNum++; + return collection; + } else { + return null; + } + } } diff --git a/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/ESContentIndexClientContentIdIteratorSource.java b/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/ESContentIndexClientContentIdIteratorSource.java index <HASH>..<HASH> 100644 --- a/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/ESContentIndexClientContentIdIteratorSource.java +++ b/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/ESContentIndexClientContentIdIteratorSource.java @@ -23,14 +23,10 @@ public class ESContentIndexClientContentIdIteratorSource extends AbstractESConte super(contentIndexClient, account, storeId, space); } - public Collection<String> getNext() { - Collection<String> contentIds = contentIndexClient.getSpaceContentIds( + @Override + protected Collection<String> getNextImpl() { + return contentIndexClient.getSpaceContentIds( account, storeId, space, pageNum, contentIndexClient.getPageSize()); - if(contentIds.size() > 0) { - pageNum++; - return contentIds; - } else { - return null; - } + } } diff --git a/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/ESContentIndexClientContentIteratorSource.java b/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/ESContentIndexClientContentIteratorSource.java index <HASH>..<HASH> 100644 --- a/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/ESContentIndexClientContentIteratorSource.java +++ b/content-index-client/src/main/java/org/duracloud/contentindex/client/iterator/ESContentIndexClientContentIteratorSource.java @@ -7,11 +7,11 @@ */ package org.duracloud.contentindex.client.iterator; +import java.util.Collection; + import org.duracloud.contentindex.client.ContentIndexItem; import org.duracloud.contentindex.client.ESContentIndexClient; -import java.util.Collection; - /** * @author Erik Paulsson * Date: 5/8/14 @@ -24,14 +24,8 @@ public class ESContentIndexClientContentIteratorSource extends AbstractESContent super(contentIndexClient, account, storeId, space); } - public Collection<ContentIndexItem> getNext() { - Collection<ContentIndexItem> items = contentIndexClient.getSpaceContents( + protected Collection<ContentIndexItem> getNextImpl() { + return contentIndexClient.getSpaceContents( account, storeId, space, pageNum, contentIndexClient.getPageSize()); - if(items.size() > 0) { - pageNum++; - return items; - } else { - return null; - } } }
Minor refactor of the ESContentIndexClientIteratorSources to remove duplicate logic.
duracloud_duracloud
train
cb4eca6f82bfb20df12b89b4c10122a547a902b2
diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -44,7 +44,7 @@ describe Restforce do 'SALESFORCE_PROXY_URI' => 'proxy', 'SALESFORCE_HOST' => 'test.host.com', 'SALESFORCE_API_VERSION' => '37.0' }. - each { |var, value| ENV.stub(:[]).with(var).and_return(value) } + each { |var, value| ENV.stub(:fetch).with(var, anything).and_return(value) } end its(:username) { should eq 'foo' }
Update the tests to handle Rubocop autocorrections in <I>dec
restforce_restforce
train
7e90827bf3ec4c081d4ec35bd1a481a27cfa0701
diff --git a/ayrton/tests/test_ayrton.py b/ayrton/tests/test_ayrton.py index <HASH>..<HASH> 100644 --- a/ayrton/tests/test_ayrton.py +++ b/ayrton/tests/test_ayrton.py @@ -79,17 +79,23 @@ class HardExpansion(unittest.TestCase): pass class A(object): + def __init__ (self, buf): + self.buffer= buf + # make someone happy def flush (self): pass + # make someone else happy + def write (self, o): + self.buffer.write (bytes (o, 'utf-8')) + class CommandExecution (unittest.TestCase): # for the moment I will just test my changes over sh.Command def testStdOut (self): old_stdout= sys.stdout - a= A () - a.buffer= io.BytesIO () + a= A (io.BytesIO ()) sys.stdout= a # do the test @@ -99,12 +105,38 @@ class CommandExecution (unittest.TestCase): # restore sanity sys.stdout= old_stdout + def testStdEqNone (self): + old_stdout= sys.stdout + a= A (io.BytesIO ()) + sys.stdout= a + + # do the test + ayrton.main ('echo ("foo", _out=None)') + # the output is empty, as it went to /dev/null + self.assertEqual (a.buffer.getvalue (), b'') + + # restore sanity + sys.stdout= old_stdout + + def testStdEqCapture (self): + old_stdout= sys.stdout + a= A (io.BytesIO ()) + sys.stdout= a + + # do the test + ayrton.main ('f= echo ("foo", _out=Capture); print ("echo: %s" % f)') + # the output is empty, as it went to /dev/null + # BUG: check why tehre's asecond \n + self.assertEqual (a.buffer.getvalue (), b'echo: foo\n\n') + + # restore sanity + sys.stdout= old_stdout + class ExportTest (unittest.TestCase): def testEnviron (self): old_stdout= sys.stdout - a= A () - a.buffer= io.BytesIO () + a= A (io.BytesIO ()) sys.stdout= a ayrton.main ('export (TEST_ENV=42); run ("./ayrton/tests/data/test_environ.sh")')
+ more output tests covering None and Capture.
StyXman_ayrton
train
54cd369ecf63c90a57b8262c2ba64764f7ae807a
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -5,6 +5,7 @@ from setuptools.command.sdist import sdist as _sdist import re import sys import time +import codecs import subprocess if sys.version < "2.2.3": from distutils.dist import DistributionMetadata @@ -13,7 +14,7 @@ if sys.version < "2.2.3": # Workaround for problems caused by this import # It's either this or hardcoding the version. -#from pyrax.version import version +# from pyrax.version import version with open("pyrax/version.py", "rt") as vfile: version_text = vfile.read() vmatch = re.search(r'version ?= ?"(.+)"$', version_text) @@ -24,6 +25,7 @@ version = vmatch.groups()[0] # zero for the next development cycle release = '0' + class sdist(_sdist): """ custom sdist command, to prep pyrax.spec file """ @@ -56,12 +58,21 @@ class sdist(_sdist): # Run parent constructor _sdist.run(self) +# Get the long description from the relevant file +try: + f = codecs.open('README.rst', encoding='utf-8') + long_description = f.read() + f.close() +except: + long_description = '' + testing_requires = ["mock"] setup( name="pyrax", version=version, description="Python language bindings for OpenStack Clouds.", + long_description=long_description, author="Rackspace", author_email="sdk-support@rackspace.com", url="https://github.com/rackspace/pyrax", @@ -82,5 +93,5 @@ setup( "pyrax", "pyrax/identity", ], - cmdclass = {'sdist': sdist} + cmdclass={'sdist': sdist} )
Use README.rst as the long_description
pycontribs_pyrax
train
46520fb31b00f1ae4d350f1aa546961a49f8791c
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index <HASH>..<HASH> 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -18,6 +18,8 @@ Next Release (TBD) (`#500 <https://github.com/aws/chalice/issues/500>`__) * Add support for Builtin Authorizers in local mode (`#404 <https://github.com/aws/chalice/issues/404>`__) +* Allow view to require API keys as well as authorization + (`#473 <https://github.com/aws/chalice/pull/473/>`__) 1.0.1 diff --git a/chalice/deploy/swagger.py b/chalice/deploy/swagger.py index <HASH>..<HASH> 100644 --- a/chalice/deploy/swagger.py +++ b/chalice/deploy/swagger.py @@ -124,9 +124,10 @@ class SwaggerGenerator(object): # to the security definitions. We have to someone indicate # this because this neeeds to be added to the global config # file. - current['security'] = [{'api_key': []}] + current.setdefault('security', []).append({'api_key': []}) if view.authorizer: - current['security'] = [{view.authorizer.name: []}] + current.setdefault('security', []).append( + {view.authorizer.name: []}) if view.view_args: self._add_view_args(current, view.view_args) return current diff --git a/tests/unit/deploy/test_swagger.py b/tests/unit/deploy/test_swagger.py index <HASH>..<HASH> 100644 --- a/tests/unit/deploy/test_swagger.py +++ b/tests/unit/deploy/test_swagger.py @@ -312,6 +312,22 @@ def test_can_use_authorizer_object(sample_app, swagger_gen): } +def test_can_use_api_key_and_authorizers(sample_app, swagger_gen): + authorizer = CustomAuthorizer( + 'MyAuth', authorizer_uri='auth-uri', header='Authorization') + + @sample_app.route('/auth', authorizer=authorizer, api_key_required=True) + def auth(): + return {'foo': 'bar'} + + doc = swagger_gen.generate_swagger(sample_app) + single_method = doc['paths']['/auth']['get'] + assert single_method.get('security') == [ + {'api_key': []}, + {'MyAuth': []}, + ] + + def test_can_use_iam_authorizer_object(sample_app, swagger_gen): authorizer = IAMAuthorizer()
Add support for api_key_required and authorizer in a view This pulls in #<I> and adds a test for it.
aws_chalice
train
7930fd649a47b31f2135780ad3d99e6fd078c83c
diff --git a/lib/mittsu/core/object_3d.rb b/lib/mittsu/core/object_3d.rb index <HASH>..<HASH> 100644 --- a/lib/mittsu/core/object_3d.rb +++ b/lib/mittsu/core/object_3d.rb @@ -239,7 +239,7 @@ module Mittsu target.set(0.0, 0.0, 1.0).apply_quaternion(@_quaternion) end - def raycast; end + def raycast(raycaster, intersects); end def traverse(&callback) callback.yield self diff --git a/lib/mittsu/core/raycaster.rb b/lib/mittsu/core/raycaster.rb index <HASH>..<HASH> 100644 --- a/lib/mittsu/core/raycaster.rb +++ b/lib/mittsu/core/raycaster.rb @@ -41,11 +41,11 @@ module Mittsu end end - def intersect_object(object, recursive) + def intersect_object(object, recursive = false) intersects = [] intersect(object, intersects, recursive) intersects.sort do |a, b| - a.distance <=> b.distance + a[:distance] <=> b[:distance] end end @@ -70,8 +70,10 @@ module Mittsu def intersect(object, intersects, recursive) object.raycast(self, intersects) - object.children.each do |child| - intersect(chil, intersects, true) + if recursive + object.children.each do |child| + intersect(child, intersects, true) + end end end end
fix: raycasting not working for Groups and OBJ loaded objects
jellymann_mittsu
train
00b9b572328b0f8b8764988659423ef010cf7f0d
diff --git a/Processor.php b/Processor.php index <HASH>..<HASH> 100644 --- a/Processor.php +++ b/Processor.php @@ -2051,7 +2051,7 @@ class Processor return $this->blankNodeMap[$id]; } - $bnode = '_:t' . $this->blankNodeCounter++; + $bnode = '_:b' . $this->blankNodeCounter++; $this->blankNodeMap[$id] = $bnode; return $bnode;
Use "_:b" as blank node identifier prefix instead of "_:t"
lanthaler_JsonLD
train
53ade5e8721a343890b8007da63e57a850798bf2
diff --git a/rafthttp/msgappv2_codec.go b/rafthttp/msgappv2_codec.go index <HASH>..<HASH> 100644 --- a/rafthttp/msgappv2_codec.go +++ b/rafthttp/msgappv2_codec.go @@ -86,12 +86,12 @@ func (enc *msgAppV2Encoder) encode(m *raftpb.Message) error { start := time.Now() switch { case isLinkHeartbeatMessage(m): - enc.uint8buf[0] = byte(msgTypeLinkHeartbeat) + enc.uint8buf[0] = msgTypeLinkHeartbeat if _, err := enc.w.Write(enc.uint8buf); err != nil { return err } case enc.index == m.Index && enc.term == m.LogTerm && m.LogTerm == m.Term: - enc.uint8buf[0] = byte(msgTypeAppEntries) + enc.uint8buf[0] = msgTypeAppEntries if _, err := enc.w.Write(enc.uint8buf); err != nil { return err } @@ -179,7 +179,7 @@ func (dec *msgAppV2Decoder) decode() (raftpb.Message, error) { if _, err := io.ReadFull(dec.r, dec.uint8buf); err != nil { return m, err } - typ = uint8(dec.uint8buf[0]) + typ = dec.uint8buf[0] switch typ { case msgTypeLinkHeartbeat: return linkHeartbeatMessage, nil diff --git a/rafthttp/peer.go b/rafthttp/peer.go index <HASH>..<HASH> 100644 --- a/rafthttp/peer.go +++ b/rafthttp/peer.go @@ -256,7 +256,7 @@ func (p *peer) send(m raftpb.Message) { zap.String("message-type", m.Type.String()), zap.String("local-member-id", p.localID.String()), zap.String("from", types.ID(m.From).String()), - zap.String("remote-peer-id", types.ID(p.id).String()), + zap.String("remote-peer-id", p.id.String()), zap.Bool("remote-peer-active", p.status.isActive()), ) } else { @@ -269,7 +269,7 @@ func (p *peer) send(m raftpb.Message) { zap.String("message-type", m.Type.String()), zap.String("local-member-id", p.localID.String()), zap.String("from", types.ID(m.From).String()), - zap.String("remote-peer-id", types.ID(p.id).String()), + zap.String("remote-peer-id", p.id.String()), zap.Bool("remote-peer-active", p.status.isActive()), ) } else { diff --git a/rafthttp/remote.go b/rafthttp/remote.go index <HASH>..<HASH> 100644 --- a/rafthttp/remote.go +++ b/rafthttp/remote.go @@ -62,7 +62,7 @@ func (g *remote) send(m raftpb.Message) { zap.String("message-type", m.Type.String()), zap.String("local-member-id", g.localID.String()), zap.String("from", types.ID(m.From).String()), - zap.String("remote-peer-id", types.ID(g.id).String()), + zap.String("remote-peer-id", g.id.String()), zap.Bool("remote-peer-active", g.status.isActive()), ) } else { @@ -75,7 +75,7 @@ func (g *remote) send(m raftpb.Message) { zap.String("message-type", m.Type.String()), zap.String("local-member-id", g.localID.String()), zap.String("from", types.ID(m.From).String()), - zap.String("remote-peer-id", types.ID(g.id).String()), + zap.String("remote-peer-id", g.id.String()), zap.Bool("remote-peer-active", g.status.isActive()), ) } else {
rafthttp: fix "unconvert" warnings
etcd-io_etcd
train
ccba6ea46d1f1db099406a5a963e20766da6ed72
diff --git a/lib/console-reporter.js b/lib/console-reporter.js index <HASH>..<HASH> 100644 --- a/lib/console-reporter.js +++ b/lib/console-reporter.js @@ -414,13 +414,13 @@ function excludeFromReporting(name) { } function printRates(rates, report) { - return rates.map((name) => { + return rates.sort().map((name) => { return util.padded(`${trimName(name)}:`, report.rates[name]) + '/sec'; }); } function printCounters(counters, report) { - return counters.map((name) => { + return counters.sort().map((name) => { const value = report.counters[name]; return util.padded(`${trimName(name)}:`, value); });
feat(console-reporter): print metrics in alphabetical order
artilleryio_artillery
train
ed9b6b39a9d1d4a7834076bcef416e7873fca4ed
diff --git a/lib/shelly/app.rb b/lib/shelly/app.rb index <HASH>..<HASH> 100644 --- a/lib/shelly/app.rb +++ b/lib/shelly/app.rb @@ -4,7 +4,8 @@ require 'shelly/backup' module Shelly class App < Model - DATABASE_KINDS = %w(postgresql mongodb redis none) + DATABASE_KINDS = %w(postgresql mongodb redis) + DATABASE_CHOICES = DATABASE_KINDS + %w(none) SERVER_SIZES = %w(small large) attr_accessor :code_name, :databases, :ruby_version, :environment, diff --git a/lib/shelly/cli/main.rb b/lib/shelly/cli/main.rb index <HASH>..<HASH> 100644 --- a/lib/shelly/cli/main.rb +++ b/lib/shelly/cli/main.rb @@ -71,7 +71,7 @@ module Shelly method_option "code-name", :type => :string, :aliases => "-c", :desc => "Unique code-name of your cloud" method_option :databases, :type => :array, :aliases => "-d", - :banner => Shelly::App::DATABASE_KINDS.join(', '), + :banner => Shelly::App::DATABASE_CHOICES.join(', '), :desc => "List of databases of your choice" method_option :size, :type => :string, :aliases => "-s", :desc => "Server size [large, small]" @@ -417,7 +417,7 @@ We have been notified about it. We will be adding new resources shortly} def valid_databases?(databases) return true unless databases.present? - kinds = Shelly::App::DATABASE_KINDS + kinds = Shelly::App::DATABASE_CHOICES databases.all? { |kind| kinds.include?(kind) } end @@ -452,7 +452,7 @@ We have been notified about it. We will be adding new resources shortly} end def ask_for_databases - kinds = Shelly::App::DATABASE_KINDS + kinds = Shelly::App::DATABASE_CHOICES databases = ask("Which database do you want to use #{kinds.join(", ")} (postgresql - default):") begin databases = databases.split(/[\s,]/).reject(&:blank?) diff --git a/lib/shelly/templates/Cloudfile.erb b/lib/shelly/templates/Cloudfile.erb index <HASH>..<HASH> 100644 --- a/lib/shelly/templates/Cloudfile.erb +++ b/lib/shelly/templates/Cloudfile.erb @@ -12,9 +12,12 @@ thin: <%= @thin %> # whenever: on # delayed_job: 1 - <%- if @databases.present? -%> databases: + <%- if @databases.present? -%> <%- @databases.each do |kind| -%> - <%= kind %> <%- end -%> - <%- end -%> + <%- end -%> + <%- (Shelly::App::DATABASE_KINDS - @databases).each do |kind| -%> + # - <%= kind %> + <%- end -%> diff --git a/spec/shelly/cloudfile_spec.rb b/spec/shelly/cloudfile_spec.rb index <HASH>..<HASH> 100644 --- a/spec/shelly/cloudfile_spec.rb +++ b/spec/shelly/cloudfile_spec.rb @@ -53,6 +53,7 @@ foo-staging: databases: - postgresql - mongodb + # - redis config @cloudfile.generate.should == expected @@ -80,6 +81,7 @@ foo-staging: databases: - postgresql - mongodb + # - redis config @cloudfile.generate.should == expected end
Not used databases are added as comment to Cloudfile. If database is not used, it's still put in the Cloudfile just for reference.
Ragnarson_shelly
train
79e6471145c49d8d03bf0a26ed4297015f567df9
diff --git a/lib/japr/pipeline.rb b/lib/japr/pipeline.rb index <HASH>..<HASH> 100644 --- a/lib/japr/pipeline.rb +++ b/lib/japr/pipeline.rb @@ -158,9 +158,7 @@ module JAPR # Bundle multiple assets into a single asset def bundle - content = @assets.map do |a| - a.content - end.join("\n") + content = @assets.map(&:content).join("\n") hash = JAPR::Pipeline.hash(@source, @manifest, @options) @assets = [JAPR::Asset.new(content, "#{@prefix}-#{hash}#{@type}")] diff --git a/spec/helpers/extensions/ruby/module.rb b/spec/helpers/extensions/ruby/module.rb index <HASH>..<HASH> 100644 --- a/spec/helpers/extensions/ruby/module.rb +++ b/spec/helpers/extensions/ruby/module.rb @@ -9,6 +9,6 @@ # => true class Module def extend?(object) - kind_of?(object) + is_a?(object) end end
Minor refactoring (to pass rubocop test)
janosrusiczki_japr
train
27470c0e8dac2ac82ae44d6366f17fd644c3cea4
diff --git a/src/webui/src/components/Header/index.js b/src/webui/src/components/Header/index.js index <HASH>..<HASH> 100644 --- a/src/webui/src/components/Header/index.js +++ b/src/webui/src/components/Header/index.js @@ -3,7 +3,9 @@ import {Button, Dialog, Input, MessageBox} from 'element-react'; import styled from 'styled-components'; import API from '../../../utils/api'; import storage from '../../../utils/storage'; -import _ from 'lodash'; +import isString from 'lodash/isString'; +import get from 'lodash/get'; +import isNumber from 'lodash/isNumber'; import {Link} from 'react-router-dom'; import classes from './header.scss'; @@ -60,7 +62,7 @@ export default class Header extends React.Component { storage.setItem('username', resp.data.username); location.reload(); } catch (e) { - if (_.get(e, 'response.status', 0) === 401) { + if (get(e, 'response.status', 0) === 401) { MessageBox.alert(e.response.data.error); } else { MessageBox.alert('Unable to login:' + e.message); @@ -70,7 +72,7 @@ export default class Header extends React.Component { get isTokenExpire() { let token = storage.getItem('token'); - if (!_.isString(token)) return true; + if (!isString(token)) return true; let payload = token.split('.')[1]; if (!payload) return true; try { @@ -79,7 +81,7 @@ export default class Header extends React.Component { console.error('Invalid token:', err, token); // eslint-disable-line return false; } - if (!payload.exp || !_.isNumber(payload.exp)) return true; + if (!payload.exp || !isNumber(payload.exp)) return true; let jsTimestamp = (payload.exp * 1000) - 30000; // Report as expire before (real expire time - 30s) let expired = Date.now() >= jsTimestamp;
fix: avoid include complete lodash library to the bundle, save <I>kb.
verdaccio_verdaccio
train
97cf41a7db265a6fd069151b915bcfdaee498541
diff --git a/src/xqt/wrappers/pyqt4.py b/src/xqt/wrappers/pyqt4.py index <HASH>..<HASH> 100644 --- a/src/xqt/wrappers/pyqt4.py +++ b/src/xqt/wrappers/pyqt4.py @@ -33,13 +33,13 @@ from ..lazyload import lazy_import # define wrappers def py2q(py_object): - if QtCore.QT_VERSION < 264198: + if SIP_VERSION != '2' and QtCore.QT_VERSION < 264198: return QtCore.QVariant(py_object) else: return py_object def q2py(q_variant, default=None): - if not isinstance(q_variant, QtCore.QVariant): + if SIP_VERSION == '2' or not isinstance(q_variant, QtCore.QVariant): return q_variant elif QtCore.QT_VERSION < 264198: return q_variant.toPyObject() if not q_variant.isNull() else default
checking the SIP version to decide if QVariant is needed or not
bitesofcode_xqt
train
c6ad9b0e8d96cd4d98502e77d6d2552b32501067
diff --git a/global-styles.js b/global-styles.js index <HASH>..<HASH> 100644 --- a/global-styles.js +++ b/global-styles.js @@ -13,12 +13,6 @@ $_documentContainer.setAttribute('style', 'display: none;'); $_documentContainer.innerHTML = `<custom-style> <style is="custom-style"> - * { - font-size: 1.2em; - line-height: 1.2em; - /* Not sure why this does not have an affect when inside html style declaration */ - --paper-input-container-shared-input-style_-_line-height: 1.2em; - } html { --document-background-color: #FAFAFA; --primary-color-dark: #212a3f; @@ -43,8 +37,6 @@ $_documentContainer.innerHTML = `<custom-style> h1, h2, h3, h4, h5 { @apply --paper-font-common-base; color: var(--primary-text-color); - font-weight: 400; - font-size: 2em; margin: 25px 0px 5px 15px; } </style>
Remove styles that have global scope as to not interfere with apps that use this
Tangerine-Community_tangy-form
train
1ce5db6c0a85907f13a5c733e9adfd460114ca97
diff --git a/src/test/java/com/lambdaworks/redis/AbstractRedisClientTest.java b/src/test/java/com/lambdaworks/redis/AbstractRedisClientTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/lambdaworks/redis/AbstractRedisClientTest.java +++ b/src/test/java/com/lambdaworks/redis/AbstractRedisClientTest.java @@ -2,8 +2,6 @@ package com.lambdaworks.redis; -import java.util.concurrent.TimeUnit; - import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -33,8 +31,26 @@ public abstract class AbstractRedisClientTest extends AbstractTest { public void openConnection() throws Exception { client.setOptions(new ClientOptions.Builder().build()); redis = connect(); - redis.flushall(); - redis.flushdb(); + boolean scriptRunning; + do { + + scriptRunning = false; + + try { + redis.flushall(); + redis.flushdb(); + } catch (RedisException e) { + if (e.getMessage() != null && e.getMessage().contains("BUSY")) { + scriptRunning = true; + try { + redis.scriptKill(); + } catch (RedisException e1) { + // I know, it sounds crazy, but there is a possibility where one of the commands above raises BUSY. + // Meanwhile the script ends and a call to SCRIPT KILL says NOTBUSY. + } + } + } + } while (scriptRunning); } @After
Generic guard for tests when Redis keeps still running Lua scripts
lettuce-io_lettuce-core
train
5cdef1fe0f8db0bf26766f8e0e84b89fe8644fe6
diff --git a/src/org/zaproxy/zap/extension/alert/ExtensionAlert.java b/src/org/zaproxy/zap/extension/alert/ExtensionAlert.java index <HASH>..<HASH> 100644 --- a/src/org/zaproxy/zap/extension/alert/ExtensionAlert.java +++ b/src/org/zaproxy/zap/extension/alert/ExtensionAlert.java @@ -671,7 +671,8 @@ public class ExtensionAlert extends ExtensionAdaptor implements SessionChangedLi // Deliberately include i! Alert alert2 = alerts.get(j); if (alert.getPluginId() == alert2.getPluginId()) { - if (count < this.getAlertParam().getMaximumInstances()) { + if (this.getAlertParam().getMaximumInstances() == 0 || + count < this.getAlertParam().getMaximumInstances()) { sb.append(" <instance>\n"); sb.append(alert2.getUrlParamXML()); sb.append(" </instance>\n");
Treat maxInstances == 0 as unlimited
zaproxy_zaproxy
train
0e91f2aa550db60dfe4a8cf55f7846013b8fa750
diff --git a/thumbor/handlers/__init__.py b/thumbor/handlers/__init__.py index <HASH>..<HASH> 100644 --- a/thumbor/handlers/__init__.py +++ b/thumbor/handlers/__init__.py @@ -110,6 +110,10 @@ class BaseHandler(tornado.web.RequestHandler): # Return a Bad Gateway status if the error came from upstream self._error(502) return + elif result.loader_error == LoaderResult.ERROR_TIMEOUT: + # Return a Gateway Timeout status if upstream timed out (i.e. 599) + self._error(504) + return else: self._error(500) return diff --git a/thumbor/loaders/__init__.py b/thumbor/loaders/__init__.py index <HASH>..<HASH> 100644 --- a/thumbor/loaders/__init__.py +++ b/thumbor/loaders/__init__.py @@ -13,6 +13,7 @@ class LoaderResult(object): ERROR_NOT_FOUND = 'not_found' ERROR_UPSTREAM = 'upstream' + ERROR_TIMEOUT = 'timeout' def __init__(self, buffer=None, successful=True, error=None, metadata=dict()): ''' diff --git a/thumbor/loaders/http_loader.py b/thumbor/loaders/http_loader.py index <HASH>..<HASH> 100644 --- a/thumbor/loaders/http_loader.py +++ b/thumbor/loaders/http_loader.py @@ -46,7 +46,11 @@ def return_contents(response, url, callback, context): context.metrics.incr('original_image.status.' + str(response.code)) if response.error: result.successful = False - result.error = LoaderResult.ERROR_NOT_FOUND + if response.code == 599: + # Return a Gateway Timeout status downstream if upstream times out + result.error = LoaderResult.ERROR_TIMEOUT + else: + result.error = LoaderResult.ERROR_NOT_FOUND logger.warn("ERROR retrieving image {0}: {1}".format(url, str(response.error)))
Pass upstream's <I>s as <I>s downstream (for cache) If thumbor gets a `<I> Timeout`, we want to pass that downstream as a `<I> Gateway Timeout`, not as a `<I> Not Found`. This improves our ability to cache results correctly at the CDN level.
thumbor_thumbor
train
a8cfe5380f94c7511e940997201f242147601d63
diff --git a/ChangeLog b/ChangeLog index <HASH>..<HASH> 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +2.0.3-stable (2014-??-??) + * Fixed: Now throwing an error when a Request object is being created with + arguments that were valid for sabre/http 1.0. Hopefully this will aid + with debugging for upgraders. + 2.0.2-stable (2014-02-09) * Fixed: Potential security problem in the client. diff --git a/lib/Sabre/HTTP/Request.php b/lib/Sabre/HTTP/Request.php index <HASH>..<HASH> 100644 --- a/lib/Sabre/HTTP/Request.php +++ b/lib/Sabre/HTTP/Request.php @@ -2,6 +2,8 @@ namespace Sabre\HTTP; +use InvalidArgumentException; + /** * The Request class represents a single HTTP request. * @@ -38,6 +40,9 @@ class Request extends Message implements RequestInterface { */ public function __construct($method = null, $url = null, array $headers = null, $body = null) { + if (is_array($method)) { + throw new InvalidArgumentException('The first argument for this constructor should be a string or null, not an array. Did you upgrade from sabre/http 1.0 to 2.0?'); + } if (!is_null($method)) $this->setMethod($method); if (!is_null($url)) $this->setUrl($url); if (!is_null($headers)) $this->setHeaders($headers); diff --git a/lib/Sabre/HTTP/Version.php b/lib/Sabre/HTTP/Version.php index <HASH>..<HASH> 100644 --- a/lib/Sabre/HTTP/Version.php +++ b/lib/Sabre/HTTP/Version.php @@ -14,6 +14,6 @@ class Version { /** * Full version number */ - const VERSION = '2.0.2'; + const VERSION = '2.0.3'; } diff --git a/tests/Sabre/HTTP/RequestTest.php b/tests/Sabre/HTTP/RequestTest.php index <HASH>..<HASH> 100644 --- a/tests/Sabre/HTTP/RequestTest.php +++ b/tests/Sabre/HTTP/RequestTest.php @@ -138,4 +138,14 @@ HI; $this->assertEquals($expected, (string)$request); } + + /** + * @expectedException \InvalidArgumentException + */ + function testConstructorWithArray() { + + $request = new Request(array()); + + } + }
Throwing exceptions when incorrectly constructing a request.
sabre-io_http
train
04775975e0984a6123eaabbf8db08a52dd4ac3e9
diff --git a/pyprophet/levels_contexts.py b/pyprophet/levels_contexts.py index <HASH>..<HASH> 100644 --- a/pyprophet/levels_contexts.py +++ b/pyprophet/levels_contexts.py @@ -447,7 +447,7 @@ DETACH DATABASE sdb; ''' % infile) click.echo("Info: Subsampled precursor table of file %s to %s. For scoring merged subsampled file." % (infile, outfile)) - c.executescript(''' + c.executescript(''' PRAGMA synchronous = OFF; ATTACH DATABASE "%s" AS sdb;
[FEATURE Subsample Merged File] Adding TRANSITION_PRECURSOR_MAPPING table
PyProphet_pyprophet
train
e695e82728f6337286b7fed1cdc250b933af2929
diff --git a/spec/page-object/elements/element_spec.rb b/spec/page-object/elements/element_spec.rb index <HASH>..<HASH> 100644 --- a/spec/page-object/elements/element_spec.rb +++ b/spec/page-object/elements/element_spec.rb @@ -88,14 +88,12 @@ describe PageObject::Elements::Element do end context "when using Watir" do - let(:watir_driver) { double('watir') } + let(:watir_driver) { double('watir_element_driver') } let(:watir_element) { PageObject::Elements::Element.new(watir_driver, :platform => :watir_webdriver) } it "should know when it is visible" do - wdriver = double('watir') - element = ::PageObject::Elements::Element.new(wdriver, :platform => :watir_webdriver) - wdriver.should_receive(:present?).and_return(true) - element.visible?.should == true + watir_driver.should_receive(:present?).and_return(true) + watir_element.visible?.should == true end it "should know when it is not visible" do
trying to fix the travis problem
cheezy_page-object
train
daf46755f844ee93b7a91b9da2d830ae4b906e0c
diff --git a/lib/moped/query.rb b/lib/moped/query.rb index <HASH>..<HASH> 100644 --- a/lib/moped/query.rb +++ b/lib/moped/query.rb @@ -142,14 +142,14 @@ module Moped result["values"] end - # @return [Numeric] the number of documents that match the selector. + # @return [Integer] the number of documents that match the selector. def count result = collection.database.command( count: collection.name, query: selector ) - result["n"] + result["n"].to_i end # Update a single document matching the query's selector. diff --git a/spec/moped/query_spec.rb b/spec/moped/query_spec.rb index <HASH>..<HASH> 100644 --- a/spec/moped/query_spec.rb +++ b/spec/moped/query_spec.rb @@ -228,7 +228,11 @@ describe Moped::Query do end it "returns the number of matching document" do - users.find(scope: scope).count.should eq 2 + users.find(scope: scope).count.should eq(2) + end + + it "returns a fixnum" do + users.find(scope: scope).count.should be_a(Integer) end end
Count should return an integer, not a float
mongoid_moped
train
157dafe39f6bfe4efe9fcb49879a960f5e0de8f0
diff --git a/src/TwitterOAuth.php b/src/TwitterOAuth.php index <HASH>..<HASH> 100644 --- a/src/TwitterOAuth.php +++ b/src/TwitterOAuth.php @@ -375,12 +375,12 @@ class TwitterOAuth switch ($method) { case 'GET': if (!empty($postfields)) { - $options[CURLOPT_URL] .= '?' . http_build_query($postfields); + $options[CURLOPT_URL] .= '?' . Util::buildHttpQuery($postfields); } break; case 'POST': $options[CURLOPT_POST] = true; - $options[CURLOPT_POSTFIELDS] = http_build_query($postfields); + $options[CURLOPT_POSTFIELDS] = Util::buildHttpQuery($postfields); break; } diff --git a/tests/TwitterOAuthTest.php b/tests/TwitterOAuthTest.php index <HASH>..<HASH> 100644 --- a/tests/TwitterOAuthTest.php +++ b/tests/TwitterOAuthTest.php @@ -110,7 +110,8 @@ class TwitterOAuthTest extends \PHPUnit_Framework_TestCase public function testGetAccountVerifyCredentials() { - $this->twitter->get('account/verify_credentials'); + // Include entities boolean added to test parameter value cohearsion + $this->twitter->get('account/verify_credentials', array("include_entities" => false)); $this->assertEquals(200, $this->twitter->lastHttpCode()); }
http_build_query converts false to 0 causing sig issues
abraham_twitteroauth
train
b184156697b991da5a4ec549af3aec94353a74f1
diff --git a/molgenis-ontology-core/src/main/java/org/molgenis/ontology/core/meta/OntologyTermNodePathMetaData.java b/molgenis-ontology-core/src/main/java/org/molgenis/ontology/core/meta/OntologyTermNodePathMetaData.java index <HASH>..<HASH> 100644 --- a/molgenis-ontology-core/src/main/java/org/molgenis/ontology/core/meta/OntologyTermNodePathMetaData.java +++ b/molgenis-ontology-core/src/main/java/org/molgenis/ontology/core/meta/OntologyTermNodePathMetaData.java @@ -17,9 +17,10 @@ public class OntologyTermNodePathMetaData extends DefaultEntityMetaData private OntologyTermNodePathMetaData() { super(SIMPLE_NAME, OntologyPackage.getPackageInstance()); - addAttributeMetaData(new DefaultAttributeMetaData(ID).setIdAttribute(true).setNillable(false).setVisible(false)); - addAttributeMetaData(new DefaultAttributeMetaData(ONTOLOGY_TERM_NODE_PATH, FieldTypeEnum.STRING).setNillable( - false).setLabelAttribute(true)); + addAttributeMetaData( + new DefaultAttributeMetaData(ID).setIdAttribute(true).setNillable(false).setVisible(false)); + addAttributeMetaData(new DefaultAttributeMetaData(ONTOLOGY_TERM_NODE_PATH, FieldTypeEnum.TEXT) + .setNillable(false).setLabelAttribute(true)); addAttributeMetaData(new DefaultAttributeMetaData(ROOT, FieldTypeEnum.BOOL).setNillable(false)); } } \ No newline at end of file
changed the nodePath from the String type to the Text type
molgenis_molgenis
train
e3071c4cf859180a47f3f489ab852a81fbb8857e
diff --git a/prometheus_client/exposition.py b/prometheus_client/exposition.py index <HASH>..<HASH> 100644 --- a/prometheus_client/exposition.py +++ b/prometheus_client/exposition.py @@ -172,7 +172,8 @@ def delete_from_gateway(gateway, job, grouping_key=None, timeout=None): def _use_gateway(method, gateway, job, registry, grouping_key, timeout): - if not (gateway.startswith('http://') or gateway.startswith('https://')): + gateway_url = urlparse(gateway) + if not gateway_url.scheme: gateway = 'http://{0}'.format(gateway) url = '{0}/metrics/job/{1}'.format(gateway, quote_plus(job))
Just check for a url scheme to allow users to provide a handler.
prometheus_client_python
train
4fc7389b1da3cc918beb642c9f79c0e6586b8047
diff --git a/lib/Doctrine/ORM/Tools/Setup.php b/lib/Doctrine/ORM/Tools/Setup.php index <HASH>..<HASH> 100644 --- a/lib/Doctrine/ORM/Tools/Setup.php +++ b/lib/Doctrine/ORM/Tools/Setup.php @@ -173,6 +173,11 @@ class Setup $memcache->connect('127.0.0.1'); $cache = new \Doctrine\Common\Cache\MemcacheCache(); $cache->setMemcache($memcache); + } else if (extension_loaded('redis')) { + $redis = new \Redis(); + $redis->connect('127.0.0.1'); + $cache = new \Doctrine\Common\Cache\RedisCache(); + $cache->setRedis($redis); } else { $cache = new ArrayCache; }
New cache driver definition for Doctrine running in non-dev mode and cache driver is not set. This cache driver was added with doctrine/common#<I>
doctrine_orm
train
ded70959e952d797068265b4b0add96a3eebf3b9
diff --git a/client.go b/client.go index <HASH>..<HASH> 100644 --- a/client.go +++ b/client.go @@ -415,8 +415,6 @@ func clientWriter(c *Client, w io.Writer, pendingRequests map[uint64]*clientMess var m *clientMessage select { - case <-stopChan: - return case m = <-c.requestsChan: default: select { diff --git a/server.go b/server.go index <HASH>..<HASH> 100644 --- a/server.go +++ b/server.go @@ -303,8 +303,6 @@ func serverWriter(s *Server, w io.Writer, clientAddr string, responsesChan <-cha var m *serverMessage select { - case <-stopChan: - return case m = <-responsesChan: default: select {
Code cleanup & optimization: removed redundant select case in write loops on both client and server
valyala_gorpc
train
644b5b427f7ecf1d5b05dbb831350cc2c7a4414c
diff --git a/src/classes/HUD.js b/src/classes/HUD.js index <HASH>..<HASH> 100644 --- a/src/classes/HUD.js +++ b/src/classes/HUD.js @@ -310,11 +310,11 @@ Garnish.HUD = Garnish.Base.extend({ if (this.orientation == 'top' || this.orientation == 'bottom') { maxHudBodyWidth = windowWidth - this.settings.windowSpacing * 2; - maxHudBodyHeight = clearances[this.orientation]; + maxHudBodyHeight = clearances[this.orientation] - this.settings.windowSpacing - this.settings.triggerSpacing; } else { - maxHudBodyWidth = clearances[this.orientation]; + maxHudBodyWidth = clearances[this.orientation] - this.settings.windowSpacing - this.settings.triggerSpacing; maxHudBodyHeight = windowHeight - this.settings.windowSpacing * 2; }
Fixed a bug where HUDs weren’t facoring in window/trigger padding when calculating the max size of the HUD alongside the trigger element
pixelandtonic_garnishjs
train
4c92bab37a73c886789753089fc80e2609525424
diff --git a/src/ContentBundle/Controller/Api/ContentController.php b/src/ContentBundle/Controller/Api/ContentController.php index <HASH>..<HASH> 100644 --- a/src/ContentBundle/Controller/Api/ContentController.php +++ b/src/ContentBundle/Controller/Api/ContentController.php @@ -339,6 +339,9 @@ class ContentController extends Controller $contentItem = [ 'id' => $content->getId(), + 'created_at' => $content->getCreatedAt(), + 'updated_at' => $content->getUpdatedAt(), + 'published_at' => $content->getPublishAt(), 'title' => $content->getTitle(), 'shortTitle' => $content->getShortTitle(), 'description' => $content->getDescription(),
Added create, update and publish date to response of content api call (#<I>)
Opifer_Cms
train
607cc8fce624e3341185271452e86bdd9dd49dfb
diff --git a/test/on_yubikey/cli_piv/test_key_management.py b/test/on_yubikey/cli_piv/test_key_management.py index <HASH>..<HASH> 100644 --- a/test/on_yubikey/cli_piv/test_key_management.py +++ b/test/on_yubikey/cli_piv/test_key_management.py @@ -107,6 +107,55 @@ class KeyManagement(PivTestCase): csr = x509.load_pem_x509_csr(output.encode(), default_backend()) self.assertTrue(csr.is_signature_valid) + def test_import_correct_cert_succeeds_with_pin(self): + # Set up a key in the slot and create a certificate for it + public_key_pem = ykman_cli( + 'piv', 'generate-key', '9a', '-a', 'ECCP256', '-m', + DEFAULT_MANAGEMENT_KEY, '--pin-policy', 'ALWAYS', '-') + + ykman_cli( + 'piv', 'generate-certificate', '9a', '-', + '-m', DEFAULT_MANAGEMENT_KEY, '-P', DEFAULT_PIN, '-s', 'test', + input=public_key_pem) + + ykman_cli('piv', 'export-certificate', '9a', '/tmp/test-pub-key.pem') + + with self.assertRaises(SystemExit): + ykman_cli( + 'piv', 'import-certificate', '9a', '/tmp/test-pub-key.pem', + '-m', DEFAULT_MANAGEMENT_KEY) + + ykman_cli( + 'piv', 'import-certificate', '9a', '/tmp/test-pub-key.pem', + '-m', DEFAULT_MANAGEMENT_KEY, '-P', DEFAULT_PIN) + ykman_cli( + 'piv', 'import-certificate', '9a', '/tmp/test-pub-key.pem', + '-m', DEFAULT_MANAGEMENT_KEY, input=DEFAULT_PIN) + + def test_import_wrong_cert_fails(self): + # Set up a key in the slot and create a certificate for it + public_key_pem = ykman_cli( + 'piv', 'generate-key', '9a', '-a', 'ECCP256', '-m', + DEFAULT_MANAGEMENT_KEY, '--pin-policy', 'ALWAYS', '-') + + ykman_cli( + 'piv', 'generate-certificate', '9a', '-', + '-m', DEFAULT_MANAGEMENT_KEY, '-P', DEFAULT_PIN, '-s', 'test', + input=public_key_pem) + + cert_pem = ykman_cli('piv', 'export-certificate', '9a', '-') + + # Overwrite the key with a new one + ykman_cli( + 'piv', 'generate-key', '9a', '-a', 'ECCP256', '-m', + DEFAULT_MANAGEMENT_KEY, '--pin-policy', 'ALWAYS', '-', + input=public_key_pem) + + with self.assertRaises(SystemExit): + ykman_cli( + 'piv', 'import-certificate', '9a', '-', + '-m', DEFAULT_MANAGEMENT_KEY, '-P', DEFAULT_PIN, input=cert_pem) + @unittest.skipIf(*no_attestation) def test_export_attestation_certificate(self): output = ykman_cli('piv', 'export-certificate', 'f9', '-')
Add tests of import-certificate CLI behaviour on cert verification
Yubico_yubikey-manager
train
2a4f0f308086245b301d8b11f274e91b3e3367d4
diff --git a/lib/active_support_decorators/version.rb b/lib/active_support_decorators/version.rb index <HASH>..<HASH> 100644 --- a/lib/active_support_decorators/version.rb +++ b/lib/active_support_decorators/version.rb @@ -1,3 +1,3 @@ module ActiveSupportDecorators - VERSION = '2.1.0' + VERSION = '2.1.1' end
Bumping version to <I>
EPI-USE-Labs_activesupport-decorators
train
cd8081f9522b57700e9fe448150f593dbea411b0
diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java index <HASH>..<HASH> 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java @@ -189,8 +189,7 @@ class UndertowWebServerFactoryDelegate { static List<HttpHandlerFactory> createHttpHandlerFactories(Compression compression, boolean useForwardHeaders, String serverHeader, Shutdown shutdown, HttpHandlerFactory... initialHttpHandlerFactories) { - List<HttpHandlerFactory> factories = - new ArrayList<HttpHandlerFactory>(Arrays.asList(initialHttpHandlerFactories)); + List<HttpHandlerFactory> factories = new ArrayList<>(Arrays.asList(initialHttpHandlerFactories)); if (compression != null && compression.getEnabled()) { factories.add(new CompressionHttpHandlerFactory(compression)); }
Polish "Use new ArrayList(Collection) rather than new and addAll" See gh-<I>
spring-projects_spring-boot
train
beab1d98b962bcf620622d2b3b7e547372cd4d94
diff --git a/go/vt/vtgate/planbuilder/show.go b/go/vt/vtgate/planbuilder/show.go index <HASH>..<HASH> 100644 --- a/go/vt/vtgate/planbuilder/show.go +++ b/go/vt/vtgate/planbuilder/show.go @@ -72,6 +72,8 @@ func buildShowBasicPlan(show *sqlparser.ShowBasic, vschema ContextVSchema) (engi return buildShowVMigrationsPlan(show, vschema) case sqlparser.VGtidExecGlobal: return buildShowVGtidPlan(show, vschema) + case sqlparser.GtidExecGlobal: + return buildShowGtidPlan(show, vschema) } return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] unknown show query type %s", show.Command.ToString()) @@ -495,6 +497,25 @@ func buildCreatePlan(show *sqlparser.ShowCreate, vschema ContextVSchema) (engine } func buildShowVGtidPlan(show *sqlparser.ShowBasic, vschema ContextVSchema) (engine.Primitive, error) { + send, err := buildShowGtidPlan(show, vschema) + if err != nil { + return nil, err + } + return &engine.OrderedAggregate{ + PreProcess: true, + Aggregates: []engine.AggregateParams{ + { + Opcode: engine.AggregateGtid, + Col: 1, + Alias: "global vgtid_executed", + }, + }, + TruncateColumnCount: 2, + Input: send, + }, nil +} + +func buildShowGtidPlan(show *sqlparser.ShowBasic, vschema ContextVSchema) (engine.Primitive, error) { dbName := "" if !show.DbName.IsEmpty() { dbName = show.DbName.String() @@ -507,22 +528,10 @@ func buildShowVGtidPlan(show *sqlparser.ShowBasic, vschema ContextVSchema) (engi dest = key.DestinationAllShards{} } - send := &engine.Send{ + return &engine.Send{ Keyspace: ks, TargetDestination: dest, - Query: fmt.Sprintf(`select '%s' as 'keyspace', @@global.gtid_executed, :%s`, ks.Name, engine.ShardName), + Query: fmt.Sprintf(`select '%s' as db_name, @@global.gtid_executed as gtid, :%s as shard`, ks.Name, engine.ShardName), ShardNameNeeded: true, - } - return &engine.OrderedAggregate{ - PreProcess: true, - Aggregates: []engine.AggregateParams{ - { - Opcode: engine.AggregateGtid, - Col: 1, - Alias: "global vgtid_executed", - }, - }, - TruncateColumnCount: 2, - Input: send, }, nil }
refactor show vgtid plan
vitessio_vitess
train
37b78675be6badeb1756dcc73f054985a3837ade
diff --git a/twx/botapi/botapi.py b/twx/botapi/botapi.py index <HASH>..<HASH> 100644 --- a/twx/botapi/botapi.py +++ b/twx/botapi/botapi.py @@ -585,7 +585,7 @@ class RequestMethod(str, Enum): class TelegramBotRPCRequest: api_url_base = 'https://api.telegram.org/bot' - def __init__(self, api_method, token, params=None, on_result=None, callback=None, + def __init__(self, api_method, token, params=None, on_result=None, on_success=None, callback=None, on_error=None, files=None, request_method=RequestMethod.POST): """ :param api_method: The API method to call. See https://core.telegram.org/bots/api#available-methods @@ -602,11 +602,18 @@ class TelegramBotRPCRequest: if reply_markup is not None: params['reply_markup'] = reply_markup.serialize() + if callback != None: + print('WARNING: callback is deprecated in favor of on_success') + if on_success: + print('WARNING: callback parameter will be ignored, on_success will be used instead') + else: + on_success = callback + self.api_method = api_method self.token = token self.params = params self.on_result = on_result - self.callback = callback + self.on_success = on_success self.on_error = on_error self.files = files self.request_method = RequestMethod(request_method) @@ -646,8 +653,8 @@ class TelegramBotRPCRequest: else: self.result = self.on_result(result) - if self.callback is not None: - self.callback(self.result) + if self.on_success is not None: + self.on_success(self.result) else: self.error = Error.from_result(api_response) if self.on_error:
deprecating callback in favor of on_success
datamachine_twx
train
22eeca68c908a3968f47920a6f5e7f43336e3d04
diff --git a/aws/internal/envvar/funcs_test.go b/aws/internal/envvar/funcs_test.go index <HASH>..<HASH> 100644 --- a/aws/internal/envvar/funcs_test.go +++ b/aws/internal/envvar/funcs_test.go @@ -50,8 +50,8 @@ func TestGetWithDefault(t *testing.T) { } func TestRequireOneOf(t *testing.T) { - envVar1 := "TESTENVVAR_FAILIFALLEMPTY1" - envVar2 := "TESTENVVAR_FAILIFALLEMPTY2" + envVar1 := "TESTENVVAR_REQUIREONEOF1" + envVar2 := "TESTENVVAR_REQUIREONEOF2" envVars := []string{envVar1, envVar2} t.Run("missing", func(t *testing.T) { @@ -124,7 +124,7 @@ func TestRequireOneOf(t *testing.T) { } func TestRequire(t *testing.T) { - envVar := "TESTENVVAR_FAILIFEMPTY" + envVar := "TESTENVVAR_REQUIRE" t.Run("missing", func(t *testing.T) { os.Unsetenv(envVar)
Cleans up envvar testing
terraform-providers_terraform-provider-aws
train
398f700ed9a255d31484708abf190a4350a36a09
diff --git a/packages/openneuro-server/versions.js b/packages/openneuro-server/versions.js index <HASH>..<HASH> 100644 --- a/packages/openneuro-server/versions.js +++ b/packages/openneuro-server/versions.js @@ -1,2 +1,2 @@ -require('babel-core/register') +require('@babel/register') require('./migrations/s3-versioning')
Fix bug with mixed babel versions and versioning migration.
OpenNeuroOrg_openneuro
train
0e47b280ae6159dbc8817f3c7bd3e296af480c5d
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index <HASH>..<HASH> 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -156,6 +156,7 @@ Indexing - When called on an unsorted ``MultiIndex``, the ``loc`` indexer now will raise ``UnsortedIndexError`` only if proper slicing is used on non-sorted levels (:issue:`16734`). - Fixes regression in 0.20.3 when indexing with a string on a ``TimedeltaIndex`` (:issue:`16896`). - Fixed ``TimedeltaIndex.get_loc`` handling of ``np.timedelta64`` inputs (:issue:`16909`). +- Fix :meth:`MultiIndex.sort_index` ordering when ``ascending`` argument is a list, but not all levels are specified, or are in a different order (:issue:`16934`). I/O ^^^ diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index <HASH>..<HASH> 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1697,7 +1697,8 @@ class MultiIndex(Index): raise ValueError("level must have same length as ascending") from pandas.core.sorting import lexsort_indexer - indexer = lexsort_indexer(self.labels, orders=ascending) + indexer = lexsort_indexer([self.labels[lev] for lev in level], + orders=ascending) # level ordering else: diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index <HASH>..<HASH> 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -2781,3 +2781,26 @@ class TestSorted(Base): result = s.sort_index(na_position='first') expected = s.iloc[[1, 2, 3, 0]] tm.assert_series_equal(result, expected) + + def test_sort_ascending_list(self): + # GH: 16934 + + # Set up a Series with a three level MultiIndex + arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], + ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'], + [4, 3, 2, 1, 4, 3, 2, 1]] + tuples = list(zip(*arrays)) + index = pd.MultiIndex.from_tuples(tuples, + names=['first', 'second', 'third']) + s = pd.Series(range(8), index=index) + + # Sort with boolean ascending + result = s.sort_index(level=['third', 'first'], ascending=False) + expected = s.iloc[[4, 0, 5, 1, 6, 2, 7, 3]] + tm.assert_series_equal(result, expected) + + # Sort with list of boolean ascending + result = s.sort_index(level=['third', 'first'], + ascending=[False, True]) + expected = s.iloc[[0, 4, 1, 5, 2, 6, 3, 7]] + tm.assert_series_equal(result, expected)
BUG: MultiIndex sort with ascending as list (#<I>)
pandas-dev_pandas
train
9536723c95c5b9deff4c6c6d6423b23a7025e58b
diff --git a/lib/puppet/util/command_line.rb b/lib/puppet/util/command_line.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/util/command_line.rb +++ b/lib/puppet/util/command_line.rb @@ -40,11 +40,15 @@ module Puppet [usage, available].join("\n") end + def require_application(application) + require File.join(appdir, application) + end + def execute if subcommand_name.nil? puts usage_message elsif available_subcommands.include?(subcommand_name) #subcommand - require File.join(appdir, subcommand_name) + require_application subcommand_name Puppet::Application.find(subcommand_name).new(self).run else abort "Error: Unknown command #{subcommand_name}.\n#{usage_message}"
Feature #<I>: method extract require_application It's useful to be able to require specific applications' ruby source by name, even if we aren't about to run them.
puppetlabs_puppet
train
16ff808609770e40c5a5d3ab8bd7af47b9fbebc0
diff --git a/lib/jsonapi/acts_as_resource_controller.rb b/lib/jsonapi/acts_as_resource_controller.rb index <HASH>..<HASH> 100644 --- a/lib/jsonapi/acts_as_resource_controller.rb +++ b/lib/jsonapi/acts_as_resource_controller.rb @@ -60,15 +60,19 @@ module JSONAPI end def get_related_resource - ActiveSupport::Deprecation.warn "In #{self.class.name} you exposed a `get_related_resource`"\ + # :nocov: + ActiveSupport::Deprecation.warn "In #{self.class.name} you exposed a `get_related_resource`"\ " action. Please use `show_related_resource` instead." show_related_resource + # :nocov: end def get_related_resources + # :nocov: ActiveSupport::Deprecation.warn "In #{self.class.name} you exposed a `get_related_resources`"\ " action. Please use `index_related_resource` instead." index_related_resources + # :nocov: end def process_request diff --git a/lib/jsonapi/link_builder.rb b/lib/jsonapi/link_builder.rb index <HASH>..<HASH> 100644 --- a/lib/jsonapi/link_builder.rb +++ b/lib/jsonapi/link_builder.rb @@ -61,8 +61,10 @@ module JSONAPI unless scopes.empty? "#{ scopes.first.to_s.camelize }::Engine".safe_constantize end + # :nocov: rescue LoadError => _e nil + # :nocov: end end @@ -139,7 +141,9 @@ module JSONAPI def regular_resource_path(source) if source.is_a?(JSONAPI::CachedResponseFragment) + # :nocov: "#{regular_resources_path(source.resource_klass)}/#{source.id}" + # :nocov: else "#{regular_resources_path(source.class)}/#{source.id}" end diff --git a/lib/jsonapi/relationship.rb b/lib/jsonapi/relationship.rb index <HASH>..<HASH> 100644 --- a/lib/jsonapi/relationship.rb +++ b/lib/jsonapi/relationship.rb @@ -25,7 +25,9 @@ module JSONAPI alias_method :polymorphic?, :polymorphic def primary_key + # :nocov: @primary_key ||= resource_klass._primary_key + # :nocov: end def resource_klass @@ -33,7 +35,9 @@ module JSONAPI end def table_name + # :nocov: @table_name ||= resource_klass._table_name + # :nocov: end def self.polymorphic_types(name) @@ -72,7 +76,9 @@ module JSONAPI end def belongs_to? + # :nocov: false + # :nocov: end def readonly? @@ -97,7 +103,9 @@ module JSONAPI end def belongs_to? + # :nocov: foreign_key_on == :self + # :nocov: end def polymorphic_type
Update coverage directives for uncovered lines
cerebris_jsonapi-resources
train
048a72f72bb8516a96b3680ee52b5277f27fda11
diff --git a/test/src/Ouzo/Core/Tools/Model/Template/ClassStubPlaceholderReplacerTest.php b/test/src/Ouzo/Core/Tools/Model/Template/ClassStubPlaceholderReplacerTest.php index <HASH>..<HASH> 100644 --- a/test/src/Ouzo/Core/Tools/Model/Template/ClassStubPlaceholderReplacerTest.php +++ b/test/src/Ouzo/Core/Tools/Model/Template/ClassStubPlaceholderReplacerTest.php @@ -6,6 +6,7 @@ use Ouzo\Tests\Assert; use Ouzo\Tests\Mock\Mock; use Ouzo\Tools\Model\Template\ClassStubPlaceholderReplacer; +use Ouzo\Tools\Model\Template\Dialect\Dialect; use Ouzo\Tools\Model\Template\TableInfo; class ClassStubPlaceholderReplacerTest extends PHPUnit_Framework_TestCase @@ -16,6 +17,7 @@ class ClassStubPlaceholderReplacerTest extends PHPUnit_Framework_TestCase public function shouldDoNotAddTableNameIfIsDefault() { //given + /** @var Dialect $dialect */ $dialect = Mock::mock('Ouzo\Tools\Model\Template\Dialect\Dialect'); Mock::when($dialect)->tableName()->thenReturn('customers'); Mock::when($dialect)->columns()->thenReturn(array()); @@ -37,6 +39,7 @@ class ClassStubPlaceholderReplacerTest extends PHPUnit_Framework_TestCase public function shouldDoNotAddPrimaryKeyNameIfIsDefault() { //given + /** @var Dialect $dialect */ $dialect = Mock::mock('Ouzo\Tools\Model\Template\Dialect\Dialect'); Mock::when($dialect)->primaryKey()->thenReturn('id'); Mock::when($dialect)->columns()->thenReturn(array()); @@ -58,6 +61,7 @@ class ClassStubPlaceholderReplacerTest extends PHPUnit_Framework_TestCase public function shouldDoNotAddSequenceNameIfIsDefault() { //given + /** @var Dialect $dialect */ $dialect = Mock::mock('Ouzo\Tools\Model\Template\Dialect\Dialect'); Mock::when($dialect)->primaryKey()->thenReturn('id'); Mock::when($dialect)->tableName()->thenReturn('customers'); @@ -81,6 +85,7 @@ class ClassStubPlaceholderReplacerTest extends PHPUnit_Framework_TestCase public function shouldAddEmptyPrimaryKeyEntryWhenNoFoundPrimaryKeyInTable() { //given + /** @var Dialect $dialect */ $dialect = Mock::mock('Ouzo\Tools\Model\Template\Dialect\Dialect'); Mock::when($dialect)->primaryKey()->thenReturn(''); Mock::when($dialect)->columns()->thenReturn(array()); diff --git a/test/src/Ouzo/Core/Tools/Model/Template/TableInfoTest.php b/test/src/Ouzo/Core/Tools/Model/Template/TableInfoTest.php index <HASH>..<HASH> 100644 --- a/test/src/Ouzo/Core/Tools/Model/Template/TableInfoTest.php +++ b/test/src/Ouzo/Core/Tools/Model/Template/TableInfoTest.php @@ -6,6 +6,7 @@ use Ouzo\Tests\Assert; use Ouzo\Tests\Mock\Mock; use Ouzo\Tools\Model\Template\DatabaseColumn; +use Ouzo\Tools\Model\Template\Dialect\Dialect; use Ouzo\Tools\Model\Template\TableInfo; class TableInfoTest extends PHPUnit_Framework_TestCase @@ -16,6 +17,7 @@ class TableInfoTest extends PHPUnit_Framework_TestCase public function shouldReturnFieldsWithoutPrimaryKeyWhenIsNotDefault() { //given + /** @var Dialect $dialect */ $dialect = Mock::mock('Ouzo\Tools\Model\Template\Dialect\Dialect'); Mock::when($dialect)->primaryKey()->thenReturn('id_name'); Mock::when($dialect)->columns()->thenReturn(array( @@ -38,6 +40,7 @@ class TableInfoTest extends PHPUnit_Framework_TestCase public function shouldReturnFieldsWithPrimaryKeyWhenIsDefault() { //given + /** @var Dialect $dialect */ $dialect = Mock::mock('Ouzo\Tools\Model\Template\Dialect\Dialect'); Mock::when($dialect)->primaryKey()->thenReturn('id'); Mock::when($dialect)->columns()->thenReturn(array(
Corrected PhpDoc type hints
letsdrink_ouzo
train
782953a34936f85bcd362d4ab67e30b578d6e3e5
diff --git a/src/Paginate/ToHtml.php b/src/Paginate/ToHtml.php index <HASH>..<HASH> 100644 --- a/src/Paginate/ToHtml.php +++ b/src/Paginate/ToHtml.php @@ -24,6 +24,11 @@ class ToHtml public function __construct( $uri=null ) { $this->currUri = $uri ?: $this->getRequestUri(); + if( strpos( $this->currUri, '?' ) === false ) { + $this->currUri .= '?'; + } else { + $this->currUri .= '&'; + } } /** @@ -78,7 +83,7 @@ class ToHtml { if( $page != $this->currPage ) { $key = $this->pager->getPageKey(); - $html = "<li><a href='{$this->currUri}?{$key}={$page}' >{$label}</a></li>"; + $html = "<li><a href='{$this->currUri}{$key}={$page}' >{$label}</a></li>"; } elseif( $type == 'disable' ) { $html = "<li class='disabled'><a href='#' >{$label}</a></li>"; } else {
[fix] incase uri contains '?' character, add '&' as the url for pagination.
asaokamei_ScoreSql
train
6735b976dc8acb1078f9f4944c373ec47c6ede57
diff --git a/gandi/cli/commands/vm.py b/gandi/cli/commands/vm.py index <HASH>..<HASH> 100644 --- a/gandi/cli/commands/vm.py +++ b/gandi/cli/commands/vm.py @@ -204,7 +204,8 @@ def delete(gandi, background, force, resource): help='Run command in background mode (default=False).') @option('--sshkey', multiple=True, help='Authorize ssh authentication for the given ssh key.') -@option('--size', type=click.INT, default=None, help="System disk size in MiB.") +@click.option('--size', type=click.INT, default=None, + help="System disk size in MiB.") @pass_gandi def create(gandi, datacenter, memory, cores, ip_version, bandwidth, login, password, hostname, image, run, background, sshkey, size):
vm: don't store system disk size in configuration file It fixes the following error starting from an empty configuration file: Error: Invalid value for "--size": s is not a valid integer
Gandi_gandi.cli
train
2fe4b86c6f85f95da4d70accc2cba89580d5c349
diff --git a/test/MarketCollateralPoolAccounting.js b/test/MarketCollateralPoolAccounting.js index <HASH>..<HASH> 100644 --- a/test/MarketCollateralPoolAccounting.js +++ b/test/MarketCollateralPoolAccounting.js @@ -8,8 +8,7 @@ const Helpers = require('./helpers/Helpers.js'); const utility = require('./utility.js'); // basic tests to ensure MarketCollateralPool works and is set up to allow trading -contract('MarketCollateralPool', function(accounts) { - let balancePerAcct; +contract('MarketCollateralPool.Accounting', function(accounts) { let collateralToken; let initBalance; let collateralPool; diff --git a/test/MarketContractOraclize.js b/test/MarketContractOraclize.js index <HASH>..<HASH> 100644 --- a/test/MarketContractOraclize.js +++ b/test/MarketContractOraclize.js @@ -450,17 +450,41 @@ contract('MarketContractOraclize', function(accounts) { assert.ok(error instanceof Error, 'Order did not fail'); }); + it('should fail for attempt to cancel twice full qty', async function() { + const orderQty = 2; + const orderToCancel = 2; + + await tradeHelper.cancelOrder( + [accounts[0], accounts[1], accounts[2]], + [entryOrderPrice, orderQty, orderToCancel] + ); + + await tradeHelper.cancelOrder( + [accounts[0], accounts[1], accounts[2]], + [entryOrderPrice, orderQty, orderToCancel] + ); + + const events = await utility.getEvent(marketContract, 'Error'); + assert.equal( + ErrorCodes.ORDER_DEAD, + events[0].args.errorCode.toNumber(), + 'Error event is not order dead.' + ); + }); + it('should fail for attempt to trade after settlement', async function() { const orderQty = 2; const orderToFill = 2; - const settlementPrice = 50000; + const settlementPrice = await marketContract.PRICE_FLOOR() - 1; const isExpired = true; await tradeHelper.tradeOrder( [accounts[0], accounts[1], accounts[2]], [entryOrderPrice, orderQty, orderToFill], isExpired ); + await tradeHelper.attemptToSettleContract(settlementPrice); + assert.isTrue(await marketContract.isSettled(), "Contract not settled properly"); let error; try { @@ -489,8 +513,6 @@ contract('MarketContractOraclize', function(accounts) { it('should fail for attempt to self-trade', async function() { const orderQty = 2; const orderToFill = 2; - const settlementPrice = 50000; - const isExpired = false; let error; try { @@ -505,39 +527,13 @@ contract('MarketContractOraclize', function(accounts) { assert.ok(error instanceof Error, 'tradeOrder() should fail for self-trade attempt'); }); - it('should fail for attempt to cancel twice full qty', async function() { - const orderQty = 2; - const orderToCancel = 2; - const settlementPrice = 20000; - - await tradeHelper.cancelOrder( - [accounts[0], accounts[1], accounts[2]], - [entryOrderPrice, orderQty, orderToCancel] - ); - - await tradeHelper.cancelOrder( - [accounts[0], accounts[1], accounts[2]], - [entryOrderPrice, orderQty, orderToCancel] - ); - - const events = await utility.getEvent(marketContract, 'Error'); - assert.equal( - ErrorCodes.ORDER_DEAD, - events[0].args.errorCode.toNumber(), - 'Error event is not order dead.' - ); - }); - it('should fail for attempt to cancel after settlement', async function() { const orderQty = 2; const orderToCancel = 1; - const settlementPrice = 20000; - await tradeHelper.tradeOrder( - [accounts[0], accounts[1], accounts[2]], - [entryOrderPrice, orderQty, orderToCancel], - true - ); + const settlementPrice = await marketContract.PRICE_FLOOR() - 1; + await tradeHelper.attemptToSettleContract(settlementPrice); + assert.isTrue(await marketContract.isSettled(), "Contract not settled properly"); let error; try {
fixes issues with tests that were not properly settling contracts
MARKETProtocol_MARKETProtocol
train
cdd512e476a47ef0ad5bdf9e9289c8d19b5970fe
diff --git a/src/sos/step_executor.py b/src/sos/step_executor.py index <HASH>..<HASH> 100755 --- a/src/sos/step_executor.py +++ b/src/sos/step_executor.py @@ -809,7 +809,9 @@ class Base_Step_Executor: if 'exception' in res: if isinstance(res['exception'], ProcessKilled): raise res['exception'] - if env.config['keep_going']: + elif isinstance(res['exception'], RemovedTarget): + pass + elif env.config['keep_going']: env.logger.error( f'''{self.step.step_name()} {f'(index={res["index"]})' if len(self._substeps) > 1 else ""} failed.''' ) @@ -1163,6 +1165,8 @@ class Base_Step_Executor: # in theory, we should be able to handled removed target from here # by rerunning the substep, but we it is too much work for this # corner case. Let us simply rerun the entire step. + elif isinstance(excp, RemovedTarget): + raise excp else: self.exec_error.append(f'index={proc_result["index"]}', excp) @@ -1961,6 +1965,13 @@ class Step_Executor(Base_Step_Executor): self.socket.send_pyobj(res) else: return res + except RemovedTarget as e: + # removed target needs to be handled differently since the workflow manager + # use type information to get removed targets + if self.socket is not None and not self.socket.closed: + self.socket.send_pyobj(e) + else: + raise e except Exception as e: if env.verbosity > 2: sys.stderr.write(get_traceback())
Fix handling of RemvoedTargets
vatlab_SoS
train
06ce00bd88ce15ec4cf19e46f2da0860fa787648
diff --git a/lib/guard/ui.rb b/lib/guard/ui.rb index <HASH>..<HASH> 100644 --- a/lib/guard/ui.rb +++ b/lib/guard/ui.rb @@ -16,7 +16,6 @@ module Guard # # @param [String] message the message to show # @option options [Boolean] reset whether to clean the output before - # @return [Boolean] always true # def info(message, options = { }) unless ENV['GUARD_ENV'] == 'test' @@ -29,7 +28,6 @@ module Guard # # @param [String] message the message to show # @option options [Boolean] reset whether to clean the output before - # @return [Boolean] always false # def error(message, options = { }) unless ENV['GUARD_ENV'] == 'test'
Remove return statement from docs.
guard_guard
train
f8163a99ebda5a4008b4a4c2b72f5b78320dfe39
diff --git a/filesystem/File.php b/filesystem/File.php index <HASH>..<HASH> 100755 --- a/filesystem/File.php +++ b/filesystem/File.php @@ -632,7 +632,7 @@ class File extends DataObject { } function validate() { - if(!File::$apply_restrictions_to_admin && Permission::check('ADMIN')) { + if(File::$apply_restrictions_to_admin || !Permission::check('ADMIN')) { $extension = strtolower(pathinfo($this->Name, PATHINFO_EXTENSION)); if($extension && !in_array($extension, self::$allowed_extensions)) {
BUGFIX: Apply file extension restrictions to extensions properly. (from r<I>) (from r<I>) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@<I> <I>b<I>ca-7a2a-<I>-9d3b-<I>d<I>a<I>a9
silverstripe_silverstripe-framework
train
7cab255a97fceb48e3b59b3d39b5fe58c6dad54b
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -199,6 +199,12 @@ *Yves Senn* +* Fixes bug when using includes combined with select, the select statement was overwritten. + + Fixes #11773 + + *Edo Balvers* + * Load fixtures from linked folders. *Kassio Borges* diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -261,7 +261,7 @@ module ActiveRecord end def construct_relation_for_association_find(join_dependency) - relation = except(:select).select(join_dependency.columns) + relation = except(:select).select(join_dependency.columns + select_values) apply_join_dependency(relation, join_dependency) end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -486,6 +486,14 @@ class RelationTest < ActiveRecord::TestCase assert_equal Developer.where(name: 'David').map(&:id).sort, developers end + def test_includes_with_select + query = Post.select('comments_count AS ranking').order('ranking').includes(:comments) + .where(comments: { id: 1 }) + + assert_equal ['comments_count AS ranking'], query.select_values + assert_equal 1, query.to_a.size + end + def test_loading_with_one_association posts = Post.preload(:comments) post = posts.find { |p| p.id == 1 }
Fixes #<I> when using includes combined with select, the select statement was overwritten.
rails_rails
train
04eeb1234d5449af1a57c367aa6eb12c2a28701c
diff --git a/src/org/dmfs/httpclientinterfaces/HttpMethod.java b/src/org/dmfs/httpclientinterfaces/HttpMethod.java index <HASH>..<HASH> 100644 --- a/src/org/dmfs/httpclientinterfaces/HttpMethod.java +++ b/src/org/dmfs/httpclientinterfaces/HttpMethod.java @@ -17,6 +17,10 @@ package org.dmfs.httpclientinterfaces; +import java.util.HashMap; +import java.util.Map; + + /** * Represents an HTTP method. This class provides static members for HTTP methods defined in <a href="https://tools.ietf.org/html/rfc7231#section-4.3">RFC 7231, * section 4.3</a>. @@ -83,11 +87,30 @@ public final class HttpMethod /** + * Returns a known method for the given verb. + * + * @param verb + * The verb of the method. + * @return An {@link HttpMethod} or <code>null</code> if no method with that verb is known. + */ + public final static HttpMethod get(String verb) + { + synchronized (REGISTERED_METHODS) + { + return REGISTERED_METHODS.get(verb); + } + } + + + /** * Creates a non-safe and non-idempotent {@link HttpMethod} for the given verb. * * @param verb * The verb of the method. * @return An {@link HttpMethod}. + * + * @throws IllegalArgumentException + * If an idempotent or safe method with the same verb has already been created. */ public final static HttpMethod method(String verb) { @@ -101,6 +124,9 @@ public final class HttpMethod * @param verb * The verb of the method. * @return An {@link HttpMethod}. + * + * @throws IllegalArgumentException + * If a non-idempotent or safe method with the same verb has already been created. */ public final static HttpMethod idempotentMethod(String verb) { @@ -114,6 +140,9 @@ public final class HttpMethod * @param verb * The verb of the method. * @return An {@link HttpMethod}. + * + * @throws IllegalArgumentException + * If a non-safe method with the same verb has already been created. */ public final static HttpMethod safeMethod(String verb) { @@ -131,13 +160,34 @@ public final class HttpMethod * @param idempotent * <code>true</code> if the method is idempotent, <code>false</code> otherwise. * @return An {@link HttpMethod}. + * + * @throws IllegalArgumentException + * if the verb has already been created with different properties. */ public final static HttpMethod Method(String verb, boolean safe, boolean idempotent) { - return new HttpMethod(verb, safe, idempotent); + synchronized (REGISTERED_METHODS) + { + HttpMethod method = REGISTERED_METHODS.get(verb); + if (method == null) + { + return new HttpMethod(verb, safe, idempotent); + } + + if (method.safe != safe || method.idempotent != idempotent) + { + throw new IllegalArgumentException("Attempt to re-register a verb with different semantics!"); + } + return method; + } } /** + * A map to store all known HTTP methods. It's used by {@link #get(String)} to return an appropriate {@link HttpMethod} instance. + */ + private final static Map<String, HttpMethod> REGISTERED_METHODS = new HashMap<String, HttpMethod>(20); + + /** * The HTTP verb of this method. */ public final String verb; @@ -171,8 +221,46 @@ public final class HttpMethod */ private HttpMethod(String verb, boolean safe, boolean idempotent) { + if (verb == null) + { + throw new IllegalArgumentException("Method verb must not be null"); + } + this.verb = verb; this.safe = safe; this.idempotent = idempotent; + + register(); + } + + + /** + * Register this {@link HttpMethod} in {@link #REGISTERED_METHODS}. + */ + private void register() + { + synchronized (REGISTERED_METHODS) + { + REGISTERED_METHODS.put(verb, this); + } + } + + + @Override + public int hashCode() + { + return verb.hashCode(); + } + + + @Override + public boolean equals(Object obj) + { + if (!(obj instanceof HttpMethod)) + { + return false; + } + HttpMethod other = (HttpMethod) obj; + return obj == this || verb.equals(other.verb) && safe == other.safe && idempotent == other.idempotent; } }
Add a registry for HttpMethods. This can be used to retrieve an HttpMethod by giving its verb.
dmfs_http-client-interfaces
train
cdbbb4db9d15d8648a353f35ed8f9782d44b5d65
diff --git a/app/assets/javascripts/fae/form/_validator.js b/app/assets/javascripts/fae/form/_validator.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/fae/form/_validator.js +++ b/app/assets/javascripts/fae/form/_validator.js @@ -264,8 +264,12 @@ Fae.form.validator = { _create_counter_text: function($elem, max, current) { var prep = "Maximum Characters: " + max; + var text = "Characters Left: "; + if (current < 0) { + text = "Characters Over: "; + } if (current > 0 || $elem.val().length > 0) { - prep += " / <span class='characters-left'>Characters Left: " + current + "</span>"; + prep += " / <span class='characters-left'>" + text + Math.abs(current) + "</span>"; } return prep; }, diff --git a/spec/features/page_validations_spec.rb b/spec/features/page_validations_spec.rb index <HASH>..<HASH> 100644 --- a/spec/features/page_validations_spec.rb +++ b/spec/features/page_validations_spec.rb @@ -112,7 +112,7 @@ feature 'page validations' do fill_in 'home_page_introduction_attributes_content', with: 'Add a couple more...' expect(page.find(:css, 'span.characters-left').text).to eq('Characters Left: 80') fill_in 'home_page_introduction_attributes_content', with: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent pulvinar euismod nisl, in pellentesque sapien ornare ac. Ut mattis vel elit id gravida. Nulla interdum rhoncus ante, eget congue nisi congue laoreet. Mauris finibus sagittis lacus, id condimentum metus dictum id. Aenean vel libero vel nibh ultrices pretium in non felis. Nullam eu mattis sem. Phasellus vehicula quam leo, a malesuada ex lobortis nec. Sed ac augue venenatis, vestibulum eros quis, venenatis tellus. Duis semper erat vel tempus accumsan. Nulla convallis justo aliquet aliquet sagittis. Aliquam eleifend arcu magna, ac convallis massa pulvinar nec.' - expect(page.find(:css, 'span.characters-left').text).to eq('Characters Left: 0') + expect(page.find(:css, 'span.characters-left').text).to include('Characters Over') end end diff --git a/spec/features/validations_spec.rb b/spec/features/validations_spec.rb index <HASH>..<HASH> 100644 --- a/spec/features/validations_spec.rb +++ b/spec/features/validations_spec.rb @@ -66,7 +66,7 @@ feature 'validations' do fill_in 'release_name', with: 'Test' expect(page.find(:css, 'span.characters-left').text).to eq('Characters Left: 11') fill_in 'release_name', with: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent pulvinar euismod nisl, in pellentesque sapien ornare ac.' - expect(page.find(:css, 'span.characters-left').text).to eq('Characters Left: 0') + expect(page.find(:css, 'span.characters-left').text).to include('Characters Over') end end
refs #<I> - update character limit text to display characters over
wearefine_fae
train
1e3088b81959d0ebfb60dae047a97cdd6d97229e
diff --git a/lib/ooor/session_handler.rb b/lib/ooor/session_handler.rb index <HASH>..<HASH> 100644 --- a/lib/ooor/session_handler.rb +++ b/lib/ooor/session_handler.rb @@ -17,7 +17,7 @@ module Ooor if config[:reload] || !s = sessions[spec] create_new_session(config, spec, web_session) else - s.tap {|s| s.session.merge!(web_session)} + s.tap {|s| s.web_session.merge!(web_session)} end end @@ -27,19 +27,26 @@ module Ooor Ooor::Session.new(connections[c_spec], web_session) else Ooor::Session.new(create_new_connection(config, c_spec), web_session).tap do |s| - if config[:database] && config[:username] - s.config[:user_id] = s.common.login(config[:database], config[:username], config[:password]) # NOTE do that lazily? - end - connections[spec] = s.connection + connections[c_spec] = s.connection end end end + def register_session(session) + spec = session_spec(session.config, session.web_session[:session_id]) + sessions[spec] = session + end + def create_new_connection(config, spec) config = Ooor.default_config.merge(config) if Ooor.default_config.is_a? Hash Connection.new(config) end + def reset! + @sessions = {} + @connections = {} + end + def sessions; @sessions ||= {}; end def connections; @connections ||= {}; end end
fixed several bugs with the connection and session pools
akretion_ooor
train
ac2ce51f8eb019406736beb9ff595e86696e3e01
diff --git a/src/test/java/uk/co/real_logic/agrona/concurrent/AtomicBufferTest.java b/src/test/java/uk/co/real_logic/agrona/concurrent/AtomicBufferTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/uk/co/real_logic/agrona/concurrent/AtomicBufferTest.java +++ b/src/test/java/uk/co/real_logic/agrona/concurrent/AtomicBufferTest.java @@ -74,9 +74,10 @@ public class AtomicBufferTest buffer.checkLimit(position); } - @Theory - public void shouldVerifyBufferAlignment(final AtomicBuffer buffer) + @Test + public void shouldVerifyBufferAlignment() { + final AtomicBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(1024)); try { buffer.verifyAlignment(); diff --git a/src/test/java/uk/co/real_logic/agrona/concurrent/CountersManagerTest.java b/src/test/java/uk/co/real_logic/agrona/concurrent/CountersManagerTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/uk/co/real_logic/agrona/concurrent/CountersManagerTest.java +++ b/src/test/java/uk/co/real_logic/agrona/concurrent/CountersManagerTest.java @@ -24,7 +24,7 @@ import uk.co.real_logic.agrona.concurrent.status.UnsafeBufferPosition; import java.util.function.BiConsumer; -import static java.nio.ByteBuffer.allocate; +import static java.nio.ByteBuffer.allocateDirect; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; @@ -35,8 +35,8 @@ public class CountersManagerTest { private static final int NUMBER_OF_COUNTERS = 4; - private UnsafeBuffer labelsBuffer = new UnsafeBuffer(allocate(NUMBER_OF_COUNTERS * CountersManager.LABEL_SIZE)); - private UnsafeBuffer counterBuffer = new UnsafeBuffer(allocate(NUMBER_OF_COUNTERS * CountersManager.COUNTER_SIZE)); + private UnsafeBuffer labelsBuffer = new UnsafeBuffer(allocateDirect(NUMBER_OF_COUNTERS * CountersManager.LABEL_SIZE)); + private UnsafeBuffer counterBuffer = new UnsafeBuffer(allocateDirect(NUMBER_OF_COUNTERS * CountersManager.COUNTER_SIZE)); private CountersManager manager = new CountersManager(labelsBuffer, counterBuffer); private CountersManager otherManager = new CountersManager(labelsBuffer, counterBuffer);
[Java]: Resolved issue #9 so that only direct ByteBuffers are used for <I>-bit JVMs.
real-logic_agrona
train
36fc0f0e10697918f003eaa55fdcfed18787b8e8
diff --git a/lib/metadata/scoreProfileGeneric.json b/lib/metadata/scoreProfileGeneric.json index <HASH>..<HASH> 100644 --- a/lib/metadata/scoreProfileGeneric.json +++ b/lib/metadata/scoreProfileGeneric.json @@ -86,8 +86,8 @@ "policies": { "fontsCount": 1, "heavyFonts": 0.5, - "nonWoff2Fonts": 0.5, - "unusedUnicodeRanges": 0.1 + "unusedUnicodeRanges": 0.5, + "nonWoff2Fonts": 0.5 } }, "serverConfig": { diff --git a/lib/runner.js b/lib/runner.js index <HASH>..<HASH> 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -78,6 +78,12 @@ var Runner = function(params) { milestone: 'redownload' }); + // Fix: don't display Unicode ranges if the module is not present in Phantomas + if (!data.toolsResults.phantomas.metrics.charactersCount) { + delete data.toolsResults.redownload.metrics.unusedUnicodeRanges; + delete data.toolsResults.redownload.offenders.unusedUnicodeRanges; + } + // Rules checker var policies = require('./metadata/policies'); data.rules = rulesChecker.check(data, policies); diff --git a/lib/tools/redownload/redownload.js b/lib/tools/redownload/redownload.js index <HASH>..<HASH> 100644 --- a/lib/tools/redownload/redownload.js +++ b/lib/tools/redownload/redownload.js @@ -21,7 +21,6 @@ var brotliCompressor = require('./brotliCompressor'); var contentTypeChecker = require('./contentTypeChecker'); var fontAnalyzer = require('./fontAnalyzer'); var imageDimensions = require('./imageDimensions'); -var cdnDetector = require('./cdnDetector/cdnDetector'); var Redownload = function() { @@ -76,8 +75,6 @@ var Redownload = function() { redownloadEntry(entry, httpAuth, proxy) - .then(cdnDetector.detectCDN) - .then(contentTypeChecker.checkContentType) .then(imageOptimizer.optimizeImage)
Working on implementing unicode ranges again
gmetais_YellowLabTools
train
85db2b1fc0d286e0e3d14b695a512693ab35d055
diff --git a/src/org/jgroups/stack/DefaultRetransmitter.java b/src/org/jgroups/stack/DefaultRetransmitter.java index <HASH>..<HASH> 100644 --- a/src/org/jgroups/stack/DefaultRetransmitter.java +++ b/src/org/jgroups/stack/DefaultRetransmitter.java @@ -58,7 +58,7 @@ public class DefaultRetransmitter extends Retransmitter { Task new_task; for(long seqno=first_seqno; seqno <= last_seqno; seqno++) { // each task needs its own retransmission interval, as they are stateful *and* mutable, so we *need* to copy ! - new_task=new SeqnoTask(seqno, RETRANSMIT_TIMEOUTS.copy(), cmd, sender); + new_task=new SeqnoTask(seqno, retransmit_timeouts.copy(), cmd, sender); Task old_task=msgs.putIfAbsent(seqno, new_task); if(old_task == null) // only schedule if we actually *added* the new task ! new_task.doSchedule(); // Entry adds itself to the timer @@ -72,13 +72,10 @@ public class DefaultRetransmitter extends Retransmitter { * respective entry, cancel the entry from the retransmission * scheduler and remove it from the pending entries */ - public int remove(long seqno) { + public void remove(long seqno) { Task task=msgs.remove(seqno); - if(task != null) { + if(task != null) task.cancel(); - return task.getNumRetransmits(); - } - return -1; } /** @@ -87,24 +84,22 @@ public class DefaultRetransmitter extends Retransmitter { * @param remove_all_below If true, all seqnos below seqno are removed, too * @return */ - public int remove(long seqno, boolean remove_all_below) { - if(!remove_all_below) - return remove(seqno); + public void remove(long seqno, boolean remove_all_below) { + if(!remove_all_below) { + remove(seqno); + return; + } if(msgs.isEmpty()) - return 0; + return; ConcurrentNavigableMap<Long,Task> to_be_removed=msgs.headMap(seqno, true); if(to_be_removed.isEmpty()) - return 0; + return; Collection<Task> values=to_be_removed.values(); - int num_xmits=0; for(Task task: values) { - if(task != null) { + if(task != null) task.cancel(); - num_xmits+=task.getNumRetransmits(); - } } to_be_removed.clear(); - return num_xmits; } /** diff --git a/src/org/jgroups/stack/RangeBasedRetransmitter.java b/src/org/jgroups/stack/RangeBasedRetransmitter.java index <HASH>..<HASH> 100644 --- a/src/org/jgroups/stack/RangeBasedRetransmitter.java +++ b/src/org/jgroups/stack/RangeBasedRetransmitter.java @@ -71,7 +71,7 @@ public class RangeBasedRetransmitter extends Retransmitter { num_single_msgs.incrementAndGet(); // each task needs its own retransmission interval, as they are stateful *and* mutable, so we *need* to copy ! - RangeTask new_task=new RangeTask(range, RETRANSMIT_TIMEOUTS.copy(), cmd, sender); + RangeTask new_task=new RangeTask(range, retransmit_timeouts.copy(), cmd, sender); Seqno old_range=ranges.put(range, range); if(old_range != null) @@ -90,38 +90,30 @@ public class RangeBasedRetransmitter extends Retransmitter { * respective entry, cancel the entry from the retransmission * scheduler and remove it from the pending entries */ - public int remove(long seqno) { - int retval=0; + public void remove(long seqno) { Seqno range=ranges.get(new Seqno(seqno, true)); if(range == null) - return 0; + return; range.set(seqno); - if(log.isTraceEnabled()) - log.trace("removed " + sender + " #" + seqno + " from retransmitter"); // if the range has no missing messages, get the associated task and cancel it if(range.getNumberOfMissingMessages() == 0) { Task task=tasks.remove(range); - if(task != null) { + if(task != null) task.cancel(); - retval=task.getNumRetransmits(); - } else log.error("task for range " + range + " not found"); ranges.remove(range); if(log.isTraceEnabled()) log.trace("all messages for " + sender + " [" + range + "] have been received; removing range"); } - - return retval; } /** - * Reset the retransmitter: clear all msgs and cancel all the - * respective tasks + * Reset the retransmitter: clear all msgs and cancel all the respective tasks */ public void reset() { synchronized(ranges) { @@ -150,12 +142,15 @@ public class RangeBasedRetransmitter extends Retransmitter { public String toString() { int missing_msgs=0; - for(Seqno range: ranges.keySet()) + int size=0; + for(Seqno range: ranges.keySet()) { missing_msgs+=range.getNumberOfMissingMessages(); + size++; + } StringBuilder sb=new StringBuilder(); sb.append(missing_msgs).append(" messages to retransmit"); - if(missing_msgs < 50) { + if(size < 50) { Collection<Range> all_missing_msgs=new LinkedList<Range>(); for(Seqno range: ranges.keySet()) { all_missing_msgs.addAll(range.getMessagesToRetransmit());
changed remove() to return void instead of number of retransmissions
belaban_JGroups
train
e2fa36630f31f6c5077cdd6f9784a19065aff95d
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -22,9 +22,9 @@ class TestCommand(Command): setup( name='parse_rest', - version='0.2.20141004', + version='0.2.20170114', description='A client library for Parse.com\'.s REST API', - url='https://github.com/dgrtwo/ParsePy', + url='https://github.com/milesrichardson/ParsePy', packages=['parse_rest'], package_data={"parse_rest": [os.path.join("cloudcode", "*", "*")]}, install_requires=['six'],
bring setup.py up to date
milesrichardson_ParsePy
train
fde35add287deca1c5672b4c46bee06384595293
diff --git a/lib/postal/http.rb b/lib/postal/http.rb index <HASH>..<HASH> 100644 --- a/lib/postal/http.rb +++ b/lib/postal/http.rb @@ -42,7 +42,7 @@ module Postal #request.add_field 'X-Postal-Signature', signature end - request['User-Agent'] = options[:user_agent] || "Postal/#{Postal::VERSION}" + request['User-Agent'] = options[:user_agent] || "Postal/#{Postal.version}" connection = Net::HTTP.new(uri.host, uri.port) diff --git a/lib/postal/version.rb b/lib/postal/version.rb index <HASH>..<HASH> 100644 --- a/lib/postal/version.rb +++ b/lib/postal/version.rb @@ -1,3 +1,11 @@ module Postal + VERSION = '1.0.0' + REVISION = nil + CHANNEL = 'dev' + + def self.version + [VERSION, REVISION, CHANNEL].compact.join('-') + end + end diff --git a/script/version.rb b/script/version.rb index <HASH>..<HASH> 100644 --- a/script/version.rb +++ b/script/version.rb @@ -1,3 +1,3 @@ #!/usr/bin/env ruby require File.expand_path('../../lib/postal/version', __FILE__) -puts Postal::VERSION +puts Postal.version
update version to include revision & channel
atech_postal
train
011e49638a31c94b5d133ec33bbc83e441ec0ff7
diff --git a/lib/parse-inline-shims.js b/lib/parse-inline-shims.js index <HASH>..<HASH> 100644 --- a/lib/parse-inline-shims.js +++ b/lib/parse-inline-shims.js @@ -60,8 +60,10 @@ var go = module.exports = function (config) { // "key": { "exports": "export" .. } if (typeof conf === 'string') conf = { exports: conf }; + var exps = conf.exports && conf.exports.length ? conf.exports.trim() : null; + acc[field.trim()] = { - exports: conf.exports.trim() + exports: exps , depends: parseDepends(conf.depends) }
allowing to omit exports for inline shims
thlorenz_browserify-shim
train
f5ad08fab97bd3f3ea17654f6a81b363238e8bf0
diff --git a/buildbot/slave/commands.py b/buildbot/slave/commands.py index <HASH>..<HASH> 100755 --- a/buildbot/slave/commands.py +++ b/buildbot/slave/commands.py @@ -308,6 +308,8 @@ class ShellCommand: self.sendRC = sendRC self.logfiles = logfiles self.workdir = workdir + if not os.path.exists(workdir): + os.makedirs(workdir) self.environ = os.environ.copy() if environ: if environ.has_key('PYTHONPATH'):
(refs #<I>) automatically create workdir if it doesn't exist
buildbot_buildbot
train