hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
c3dbdb45bdaaa6648233b370fbd26dfef32b187a
diff --git a/src/HTML/HTMLHelper.php b/src/HTML/HTMLHelper.php index <HASH>..<HASH> 100644 --- a/src/HTML/HTMLHelper.php +++ b/src/HTML/HTMLHelper.php @@ -845,7 +845,13 @@ class HTMLHelper */ public static function determineEpisodeImagePath($episode, $show) { if (empty($episode->featured_image)) { - return Config('app.url') .'/'. Config::get('lasallecastfrontend.images_shows') .'/'. $show->featured_image; + + // I'm gonna be a very bad boy here and just return the cloudfront path, + // because, at this point, LaSalleCast is just for moi, and I use AWS cloudfront + + return $show->featured_image; + + //return Config('app.url') .'/'. Config::get('lasallecastfrontend.images_shows') .'/'. $show->featured_image; } return $show->image_file_storage_url . $episode->featured_image;
Modify method to deal with my Media site's using AWS Cloudfront. #<I>
lasallecms_lasallecms-l5-helpers-pkg
train
2010f93f414ea5bee6e69fcf2d165b5b1d068bbf
diff --git a/lib/def.js b/lib/def.js index <HASH>..<HASH> 100644 --- a/lib/def.js +++ b/lib/def.js @@ -383,50 +383,45 @@ var customFunctions = Object.create(null); infer.registerFunction = function(name, f) { customFunctions[name] = f; }; - var _constraints; - function constraints() { - if (_constraints) return _constraints; - _constraints = {}; - _constraints.IsCreated = infer.constraint("created, target, spec", { - addType: function(tp) { - if (tp instanceof infer.Obj && this.created++ < 5) { - var derived = new infer.Obj(tp), spec = this.spec; - if (spec instanceof infer.AVal) spec = spec.getType(); - if (spec instanceof infer.Obj) for (var prop in spec.props) { - var cur = spec.props[prop].types[0]; - var p = derived.defProp(prop); - if (cur && cur instanceof infer.Obj && cur.props.value) { - var vtp = cur.props.value.getType(); - if (vtp) p.addType(vtp); - } + var IsCreated = infer.constraint("created, target, spec", { + addType: function(tp) { + if (tp instanceof infer.Obj && this.created++ < 5) { + var derived = new infer.Obj(tp), spec = this.spec; + if (spec instanceof infer.AVal) spec = spec.getType(); + if (spec instanceof infer.Obj) for (var prop in spec.props) { + var cur = spec.props[prop].types[0]; + var p = derived.defProp(prop); + if (cur && cur instanceof infer.Obj && cur.props.value) { + var vtp = cur.props.value.getType(); + if (vtp) p.addType(vtp); } - this.target.addType(derived) } + this.target.addType(derived) } - }); - _constraints.IsBound = infer.constraint("args, target", { - addType: function(tp) { - if (!(tp instanceof infer.Fn)) return; - var cut = Math.max(0, this.args.length - 1); - this.target.addType(new infer.Fn(tp.name, this.args[0] || infer.ANull, - tp.args.slice(cut), tp.argNames.slice(cut), tp.retval)); - } - }); - return _constraints; - } + } + }); infer.registerFunction("Object_create", function(self, args, argNodes) { if (argNodes.length && argNodes[0].type == "Literal" && argNodes[0].value == null) return new infer.Obj(); var result = new infer.AVal; - if (args[0]) args[0].propagate(new (constraints().IsCreated)(0, result, args[1])); + if (args[0]) args[0].propagate(new IsCreated(0, result, args[1])); return result; }); + var IsBound = infer.constraint("args, target", { + addType: function(tp) { + if (!(tp instanceof infer.Fn)) return; + var cut = Math.max(0, this.args.length - 1); + this.target.addType(new infer.Fn(tp.name, this.args[0] || infer.ANull, + tp.args.slice(cut), tp.argNames.slice(cut), tp.retval)); + } + }); + infer.registerFunction("Function_bind", function(self, args) { var result = new infer.AVal; - self.propagate(new (constraints().IsBound)(args, result)); + self.propagate(new IsBound(args, result)); return result; }); diff --git a/lib/infer.js b/lib/infer.js index <HASH>..<HASH> 100644 --- a/lib/infer.js +++ b/lib/infer.js @@ -22,9 +22,6 @@ })(function(exports, acorn, acorn_loose, walk, def, signal) { "use strict"; - // Delayed initialization because of cyclic dependencies. - def = exports.def = def.init({}, exports); - var toString = exports.toString = function(type, maxDepth, parent) { return !type || type == parent ? "?": type.toString(maxDepth); }; @@ -1403,4 +1400,9 @@ var scope = scopeAt(ast, pos, defaultScope), locals = []; scope.gatherProperties(f, 0); }; + + // INIT DEF MODULE + + // Delayed initialization because of cyclic dependencies. + def = exports.def = def.init({}, exports); });
Less awkward initialization of lib/def.js Only run the initializer when the infer module has been initialized Removes need to lazy-init constraints in def.js.
ternjs_tern
train
9d55e748f48abd32e9e0fa23fb6fbd3e7306a431
diff --git a/lib/ronin/formatting/extensions/binary/string.rb b/lib/ronin/formatting/extensions/binary/string.rb index <HASH>..<HASH> 100644 --- a/lib/ronin/formatting/extensions/binary/string.rb +++ b/lib/ronin/formatting/extensions/binary/string.rb @@ -91,4 +91,61 @@ class String Base64.decode64(self) end + # + # Converts a multitude of hexdump formats back into their original + # binary form using the given _options_. + # + # _options_ may contain the following keys: + # <tt>:segment</tt>:: The length in bytes of each segment in the hexdump. + # Defaults to 16, if not specified. + # <tt>:encoding</tt>: Denotes the encoding uses for the bytes within the + # hexdump. Must be either <tt>:dec</tt>, + # <tt>:hex</tt> or <tt>:octal</tt>, defaults to + # <tt>:hex</tt> if unspecified. + # + def unhexdump(options={}) + encoding = (options[:encoding] || :hex) + current_addr = last_addr = 0 + repeated = false + + segment_length = (options[:segment] || 16) + segment = [] + bytes = [] + + each_line do |line| + words = line.split + + if words.first == '*' + repeated = true + elsif words.length > 0 + current_addr = words.first.hex + + if repeated + (current_addr - last_addr).times { bytes += segment } + repeated = false + end + + segment = [] + + words[1..-1].each do |word| + break unless word =~ /^[0-9-a-fA-F]+$/ + + case encoding + when :dec + segment << word.to_i + when :hex + segment << word.hex + when :octal + segment << word.oct + end + end + + bytes += segment + last_addr = current_addr + end + end + + return bytes + end + end
Added a basic String#unhexdump method. * Supports decimal, hexadecimal and octal encoding. * Supports configurable segment lengths. * Supports '*' style repeation of segments.
ronin-ruby_ronin
train
c1468607626b1937efcf2799d73f5c63e1609d90
diff --git a/lib/gir_ffi/builders/property_builder.rb b/lib/gir_ffi/builders/property_builder.rb index <HASH>..<HASH> 100644 --- a/lib/gir_ffi/builders/property_builder.rb +++ b/lib/gir_ffi/builders/property_builder.rb @@ -9,52 +9,87 @@ module GirFFI def getter_def case type_info.tag when :glist, :ghash - argument_info = FieldArgumentInfo.new(@info.getter_name, type_info) - builder = ReturnValueBuilder.new(VariableNameGenerator.new, argument_info) - - return <<-CODE.reset_indentation - def #{@info.getter_name} - #{builder.callarg} = get_property("#{@info.name}").get_value_plain - #{builder.post.join("\n")} - #{builder.retval} - end - CODE + converting_getter_def else - return <<-CODE.reset_indentation - def #{@info.getter_name} - get_property("#{@info.name}").get_value - end - CODE + simple_getter_def end end def setter_def case type_info.flattened_tag when :glist, :ghash, :strv - argument_info = FieldArgumentInfo.new("value", type_info) - builder = ArgumentBuilder.new(VariableNameGenerator.new, argument_info) - - return <<-CODE.reset_indentation - def #{@info.getter_name}= value - #{builder.pre.join("\n")} - set_property("#{@info.name}", #{builder.callarg}) - end - CODE + converting_setter_def else - return <<-CODE.reset_indentation - def #{@info.getter_name}= value - set_property("#{@info.name}", value) - end - CODE + simple_setter_def end end private + def converting_getter_def + return <<-CODE.reset_indentation + def #{getter_name} + #{getter_builder.callarg} = get_property("#{property_name}").get_value_plain + #{getter_builder.post.join("\n")} + #{getter_builder.retval} + end + CODE + end + + def simple_getter_def + return <<-CODE.reset_indentation + def #{getter_name} + get_property("#{property_name}").get_value + end + CODE + end + + def getter_builder + @getter_builder ||= ReturnValueBuilder.new(VariableNameGenerator.new, + argument_info) + end + + def converting_setter_def + return <<-CODE.reset_indentation + def #{setter_name} value + #{setter_builder.pre.join("\n")} + set_property("#{property_name}", #{setter_builder.callarg}) + end + CODE + end + + def simple_setter_def + return <<-CODE.reset_indentation + def #{setter_name} value + set_property("#{property_name}", value) + end + CODE + end + + def setter_builder + @setter_builder ||= ArgumentBuilder.new(VariableNameGenerator.new, + argument_info) + end + + def property_name + @info.name + end + + def getter_name + @info.getter_name + end + + def setter_name + @info.setter_name + end + def type_info @type_info ||= @info.property_type end + def argument_info + @argument_info ||= FieldArgumentInfo.new("value", type_info) + end end end end diff --git a/lib/gir_ffi/info_ext/i_property_info.rb b/lib/gir_ffi/info_ext/i_property_info.rb index <HASH>..<HASH> 100644 --- a/lib/gir_ffi/info_ext/i_property_info.rb +++ b/lib/gir_ffi/info_ext/i_property_info.rb @@ -5,6 +5,10 @@ module GirFFI def getter_name name.gsub(/-/, '_') end + + def setter_name + "#{getter_name}=" + end end end end
Refactor complicated #getter_def and #setter_def of PropertyBuilder
mvz_gir_ffi
train
fd8e4d0a82d09472738aa774f943f20d8bc9b090
diff --git a/lib/js-yaml/parser.js b/lib/js-yaml/parser.js index <HASH>..<HASH> 100644 --- a/lib/js-yaml/parser.js +++ b/lib/js-yaml/parser.js @@ -120,8 +120,8 @@ module.exports = function parse(input, settings) { character = input.charCodeAt(position), safeMode = true, legacyMode, - implicitResolvers = [], - explicitResolvers = {}, + implicitResolvers = coreSchema.compileImplicit(null), + explicitResolvers = coreSchema.compileExplicit(null), directiveHandlers = {}, tagMap, result, @@ -134,15 +134,6 @@ module.exports = function parse(input, settings) { } } - coreSchema.implicit.forEach(function (type) { - implicitResolvers.push(type.resolver); - explicitResolvers[type.tag] = type.resolver; - }); - - coreSchema.explicit.forEach(function (type) { - explicitResolvers[type.tag] = type.resolver; - }); - // NOTE: This is just a stub. function output(node) { if (null === documentsCollection) { @@ -1202,7 +1193,7 @@ module.exports = function parse(input, settings) { for (index = 0, amount = implicitResolvers.length; index < amount; index += 1) { - _result = implicitResolvers[index](result, false); + _result = implicitResolvers[index].resolver(result, false); if (NIL !== _result) { result = _result; @@ -1210,7 +1201,7 @@ module.exports = function parse(input, settings) { } } } else if (_hasOwn.call(explicitResolvers, tag)) { - _result = explicitResolvers[tag](result, true); + _result = explicitResolvers[tag].resolver(result, true); if (NIL !== _result) { result = _result; diff --git a/lib/js-yaml/schema.js b/lib/js-yaml/schema.js index <HASH>..<HASH> 100644 --- a/lib/js-yaml/schema.js +++ b/lib/js-yaml/schema.js @@ -1,7 +1,59 @@ 'use strict'; -module.exports = function Schema(definition) { +function Schema(definition) { + this.include = definition.include || []; this.implicit = definition.implicit || []; this.explicit = definition.explicit || []; +} + + +Schema.prototype.compileImplicit = function compileImplicit(result) { + var index, length, type; + + if (!result) { + result = []; + } + + for (index = 0, length = this.implicit.length; index < length; index += 1) { + type = this.implicit[index]; + + if (-1 === result.indexOf(type)) { + result.push(type); + } + } + + for (index = 0, length = this.include.length; index < length; index += 1) { + result = this.include[index].compileImplicit(result); + } + + return result; +}; + + +Schema.prototype.compileExplicit = function compileExplicit(result) { + var index, length, type; + + if (!result) { + result = {}; + } + + for (index = 0, length = this.include.length; index < length; index += 1) { + result = this.include[index].compileExplicit(result); + } + + for (index = 0, length = this.implicit.length; index < length; index += 1) { + type = this.implicit[index]; + result[type.tag] = type; + } + + for (index = 0, length = this.explicit.length; index < length; index += 1) { + type = this.explicit[index]; + result[type.tag] = type; + } + + return result; }; + + +module.exports = Schema;
Add compilation and inheritance of the schemas.
nodeca_js-yaml
train
5ce0523322840030f990e4ea70648e5cdcca4522
diff --git a/lib/api.js b/lib/api.js index <HASH>..<HASH> 100644 --- a/lib/api.js +++ b/lib/api.js @@ -199,13 +199,13 @@ Api.prototype = { /** * Check if we have to instantiate returned data */ - if (requestOptions.dataClass) { + if (requestOptions.dataClass && !resolveWithFullResponse) { if (_.isArray(data)) { - data = _.map(data, function(dataItem) { + resolveArgument = _.map(data, function(dataItem) { return new requestOptions.dataClass(dataItem); }) } else { - data = new requestOptions.dataClass(data); + resolveArgument = new requestOptions.dataClass(data); } } } diff --git a/lib/config.js b/lib/config.js index <HASH>..<HASH> 100644 --- a/lib/config.js +++ b/lib/config.js @@ -11,7 +11,7 @@ module.exports = { /** * Base URL to MangoPay API - * Producion URL changes to baseUrl: 'https://api.mangopay.com' + * Production URL changes to baseUrl: 'https://api.mangopay.com' */ baseUrl: 'https://api.sandbox.mangopay.com',
Fix classes instantiation when specified after promise refactoring
Mangopay_mangopay2-nodejs-sdk
train
15c31e7669f666472e1339e30e873a5b1739c279
diff --git a/qless/__init__.py b/qless/__init__.py index <HASH>..<HASH> 100755 --- a/qless/__init__.py +++ b/qless/__init__.py @@ -47,6 +47,9 @@ class client(object): def tagged(self, tag, offset=0, count=25): return json.loads(self._tag([], ['get', tag, offset, count])) + def tags(self, offset=0, count=100): + return json.loads(self._tag([], ['top', offset, count])) + def complete(self, offset=0, count=25): return self._jobs([], ['complete', offset, count]) diff --git a/qless/qless-core b/qless/qless-core index <HASH>..<HASH> 160000 --- a/qless/qless-core +++ b/qless/qless-core @@ -1 +1 @@ -Subproject commit 09bc1dcf6255e720ee0afba4a3b45026f6f0525e +Subproject commit 867a503e3e598d31d7cadfdab8c6e13074a4cb8d diff --git a/test.py b/test.py index <HASH>..<HASH> 100755 --- a/test.py +++ b/test.py @@ -397,6 +397,34 @@ class TestTag(TestQless): jid = self.q.put(qless.Job, {'test': 'tag_put'}, tags=['foo', 'bar']) self.assertEqual(self.client.tagged('foo'), {'total': 1, 'jobs': [jid]}) self.assertEqual(self.client.tagged('bar'), {'total': 1, 'jobs': [jid]}) + + def test_tag_top(self): + # 1) Make sure that it only includes tags with more than one job associated with it + # 2) Make sure that when jobs are untagged, it decrements the count + # 3) When we tag a job, it increments the count + # 4) When jobs complete and expire, it decrements the count + # 5) When jobs are put, make sure it shows up in the tags + # 6) When canceled, decrements + self.assertEqual(self.client.tags(), {}) + jids = [self.q.put(qless.Job, {}, tags=['foo']) for i in range(10)] + self.assertEqual(self.client.tags(), ['foo']) + jobs = [self.client.job(jid).cancel() for jid in jids] + self.assertEqual(self.client.tags(), {}) + # Add only one back + a = self.q.put(qless.Job, {}, tags=['foo']) + self.assertEqual(self.client.tags(), {}) + # Add a second, and then tag it + b = self.client.job(self.q.put(qless.Job, {})) + b.tag('foo') + self.assertEqual(self.client.tags(), ['foo']) + b.untag('foo') + self.assertEqual(self.client.tags(), {}) + b.tag('foo') + # Test job expiration + self.client.config.set('jobs-history-count', 0) + self.assertEqual(len(self.q), 2) + self.q.pop().complete() + self.assertEqual(self.client.tags(), {}) class TestFail(TestQless): def test_fail_failed(self):
Added support (and tests) for getting the most-used tags.
seomoz_qless-py
train
535c034c06e7b62dfc516908d20488490da68a7f
diff --git a/indexing-service/src/main/java/io/druid/indexing/worker/Worker.java b/indexing-service/src/main/java/io/druid/indexing/worker/Worker.java index <HASH>..<HASH> 100644 --- a/indexing-service/src/main/java/io/druid/indexing/worker/Worker.java +++ b/indexing-service/src/main/java/io/druid/indexing/worker/Worker.java @@ -44,7 +44,7 @@ public class Worker @JsonProperty("version") String version ) { - this.scheme = scheme; + this.scheme = scheme == null ? "http" : scheme; // needed for backwards compatibility with older workers (pre-#4270) this.host = host; this.ip = ip; this.capacity = capacity;
assume scheme to be http if not present (#<I>)
apache_incubator-druid
train
93f390a14017393e6963be42f6a236a77078b988
diff --git a/babelapi/cli.py b/babelapi/cli.py index <HASH>..<HASH> 100644 --- a/babelapi/cli.py +++ b/babelapi/cli.py @@ -23,12 +23,6 @@ _cmdline_parser.add_argument( help='Print debugging statements.', ) _cmdline_parser.add_argument( - '-q', - '--quiet', - action='store_true', - help='Only print error messages.', -) -_cmdline_parser.add_argument( 'generator', type=str, help='Specify the path to a generator. It must have a .babelg.py extension.',
Removed -q flag from command line parser.
dropbox_stone
train
c452097e158b824e9402777638e935ed13485fa2
diff --git a/admin/index.php b/admin/index.php index <HASH>..<HASH> 100644 --- a/admin/index.php +++ b/admin/index.php @@ -100,7 +100,7 @@ print_header($strlicense, $strlicense, $strlicense, "", "", false, "&nbsp;", "&nbsp;"); print_heading("<a href=\"http://moodle.org\">Moodle</a> - Modular Object-Oriented Dynamic Learning Environment"); print_heading(get_string("copyrightnotice")); - print_simple_box_start("center"); + print_simple_box_start("center", '80%'); echo text_to_html(get_string("gpl")); print_simple_box_end(); echo "<br />"; @@ -205,7 +205,7 @@ notify("ERROR: Could not update release version in database!!"); } print_continue("index.php"); - print_simple_box_start("CENTER"); + print_simple_box_start("center", '80%'); if (file_exists("$CFG->dirroot/lang/en_utf8/docs/release.html")) { include("$CFG->dirroot/lang/en_utf8/docs/release.html"); } @@ -317,7 +317,7 @@ /// Deprecated database! Warning!! if (!empty($CFG->migrated_to_new_db)) { - print_simple_box_start('center','50%'); + print_simple_box_start('center','60%'); print_string('dbmigrationdeprecateddb','admin'); print_simple_box_end(); } @@ -357,7 +357,7 @@ if (!isset($CFG->registered) || $CFG->registered < (time() - 3600*24*30*6)) { $options = array(); $options['sesskey'] = $USER->sesskey; - print_simple_box_start('center'); + print_simple_box_start('center','60%'); echo '<div align="center">'; print_string('pleaseregister', 'admin'); print_single_button('register.php', $options, get_string('registration')); @@ -470,15 +470,14 @@ print_simple_box_end(); - print_simple_box_start(); - //////DUMMY FUNCTION HERE - if (optional_param('dbmigrate')) { + if (optional_param('dbmigrate')) { // ??? Is this actually used? + print_simple_box_start('center','60%'); require_once($CFG->dirroot.'/admin/utfdbmigrate.php'); db_migrate2utf8(); + print_simple_box_end(); } - print_simple_box_end(); print_footer($site);
Slightly fixing some bodgy boxes
moodle_moodle
train
07e916f9d5d88c1ea3e5fc8c6d81ffbb5cd1ad29
diff --git a/lib/Gitlab/Model/Commit.php b/lib/Gitlab/Model/Commit.php index <HASH>..<HASH> 100644 --- a/lib/Gitlab/Model/Commit.php +++ b/lib/Gitlab/Model/Commit.php @@ -79,7 +79,7 @@ class Commit extends AbstractModel /** * @param Project $project - * @param int|null $id + * @param string|null $id * @param Client|null $client * * @return void
Fix phpdoc for model Commit (#<I>)
m4tthumphrey_php-gitlab-api
train
f89f794a358b9a9ef3825ba7c24aa673706a6f60
diff --git a/caas/kubernetes/provider/application/application.go b/caas/kubernetes/provider/application/application.go index <HASH>..<HASH> 100644 --- a/caas/kubernetes/provider/application/application.go +++ b/caas/kubernetes/provider/application/application.go @@ -979,7 +979,7 @@ func (a *app) Units() ([]caas.Unit, error) { logger.Warningf("volume for volume mount %q not found", volMount.Name) continue } - if vol.Secret != nil && strings.HasPrefix(vol.Secret.SecretName, a.name+"-token") { + if vol.Secret != nil && strings.Contains(vol.Secret.SecretName, "-token") { logger.Tracef("ignoring volume source for service account secret: %v", vol.Name) continue } diff --git a/caas/kubernetes/provider/application/application_test.go b/caas/kubernetes/provider/application/application_test.go index <HASH>..<HASH> 100644 --- a/caas/kubernetes/provider/application/application_test.go +++ b/caas/kubernetes/provider/application/application_test.go @@ -1461,6 +1461,25 @@ func (s *applicationSuite) TestUnits(c *gc.C) { }, }, ) + // Add a volume with a secret for lp:1925721, the secret name must contain + // `-token` to be ignored. + podSpec.Volumes = append(podSpec.Volumes, + corev1.Volume{ + Name: "testme", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, + Secret: &corev1.SecretVolumeSource{ + SecretName: "charm-data-token", + }, + }, + }, + ) + podSpec.Containers[0].VolumeMounts = append(podSpec.Containers[0].VolumeMounts, + corev1.VolumeMount{ + Name: "testme", + MountPath: "path/to/here", + }, + ) pod := corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Namespace: s.namespace,
Fix for LP:<I>. The secret name for a Volume must contain `-token`, the app name is not required.
juju_juju
train
bdb5335f4d15e099951fbc93a4bb83529546fc57
diff --git a/sh.py b/sh.py index <HASH>..<HASH> 100644 --- a/sh.py +++ b/sh.py @@ -468,7 +468,7 @@ class Command(object): if not path: raise CommandNotFound(program) cmd = cls(path) - if default_kwargs: cmd = cmd.bake(default_kwargs) + if default_kwargs: cmd = cmd.bake(**default_kwargs) return cmd @@ -1503,7 +1503,7 @@ class StreamBufferer(object): # the exec() statement used in this file requires the "globals" argument to # be a dictionary class Environment(dict): - def __init__(self, globs, baked_args): + def __init__(self, globs, baked_args={}): self.globs = globs self.baked_args = baked_args @@ -1598,7 +1598,7 @@ def run_repl(env): # system PATH worth of commands. in this case, we just proxy the # import lookup to our Environment class class SelfWrapper(ModuleType): - def __init__(self, self_module, baked_args): + def __init__(self, self_module, baked_args={}): # this is super ugly to have to copy attributes like this, # but it seems to be the only way to make reload() behave # nicely. if i make these attributes dynamic lookups in diff --git a/test.py b/test.py index <HASH>..<HASH> 100644 --- a/test.py +++ b/test.py @@ -1340,7 +1340,14 @@ sys.stdout.write("te漢字st") def test_shared_secial_args(self): import sh - from StringIO import StringIO + + if IS_PY3: + from io import StringIO + from io import BytesIO as cStringIO + else: + from StringIO import StringIO + from cStringIO import StringIO as cStringIO + out1 = sh.ls('.') out2 = StringIO() sh_new = sh(_out=out2)
top-level sh module baking. closes #<I> #<I> and #<I>
amoffat_sh
train
6066063a7411304c7d85717ac6d5dff4ce7c9bf3
diff --git a/lib/hyrax/collection_name.rb b/lib/hyrax/collection_name.rb index <HASH>..<HASH> 100644 --- a/lib/hyrax/collection_name.rb +++ b/lib/hyrax/collection_name.rb @@ -10,6 +10,8 @@ module Hyrax @human = 'Collection' @i18n_key = :collection + @param_key = 'collection' + @plural = 'collections' @route_key = 'collections' @singular_route_key = 'collection' end diff --git a/spec/models/hyrax/pcdm_collection_spec.rb b/spec/models/hyrax/pcdm_collection_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/hyrax/pcdm_collection_spec.rb +++ b/spec/models/hyrax/pcdm_collection_spec.rb @@ -13,6 +13,8 @@ RSpec.describe Hyrax::PcdmCollection do expect(subject.model_name) .to have_attributes(human: "Collection", i18n_key: :collection, + param_key: "collection", + plural: "collections", route_key: "collections", singular_route_key: "collection") end
add param_key and plural to `Hyrax::CollectionName` we want the collection form data to be the same regardless of the model used. ActiveModel naming is the right place to handle this.
samvera_hyrax
train
3115c6ec513d4b36a57c943a7cc5f22e05535472
diff --git a/spec/grape/integration/rack_spec.rb b/spec/grape/integration/rack_spec.rb index <HASH>..<HASH> 100644 --- a/spec/grape/integration/rack_spec.rb +++ b/spec/grape/integration/rack_spec.rb @@ -18,6 +18,10 @@ describe Rack do 'CONTENT_TYPE' => 'application/json' } env = Rack::MockRequest.env_for('/', options) + + major, minor, release = Rack.release.split('.').map(&:to_i) + pending 'Rack 1.5.3 or 1.6.1 required' unless major >= 1 && ((minor == 5 && release >= 3) || (minor >= 6)) + expect(JSON.parse(app.call(env)[2].body.first)['params_keys']).to match_array('test') ensure input.close
Fix: build for Rails 3 integration.
ruby-grape_grape
train
c45b5ff79e076e2a46b33514af2345812b1dd6fa
diff --git a/toml.py b/toml.py index <HASH>..<HASH> 100644 --- a/toml.py +++ b/toml.py @@ -558,7 +558,7 @@ def _load_array(a): tmpa = a[1:-1].strip() if tmpa != '' and tmpa[0] == '"': strarray = True - if '{' not in a[1:-1]: + if not a[1:-1].strip().startswith('{'): a = a[1:-1].split(',') else: # a is an inline object, we must find the matching parenthesis to difine groups
Fix #<I> detection of array of objects (inline tables) A string can contain '{', so "{ in s" is not a good enough test of whether something is an inline table.
uiri_toml
train
42eed95a0dac421f189268141cd9ab1536eafc63
diff --git a/zzk/virtualips/virtualips.go b/zzk/virtualips/virtualips.go index <HASH>..<HASH> 100644 --- a/zzk/virtualips/virtualips.go +++ b/zzk/virtualips/virtualips.go @@ -37,8 +37,8 @@ func RemoveAllVirtualIPs() error { } glog.V(2).Infof("Removing all virtual IPs...") for _, virtualIP := range interfaceMap { - if err := unbindVirtualIP(virtualIP); err != nil { - return fmt.Errorf("unbindVirtualIP failed: %v", err) + if err := removeVirtualIP(virtualIP.IP); err != nil { + return fmt.Errorf("removeVirtualIP failed: %v", err) } } glog.V(2).Infof("All virtual IPs have been removed.") @@ -390,19 +390,13 @@ func createVirtualInterfaceMap() (error, map[string]pool.VirtualIP) { return err, interfaceMap } - virtualIPAddressAndCIDRStr := strings.Split(string(virtualIPAddressAndCIDR), "/") - if len(virtualIPAddressAndCIDRStr) != 2 { - err := fmt.Errorf("Unexpected IPAddress/CIDR format: %v", virtualIPAddressAndCIDRStr) + virtualIPAddress, network, err := net.ParseCIDR(strings.TrimSpace(string(virtualIPAddressAndCIDR))) + if err != nil { return err, interfaceMap } - virtualIPAddress := strings.TrimSpace(virtualIPAddressAndCIDRStr[0]) - cidr := strings.TrimSpace(virtualIPAddressAndCIDRStr[1]) - netmask := convertCIDRToNetmask(cidr) - if netmask == "" { - return fmt.Errorf("Illegal CIDR: %v", cidr), interfaceMap - } + netmask := net.IP(network.Mask) - interfaceMap[virtualInterfaceName] = pool.VirtualIP{PoolID: "", IP: strings.TrimSpace(string(virtualIPAddress)), Netmask: netmask, BindInterface: bindInterface} + interfaceMap[virtualInterfaceName] = pool.VirtualIP{PoolID: "", IP: virtualIPAddress.String(), Netmask: netmask.String(), BindInterface: bindInterface} } return nil, interfaceMap @@ -456,7 +450,7 @@ func removeVirtualIP(virtualIPAddress string) error { } } - glog.Warningf("Requested virtual IP address: %v is not on this host.", virtualIPAddress) + glog.Infof("Requested virtual IP address: %v was not on this host.", virtualIPAddress) return nil } @@ -497,82 +491,3 @@ func unbindVirtualIP(virtualIP pool.VirtualIP) error { glog.Infof("Removed virtual interface: %+v", virtualIP) return nil } - -func convertCIDRToNetmask(cidr string) string { - switch { - case cidr == "0": - return "0.0.0.0" - case cidr == "1": - return "128.0.0.0" - case cidr == "2": - return "192.0.0.0" - case cidr == "3": - return "224.0.0.0" - case cidr == "4": - return "240.0.0.0" - case cidr == "5": - return "248.0.0.0" - case cidr == "6": - return "252.0.0.0" - case cidr == "7": - return "254.0.0.0" - - // class A - case cidr == "8": - return "255.0.0.0" - case cidr == "9": - return "255.128.0.0" - case cidr == "10": - return "255.192.0.0" - case cidr == "11": - return "255.224.0.0" - case cidr == "12": - return "255.240.0.0" - case cidr == "13": - return "255.248.0.0" - case cidr == "14": - return "255.252.0.0" - case cidr == "15": - return "255.254.0.0" - - // class B - case cidr == "16": - return "255.255.0.0" - case cidr == "17": - return "255.255.128.0" - case cidr == "18": - return "255.255.192.0" - case cidr == "19": - return "255.255.224.0" - case cidr == "20": - return "255.255.240.0" - case cidr == "21": - return "255.255.248.0" - case cidr == "22": - return "255.255.252.0" - case cidr == "23": - return "255.255.254.0" - - // class C - case cidr == "24": - return "255.255.255.0" - - case cidr == "25": - return "255.255.255.128" - case cidr == "26": - return "255.255.255.192" - case cidr == "27": - return "255.255.255.224" - case cidr == "28": - return "255.255.255.240" - case cidr == "29": - return "255.255.255.248" - case cidr == "30": - return "255.255.255.252" - case cidr == "31": - return "255.255.255.254" - case cidr == "32": - return "255.255.255.255" - } - return "" -}
CIDRs can be translated to a netmask
control-center_serviced
train
394862d5415b3e0ef0a67d112a55bff9f1e0a753
diff --git a/tx.go b/tx.go index <HASH>..<HASH> 100644 --- a/tx.go +++ b/tx.go @@ -242,7 +242,6 @@ func (tx *Tx) Copy(w io.Writer) error { // Open reader on the database. f, err := os.OpenFile(tx.db.path, os.O_RDONLY|odirect, 0) if err != nil { - _ = tx.Rollback() return err } @@ -251,14 +250,12 @@ func (tx *Tx) Copy(w io.Writer) error { _, err = io.CopyN(w, f, int64(tx.db.pageSize*2)) tx.db.metalock.Unlock() if err != nil { - _ = tx.Rollback() _ = f.Close() return fmt.Errorf("meta copy: %s", err) } // Copy data pages. if _, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2)); err != nil { - _ = tx.Rollback() _ = f.Close() return err } diff --git a/tx_test.go b/tx_test.go index <HASH>..<HASH> 100644 --- a/tx_test.go +++ b/tx_test.go @@ -338,6 +338,57 @@ func TestTx_CopyFile(t *testing.T) { }) } +type failWriterError struct{} + +func (failWriterError) Error() string { + return "error injected for tests" +} + +type failWriter struct { + // fail after this many bytes + After int +} + +func (f *failWriter) Write(p []byte) (n int, err error) { + n = len(p) + if n > f.After { + n = f.After + err = failWriterError{} + } + f.After -= n + return n, err +} + +// Ensure that Copy handles write errors right. +func TestTx_CopyFile_Error_Meta(t *testing.T) { + withOpenDB(func(db *DB, path string) { + db.Update(func(tx *Tx) error { + tx.CreateBucket([]byte("widgets")) + tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")) + tx.Bucket([]byte("widgets")).Put([]byte("baz"), []byte("bat")) + return nil + }) + + err := db.View(func(tx *Tx) error { return tx.Copy(&failWriter{}) }) + assert.EqualError(t, err, "meta copy: error injected for tests") + }) +} + +// Ensure that Copy handles write errors right. +func TestTx_CopyFile_Error_Normal(t *testing.T) { + withOpenDB(func(db *DB, path string) { + db.Update(func(tx *Tx) error { + tx.CreateBucket([]byte("widgets")) + tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")) + tx.Bucket([]byte("widgets")).Put([]byte("baz"), []byte("bat")) + return nil + }) + + err := db.View(func(tx *Tx) error { return tx.Copy(&failWriter{3 * db.pageSize}) }) + assert.EqualError(t, err, "error injected for tests") + }) +} + func ExampleTx_Rollback() { // Open the database. db, _ := Open(tempfile(), 0666)
Do not attempt manual transaction rollback in Tx.Copy The typical use these days is with a managed transaction, via db.View. The first case (error when re-opening database file) is not tested; it is harder to instrument, and I have other plans for it.
boltdb_bolt
train
2e9312dcd6696495a53de9793254543d9a9f5eec
diff --git a/spec/footnotes_spec.rb b/spec/footnotes_spec.rb index <HASH>..<HASH> 100644 --- a/spec/footnotes_spec.rb +++ b/spec/footnotes_spec.rb @@ -56,12 +56,9 @@ describe "Footnotes" do end end - #TODO doe's not pased with 1.8.7 - if RUBY_VERSION >= '1.9.0' - it "foonotes_included" do - footnotes_perform! - @controller.response_body.should_not == HTML_DOCUMENT - end + it "foonotes_included" do + footnotes_perform! + @controller.response_body.should_not == HTML_DOCUMENT end specify "footnotes_not_included_when_request_is_xhr" do
Remove condition for deprecated ruby version
josevalim_rails-footnotes
train
646477a2359c516d7fad2c230155046fe662b6be
diff --git a/cheroot/test/test_cli.py b/cheroot/test/test_cli.py index <HASH>..<HASH> 100644 --- a/cheroot/test/test_cli.py +++ b/cheroot/test/test_cli.py @@ -1,37 +1,70 @@ +"""Tests to verify the command line interface.""" +# -*- coding: utf-8 -*- +# vim: set fileencoding=utf-8 : +import sys + +import pytest + from cheroot.cli import ( Application, - parse_wsgi_bind_addr + parse_wsgi_bind_addr, ) -def test_parse_wsgi_bind_location_for_tcpip(): - assert parse_wsgi_bind_addr('192.168.1.1:80') == ('192.168.1.1', 80) - assert parse_wsgi_bind_addr('[::1]:8000') == ('::1', 8000) +@pytest.mark.parametrize( + 'raw_bind_addr, expected_bind_addr', ( + ('192.168.1.1:80', ('192.168.1.1', 80)), + ('[::1]:8000', ('::1', 8000)), + ), +) +def test_parse_wsgi_bind_addr_for_tcpip(raw_bind_addr, expected_bind_addr): + """Check the parsing of the --bind option for TCP/IP addresses.""" + assert parse_wsgi_bind_addr(raw_bind_addr) == expected_bind_addr -def test_parse_wsgi_bind_location_for_unix_socket(): +def test_parse_wsgi_bind_addr_for_unix_socket(): + """Check the parsing of the --bind option for UNIX Sockets.""" assert parse_wsgi_bind_addr('/tmp/cheroot.sock') == '/tmp/cheroot.sock' def test_parse_wsgi_bind_addr_for_abstract_unix_socket(): + """Check the parsing of the --bind option for Abstract UNIX Sockets.""" assert parse_wsgi_bind_addr('@cheroot') == '\0cheroot' -def test_Aplication_resolve(): - import sys - - class WSGIAppMock: - def application(self): - pass - - def main(self): - pass - try: - wsgi_app_mock = WSGIAppMock() - sys.modules['mypkg.wsgi'] = wsgi_app_mock - app = Application.resolve('mypkg.wsgi') - assert app.wsgi_app == wsgi_app_mock.application - app = Application.resolve('mypkg.wsgi:main') - assert app.wsgi_app == wsgi_app_mock.main - finally: - del sys.modules['mypkg.wsgi'] +class WSGIAppMock: + """Mock of a wsgi module.""" + + def application(self): + """Empty application method. + + Default method to be called when no specific callable + is defined in the wsgi application identifier. + + It has an empty body because we are expecting to verify that + the same method is return no the actual execution of it. + """ + + def main(self): + """Empty custom method (callable) inside the mocked WSGI app. + + It has an empty body because we are expecting to verify that + the same method is return no the actual execution of it. + """ + + +@pytest.mark.parametrize( + 'wsgi_app_spec, pkg_name, app_method, mocked_app', ( + ('mypkg.wsgi', 'mypkg.wsgi', 'application', WSGIAppMock()), + ('mypkg.wsgi:application', 'mypkg.wsgi', 'application', WSGIAppMock()), + ('mypkg.wsgi:main', 'mypkg.wsgi', 'main', WSGIAppMock()), + ), +) +def test_Aplication_resolve( + monkeypatch, + wsgi_app_spec, pkg_name, app_method, mocked_app, +): + """Check the wsgi application name conversion.""" + monkeypatch.setitem(sys.modules, pkg_name, mocked_app) + expected_app = getattr(mocked_app, app_method) + assert Application.resolve(wsgi_app_spec).wsgi_app == expected_app
Modify test_cli.py to make it follow the pytest and sytlistic conventions.
cherrypy_cheroot
train
531768b374129ba2259d7a1035aaf840f1d52b50
diff --git a/lib/rye/hop.rb b/lib/rye/hop.rb index <HASH>..<HASH> 100644 --- a/lib/rye/hop.rb +++ b/lib/rye/hop.rb @@ -273,7 +273,7 @@ module Rye @rye_opts[:paranoid] = false retry else - raise Net::SSH::HostKeyMismatch + raise ex end rescue Net::SSH::AuthenticationFailed => ex print "\a" if retried == 0 && @rye_info # Ring the bell once @@ -285,7 +285,7 @@ module Rye @rye_opts[:auth_methods].push *['keyboard-interactive', 'password'] retry else - raise Net::SSH::AuthenticationFailed + raise ex end end
Propogate AuthenticationFailed and HostKeyMismatch exceptions for Rye::Hop
delano_rye
train
2ef4baf0d952c0923060e01d5977f6d980e6195f
diff --git a/protoc-gen-go/testdata/main_test.go b/protoc-gen-go/testdata/main_test.go index <HASH>..<HASH> 100644 --- a/protoc-gen-go/testdata/main_test.go +++ b/protoc-gen-go/testdata/main_test.go @@ -36,8 +36,8 @@ package testdata import ( "testing" - mytestpb "./my_test" multipb "github.com/golang/protobuf/protoc-gen-go/testdata/multi" + mytestpb "github.com/golang/protobuf/protoc-gen-go/testdata/my_test" ) func TestLink(t *testing.T) {
protoc-gen-go: remove relative import in main_test.go (#<I>) No particular reason for this to be a ./ import, and it confuses vgo.
golang_protobuf
train
0b0a32f71302ea472093f0cc2ba3b2ec3fa6dfd4
diff --git a/sportsreference/ncaab/schedule.py b/sportsreference/ncaab/schedule.py index <HASH>..<HASH> 100644 --- a/sportsreference/ncaab/schedule.py +++ b/sportsreference/ncaab/schedule.py @@ -398,7 +398,7 @@ class Schedule: """ if not year: year = utils._find_year_for_season('ncaab') - doc = pq(SCHEDULE_URL % (year, abbreviation)) + doc = pq(SCHEDULE_URL % (abbreviation.lower(), year)) schedule = utils._get_stats_table(doc, 'table#schedule') for item in schedule:
Fix the URL to pull NCAAB stats from
roclark_sportsreference
train
c4741931810cf22d179213e35d85c5cb144f97f1
diff --git a/server/sources.go b/server/sources.go index <HASH>..<HASH> 100644 --- a/server/sources.go +++ b/server/sources.go @@ -53,7 +53,7 @@ func newSourceResponse(src chronograf.Source) sourceResponse { }, } - if src.Type == chronograf.InfluxEnterprise { + if src.Type == chronograf.InfluxEnterprise && len(src.MetaURL) != 0 { res.Links.Roles = fmt.Sprintf("%s/%d/roles", httpAPISrcs, src.ID) } return res
Will not supply roles if there is no metaURL
influxdata_influxdb
train
9031cd090bf2972d58c76cb77feec8be41c012e6
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/cache/OCacheEntryImpl.java b/core/src/main/java/com/orientechnologies/orient/core/storage/cache/OCacheEntryImpl.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/cache/OCacheEntryImpl.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/cache/OCacheEntryImpl.java @@ -42,6 +42,14 @@ public class OCacheEntryImpl implements OCacheEntry { private int hash; public OCacheEntryImpl(final long fileId, final int pageIndex, final OCachePointer dataPointer) { + if (fileId < 0) { + throw new IllegalStateException("File id has invalid value " + fileId); + } + + if (pageIndex < 0) { + throw new IllegalStateException("Page index has invalid value " + pageIndex); + } + this.fileId = fileId; this.pageIndex = pageIndex; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/cache/OCachePointer.java b/core/src/main/java/com/orientechnologies/orient/core/storage/cache/OCachePointer.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/cache/OCachePointer.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/cache/OCachePointer.java @@ -60,6 +60,15 @@ public final class OCachePointer { this.pointer = pointer; this.bufferPool = bufferPool; + if (fileId < 0) { + throw new IllegalStateException("File id has invalid value " + fileId); + } + + if (pageIndex < 0) { + throw new IllegalStateException("Page index has invalid value " + pageIndex); + } + + this.fileId = fileId; this.pageIndex = pageIndex; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/cache/local/OWOWCache.java b/core/src/main/java/com/orientechnologies/orient/core/storage/cache/local/OWOWCache.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/cache/local/OWOWCache.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/cache/local/OWOWCache.java @@ -160,7 +160,7 @@ public final class OWOWCache extends OAbstractWriteCache implements OWriteCache, private static final int PAGE_OFFSET_TO_CHECKSUM_FROM = OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE; - private static final int CHUNK_SIZE = 64 * 1024 * 1024; + private static final int CHUNK_SIZE = 4 * 1024 * 1024; /** * Executor which runs in single thread all tasks are related to flush of write cache data. @@ -1182,7 +1182,12 @@ public final class OWOWCache extends OAbstractWriteCache implements OWriteCache, //otherwise we switch storage in read-only mode freeSpaceCheckAfterNewPageAdd(); - return (int) allocationIndex; + final int pageIndex = (int) allocationIndex; + if (pageIndex < 0) { + throw new IllegalStateException("Illegal page index value " + pageIndex); + } + + return pageIndex; } else { allocationIndex = fileClassic.getFileSize() / pageSize; } @@ -2736,7 +2741,7 @@ public final class OWOWCache extends OAbstractWriteCache implements OWriteCache, if (firstSegment != null && firstSegment.getKey() < endSegment) { final TreeSet<PageKey> pages = firstSegment.getValue(); - if (pages.size() >= 16 * chunkSize) { + if (pages.size() >= 256 * chunkSize) { flushChunk(lsnFlushInterval, startSegment, endSegment); } } @@ -3037,7 +3042,7 @@ public final class OWOWCache extends OAbstractWriteCache implements OWriteCache, flushTs = System.nanoTime(); } - boolean fsyncFiles = false; + final boolean fsyncFiles; int flushedPages = 0; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java @@ -294,7 +294,7 @@ public final class OFileClassic implements OClosableItem { try { if (iOffset < 0 || iOffset + iLength > size) { throw new OIOException( - "You cannot access outside the file size (" + size + " bytes). You have requested portion " + iOffset + "-" + (iOffset + "You cannot access outside the file size (" + size + " bytes). You have requested portion from " + iOffset + "-" + (iOffset + iLength) + " bytes. File: " + this); }
Size of chunk for single flush was decreased. Page index validation was added.
orientechnologies_orientdb
train
1db2002d1fd5f3f08bdf44757e56d8add8b6020e
diff --git a/impl/src/main/java/org/ehcache/internal/persistence/DefaultLocalPersistenceService.java b/impl/src/main/java/org/ehcache/internal/persistence/DefaultLocalPersistenceService.java index <HASH>..<HASH> 100644 --- a/impl/src/main/java/org/ehcache/internal/persistence/DefaultLocalPersistenceService.java +++ b/impl/src/main/java/org/ehcache/internal/persistence/DefaultLocalPersistenceService.java @@ -36,6 +36,7 @@ import java.security.NoSuchAlgorithmException; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; +import java.util.Locale; import java.util.Set; import static java.lang.Integer.toHexString; @@ -265,23 +266,32 @@ public class DefaultLocalPersistenceService implements LocalPersistenceService { } private static boolean tryRecursiveDelete(File file) { - boolean success = true; - for (int i = 0; i < 5; i++) { - success = recursiveDelete(file); - if (success) { - break; - } else { - System.gc(); - System.runFinalization(); + boolean interrupted = false; + try { + for (int i = 0; i < 5; i++) { + if (recursiveDelete(file) || !isWindows()) { + return true; + } else { + System.gc(); + System.runFinalization(); - try { - Thread.sleep(50); - } catch (InterruptedException e) { - // do nothing ? + try { + Thread.sleep(50); + } catch (InterruptedException e) { + interrupted = true; + } } } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } } - return success; + return false; + } + + private static boolean isWindows() { + return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows"); } /** diff --git a/impl/src/test/java/org/ehcache/internal/persistence/CacheManagerDestroyRemovesPersistenceTest.java b/impl/src/test/java/org/ehcache/internal/persistence/CacheManagerDestroyRemovesPersistenceTest.java index <HASH>..<HASH> 100644 --- a/impl/src/test/java/org/ehcache/internal/persistence/CacheManagerDestroyRemovesPersistenceTest.java +++ b/impl/src/test/java/org/ehcache/internal/persistence/CacheManagerDestroyRemovesPersistenceTest.java @@ -56,11 +56,10 @@ public class CacheManagerDestroyRemovesPersistenceTest { } @Test - public void testDestoryCacheDestroysPersistenceContext() throws URISyntaxException, CachePersistenceException { + public void testDestroyCacheDestroysPersistenceContext() throws URISyntaxException, CachePersistenceException { File file = new File(getStoragePath(), "testDestory"); initCacheManager(file); - persistentCacheManager.destroyCache("persistent-cache"); assertThat(file.list().length, is(1));
Adding os check and review comments #<I>
ehcache_ehcache3
train
cf2c953ef9cb68f38aec859ee647ed0865e44d20
diff --git a/revapi-java/src/main/java/org/revapi/java/JavaElementDifferenceAnalyzer.java b/revapi-java/src/main/java/org/revapi/java/JavaElementDifferenceAnalyzer.java index <HASH>..<HASH> 100644 --- a/revapi-java/src/main/java/org/revapi/java/JavaElementDifferenceAnalyzer.java +++ b/revapi-java/src/main/java/org/revapi/java/JavaElementDifferenceAnalyzer.java @@ -270,6 +270,9 @@ public final class JavaElementDifferenceAnalyzer implements DifferenceAnalyzer { case RETURN_TYPE: message = "revapi.java.uses.returnType"; break; + case CONTAINS: + message = "revapi.java.uses.contains"; + break; default: throw new AssertionError("Invalid use type."); } diff --git a/revapi-java/src/main/java/org/revapi/java/compilation/ProbingEnvironment.java b/revapi-java/src/main/java/org/revapi/java/compilation/ProbingEnvironment.java index <HASH>..<HASH> 100644 --- a/revapi-java/src/main/java/org/revapi/java/compilation/ProbingEnvironment.java +++ b/revapi-java/src/main/java/org/revapi/java/compilation/ProbingEnvironment.java @@ -279,6 +279,9 @@ public final class ProbingEnvironment implements TypeEnvironment { } } break; + case CONTAINS: + user = userType; + break; } if (user == null) { diff --git a/revapi-java/src/main/resources/org/revapi/java/messages.properties b/revapi-java/src/main/resources/org/revapi/java/messages.properties index <HASH>..<HASH> 100644 --- a/revapi-java/src/main/resources/org/revapi/java/messages.properties +++ b/revapi-java/src/main/resources/org/revapi/java/messages.properties @@ -7,3 +7,4 @@ revapi.java.uses.hasType={0} revapi.java.uses.returnType=is returned from {0} revapi.java.uses.parameterType=is used as parameter in {0} revapi.java.uses.isThrown=is thrown from {0} +revapi.java.uses.contains=contains {0}
Correctly report "contains" use sites.
revapi_revapi
train
9745ec399b488c6c812eeb1e6b935a382d02895f
diff --git a/packages/avatar/src/Avatar.js b/packages/avatar/src/Avatar.js index <HASH>..<HASH> 100644 --- a/packages/avatar/src/Avatar.js +++ b/packages/avatar/src/Avatar.js @@ -6,6 +6,8 @@ import { ThemeContext } from "@hig/theme-context"; import { sizes, AVAILABLE_SIZES } from "./sizes"; import stylesheet from "./Avatar.stylesheet"; +const COLOR_VARIANT_COUNT = 7; + /** * @param {number} value * @param {number[]} range1 @@ -24,7 +26,11 @@ function convertRanges(value, range1, range2) { * @returns {string} */ function backgroundIdFromName(name) { - return convertRanges(name.charCodeAt(0) - 65, [0, 26], [1, 8]); + return convertRanges( + name.charCodeAt(0) - 65, + [0, 26], + [1, COLOR_VARIANT_COUNT] + ); } /**
fix: Shows a bg color for names starting w/ Z
Autodesk_hig
train
e599fb9b01356a73c445092e5a415fb9ca1db1f1
diff --git a/src/github.com/CapillarySoftware/gostat/bucketer/bucketer_test.go b/src/github.com/CapillarySoftware/gostat/bucketer/bucketer_test.go index <HASH>..<HASH> 100644 --- a/src/github.com/CapillarySoftware/gostat/bucketer/bucketer_test.go +++ b/src/github.com/CapillarySoftware/gostat/bucketer/bucketer_test.go @@ -35,6 +35,10 @@ var _ = Describe("Bucketer", func() { // the previous bucket's min time is exactly one minute less than the current bucket's min time Expect(x.currentBucketMinTime.Sub(x.previousBucketMinTime)).To(Equal(time.Duration(time.Minute))) + + // verify the input channels + Expect(x.input).NotTo(BeClosed()) + Expect(x.shutdown).NotTo(BeClosed()) }) })
assert receive channels are not closed on construction
CapillarySoftware_gostat
train
1f2b2908bd8328db5f3e4e9dc6010476f75648ca
diff --git a/lib/xcodeproj/workspace.rb b/lib/xcodeproj/workspace.rb index <HASH>..<HASH> 100644 --- a/lib/xcodeproj/workspace.rb +++ b/lib/xcodeproj/workspace.rb @@ -97,15 +97,17 @@ module Xcodeproj # def <<(path_or_reference) return unless @document && @document.respond_to?(:root) - case - when path_or_reference.is_a?(String) + + case path_or_reference + when String project_file_reference = Xcodeproj::Workspace::FileReference.new(path_or_reference) - when path_or_reference.is_a?(Xcodeproj::Workspace::FileReference) + when Xcodeproj::Workspace::FileReference project_file_reference = path_or_reference projpath = nil else - raise ArgumentError, 'Input to the << operator must be a file path or FileReference' + raise ArgumentError, "Input to the << operator must be a file path or FileReference, got #{path_or_reference.inspect}" end + @document.root.add_element(project_file_reference.to_node) load_schemes_from_project File.expand_path(projpath || project_file_reference.path) end
[Workspace] Raise a better exception when adding an invalid object to a workspace
CocoaPods_Xcodeproj
train
f33d603f92c6168c73f97c7b32f80eb0f55c6bef
diff --git a/jetserver/src/main/java/org/menacheri/jetserver/app/impl/DefaultSession.java b/jetserver/src/main/java/org/menacheri/jetserver/app/impl/DefaultSession.java index <HASH>..<HASH> 100644 --- a/jetserver/src/main/java/org/menacheri/jetserver/app/impl/DefaultSession.java +++ b/jetserver/src/main/java/org/menacheri/jetserver/app/impl/DefaultSession.java @@ -30,11 +30,11 @@ public class DefaultSession implements Session /** * session id */ - protected final String id; + protected final Object id; /** * event dispatcher */ - protected final EventDispatcher eventDispatcher; + protected EventDispatcher eventDispatcher; /** * session parameters @@ -93,16 +93,16 @@ public class DefaultSession implements Session /** * Used to set a unique id on the incoming sessions to this room. */ - private static final AtomicInteger SESSION_ID = new AtomicInteger(0); - private String id = null; - private EventDispatcher eventDispatcher = null; - private Map<String, Object> sessionAttributes = null; - private long creationTime = 0l; - private long lastReadWriteTime = 0l; - private Status status = Status.NOT_CONNECTED; - private boolean isWriteable = true; - private volatile boolean isShuttingDown = false; - private boolean isUDPEnabled = false;// By default UDP is not enabled. + protected static final AtomicInteger SESSION_ID = new AtomicInteger(0); + protected Object id = null; + protected EventDispatcher eventDispatcher = null; + protected Map<String, Object> sessionAttributes = null; + protected long creationTime = 0l; + protected long lastReadWriteTime = 0l; + protected Status status = Status.NOT_CONNECTED; + protected boolean isWriteable = true; + protected volatile boolean isShuttingDown = false; + protected boolean isUDPEnabled = false;// By default UDP is not enabled. public Session build() { @@ -123,7 +123,7 @@ public class DefaultSession implements Session } if (null == eventDispatcher) { - eventDispatcher = EventDispatchers.newJetlangEventDispatcher(); + eventDispatcher = EventDispatchers.newJetlangEventDispatcher(null,null); } if(null == sessionAttributes) { @@ -132,7 +132,7 @@ public class DefaultSession implements Session creationTime = System.currentTimeMillis(); } - public String getId() + public Object getId() { return id; }
id is now of type object. Also, private builder variables have been made protected.
menacher_java-game-server
train
d8845e3245491a85c2cc6c932d5fad2c260c19d3
diff --git a/h2o-core/src/main/java/water/api/ModelMetricsBinomialV3.java b/h2o-core/src/main/java/water/api/ModelMetricsBinomialV3.java index <HASH>..<HASH> 100644 --- a/h2o-core/src/main/java/water/api/ModelMetricsBinomialV3.java +++ b/h2o-core/src/main/java/water/api/ModelMetricsBinomialV3.java @@ -22,6 +22,9 @@ public class ModelMetricsBinomialV3<I extends ModelMetricsBinomial, S extends Mo @API(help="The Gini score for this scoring run.", direction=API.Direction.OUTPUT) public double Gini; + @API(help="The class labels of the response.", direction=API.Direction.OUTPUT) + public String[] domain; + // @API(help = "The ConfusionMatrix at the threshold for maximum F1.", direction = API.Direction.OUTPUT) // public ConfusionMatrixBase cm;
PUBDEV-<I>: Add the class labels of the response for binomial model metrics.
h2oai_h2o-3
train
edf71754f25ceae3e8d53fde531332973f47f661
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/RemoteProtocolCommandsTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/RemoteProtocolCommandsTest.java index <HASH>..<HASH> 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/RemoteProtocolCommandsTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/RemoteProtocolCommandsTest.java @@ -31,7 +31,7 @@ public class RemoteProtocolCommandsTest extends DocumentDBBaseTest { super(url); } - @Test + @Test(enabled = false) public void testConnect() throws Exception { final OServerAdmin admin = new OServerAdmin("remote:localhost:" + serverPort).connect("root", ODatabaseHelper.getServerRootPassword());
disables connectTest that fails silently avoind creation of jacoco report
orientechnologies_orientdb
train
171437ed9bf324dced90c304a93412d2eed28b63
diff --git a/worker/worker-execution/score-worker-execution-impl/src/main/java/io/cloudslang/worker/execution/services/ExecutionServiceImpl.java b/worker/worker-execution/score-worker-execution-impl/src/main/java/io/cloudslang/worker/execution/services/ExecutionServiceImpl.java index <HASH>..<HASH> 100644 --- a/worker/worker-execution/score-worker-execution-impl/src/main/java/io/cloudslang/worker/execution/services/ExecutionServiceImpl.java +++ b/worker/worker-execution/score-worker-execution-impl/src/main/java/io/cloudslang/worker/execution/services/ExecutionServiceImpl.java @@ -446,7 +446,10 @@ public final class ExecutionServiceImpl implements ExecutionService { pauseService.pauseExecution(executionId, branchId, reason); // this creates a DB record for this branch, as Pending-paused } } else if (reason == NO_ROBOTS_IN_GROUP || reason == PENDING_ROBOT) { - pauseService.pauseExecution(executionId, branchId, reason); + Long pauseId = pauseService.pauseExecution(executionId, branchId, reason); + if (pauseId != null && reason == NO_ROBOTS_IN_GROUP) { + logger.warn("Can't assign robot for group name: " + systemContext.getRobotGroupName() + "; because there are no available robots for that group."); + } } addPauseEvent(systemContext); // dump bus events here because out side is too late
Log warning for no robots in group (#<I>) * Add method signature to retrieve the context * log warning can't assign robot to group
CloudSlang_score
train
5ad7f4a9f863f40b79afba0f0a5fd6e689b6625a
diff --git a/VERSION b/VERSION index <HASH>..<HASH> 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.3 \ No newline at end of file +0.1.4 \ No newline at end of file diff --git a/oa-oauth/lib/omniauth/strategies/facebook.rb b/oa-oauth/lib/omniauth/strategies/facebook.rb index <HASH>..<HASH> 100644 --- a/oa-oauth/lib/omniauth/strategies/facebook.rb +++ b/oa-oauth/lib/omniauth/strategies/facebook.rb @@ -24,9 +24,9 @@ module OmniAuth @data ||= MultiJson.decode(@access_token.get('/me')) end - def request_phase(options = {}) + def request_phase options[:scope] ||= "email,offline_access" - super(options) + super end def user_info diff --git a/oa-oauth/lib/omniauth/strategies/gowalla.rb b/oa-oauth/lib/omniauth/strategies/gowalla.rb index <HASH>..<HASH> 100644 --- a/oa-oauth/lib/omniauth/strategies/gowalla.rb +++ b/oa-oauth/lib/omniauth/strategies/gowalla.rb @@ -26,9 +26,9 @@ module OmniAuth @data ||= MultiJson.decode(@access_token.get("/users/me.json")) end - def request_phase(options = {}) + def request_phase options[:scope] ||= "email,offline_access" - super(options) + super end def user_info diff --git a/oa-oauth/lib/omniauth/strategies/oauth2.rb b/oa-oauth/lib/omniauth/strategies/oauth2.rb index <HASH>..<HASH> 100644 --- a/oa-oauth/lib/omniauth/strategies/oauth2.rb +++ b/oa-oauth/lib/omniauth/strategies/oauth2.rb @@ -8,6 +8,8 @@ module OmniAuth class OAuth2 include OmniAuth::Strategy + attr_accessor :options, :client + class CallbackError < StandardError attr_accessor :error, :error_reason, :error_uri @@ -20,15 +22,13 @@ module OmniAuth def initialize(app, name, client_id, client_secret, options = {}) super(app, name) - @options = options - @client = ::OAuth2::Client.new(client_id, client_secret, options) + self.options = options + self.client = ::OAuth2::Client.new(client_id, client_secret, options) end protected - - attr_accessor :client - - def request_phase(options = {}) + + def request_phase redirect client.web_server.authorize_url({:redirect_uri => callback_url}.merge(options)) end
Fix options in OAuth2 strategy to actually allow scope passing.
omniauth_omniauth
train
b09cdb0131507c8f5b4c6a8aee5dab25c5a3fb11
diff --git a/pypot/_version.py b/pypot/_version.py index <HASH>..<HASH> 100644 --- a/pypot/_version.py +++ b/pypot/_version.py @@ -1 +1 @@ -__version__ = '2.1.0rc2' +__version__ = '2.1.0rc3'
Prepare for release <I>rc3
poppy-project_pypot
train
dac7c56b26dbe2b3489e88329dd70e0787c73087
diff --git a/lib/plugins/aws/package/compile/events/cognitoUserPool/index.js b/lib/plugins/aws/package/compile/events/cognitoUserPool/index.js index <HASH>..<HASH> 100644 --- a/lib/plugins/aws/package/compile/events/cognitoUserPool/index.js +++ b/lib/plugins/aws/package/compile/events/cognitoUserPool/index.js @@ -49,9 +49,9 @@ class AwsCompileCognitoUserPoolEvents { // Generate CloudFormation templates for Cognito User Pool changes _.forEach(userPools, poolName => { - const currentPoolTriggerFunctions = _.filter(cognitoUserPoolTriggerFunctions, { - poolName, - }); + const currentPoolTriggerFunctions = cognitoUserPoolTriggerFunctions.filter( + triggerFn => triggerFn.poolName === poolName + ); const userPoolCFResource = this.generateTemplateForPool( poolName, currentPoolTriggerFunctions @@ -348,7 +348,9 @@ class AwsCompileCognitoUserPoolEvents { const userPools = result.userPools; _.forEach(userPools, poolName => { - const currentPoolTriggerFunctions = _.filter(cognitoUserPoolTriggerFunctions, { poolName }); + const currentPoolTriggerFunctions = cognitoUserPoolTriggerFunctions.filter( + triggerFn => triggerFn.poolName === poolName + ); const userPoolLogicalId = this.provider.naming.getCognitoUserPoolLogicalId(poolName); // If overrides exist in `Resources`, merge them in diff --git a/lib/plugins/package/lib/zipService.js b/lib/plugins/package/lib/zipService.js index <HASH>..<HASH> 100644 --- a/lib/plugins/package/lib/zipService.js +++ b/lib/plugins/package/lib/zipService.js @@ -168,7 +168,7 @@ function excludeNodeDevDependencies(servicePath) { ); // filter out non node_modules file paths - const packageJsonPaths = _.filter(packageJsonFilePaths, filePath => { + const packageJsonPaths = packageJsonFilePaths.filter(filePath => { const isNodeModulesDir = !!filePath.match(/node_modules/); return !isNodeModulesDir; });
refactor: Replace _.filter with array.filter (#<I>)
serverless_serverless
train
933dec6571f3d3d84df9537f81177267fdecf4cc
diff --git a/src/Mouf/MoufClassExplorer.php b/src/Mouf/MoufClassExplorer.php index <HASH>..<HASH> 100755 --- a/src/Mouf/MoufClassExplorer.php +++ b/src/Mouf/MoufClassExplorer.php @@ -99,6 +99,10 @@ class MoufClassExplorer { } } + foreach ($this->forbiddenClasses as $badClass=>$errorMessage) { + unset($classMap[$badClass]); + } + if ($nbRun <= 1) { break; } @@ -107,10 +111,8 @@ class MoufClassExplorer { // BUT, the complete list of file has never been tested together. // and sometimes, a class included can trigger errors if another class is included at the same time // (most of the time, when a require is performed on a file already loaded, triggering a "class already defined" error. - foreach ($this->forbiddenClasses as $badClass=>$errorMessage) { - unset($classMap[$badClass]); - } + } while (true); // Let's remove from the classmap any class in error.
Improving performance of the class analyzer
thecodingmachine_mouf
train
68356e5ddd1f02947c8f3e7b41029187f60c7c4c
diff --git a/src/Database/PdoConnectionInterface.php b/src/Database/PdoConnectionInterface.php index <HASH>..<HASH> 100644 --- a/src/Database/PdoConnectionInterface.php +++ b/src/Database/PdoConnectionInterface.php @@ -11,21 +11,21 @@ namespace Spin\Database; interface PdoConnectionInterface { # PDO Class Interface - // function __construct ( string $dsn [, string $username [, string $password [, array $options ]]] ) - // function beginTransaction(): bool; - // function commit(): bool; - // function errorCode(): mixed; - // function errorInfo(): array; - // function exec(string $statement): int; - // function getAttribute(int $attribute): mixed; - // function getAvailableDrivers(): array; - // function inTransaction(): bool; - // function lastInsertId (string $name=NULL): string; - // function prepare(string $statement, array $driver_options = array()): PDOStatement; - // function query(string $statement): PDOStatement; - // function quote(string $string, int $parameter_type=PDO::PARAM_STR): string; - // function rollBack(): bool; - // function setAttribute(int $attribute , mixed $value): bool; + // function __construct ( string $dsn, string $username='', string $password='', array $options=[] ); + function beginTransaction(): bool; + function commit(): bool; + function errorCode(); + function errorInfo(): array; + function exec(string $statement): int; + function getAttribute(int $attribute); + function getAvailableDrivers(): array; + function inTransaction(): bool; + function lastInsertId (string $name=NULL): string; + function prepare(string $statement, array $driver_options = array()): \PDOStatement; + function query(string $statement): \PDOStatement; + function quote(string $string, int $parameter_type=\PDO::PARAM_STR): string; + function rollBack(): bool; + function setAttribute(int $attribute, $value): bool; # Custom additions function connect(): bool;
PdoConnectionInterface change
Celarius_spin-framework
train
ffc004fcc6ead6cf591725b9caea2e2a47b74e87
diff --git a/salt/modules/inspectlib/collector.py b/salt/modules/inspectlib/collector.py index <HASH>..<HASH> 100644 --- a/salt/modules/inspectlib/collector.py +++ b/salt/modules/inspectlib/collector.py @@ -21,10 +21,6 @@ from salt.modules.inspectlib.dbhandle import DBHandle class Inspector(object): - class InspectorSnapshotException(Exception): - ''' - Snapshot exception. - ''' MODE = ['configuration', 'payload', 'all']
Moved InspectorSnapshotException externally
saltstack_salt
train
ecb43a605191652a846da3922f75e18eb2ee81ab
diff --git a/openquake/commonlib/readinput.py b/openquake/commonlib/readinput.py index <HASH>..<HASH> 100644 --- a/openquake/commonlib/readinput.py +++ b/openquake/commonlib/readinput.py @@ -509,8 +509,7 @@ def get_job_info(oqparam, csm, sitecol): # the imtls object has values [NaN] when the levels are unknown # (this is a valid case for the event based hazard calculator) n_imts = len(imtls) - n_levels = sum(len(ls) if hasattr(ls, '__len__') else 0 - for ls in imtls.values()) / float(n_imts) + n_levels = len(oqparam.imtls.array) n_realizations = oqparam.number_of_logic_tree_samples or sum( sm.num_gsim_paths for sm in csm)
Saved the total number of levels in job_info
gem_oq-engine
train
4e285dba7f8ca8cb1b99b10e03afd0fc8f391783
diff --git a/demosys/timers/rocket.py b/demosys/timers/rocket.py index <HASH>..<HASH> 100644 --- a/demosys/timers/rocket.py +++ b/demosys/timers/rocket.py @@ -16,10 +16,12 @@ class RocketTimer(BaseTimer): self.mode = config.get('mode') or 'editor' self.files = config.get('files') or './tracks' self.project = config.get('project') or 'project.xml' + self.start_paused = False self.controller = TimeController(config.get('rps', 24)) if self.mode == 'editor': self.rocket = Rocket.from_socket(self.controller, track_path=self.files) + self.start_paused = True elif self.mode == 'project': self.rocket = Rocket.from_project_file(self.controller, self.project) elif self.mode == 'files': @@ -41,7 +43,8 @@ class RocketTimer(BaseTimer): def start(self): """Start the timer""" - self.rocket.start() + if not self.start_paused: + self.rocket.start() def get_time(self): """Get the current time in seconds"""
RocketTimer should start in paused state
Contraz_demosys-py
train
08f9af5172df36422abba7be886b717fc4503efa
diff --git a/modin/backends/pandas/query_compiler.py b/modin/backends/pandas/query_compiler.py index <HASH>..<HASH> 100644 --- a/modin/backends/pandas/query_compiler.py +++ b/modin/backends/pandas/query_compiler.py @@ -1181,25 +1181,39 @@ class PandasQueryCompiler(BaseQueryCompiler): by, type(self) ), "Can only use groupby reduce with another Query Compiler" + other_len = len(by.columns) + def _map(df, other): + other = other.squeeze(axis=axis ^ 1) + if isinstance(other, pandas.DataFrame): + df = pandas.concat( + [df] + [other[[o for o in other if o not in df]]], axis=1 + ) + other = list(other.columns) return map_func( - df.groupby(by=other.squeeze(axis=axis ^ 1), axis=axis, **groupby_args), - **map_args + df.groupby(by=other, axis=axis, **groupby_args), **map_args ).reset_index(drop=False) if reduce_func is not None: def _reduce(df): + if other_len > 1: + by = list(df.columns[0:other_len]) + else: + by = df.columns[0] return reduce_func( - df.groupby(by=df.columns[0], axis=axis, **groupby_args), - **reduce_args + df.groupby(by=by, axis=axis, **groupby_args), **reduce_args ) else: def _reduce(df): + if other_len > 1: + by = list(df.columns[0:other_len]) + else: + by = df.columns[0] return map_func( - df.groupby(by=df.columns[0], axis=axis, **groupby_args), **map_args + df.groupby(by=by, axis=axis, **groupby_args), **map_args ) if axis == 0: diff --git a/modin/pandas/dataframe.py b/modin/pandas/dataframe.py index <HASH>..<HASH> 100644 --- a/modin/pandas/dataframe.py +++ b/modin/pandas/dataframe.py @@ -410,20 +410,28 @@ class DataFrame(BasePandasDataset): else: by = self.__getitem__(by)._query_compiler elif is_list_like(by): - if isinstance(by, Series): - idx_name = by.name - by = by.values - mismatch = len(by) != len(self.axes[axis]) - if mismatch and all( - obj in self - or (hasattr(self.index, "names") and obj in self.index.names) - for obj in by - ): - # In the future, we will need to add logic to handle this, but for now - # we default to pandas in this case. - pass - elif mismatch: - raise KeyError(next(x for x in by if x not in self)) + # fastpath for multi column groupby + if axis == 0 and all(o in self for o in by): + warnings.warn( + "Multi-column groupby is a new feature. " + "Please report any bugs/issues to bug_reports@modin.org." + ) + by = self.__getitem__(by)._query_compiler + else: + if isinstance(by, Series): + idx_name = by.name + by = by.values + mismatch = len(by) != len(self.axes[axis]) + if mismatch and all( + obj in self + or (hasattr(self.index, "names") and obj in self.index.names) + for obj in by + ): + # In the future, we will need to add logic to handle this, but for now + # we default to pandas in this case. + pass + elif mismatch: + raise KeyError(next(x for x in by if x not in self)) from .groupby import DataFrameGroupBy diff --git a/modin/pandas/groupby.py b/modin/pandas/groupby.py index <HASH>..<HASH> 100644 --- a/modin/pandas/groupby.py +++ b/modin/pandas/groupby.py @@ -84,7 +84,13 @@ class DataFrameGroupBy(object): @property def _index_grouped(self): if self._index_grouped_cache is None: - if self._is_multi_by: + if hasattr(self._by, "columns") and len(self._by.columns) > 1: + by = list(self._by.columns) + is_multi_by = True + else: + by = self._by + is_multi_by = self._is_multi_by + if is_multi_by: # Because we are doing a collect (to_pandas) here and then groupby, we # end up using pandas implementation. Add the warning so the user is # aware. @@ -92,9 +98,9 @@ class DataFrameGroupBy(object): ErrorMessage.default_to_pandas("Groupby with multiple columns") self._index_grouped_cache = { k: v.index - for k, v in self._df._query_compiler.getitem_column_array(self._by) + for k, v in self._df._query_compiler.getitem_column_array(by) .to_pandas() - .groupby(by=self._by) + .groupby(by=by) } else: if isinstance(self._by, type(self._query_compiler)): diff --git a/modin/pandas/test/test_groupby.py b/modin/pandas/test/test_groupby.py index <HASH>..<HASH> 100644 --- a/modin/pandas/test/test_groupby.py +++ b/modin/pandas/test/test_groupby.py @@ -465,8 +465,7 @@ def test_multi_column_groupby(): ray_df = from_pandas(pandas_df) by = ["col1", "col2"] - with pytest.warns(UserWarning): - ray_df.groupby(by).count() + ray_df_equals_pandas(ray_df.groupby(by).count(), pandas_df.groupby(by).count()) with pytest.warns(UserWarning): for k, _ in ray_df.groupby(by):
Add support for grouping by multiple columns when doing a reduct… (#<I>) * Resolves #<I> * Adds support for grouping by multiple columns. * Does this grouping by broadcasting the columns. * A preliminary performance evaluation shows that it is significantly faster than before, but still has some room for improvement. * Minimal code changes to add this new feature. * We still default to pandas when the user is looping over the dataframe * Even though this is common, it is exceptionally hard to optimize, and out of scope for this PR.
modin-project_modin
train
c51e4880930d6cdee6ef969aeda1462fc3d3d56c
diff --git a/pynmea2/types/talker.py b/pynmea2/types/talker.py index <HASH>..<HASH> 100644 --- a/pynmea2/types/talker.py +++ b/pynmea2/types/talker.py @@ -625,6 +625,61 @@ class VLW(TalkerSentence): ('Trip distance nautical miles since reset','trip_distance_reset_miles'), ) +# ---------------------------------- To Be Implemented ------------------------ # +# ---------------------------------------------------------------------------- # + +#class ROT(TalkerSentence): +# """ Rate of Turn +# """ + # fields = ( + #("Rate of turn", "rate_of_turn"), #- indicates bow turn to port + #("valid data","valid_data"), #A=valid data, B= invalid data + # ) + +#class RPM(TalkerSentence): +# """ Revolutions +# """ + # fields = ( + #("Source", "source"),#S = Shaft, E = Engine + #("Engine or shaft number", "engine_no"), + #("Speed", "speed"),#RPM + #("Propeller pitch", "pitch"),#- means astern + #("Status", "status"),#A means valid + # ) + +# 1 2 3 4 5 6 +# | | | | | | +# $--RPM,a,x,x.x,x.x,A*hh<CR><LF> + +# Field Number: +# 1) Sourse, S = Shaft, E = Engine +# 2) Engine or shaft number +# 3) Speed, Revolutions per minute +# 4) Propeller pitch, % of maximum, "-" means astern +# 5) Status, A means data is valid +# 6) Checksum + +#class VPW(TalkerSentence): +# """ Speed, Measured Parallel to Wind +# """ + # fields = ( + #("Speed knots", "speed_kn"),#- means downwind + #("Unit knots", "unit_knots"),#N means knots + #("Speed m/s", "speed_ms"), + #("Unit m/s", "unit_ms"),#M means m/s + # ) + #VPW - Speed - Measured Parallel to Wind + + # 1 2 3 4 5 + # | | | | | + #$--VPW,x.x,N,x.x,M*hh<CR><LF> + + #Field Number: + # 1) Speed, "-" means downwind + # 2) N = Knots + # 3) Speed, "-" means downwind + # 4) M = Meters per second + # 5) Checksum # ---------------------------------- Not Yet Implemented --------------------- # # ---------------------------------------------------------------------------- #
Update talker.py Added ROT, RPM, VPW
Knio_pynmea2
train
57c5689cfc1ea34762a9b2baca105ba6eb66f4e3
diff --git a/src/instrumentTest/java/com/couchbase/cblite/testapp/tests/Replicator.java b/src/instrumentTest/java/com/couchbase/cblite/testapp/tests/Replicator.java index <HASH>..<HASH> 100644 --- a/src/instrumentTest/java/com/couchbase/cblite/testapp/tests/Replicator.java +++ b/src/instrumentTest/java/com/couchbase/cblite/testapp/tests/Replicator.java @@ -194,6 +194,8 @@ public class Replicator extends CBLiteTestCase { documentProperties.put("_deleted", true); @SuppressWarnings("unused") + CBLRevision rev2 = database.putRevision(new CBLRevision(documentProperties, database), rev1.getRevId(), false, status); + Assert.assertTrue(status.getCode() >= 200 && status.getCode() < 300); final CBLReplicator repl = database.getReplicator(remote, true, false, server.getWorkExecutor()); ((CBLPusher)repl).setCreateTarget(true);
testPusherDeletedDoc was broken, and in fact does _not_ reproduce issue #<I>
couchbase_couchbase-lite-java-core
train
6cd0898ab200238e9d344efc99c7b9ec91e8b6e5
diff --git a/doc/conf.py b/doc/conf.py index <HASH>..<HASH> 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -184,3 +184,10 @@ texinfo_documents = [ author, 'remoteStoragejs', 'One line description of project.', 'Miscellaneous'), ] + +# +# HACKFIX WARNING +# TODO Remove this when there is official support for pre-build steps on RTD +# https://github.com/readthedocs/readthedocs.org/issues/6662 +# +os.system('npm install')
Try running `npm i` from conf.py on RTD
remotestorage_remotestorage.js
train
558f65091dc1803cb843928a71e1d0e0665ce050
diff --git a/api/server.go b/api/server.go index <HASH>..<HASH> 100644 --- a/api/server.go +++ b/api/server.go @@ -6,8 +6,8 @@ package api import ( "fmt" - "net" "net/http" + "time" "github.com/codegangsta/negroni" "github.com/tsuru/config" @@ -20,6 +20,7 @@ import ( "github.com/tsuru/tsuru/log" "github.com/tsuru/tsuru/provision" "github.com/tsuru/tsuru/router" + "gopkg.in/tylerb/graceful.v1" ) const Version = "0.10.3" @@ -304,6 +305,25 @@ func RunServer(dry bool) http.Handler { fatal(err) } app.StartAutoScale() + shutdownChan := make(chan bool) + shutdownTimeout, _ := config.GetDuration("shutdown-timeout") + if shutdownTimeout == 0 { + shutdownTimeout = 10 * 60 + } + shutdownTimeout = shutdownTimeout * time.Second + srv := &graceful.Server{ + Timeout: shutdownTimeout, + Server: &http.Server{ + Addr: listen, + Handler: n, + }, + ShutdownInitiated: func() { + fmt.Println("tsuru is shutting down, waiting for pending connections to finish.") + // TODO(cezarsa): Implement shutdown handlers to stop stranded + // goroutines. + close(shutdownChan) + }, + } tls, _ := config.GetBool("use-tls") if tls { certFile, err := config.GetString("tls:cert-file") @@ -315,16 +335,15 @@ func RunServer(dry bool) http.Handler { fatal(err) } fmt.Printf("tsuru HTTP/TLS server listening at %s...\n", listen) - fatal(http.ListenAndServeTLS(listen, certFile, keyFile, n)) + err = srv.ListenAndServeTLS(certFile, keyFile) } else { - listener, err := net.Listen("tcp", listen) - if err != nil { - fatal(err) - } fmt.Printf("tsuru HTTP server listening at %s...\n", listen) - http.Handle("/", n) - fatal(http.Serve(listener, nil)) + err = srv.ListenAndServe() + } + if err != nil { + fmt.Printf("Listening stopped: %s\n", err) } + <-shutdownChan } return n }
api: graceful shutdown, wait for ongoing requests to finish
tsuru_tsuru
train
ca59f76f38ac114a60838d9ae5a7ab5951bfa828
diff --git a/Configuration/Configurator.php b/Configuration/Configurator.php index <HASH>..<HASH> 100644 --- a/Configuration/Configurator.php +++ b/Configuration/Configurator.php @@ -11,7 +11,7 @@ namespace JavierEguiluz\Bundle\EasyAdminBundle\Configuration; -use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataInfo; use JavierEguiluz\Bundle\EasyAdminBundle\Reflection\EntityMetadataInspector; use JavierEguiluz\Bundle\EasyAdminBundle\Reflection\ClassPropertyReflector;
Use the interface in the type-hint instead of a concrete implementation
EasyCorp_EasyAdminBundle
train
4353d35c0a17b521b502a56f897abad7df30a0cb
diff --git a/model/queries/SQLSelect.php b/model/queries/SQLSelect.php index <HASH>..<HASH> 100644 --- a/model/queries/SQLSelect.php +++ b/model/queries/SQLSelect.php @@ -568,14 +568,12 @@ class SQLSelect extends SQLConditionalExpression { /** - * Return the number of rows in this query if the limit were removed. Useful in paged data sets. - * - * @todo Respect HAVING and GROUPBY, which can affect the result-count + * Return the number of rows in this query, respecting limit and offset. * * @param string $column Quoted, escaped column name * @return int */ - public function count( $column = null) { + public function count($column = null) { // we can't clear the select if we're relying on its output by a HAVING clause if(!empty($this->having)) { $records = $this->execute();
Fix code docs for SQLSelect::count()
silverstripe_silverstripe-framework
train
5a613114bf0d56b5a8a65c77c29220e5eff9e7d0
diff --git a/lib/rspec/models/unidom/visitor/authenticating_spec.rb b/lib/rspec/models/unidom/visitor/authenticating_spec.rb index <HASH>..<HASH> 100644 --- a/lib/rspec/models/unidom/visitor/authenticating_spec.rb +++ b/lib/rspec/models/unidom/visitor/authenticating_spec.rb @@ -28,6 +28,9 @@ describe Unidom::Visitor::Authenticating, type: :model do it_behaves_like 'belongs_to', model_attributes, :visitor, Unidom::Visitor::Guest, guest_attributes it_behaves_like 'belongs_to', model_attributes, :credential, Unidom::Visitor::Password, password_attributes + it_behaves_like 'polymorphic scope', model_attributes, :visitor_is, :visitor, [ Unidom::Visitor::User, Unidom::Visitor::Guest ] + it_behaves_like 'polymorphic scope', model_attributes, :credential_is, :credential, [ Unidom::Visitor::Password ] + end end
1, Improve the Authenticating spec for the visitor_is scope, & the credential_is scope.
topbitdu_unidom-visitor
train
df462d5880a139d591d0800ca49b1608f43dc6fa
diff --git a/activestorage/lib/active_storage/attached/many.rb b/activestorage/lib/active_storage/attached/many.rb index <HASH>..<HASH> 100644 --- a/activestorage/lib/active_storage/attached/many.rb +++ b/activestorage/lib/active_storage/attached/many.rb @@ -37,7 +37,7 @@ module ActiveStorage # Returns true if any attachments has been made. # - # class Gallery < ActiveRecord::Base + # class Gallery < ApplicationRecord # has_many_attached :photos # end # diff --git a/activestorage/lib/active_storage/attached/model.rb b/activestorage/lib/active_storage/attached/model.rb index <HASH>..<HASH> 100644 --- a/activestorage/lib/active_storage/attached/model.rb +++ b/activestorage/lib/active_storage/attached/model.rb @@ -10,7 +10,7 @@ module ActiveStorage class_methods do # Specifies the relation between a single attachment and the model. # - # class User < ActiveRecord::Base + # class User < ApplicationRecord # has_one_attached :avatar # end # @@ -66,7 +66,7 @@ module ActiveStorage # Specifies the relation between multiple attachments and the model. # - # class Gallery < ActiveRecord::Base + # class Gallery < ApplicationRecord # has_many_attached :photos # end # diff --git a/activestorage/lib/active_storage/attached/one.rb b/activestorage/lib/active_storage/attached/one.rb index <HASH>..<HASH> 100644 --- a/activestorage/lib/active_storage/attached/one.rb +++ b/activestorage/lib/active_storage/attached/one.rb @@ -37,7 +37,7 @@ module ActiveStorage # Returns +true+ if an attachment has been made. # - # class User < ActiveRecord::Base + # class User < ApplicationRecord # has_one_attached :avatar # end #
Small docs fix inside `ActiveStorage` [ci skip] `ActiveRecord::Base` -> `ApplicationRecord` for consistency with default Rails generators and ActiveStorage guides.
rails_rails
train
051e13a3f68fab8116b71332ee92d0e1018e47bb
diff --git a/pytypes/stubfile_2_converter.py b/pytypes/stubfile_2_converter.py index <HASH>..<HASH> 100644 --- a/pytypes/stubfile_2_converter.py +++ b/pytypes/stubfile_2_converter.py @@ -34,8 +34,9 @@ import inspect import numbers import os import typing +import datetime from typing import Any, TypeVar -from pytypes import util, typelogger, type_util +from pytypes import util, typelogger, type_util, version if __name__ == '__main__': sys.path.append(sys.path[0]+os.sep+'..') @@ -283,16 +284,24 @@ def convert(in_file, out_file = None): if not os.path.exists(directory): os.makedirs(directory) assumed_glbls = set() + nw = datetime.datetime.now() with open(out_file, 'w') as out_file_handle: lines = ['"""', 'Python 2.7-compliant stubfile of ', in_file, - 'with MD5-Checksum: '+checksum, - 'This file was generated by pytypes. Do not edit directly.', + 'MD5-Checksum: '+checksum, + '\nThis file was generated by pytypes.stubfile_2_converter v'+version, + 'at '+nw.isoformat(), + 'running on '+util._python_version_string()+'.\n', + 'WARNING:', + 'If you edit this file, be aware that it was automatically generated.', + 'Save your customized version to a distinct place;', + 'this file might be overwritten without notice.', '"""', + '', '', # import section later goes here; don't forget to track in imp_index ''] - imp_index = 7 + imp_index = 13 for tpv in tpvs: _write_TypeVar(tpv, lines) diff --git a/pytypes/typelogger.py b/pytypes/typelogger.py index <HASH>..<HASH> 100644 --- a/pytypes/typelogger.py +++ b/pytypes/typelogger.py @@ -159,8 +159,8 @@ def _dump_module(module_node, path=None, python2=False, suffix=None): exec_info = 'unknown call' with open(stubpath, 'w') as stub_handle: lines = ['"""', - 'Auto created Python 2.7-compliant stubfile of ' if python2 - else 'Auto created stubfile of \n', + 'Automatically created Python 2.7-compliant stubfile of ' if python2 + else 'Automatically created stubfile of \n', src_fname, 'MD5-Checksum: '+checksum, '\nThis file was generated by pytypes.typelogger v'+version, @@ -169,9 +169,9 @@ def _dump_module(module_node, path=None, python2=False, suffix=None): util._python_version_string(), exec_info, '\nWARNING:', - 'If you edit this file, be aware it was auto generated.', + 'If you edit this file, be aware that it was automatically generated.', 'Save your customized version to a distinct place;', - 'this file might get overwritten without notice.', + 'this file might be overwritten without notice.', '"""', '', #'import typing',
Adjusted header text of auto-generated files.
Stewori_pytypes
train
af38d1d944d30ae4cccd05c0c15241f50e3dcd7c
diff --git a/react/MuiCozyTheme/makeOverrides.js b/react/MuiCozyTheme/makeOverrides.js index <HASH>..<HASH> 100644 --- a/react/MuiCozyTheme/makeOverrides.js +++ b/react/MuiCozyTheme/makeOverrides.js @@ -432,14 +432,17 @@ const makeOverrides = theme => ({ padding: 0, height: '2rem', backgroundColor: theme.palette.background.paper, - textIndent: '2rem', + textIndent: '1rem', fontWeight: 'bold', fontSize: '.75rem', textTransform: 'uppercase', alignItems: 'center', display: 'flex', lineHeight: 1.33, - color: theme.palette.text.secondary + color: theme.palette.text.secondary, + [theme.breakpoints.up('sm')]: { + textIndent: '2rem' + } }, gutters: { paddingLeft: 0,
fix(ListSubheader): Only 1rem of text indent on mobile
cozy_cozy-ui
train
d42428b488a64d2c040e1b4d019778f3c87084f7
diff --git a/anyconfig/backend/xml.py b/anyconfig/backend/xml.py index <HASH>..<HASH> 100644 --- a/anyconfig/backend/xml.py +++ b/anyconfig/backend/xml.py @@ -207,6 +207,8 @@ def elem_to_container(elem, to_container, nspaces, tags=False): else: # .. note:: Process yet anohter special cases first. if _dicts_have_unique_keys([subdic] + subdics): dic[elem.tag] = _sum_dicts([subdic] + subdics, to_container) + elif not subdic: # Only these children. + dic[elem.tag] = subdics else: subdic[children] = subdics @@ -254,12 +256,16 @@ def _elem_from_descendants(children, pprefix=_PREFIX): def _get_or_update_parent(key, val, parent=None, pprefix=_PREFIX): """ :param key: Key of current child (dict{,-like} object) - :param val: Value of current child (dict{,-like} object) + :param val: Value of current child (dict{,-like} object or [dict{,...}]) :param parent: XML ElementTree parent node object or None :param pprefix: Special parameter name prefix """ elem = ET.Element(key) - container_to_etree(val, parent=elem, pprefix=pprefix) + + vals = val if anyconfig.utils.is_iterable(val) else [val] + for val in vals: + container_to_etree(val, parent=elem, pprefix=pprefix) + if parent is None: # 'elem' is the top level etree. return elem else:
enhancement: make '@children' node omitted if there are only children nodes in XML backend
ssato_python-anyconfig
train
16637b07321b2526dcca6869c193d6c9cf537043
diff --git a/guacamole/src/main/webapp/app/clipboard/directives/guacClipboard.js b/guacamole/src/main/webapp/app/clipboard/directives/guacClipboard.js index <HASH>..<HASH> 100644 --- a/guacamole/src/main/webapp/app/clipboard/directives/guacClipboard.js +++ b/guacamole/src/main/webapp/app/clipboard/directives/guacClipboard.js @@ -288,9 +288,9 @@ angular.module('clipboard').directive('guacClipboard', ['$injector', }; // Attempt to read the clipboard if it may have changed - $window.addEventListener('copy', checkClipboard, true); - $window.addEventListener('cut', checkClipboard, true); - $window.addEventListener('focus', checkClipboard, true); + $window.addEventListener('copy', checkClipboard); + $window.addEventListener('cut', checkClipboard); + $window.addEventListener('focus', checkClipboard); // Clean up on destruction $scope.$on('$destroy', function destroyClipboard() { diff --git a/guacamole/src/main/webapp/app/clipboard/services/clipboardService.js b/guacamole/src/main/webapp/app/clipboard/services/clipboardService.js index <HASH>..<HASH> 100644 --- a/guacamole/src/main/webapp/app/clipboard/services/clipboardService.js +++ b/guacamole/src/main/webapp/app/clipboard/services/clipboardService.js @@ -55,6 +55,22 @@ angular.module('clipboard').factory('clipboardService', ['$injector', document.body.appendChild(clipboardContent); /** + * Stops the propogation of the given event through the DOM tree. This is + * identical to invoking stopPropogation() on the event directly, except + * that this function is usable as an event handler itself. + * + * @param {Event} e + * The event whose propogation through the DOM tree should be stopped. + */ + var stopEventPropagation = function stopEventPropagation(e) { + e.stopPropagation(); + }; + + // Prevent events generated due to execCommand() from disturbing external things + clipboardContent.addEventListener('copy', stopEventPropagation); + clipboardContent.addEventListener('paste', stopEventPropagation); + + /** * A stack of past node selection ranges. A range convering the nodes * currently selected within the document can be pushed onto this stack * with pushSelection(), and the most recently pushed selection can be
GUACAMOLE-<I>: Prevent clipboard events generated by the clipboardService from disturbing the operations of the guacClipboard directive.
glyptodon_guacamole-client
train
04b2ba0d3ee251c9128cf99baa379907ca032b74
diff --git a/src/RequestHandler.php b/src/RequestHandler.php index <HASH>..<HASH> 100644 --- a/src/RequestHandler.php +++ b/src/RequestHandler.php @@ -10,6 +10,7 @@ */ namespace Relay; +use InvalidArgumentException; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Server\RequestHandlerInterface; @@ -50,6 +51,10 @@ abstract class RequestHandler implements RequestHandlerInterface throw new TypeError('\$queue must be array or Traversable.'); } + if (empty($queue)) { + throw new InvalidArgumentException('$queue cannot be empty'); + } + $this->queue = $queue; if ($resolver === null) { diff --git a/tests/RelayTest.php b/tests/RelayTest.php index <HASH>..<HASH> 100644 --- a/tests/RelayTest.php +++ b/tests/RelayTest.php @@ -2,6 +2,7 @@ namespace Relay; use ArrayObject; +use InvalidArgumentException; use TypeError; use Zend\Diactoros\ServerRequestFactory; use Zend\Diactoros\Response; @@ -62,6 +63,15 @@ class RelayTest extends \PHPUnit\Framework\TestCase $relay = new Relay('bad'); } + public function testEmptyQueue() + { + $this->expectException(InvalidArgumentException::CLASS); + $this->expectExceptionMessage('$queue cannot be empty'); + + $relay = new Relay([]); + $relay->handle(ServerRequestFactory::fromGlobals()); + } + public function testResolverEntries() { $queue = [
Throw a more obvious error when the queue is empty on construction
relayphp_Relay.Relay
train
ebaa5066fcbf96e83e7be322ce8644523e979bab
diff --git a/lib/OpenLayers/Layer/ArcIMS.js b/lib/OpenLayers/Layer/ArcIMS.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Layer/ArcIMS.js +++ b/lib/OpenLayers/Layer/ArcIMS.js @@ -412,7 +412,7 @@ OpenLayers.Layer.ArcIMS = OpenLayers.Class(OpenLayers.Layer.Grid, { if (!arcxml.iserror()) { // if the arcxml is not an error, call the callback with the features parsed - callback.call(scope, arcxml.features); + callback.call(scope, response.features); } else { // if the arcxml is an error, return null features selected callback.call(scope, null);
Fix a broken aspect of my change to the ArcXML code when cleaning it up: missed an 'arcxml' -> 'response' change. Caught by dzwarg, r=me, (Pullup #<I>) git-svn-id: <URL>
openlayers_openlayers
train
460725d5c1f7181d1b54963122c81d5cca3e4ee4
diff --git a/bundler/minify.js b/bundler/minify.js index <HASH>..<HASH> 100644 --- a/bundler/minify.js +++ b/bundler/minify.js @@ -1,6 +1,6 @@ "use strict" -var http = require("http") +var http = require("https") var querystring = require("querystring") var fs = require("fs") @@ -22,7 +22,6 @@ module.exports = function(input, output, options, done) { var response = "" var req = http.request({ method: "POST", - protocol: "http:", hostname: "closure-compiler.appspot.com", path: "/compile", headers: { @@ -33,8 +32,16 @@ module.exports = function(input, output, options, done) { res.on("data", function(chunk) { response += chunk.toString() }) + res.on("end", function() { - var results = JSON.parse(response) + try { + var results = JSON.parse(response) + } catch(e) { + console.error(response); + + throw e; + } + if (results.errors) { for (var i = 0; i < results.errors.length; i++) console.log(results.errors[i]) }
fix: closure compiler requires HTTPS now (#<I>) Also barfing out the response from the server when JSON parsing errors happen
MithrilJS_mithril.js
train
63931f32e2dc68f5554ccded35c388026e760294
diff --git a/hs_restclient/__init__.py b/hs_restclient/__init__.py index <HASH>..<HASH> 100644 --- a/hs_restclient/__init__.py +++ b/hs_restclient/__init__.py @@ -5,7 +5,7 @@ Client library for HydroShare REST API """ __title__ = 'hs_restclient' -__version__ = '1.0.0' +__version__ = '1.1.0' import os import zipfile diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,7 @@ setup( # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html - version='1.0.1.dev1', + version='1.1.0', description='HydroShare REST API client library', long_description=long_description,
Change version number for <I> release
hydroshare_hs_restclient
train
9bed93eaea27d91e01452bc744d01897ea3ee9b0
diff --git a/lib/z_k/version.rb b/lib/z_k/version.rb index <HASH>..<HASH> 100644 --- a/lib/z_k/version.rb +++ b/lib/z_k/version.rb @@ -1,3 +1,3 @@ module ZK - VERSION = "0.8.2" + VERSION = "0.8.3" end
bump zk to <I>
zk-ruby_zk
train
f370adc77477ae789abac7782b489ca681c88705
diff --git a/src/main/java/com/couchbase/cblite/router/CBLRouter.java b/src/main/java/com/couchbase/cblite/router/CBLRouter.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/couchbase/cblite/router/CBLRouter.java +++ b/src/main/java/com/couchbase/cblite/router/CBLRouter.java @@ -44,6 +44,8 @@ import com.couchbase.cblite.auth.CBLPersonaAuthorizer; import com.couchbase.cblite.replicator.CBLPusher; import com.couchbase.cblite.replicator.CBLReplicator; +import org.apache.http.client.HttpResponseException; + public class CBLRouter implements Observer { @@ -599,7 +601,14 @@ public class CBLRouter implements Observer { activity.put("progress", progress); if (replicator.getError() != null) { - int statusCode = 400; // TODO: store and use appropriate status code + String msg = String.format("Replicator error: %s. Repl: %s. Source: %s, Target: %s", + replicator.getError(), replicator, source, target); + Log.e(CBLDatabase.TAG, msg); + Throwable error = replicator.getError(); + int statusCode = 400; + if (error instanceof HttpResponseException) { + statusCode = ((HttpResponseException)error).getStatusCode(); + } Object[] errorObjects = new Object[]{ statusCode, replicator.getError().toString() }; activity.put("error", errorObjects); }
Improve active_task error logging to have correct status code. (issue #<I>)
couchbase_couchbase-lite-java-core
train
d4fc2694d2ff492a3a8bf192ba97cefa5efe022b
diff --git a/src/EDI/Interpreter.php b/src/EDI/Interpreter.php index <HASH>..<HASH> 100644 --- a/src/EDI/Interpreter.php +++ b/src/EDI/Interpreter.php @@ -85,14 +85,20 @@ class Interpreter private $comparisonFunction; /** + * @var string + */ + private $outputKey; + + /** * Split multiple messages and process * - * @param string $xmlMsg Path to XML Message representation - * @param array $xmlSeg Segments processed by EDI\Analyser::loadSegmentsXml - * @param array $xmlSvc Service segments processed by EDI\Analyser::loadSegmentsXml - * @param array|null $messageTextConf Personalisation of error messages + * @param string $xmlMsg Path to XML Message representation + * @param array $xmlSeg Segments processed by EDI\Analyser::loadSegmentsXml + * @param array $xmlSvc Service segments processed by EDI\Analyser::loadSegmentsXml + * @param array|null $messageTextConf Personalisation of error messages + * @param boolean $useIdInsteadOfNameForOutput Set to true if ID from UNCEFACT should be used instead of name */ - public function __construct(string $xmlMsg, array $xmlSeg, array $xmlSvc, array $messageTextConf = null) + public function __construct(string $xmlMsg, array $xmlSeg, array $xmlSvc, array $messageTextConf = null, bool $useIdInsteadOfNameForOutput = false) { // simplexml_load_file: This can be affected by a PHP bug #62577 (https://bugs.php.net/bug.php?id=62577) $xmlData = \file_get_contents($xmlMsg); @@ -116,6 +122,13 @@ class Interpreter $this->comparisonFunction = static function ($segment, $elm) { return $segment[0] == $elm['id']; }; + + if ($useIdInsteadOfNameForOutput) { + $this->outputKey = 'id'; + } + else { + $this->outputKey = 'name'; + } } public function togglePatching(bool $flag) @@ -601,32 +614,32 @@ class Interpreter } $d_sub_desc_attr = $sub_details_desc[$d_n]['attributes']; - if (!isset($jsoncomposite[$d_sub_desc_attr['name']])) { //New - $jsoncomposite[$d_sub_desc_attr['name']] = $d_detail; - } elseif (\is_string($jsoncomposite[$d_sub_desc_attr['name']])) { // More data than one string - $jsoncomposite[$d_sub_desc_attr['name']] = [ - $jsoncomposite[$d_sub_desc_attr['name']], + if (!isset($jsoncomposite[$d_sub_desc_attr[$this->outputKey]])) { //New + $jsoncomposite[$d_sub_desc_attr[$this->outputKey]] = $d_detail; + } elseif (\is_string($jsoncomposite[$d_sub_desc_attr[$this->outputKey]])) { // More data than one string + $jsoncomposite[$d_sub_desc_attr[$this->outputKey]] = [ + $jsoncomposite[$d_sub_desc_attr[$this->outputKey]], $d_detail, ]; } else { // More and more - $jsoncomposite[$d_sub_desc_attr['name']][] = $d_detail; + $jsoncomposite[$d_sub_desc_attr[$this->outputKey]][] = $d_detail; } } } else { $d_sub_desc_attr = $sub_details_desc[0]['attributes']; - $jsoncomposite[$d_sub_desc_attr['name']] = $detail; + $jsoncomposite[$d_sub_desc_attr[$this->outputKey]] = $detail; } } else { $jsoncomposite = $detail; } - if (\array_key_exists($d_desc_attr['name'], $jsonelements)) { - $jsonelements[$d_desc_attr['name'] . $n] = $jsoncomposite; + if (\array_key_exists($d_desc_attr[$this->outputKey], $jsonelements)) { + $jsonelements[$d_desc_attr[$this->outputKey] . $n] = $jsoncomposite; } else { - $jsonelements[$d_desc_attr['name']] = $jsoncomposite; + $jsonelements[$d_desc_attr[$this->outputKey]] = $jsoncomposite; } } - $jsonsegment['key'] = $attributes['name']; + $jsonsegment['key'] = $attributes[$this->outputKey]; $jsonsegment['value'] = $jsonelements; } elseif ($xmlMap !== $this->xmlSvc) { $jsonsegment = $this->processSegment($segment, $this->xmlSvc, $segmentIdx, $errors);
Should add the possibility via constructor arg to decide whether to use "id" or "name" from UNCEFACT XML for the array output. Fixes #<I>
php-edifact_edifact
train
6fdaf50644feec6e6261f78b2d494af2e1d212d2
diff --git a/guava-gwt/test/com/google/common/net/HostAndPortTest_gwt.java b/guava-gwt/test/com/google/common/net/HostAndPortTest_gwt.java index <HASH>..<HASH> 100644 --- a/guava-gwt/test/com/google/common/net/HostAndPortTest_gwt.java +++ b/guava-gwt/test/com/google/common/net/HostAndPortTest_gwt.java @@ -18,6 +18,11 @@ public class HostAndPortTest_gwt extends com.google.gwt.junit.client.GWTTestCase @Override public String getModuleName() { return "com.google.common.net.testModule"; } +public void testFromHost() throws Exception { + com.google.common.net.HostAndPortTest testCase = new com.google.common.net.HostAndPortTest(); + testCase.testFromHost(); +} + public void testFromParts() throws Exception { com.google.common.net.HostAndPortTest testCase = new com.google.common.net.HostAndPortTest(); testCase.testFromParts(); diff --git a/guava-tests/test/com/google/common/net/HostAndPortTest.java b/guava-tests/test/com/google/common/net/HostAndPortTest.java index <HASH>..<HASH> 100644 --- a/guava-tests/test/com/google/common/net/HostAndPortTest.java +++ b/guava-tests/test/com/google/common/net/HostAndPortTest.java @@ -165,6 +165,28 @@ public class HostAndPortTest extends TestCase { } } + public void testFromHost() { + HostAndPort hp = HostAndPort.fromHost("gmail.com"); + assertEquals("gmail.com", hp.getHostText()); + assertFalse(hp.hasPort()); + + hp = HostAndPort.fromHost("[::1]"); + assertEquals("::1", hp.getHostText()); + assertFalse(hp.hasPort()); + + try { + HostAndPort.fromHost("gmail.com:80"); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + } + + try { + HostAndPort.fromHost("[gmail.com]"); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + } + } + public void testGetPortOrDefault() { assertEquals(80, HostAndPort.fromString("host:80").getPortOrDefault(123)); assertEquals(123, HostAndPort.fromString("host").getPortOrDefault(123)); diff --git a/guava/src/com/google/common/net/HostAndPort.java b/guava/src/com/google/common/net/HostAndPort.java index <HASH>..<HASH> 100644 --- a/guava/src/com/google/common/net/HostAndPort.java +++ b/guava/src/com/google/common/net/HostAndPort.java @@ -138,6 +138,23 @@ public final class HostAndPort implements Serializable { } /** + * Build a HostAndPort instance from a host only. + * + * <p>Note: Non-bracketed IPv6 literals are allowed. + * Use {@link #requireBracketsForIPv6()} to prohibit these. + * + * @param host the host-only string to parse. Must not contain a port number. + * @return if parsing was successful, a populated HostAndPort object. + * @throws IllegalArgumentException if {@code host} contains a port number. + * @since 17.0 + */ + public static HostAndPort fromHost(String host) { + HostAndPort parsedHost = fromString(host); + checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); + return parsedHost; + } + + /** * Split a freeform string into a host and port, without strict validation. * * Note that the host-only formats will leave the port field undefined. You @@ -278,7 +295,8 @@ public final class HostAndPort implements Serializable { /** Rebuild the host:port string, including brackets if necessary. */ @Override public String toString() { - StringBuilder builder = new StringBuilder(host.length() + 7); + // "[]:12345" requires 8 extra bytes. + StringBuilder builder = new StringBuilder(host.length() + 8); if (host.indexOf(':') >= 0) { builder.append('[').append(host).append(']'); } else {
Add a new HostAndPort.fromHost() factory, which behaves like fromParts() without the port number. This is useful for converting a host into possibly-bracketed form, so that a port may be appended afterward. Also, the correct buffer size is "length + 8", due to the 5-digit port, two brackets, and a colon. ------------- Created by MOE: <URL>
google_guava
train
62b1b1722165547bb7d0d8e0a3221f43b9de63d9
diff --git a/activesupport/lib/active_support/xml_mini/libxml.rb b/activesupport/lib/active_support/xml_mini/libxml.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/xml_mini/libxml.rb +++ b/activesupport/lib/active_support/xml_mini/libxml.rb @@ -14,11 +14,9 @@ module ActiveSupport data = StringIO.new(data || "") end - char = data.getc - if char.nil? + if data.eof? {} else - data.ungetc(char) LibXML::XML::Parser.io(data).parse.to_hash end end diff --git a/activesupport/lib/active_support/xml_mini/libxmlsax.rb b/activesupport/lib/active_support/xml_mini/libxmlsax.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/xml_mini/libxmlsax.rb +++ b/activesupport/lib/active_support/xml_mini/libxmlsax.rb @@ -65,12 +65,9 @@ module ActiveSupport data = StringIO.new(data || "") end - char = data.getc - if char.nil? + if data.eof? {} else - data.ungetc(char) - LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER) parser = LibXML::XML::SaxParser.io(data) document = document_class.new diff --git a/activesupport/lib/active_support/xml_mini/nokogiri.rb b/activesupport/lib/active_support/xml_mini/nokogiri.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/xml_mini/nokogiri.rb +++ b/activesupport/lib/active_support/xml_mini/nokogiri.rb @@ -19,11 +19,9 @@ module ActiveSupport data = StringIO.new(data || "") end - char = data.getc - if char.nil? + if data.eof? {} else - data.ungetc(char) doc = Nokogiri::XML(data) raise doc.errors.first if doc.errors.length > 0 doc.to_hash diff --git a/activesupport/lib/active_support/xml_mini/nokogirisax.rb b/activesupport/lib/active_support/xml_mini/nokogirisax.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/xml_mini/nokogirisax.rb +++ b/activesupport/lib/active_support/xml_mini/nokogirisax.rb @@ -71,11 +71,9 @@ module ActiveSupport data = StringIO.new(data || "") end - char = data.getc - if char.nil? + if data.eof? {} else - data.ungetc(char) document = document_class.new parser = Nokogiri::XML::SAX::Parser.new(document) parser.parse(data) diff --git a/activesupport/test/xml_mini/xml_mini_engine_test.rb b/activesupport/test/xml_mini/xml_mini_engine_test.rb index <HASH>..<HASH> 100644 --- a/activesupport/test/xml_mini/xml_mini_engine_test.rb +++ b/activesupport/test/xml_mini/xml_mini_engine_test.rb @@ -75,6 +75,11 @@ class XMLMiniEngineTest < ActiveSupport::TestCase assert_equal({}, ActiveSupport::XmlMini.parse("")) end + def test_parse_from_frozen_string + xml_string = "<root/>".freeze + assert_equal({ "root" => {} }, ActiveSupport::XmlMini.parse(xml_string)) + end + def test_array_type_makes_an_array assert_equal_rexml(<<-eoxml) <blog>
Fixes Hash.from_xml with frozen strings for all backends
rails_rails
train
db1cfc1e00ee14deadc7c9a1ae8bbdfa55dcdac7
diff --git a/packages/reactabular-tree/src/unpack.js b/packages/reactabular-tree/src/unpack.js index <HASH>..<HASH> 100644 --- a/packages/reactabular-tree/src/unpack.js +++ b/packages/reactabular-tree/src/unpack.js @@ -1,38 +1,36 @@ import omit from 'lodash/omit'; -function unpack({ +const unpack = ({ parentField = 'parent', childrenField = 'children', idField = 'id', parent -} = {}) { - return (rows) => { - if (!Array.isArray(rows)) { - return []; - } +} = {}) => (rows) => { + if (!Array.isArray(rows)) { + return []; + } - if (!rows.length) { - return rows; - } + if (!rows.length) { + return rows; + } - return [].concat( - ...rows.map(node => { - const children = node[childrenField]; - const d = parent ? { - ...omit(node, childrenField), - [parentField]: parent - } : omit(node, childrenField); + return [].concat( + ...rows.map((node) => { + const children = node[childrenField]; + const d = parent ? { + ...omit(node, childrenField), + [parentField]: parent + } : omit(node, childrenField); - return [d].concat( - unpack({ - parentField, - parent: d[idField], - idField - })(children) - ); - }) - ); - }; -} + return [d].concat( + unpack({ + parentField, + parent: d[idField], + idField + })(children) + ); + }) + ); +}; export default unpack;
tree - Rewrite `tree.unpack` in a terser form
reactabular_reactabular
train
9fc4f6cb9a5a56e1b0ccf7bb80e16900da16ee37
diff --git a/lib/review/i18n.yml b/lib/review/i18n.yml index <HASH>..<HASH> 100644 --- a/lib/review/i18n.yml +++ b/lib/review/i18n.yml @@ -81,6 +81,7 @@ ja: "%s: 'texcommand' has options ('%s'). Move it to 'texoptions'?": "%s: 'texcommand' にオプションがあります ('%s')。'texoptions' に移動しますか?" "%s: 'dvicommand' has options ('%s'). Move it to 'dvioptions'?": "%s: 'dvicommand' にオプションがあります ('%s')。'dvioptions' に移動しますか?" "Finished.": "完了しました。" + "new file %s is created.": "新しいファイル %s が作成されました。" en: image: "Figure " diff --git a/lib/review/update.rb b/lib/review/update.rb index <HASH>..<HASH> 100644 --- a/lib/review/update.rb +++ b/lib/review/update.rb @@ -30,12 +30,14 @@ module ReVIEW TEX_OPTIONS = '-interaction=nonstopmode -file-line-error' DVI_COMMAND = 'dvipdfmx' DVI_OPTIONS = '-d 5 -z 9' + # provide gentombow from vendor/. current version is 2018/08/30 v0.9j + GENTOMBOWSTY = 'gentombow09j.sty' attr_reader :config_ymls, :locale_ymls, :catalog_ymls, :tex_ymls, :epub_ymls attr_accessor :force, :specified_template def initialize - @template = nil + @template = '__DEFAULT__' @specified_template = nil @force = nil @logger = ReVIEW.logger @@ -69,9 +71,14 @@ module ReVIEW update_epub_version update_locale update_tex_parameters + if @template + if @template == '__DEFAULT__' + @template = TEX_DOCUMENTCLASS[0] + end update_tex_stys(@template, dir) end + update_tex_command update_dvi_command @@ -266,6 +273,7 @@ module ReVIEW end end else + @logger.info t('new file %s is created.', [target_rakefile]) unless @force FileUtils.cp master_rakefile, target_rakefile end @@ -279,6 +287,7 @@ module ReVIEW end end else + @logger.info t('new file %s is created.', [target_rakefile]) unless @force FileUtils.cp master_rakefile, target_rakefile end end @@ -325,10 +334,12 @@ module ReVIEW # want to use other template? @logger.error t("%s: !! 'texdocumentclass' uses new class '%s' already, but you specified '%s'. This tool can't handle such migration. Ignored. !!", [File.basename(yml), config['texdocumentclass'][0], @specified_template]) @template = nil + else + @template = config['texdocumentclass'][0] end + + # no need to update next - else - @template = config['texdocumentclass'][0] end if TEX_DOCUMENTCLASS_BAD.include?(config['texdocumentclass'][0]) @@ -366,7 +377,7 @@ module ReVIEW rewrite_yml(yml, 'texdocumentclass', %Q(["#{@template}", "#{modified_opts}"])) else @template = nil - @logger.error t("%s: ** 'texdocumentclass' specifies '%s'. Because this is unknown class for this tool, you need to update it by yourself if it won't work. **", [File.basename(yml), config['texdocumentclass']]) + @logger.error t("%s: ** 'texdocumentclass' specifies '%s'. Because this is unknown class for this tool, you need to update it by yourself if it won't work. **", [File.basename(yml), config['texdocumentclass'][0]]) end end end @@ -449,6 +460,7 @@ module ReVIEW unless File.exist?(target_styfile) # just copy + @logger.info t('new file %s is created.', [target_styfile]) unless @force FileUtils.cp master_styfile, target_styfile next end @@ -468,9 +480,9 @@ module ReVIEW end if template == 'review-jsbook' - # provide gentombow from vendor/. current version is 2018/08/30 v0.9j - unless File.exist?(File.join(texmacrodir, 'gentombow09j.sty')) - FileUtils.cp File.join(@review_dir, 'vendor/gentombow/gentombow.sty'), File.join(texmacrodir, 'gentombow09j.sty') + unless File.exist?(File.join(texmacrodir, GENTOMBOWSTY)) + @logger.info t('new file %s is created.', [File.join(texmacrodir, GENTOMBOWSTY)]) unless @force + FileUtils.cp File.join(@review_dir, 'vendor/gentombow/gentombow.sty'), File.join(texmacrodir, GENTOMBOWSTY) end end end diff --git a/test/test_update.rb b/test/test_update.rb index <HASH>..<HASH> 100644 --- a/test/test_update.rb +++ b/test/test_update.rb @@ -348,6 +348,7 @@ EOT io = StringIO.new @u.instance_eval{ @logger = ReVIEW::Logger.new(io) } @u.update_tex_stys('review-jsbook', @tmpdir) + assert_equal '', io.string File.write(File.join(@tmpdir, 'sty/review-custom.sty'), "% MY CUSTOM\n") @u.update_tex_stys('review-jsbook', @tmpdir) assert_equal '', io.string
fix updater to update sty correctly. info about new file
kmuto_review
train
7c1e4f2ca9544b0205a2423d42accdb5d3017707
diff --git a/rbd/rbd_test.go b/rbd/rbd_test.go index <HASH>..<HASH> 100644 --- a/rbd/rbd_test.go +++ b/rbd/rbd_test.go @@ -449,64 +449,64 @@ func TestErrorImageNotOpen(t *testing.T) { image := rbd.GetImage(nil, "nonexistent") err := image.Close() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) err = image.Resize(2 << 22) - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.Stat() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.IsOldFormat() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.GetSize() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.GetFeatures() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.GetStripeUnit() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.GetStripeCount() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.GetOverlap() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) err = image.Flatten() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, _, err = image.ListChildren() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, _, err = image.ListLockers() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) err = image.LockExclusive("a magic cookie") - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) err = image.LockShared("a magic cookie", "tasty") - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) err = image.BreakLock("a magic cookie", "tasty") - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.Read(nil) - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.Write(nil) - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.ReadAt(nil, 0) - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) _, err = image.WriteAt(nil, 0) - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) err = image.Flush() - assert.Equal(t, err, rbd.RbdErrorImageNotOpen) + assert.Equal(t, err, rbd.ErrImageNotOpen) } func TestNotFound(t *testing.T) { @@ -525,10 +525,10 @@ func TestNotFound(t *testing.T) { img := rbd.GetImage(ioctx, name) err = img.Open() - assert.Equal(t, err, rbd.RbdErrorNotFound) + assert.Equal(t, err, rbd.ErrNotFound) err = img.Remove() - assert.Equal(t, err, rbd.RbdErrorNotFound) + assert.Equal(t, err, rbd.ErrNotFound) ioctx.Destroy() conn.DeletePool(poolname)
rbd: convert test to use errors with conventional names We recently created errors in the rbd that match the golang convention but left aliases for external code. Switch the test code to use the newer more standard form instead of the "aliases."
ceph_go-ceph
train
673a9e3c37f481a99cde20d333b440b16e34eb29
diff --git a/js/ascendex.js b/js/ascendex.js index <HASH>..<HASH> 100644 --- a/js/ascendex.js +++ b/js/ascendex.js @@ -1686,7 +1686,7 @@ module.exports = class ascendex extends Exchange { return await this.v2PrivateAccountGroupPostFuturesLeverage (this.extend (request, params)); } - async setMarginMode (marginType, symbol, params = {}) { + async setMarginMode (marginType, symbol = undefined, params = {}) { if (marginType !== 'isolated' && marginType !== 'crossed') { throw new BadRequest (this.id + ' setMarginMode() marginType argument should be isolated or crossed'); } diff --git a/js/binance.js b/js/binance.js index <HASH>..<HASH> 100644 --- a/js/binance.js +++ b/js/binance.js @@ -4560,7 +4560,7 @@ module.exports = class binance extends Exchange { return await this[method] (this.extend (request, params)); } - async setMarginMode (marginType, symbol, params = {}) { + async setMarginMode (marginType, symbol = undefined, params = {}) { // // { "code": -4048 , "msg": "Margin type cannot be changed if there exists position." } // diff --git a/js/bybit.js b/js/bybit.js index <HASH>..<HASH> 100644 --- a/js/bybit.js +++ b/js/bybit.js @@ -2570,7 +2570,7 @@ module.exports = class bybit extends Exchange { } } - async setMarginMode (marginType, symbol, params = {}) { + async setMarginMode (marginType, symbol = undefined, params = {}) { // // { // "ret_code": 0,
standardise signature of setMarginMode
ccxt_ccxt
train
8281ff9caed1241528f1c435da5a75ee1db5f321
diff --git a/lib/sinatra.rb b/lib/sinatra.rb index <HASH>..<HASH> 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -11,6 +11,20 @@ class String end end +class Hash + def to_params + map { |k,v| "#{k}=#{URI.escape(v)}" }.join('&') + end + + def symbolize_keys + self.inject({}) { |h,(k,v)| h[k.to_sym] = v; h } + end + + def pass(*keys) + reject { |k,v| !keys.include?(k) } + end +end + class Symbol def to_proc Proc.new { |*args| args.shift.__send__(self, *args) } @@ -38,6 +52,10 @@ end module Sinatra extend self + Error = Proc.new do + "#{$!.message}\n\t#{$!.backtrace.join("\n\t")}" + end + def request_types @request_types ||= [:get, :put, :post, :delete] end @@ -48,8 +66,22 @@ module Sinatra end end - def determine_event(verb, path) - routes[verb].eject { |r| r.match(path) } + def determine_route(verb, path) + found = routes[verb].eject { |r| r.match(path) } + found ||= routes[404] + end + + def call(env) + request = Rack::Request.new(env) + route = determine_route( + request.request_method.downcase.to_sym, + request.path_info + ) + begin + [200, {}, route.block.call] + rescue => e + [500, {}, (routes[500] || Error).call] + end end class Route diff --git a/test/dispatching_test.rb b/test/dispatching_test.rb index <HASH>..<HASH> 100644 --- a/test/dispatching_test.rb +++ b/test/dispatching_test.rb @@ -1,14 +1,50 @@ require File.dirname(__FILE__) + '/helper' + + context "Dispatching" do + include Sinatra::Test::Methods + + setup do + Sinatra.routes.clear + end + specify "should return the correct block" do Sinatra.routes[:get] << r = Sinatra::Route.new('/') do 'main' end - result = Sinatra.determine_event(:get, '/') + result = Sinatra.determine_route(:get, '/') result.block.should.be r.block end + specify "should return custom 404" do + Sinatra.routes[404] = r = Proc.new { 'custom 404' } + result = Sinatra.determine_route(:get, '/') + result.should.be r + end + + specify "should give custom 500 if error when called" do + Sinatra.routes[500] = r = Proc.new { 'custom 500' } + + Sinatra.routes[:get] << Sinatra::Route.new('/') do + raise 'asdf' + end + + get_it '/' + + body.should.equal 'custom 500' + end + + specify "should give standard 500 if error when called" do + Sinatra.routes[:get] << Sinatra::Route.new('/') do + raise 'asdf' + end + + get_it '/' + + body.should.match /^asdf/ + end + end diff --git a/test/helper.rb b/test/helper.rb index <HASH>..<HASH> 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -1,3 +1,44 @@ require File.dirname(__FILE__) + "/../lib/sinatra" require 'test/spec' require 'mocha' + + +module Sinatra + + module Test + + module Methods + + def get_it(path, params = {}) + @request = Rack::MockRequest.new(Sinatra) + @response = @request.get(path, :input => params.to_params) + end + + def post_it(path, params = {}) + @request = Rack::MockRequest.new(Sinatra) + @response = @request.post(path, :input => params.to_params) + end + + def put_it(path, params = {}) + @request = Rack::MockRequest.new(Sinatra) + @response = @request.put(path, :input => params.to_params) + end + + def delete_it(path, params = {}) + @request = Rack::MockRequest.new(Sinatra) + @response = @request.delete(path, :input => params.to_params) + end + + def follow! + get_it(@response.location) + end + + def method_missing(name, *args) + @response.send(name, *args) + end + + end + + end + +end
custom <I>'s and <I>'s
sinatra_sinatra
train
695c5579399d798fe4499046b7b2636cab52b678
diff --git a/telldus/library.py b/telldus/library.py index <HASH>..<HASH> 100644 --- a/telldus/library.py +++ b/telldus/library.py @@ -174,7 +174,7 @@ class Library(object): assert Library._refcount == 0 return - for callback in self._callbacks.keys(): + for callback in list(self._callbacks.keys()): try: self.tdUnregisterCallback(callback) except:
Iterate over a copy when cleaning up callbacks
erijo_tellcore-py
train
5cfb2a78e4d3b52c7a3e2835eca8dad5706b51d6
diff --git a/src/Illuminate/Foundation/Testing/CrawlerTrait.php b/src/Illuminate/Foundation/Testing/CrawlerTrait.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Foundation/Testing/CrawlerTrait.php +++ b/src/Illuminate/Foundation/Testing/CrawlerTrait.php @@ -496,7 +496,7 @@ trait CrawlerTrait */ protected function getInputOrTextAreaValue($selector) { - $field = $this->filterByNameOrId($selector); + $field = $this->filterByNameOrId($selector, ['input', 'textarea']); if ($field->count() == 0) { throw new Exception("There are no elements with the name or ID [$selector]."); @@ -1027,15 +1027,25 @@ trait CrawlerTrait /** * Filter elements according to the given name or ID attribute. * - * @param string $name - * @param string $element + * @param string $name + * @param array|string $elements * @return \Symfony\Component\DomCrawler\Crawler */ - protected function filterByNameOrId($name, $element = '*') + protected function filterByNameOrId($name, $elements = '*') { $name = str_replace('#', '', $name); - return $this->crawler->filter("{$element}#{$name}, {$element}[name='{$name}']"); + if (is_array($elements)) { + array_walk($elements, function (&$element) use ($name) { + $element = "{$element}#{$name}, {$element}[name='{$name}']"; + }); + + $filter = implode(', ', $elements); + } else { + $filter = "{$elements}#{$name}, {$elements}[name='{$name}']"; + } + + return $this->crawler->filter($filter); } /** diff --git a/tests/Foundation/FoundationCrawlerTraitTest.php b/tests/Foundation/FoundationCrawlerTraitTest.php index <HASH>..<HASH> 100644 --- a/tests/Foundation/FoundationCrawlerTraitTest.php +++ b/tests/Foundation/FoundationCrawlerTraitTest.php @@ -34,7 +34,7 @@ class FoundationCrawlerTraitTest extends PHPUnit_Framework_TestCase public function testSeeInFieldInput() { $this->crawler->shouldReceive('filter') - ->withArgs(["*#framework, *[name='framework']"]) + ->withArgs(["input#framework, input[name='framework'], textarea#framework, textarea[name='framework']"]) ->once() ->andReturn($this->mockInput('Laravel')); @@ -44,7 +44,7 @@ class FoundationCrawlerTraitTest extends PHPUnit_Framework_TestCase public function testDontSeeInFieldInput() { $this->crawler->shouldReceive('filter') - ->withArgs(["*#framework, *[name='framework']"]) + ->withArgs(["input#framework, input[name='framework'], textarea#framework, textarea[name='framework']"]) ->once() ->andReturn($this->mockInput('Laravel')); @@ -64,7 +64,7 @@ class FoundationCrawlerTraitTest extends PHPUnit_Framework_TestCase public function testSeeInFieldTextarea() { $this->crawler->shouldReceive('filter') - ->withArgs(["*#description, *[name='description']"]) + ->withArgs(["input#description, input[name='description'], textarea#description, textarea[name='description']"]) ->once() ->andReturn($this->mockTextarea('Laravel is awesome')); @@ -74,7 +74,7 @@ class FoundationCrawlerTraitTest extends PHPUnit_Framework_TestCase public function testDontSeeInFieldTextarea() { $this->crawler->shouldReceive('filter') - ->withArgs(["*#description, *[name='description']"]) + ->withArgs(["input#description, input[name='description'], textarea#description, textarea[name='description']"]) ->once() ->andReturn($this->mockTextarea('Laravel is awesome')); @@ -92,7 +92,7 @@ class FoundationCrawlerTraitTest extends PHPUnit_Framework_TestCase $select->shouldReceive('nodeName')->once()->andReturn('select'); $this->crawler->shouldReceive('filter') - ->withArgs(["*#select, *[name='select']"]) + ->withArgs(["input#select, input[name='select'], textarea#select, textarea[name='select']"]) ->once() ->andReturn($select);
make CrawlerTrait::seeInField actually filter by input and textarea Allow an array of elements to be passed into CrawlerTrait::filterByNameOrId
laravel_framework
train
e7ed4529ea3a970fdecb47b02a014cf221a80b6d
diff --git a/periphery/gpio.py b/periphery/gpio.py index <HASH>..<HASH> 100644 --- a/periphery/gpio.py +++ b/periphery/gpio.py @@ -213,7 +213,7 @@ class GPIO(object): def name(self): """Get the line name of the GPIO. - his method is intended for use with character device GPIOs and always + This method is intended for use with character device GPIOs and always returns the empty string for sysfs GPIOs. :type: str
gpio: fix typo in docstring for name property
vsergeev_python-periphery
train
6df8503b7bddde39854096e6ff173e06aac48cff
diff --git a/docs/msg-transport-protocol.md b/docs/msg-transport-protocol.md index <HASH>..<HASH> 100644 --- a/docs/msg-transport-protocol.md +++ b/docs/msg-transport-protocol.md @@ -14,7 +14,7 @@ construct meta data with default values if `meta$` is not present. This provides for the use case of simple manual HTTP interactions with tools like `curl`. -The term _message_ refers to a single instance of outbound request +The term _message_ refers to a single instance of an outbound request JSON data transmitted between two specific service instances. The term message does *not* refer to a message flow over multiple services, *nor* to the optional JSON data response. The concept of the message @@ -35,6 +35,7 @@ flow should be used. mid: // Seneca message identifier, an opaque string, cid: // Seneca correlation identifier, an opaque string, snc: // true if synchronous (expecting response), false if asynchronous + pat: // pattern on the sending Seneca instance trk: [ // array of previously visited seneca instances including timing, { sid: // Seneca instance identifier of sender (not always redundant!) @@ -47,7 +48,7 @@ flow should be used. rtn: { // return path description urn: // full network address for http response, optional } - usr: { // user data, use this for your own meta data, optional + ctm: { // custom data, use this for your own meta data, optional ... } } diff --git a/lib/transport.js b/lib/transport.js index <HASH>..<HASH> 100644 --- a/lib/transport.js +++ b/lib/transport.js @@ -55,6 +55,7 @@ exports.listen = function (callpoint) { } } + exports.client = function (callpoint) { return function api_client () { var argsarr = new Array(arguments.length) @@ -79,17 +80,6 @@ exports.client = function (callpoint) { config.id = config.id || Common.pattern(raw_config) - // Queue messages while waiting for client to become active. - var sendqueue = [] - var sendclient = { - send: function (argsarr, done) { - var tosend = { instance: this, args: argsarr, done: done } - sendqueue.push(tosend) - } - } - - // TODO: validate pin, pins args - var pins = config.pins || (_.isArray(config.pin) ? config.pin : [config.pin || '']) @@ -99,6 +89,9 @@ exports.client = function (callpoint) { var sd = Plugins.make_delegate(self, { name: 'client$', tag: void 0 }) + var sendclient + + var transport_client = function transport_client (msg, done) { if (msg.local$) { this.prior(msg, done) @@ -122,6 +115,7 @@ exports.client = function (callpoint) { sd.add(pin, transport_client) }) + // Create client. sd.act( 'role:transport,cmd:client', @@ -130,24 +124,13 @@ exports.client = function (callpoint) { if (err) { return sd.die(internals.error(err, 'transport_client', config)) } + if (liveclient === null) { return sd.die(internals.error('transport_client_null', Common.clean(config))) } - // Process any messages waiting for this client, - // before bringing client online. - function sendnext () { - if (!sendqueue.length) { - sendclient = liveclient - } - else { - var tosend = sendqueue.shift() - sendclient.send.call(tosend.instance, tosend.args, tosend.done) - setImmediate(sendnext) - } - } - sendnext() + sendclient = liveclient }) return self diff --git a/test/transport.test.js b/test/transport.test.js index <HASH>..<HASH> 100644 --- a/test/transport.test.js +++ b/test/transport.test.js @@ -380,7 +380,8 @@ describe('transport', function () { it('transport-exact-single', function (done) { var tt = make_test_transport() - Seneca({tag: 'srv', timeout: 5555, log: 'silent', debug: { short_logs: true }}) + Seneca({tag: 'srv', timeout: 5555}) + .test(done) .use(tt) .add('foo:1', function (args, done) { // ensure action id is transferred for traceability @@ -389,8 +390,8 @@ describe('transport', function () { }) .listen({ type: 'test', pin: 'foo:1' }) .ready(function () { - Seneca({tag: 'cln', timeout: 5555, log: 'silent', - debug: {short_logs: true}}) + Seneca({tag: 'cln', timeout: 5555}) + .test(done) .use(tt) .client({type: 'test', pin: 'foo:1'}) @@ -634,14 +635,15 @@ describe('transport', function () { it('transport-local-prior-wrap', function (done) { var tt = make_test_transport() - Seneca({timeout: 5555, log: 'silent', debug: {short_logs: true}}) - .error(done) + Seneca({tag: 'srv', timeout: 5555}) + .test(done) .use(tt) .add('foo:1', testact) .listen({type: 'test', pin: 'foo:1'}) + .ready(function () { - Seneca({timeout: 5555, log: 'silent', debug: {short_logs: true}}) - .error(done) + Seneca({tag: 'cln', timeout: 5555}) + .test(done) .use(tt) .client({type: 'test', pin: 'foo:1'})
reduce complexity of .client by removing queueing; gate-executor 1.x should now handle this for us
senecajs_seneca
train
741de71614de0b3423baaa6e8bbf095e46b20833
diff --git a/spec/p/push_spec.rb b/spec/p/push_spec.rb index <HASH>..<HASH> 100644 --- a/spec/p/push_spec.rb +++ b/spec/p/push_spec.rb @@ -71,6 +71,30 @@ describe 'Flor procedures' do expect(r['payload']['ret']).to eq(nil) expect(r['payload']['l']).to eq([]) end + + it 'lets its second attribute bloom' do + + rad = %{ + sequence + + set v0 + val "hello" + set f.f0 + val "world" + + push f.l 1 + push f.l true + push f.l "buenos dias" + push f.l v0 + push f.l f.f0 + } + + r = @executor.launch(rad, payload: { 'l' => [] }) + + expect(r['point']).to eq('terminated') + expect(r['payload']['l']).to eq([ 1, true, 'false', 'hello', 'world' ]) + expect(r['payload']['ret']).to eq('world') + end end end
extend "push" spec with "bloom _2"
floraison_flor
train
6aa516d82dea9885cb4db8d56ec2ccfd4cd9b840
diff --git a/tests/test_html.py b/tests/test_html.py index <HASH>..<HASH> 100644 --- a/tests/test_html.py +++ b/tests/test_html.py @@ -1168,6 +1168,7 @@ def test_metadata_sort_desc(app_client): "/fixtures/compound_three_primary_keys", "/fixtures/compound_three_primary_keys/a,a,a", "/fixtures/paginated_view", + "/fixtures/facetable", ], ) def test_base_url_config(base_url, path):
Run base_url tests against /fixtures/facetable too, refs #<I>
simonw_datasette
train
53dadda2155a002cda6a804e59e151ea77a81c3a
diff --git a/environs/local/backend_test.go b/environs/local/backend_test.go index <HASH>..<HASH> 100644 --- a/environs/local/backend_test.go +++ b/environs/local/backend_test.go @@ -26,15 +26,25 @@ type backendSuite struct { var _ = Suite(&backendSuite{}) -const ( - environName = "test-environ" - portNo = 60006 -) +const environName = "test-environ" + +var portNo int = 60005 + +// nextPortNo increases the global port number and returns it. +func nextPortNo() int { + portNo++ + return portNo +} + +// actPortNo returns the actual global port number. +func actPortNo() int { + return portNo +} func (s *backendSuite) SetUpSuite(c *C) { var err error s.dataDir = c.MkDir() - s.listener, err = local.Listen(s.dataDir, environName, "127.0.0.1", portNo) + s.listener, err = local.Listen(s.dataDir, environName, "127.0.0.1", nextPortNo()) c.Assert(err, IsNil) createTestData(c, s.dataDir) @@ -117,7 +127,7 @@ var getTests = []testCase{ func (s *backendSuite) TestGet(c *C) { // Test retrieving a file from a storage. check := func(tc testCase) { - url := fmt.Sprintf("http://localhost:%d/%s", portNo, tc.name) + url := fmt.Sprintf("http://localhost:%d/%s", actPortNo(), tc.name) resp, err := http.Get(url) c.Assert(err, IsNil) if tc.status != 0 { @@ -183,7 +193,7 @@ var listTests = []testCase{ func (s *backendSuite) TestList(c *C) { // Test listing file of a storage. check := func(tc testCase) { - url := fmt.Sprintf("http://localhost:%d/%s*", portNo, tc.name) + url := fmt.Sprintf("http://localhost:%d/%s*", actPortNo(), tc.name) resp, err := http.Get(url) c.Assert(err, IsNil) if tc.status != 0 { @@ -225,7 +235,7 @@ var putTests = []testCase{ func (s *backendSuite) TestPut(c *C) { // Test sending a file to the storage. check := func(tc testCase) { - url := fmt.Sprintf("http://localhost:%d/%s", portNo, tc.name) + url := fmt.Sprintf("http://localhost:%d/%s", actPortNo(), tc.name) req, err := http.NewRequest("PUT", url, bytes.NewBufferString(tc.content)) c.Assert(err, IsNil) req.Header.Set("Content-Type", "application/octet-stream") @@ -281,7 +291,7 @@ func (s *backendSuite) TestRemove(c *C) { err = ioutil.WriteFile(fp, []byte(tc.content), 0644) c.Assert(err, IsNil) - url := fmt.Sprintf("http://localhost:%d/%s", portNo, tc.name) + url := fmt.Sprintf("http://localhost:%d/%s", actPortNo(), tc.name) req, err := http.NewRequest("DELETE", url, nil) c.Assert(err, IsNil) resp, err := http.DefaultClient.Do(req) diff --git a/environs/local/storage_test.go b/environs/local/storage_test.go index <HASH>..<HASH> 100644 --- a/environs/local/storage_test.go +++ b/environs/local/storage_test.go @@ -16,13 +16,10 @@ var _ = Suite(&storageSuite{}) // TestPersistence tests the adding, reading, listing and removing // of files from the local storage. func (s *storageSuite) TestPersistence(c *C) { - // Non-standard port to avoid conflict with not-yet full - // closed listener in backend test. - portNo := 60007 - listener, err := local.Listen(c.MkDir(), environName, "127.0.0.1", portNo) + listener, err := local.Listen(c.MkDir(), environName, "127.0.0.1", nextPortNo()) c.Assert(err, IsNil) defer listener.Close() - storage := local.NewStorage("127.0.0.1", portNo) + storage := local.NewStorage("127.0.0.1", actPortNo()) names := []string{ "aa", @@ -37,7 +34,7 @@ func (s *storageSuite) TestPersistence(c *C) { checkList(c, storage, "a", []string{"aa"}) checkList(c, storage, "zzz/", []string{"zzz/aa", "zzz/bb"}) - storage2 := local.NewStorage("127.0.0.1", portNo) + storage2 := local.NewStorage("127.0.0.1", actPortNo()) for _, name := range names { checkFileHasContents(c, storage2, name, []byte(name)) }
local: chnaged port during the tests
juju_juju
train
73e6d35b641f6a3f43a9ba101343132a5ae50cdf
diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index <HASH>..<HASH> 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -27,10 +27,6 @@ Metrics/BlockLength: Metrics/MethodLength: Max: 39 -# Offense count: 4 -Metrics/PerceivedComplexity: - Max: 13 - # Offense count: 8 # Configuration parameters: EnforcedStyle. # SupportedStyles: lowercase, uppercase diff --git a/lib/art-decomp/bipainter.rb b/lib/art-decomp/bipainter.rb index <HASH>..<HASH> 100644 --- a/lib/art-decomp/bipainter.rb +++ b/lib/art-decomp/bipainter.rb @@ -64,7 +64,7 @@ module ArtDecomp colour_g_vertex! g_vertex if g_vertex end - def colour_qv!(qv_vertex, colour) # rubocop:disable CyclomaticComplexity + def colour_qv!(qv_vertex, colour) # rubocop:disable CyclomaticComplexity, PerceivedComplexity return if @qv_colours[qv_vertex] == colour raise PaintingError if @qv_colours[qv_vertex] and @qv_colours[qv_vertex] != colour raise PaintingError if @qv_forbidden[qv_vertex].include? colour diff --git a/lib/art-decomp/executable.rb b/lib/art-decomp/executable.rb index <HASH>..<HASH> 100644 --- a/lib/art-decomp/executable.rb +++ b/lib/art-decomp/executable.rb @@ -5,7 +5,7 @@ require_relative 'logging' module ArtDecomp class Executable - def initialize(args, opts = { logging_class: Logging }) # rubocop:disable CyclomaticComplexity + def initialize(args, opts = { logging_class: Logging }) # rubocop:disable CyclomaticComplexity, PerceivedComplexity options = Trollop.options args do opt :archs, 'Target architecture(s)', required: true, type: :strings opt :dir, 'Results directory', required: true, type: :string diff --git a/lib/art-decomp/fsm.rb b/lib/art-decomp/fsm.rb index <HASH>..<HASH> 100644 --- a/lib/art-decomp/fsm.rb +++ b/lib/art-decomp/fsm.rb @@ -2,7 +2,7 @@ module ArtDecomp class FSM # rubocop:disable ClassLength attr_reader :codes - def self.from_kiss(kiss) # rubocop:disable CyclomaticComplexity + def self.from_kiss(kiss) # rubocop:disable CyclomaticComplexity, PerceivedComplexity kiss = File.read kiss unless kiss.index "\n" inputs, outputs, state, next_state = [], [], [], [] codes = Hash[kiss.lines.grep(/^\.code [^*]/).map(&:split).map { |_, st, code| [st.to_sym, code.to_sym] }] diff --git a/lib/art-decomp/vhdl.rb b/lib/art-decomp/vhdl.rb index <HASH>..<HASH> 100644 --- a/lib/art-decomp/vhdl.rb +++ b/lib/art-decomp/vhdl.rb @@ -4,7 +4,7 @@ module ArtDecomp @fsm = fsm end - def vhdl(name) # rubocop:disable CyclomaticComplexity + def vhdl(name) # rubocop:disable CyclomaticComplexity, PerceivedComplexity structure = @fsm.structure logic = structure[DontCare].map do |input, results| results[:next_state] = "s#{results[:next_state]}".to_sym if results[:next_state] =~ /^\d+$/
RuboCop: fix PerceivedComplexity
chastell_art-decomp
train
0328eeefba8581ad00fdce2975b00fcfabfc097a
diff --git a/benchbuild/source/base.py b/benchbuild/source/base.py index <HASH>..<HASH> 100644 --- a/benchbuild/source/base.py +++ b/benchbuild/source/base.py @@ -20,6 +20,11 @@ NestedVariants = tp.Iterable[tp.Tuple[tp.Any, ...]] @attr.s(frozen=True, eq=True) +class RevisionStr: + value: str = attr.ib() + + +@attr.s(frozen=True, eq=True) class Variant: """ Provide a 'string'-like wrapper around source version information. @@ -304,3 +309,41 @@ def sources_as_dict(*sources: Fetchable) -> SourceContext: *sources: Fetchables stored in the dictionary. """ return {src.local: src for src in sources} + + +def context_from_revisions(revs: tp.Sequence[RevisionStr], + *sources: SourceT) -> tp.Optional[VariantContext]: + """ + Create a VariantContext from a sequence of revision strings. + + A valid VariantContext can only be created, if the number of valid revision + strings is equivalent to the number of sources. + A valid revision string is one that has been found in the a source's + version. + It is required that each revision string is found in a different source + version. + + Args: + revs: sequence of revision strings, e.g. a commit-hash. + *sources: sources of a project. + + Returns: + A variant context. + """ + found: tp.List[VariantContext] = [] + for source in sources: + found.extend([ + variant for variant in source.versions() for rev in revs + if variant.version == rev + ]) + + ctx = context(*found) + + assert len(revs) == len( + found + ), "Not all revision strings have been found in source versions." + assert len(revs) == len( + ctx + ), "Not all revision strings have been found in the same source." + + return ctx
feat(source): provide an easy way to create a variant context A user can create a variant context from a sequence of revision strings. Revision strings can be any value that forms a Variant in combination with an owner object (a source). Tests will follow in a future commit.
PolyJIT_benchbuild
train
9139ab9b5a4ece82bc53a718845d227d6bbe00e5
diff --git a/tests/interpolation_test.py b/tests/interpolation_test.py index <HASH>..<HASH> 100644 --- a/tests/interpolation_test.py +++ b/tests/interpolation_test.py @@ -121,16 +121,6 @@ class DesignspaceTest(unittest.TestCase): self.expect_designspace(masters, instances, "DesignspaceTestBasic.designspace") - def test_inactive_from_active(self): - # Glyphs.app recognizes active=0 as a flag for inactive instances. - # https://github.com/googlei18n/glyphsLib/issues/129 - masters, instances = makeFamily("DesignspaceTest Inactive") - for inst in instances["data"]: - if inst.name != "Semibold": - inst.active = False - self.expect_designspace(masters, instances, - "DesignspaceTestInactive.designspace") - def test_inactive_from_exports(self): # Glyphs.app recognizes exports=0 as a flag for inactive instances. # https://github.com/googlei18n/glyphsLib/issues/129
GSInstance has no active property
googlefonts_glyphsLib
train
238dd5ecfb74b541d87d702e24e43e980211eea4
diff --git a/lib/repoman/tasks/add/asset.rb b/lib/repoman/tasks/add/asset.rb index <HASH>..<HASH> 100644 --- a/lib/repoman/tasks/add/asset.rb +++ b/lib/repoman/tasks/add/asset.rb @@ -26,50 +26,11 @@ module Repoman end - class Add < Thor - namespace :add - include Thor::Actions - include Repoman::ThorHelper - include Repoman::GenerateHelper - include ::Repoman::ActionHelper + module AddHelper - # adds :quiet, :skip, :pretent, :force - add_runtime_options! - - method_option :filter, :type => :array, :aliases => "-f", :desc => "List of regex folder name filters" - method_option :refresh, :type => :boolean, :aliases => "-r", :desc => "Refresh existing blank attributes" + def process_discovered_assets(discovered_assets=[]) - desc "assets FOLDER", "generate multiple config files by searching a folder, one level deep, for git repositories" - def assets(folder) - - say_status "collecting", "collecting top level folder names" - discovered_assets = [] - filters = options[:filter] || ['.*'] - # Thor does not allow comma separated array options, fix that here - filters = filters.first.to_s.split(',') if filters.length == 1 - Dir.glob( File.join(folder, '*/') ).each do |repo_folder| - logger.debug "filters: #{filters.inspect}" - next unless filters.find {|filter| repo_folder.match(/#{filter}/)} - next unless File.exists?(File.join(repo_folder, '.git/')) - - # check existing assets for path match, if found, use existing name instead of the generated name - existing = existing_assets.detect do |existing_asset| - existing_asset.path && repo_folder && (File.expand_path(existing_asset.path) == File.expand_path(repo_folder)) - end - - if (existing) - name = existing.name - else - name = ::Repoman::RepoAsset.path_to_name(repo_folder) - end - - asset = ::Repoman::RepoAsset.new(name) - asset.path = File.expand_path(repo_folder) - - discovered_assets << asset - end - - say_status "configuring", "setting discovered asset configuration paths" + say_status "configuring", "setting discovered asset attributes" discovered_assets.each do |discovered_asset| folder = File.dirname(asset_name_to_config_file(discovered_asset.name)) discovered_asset.configuration.folder = folder @@ -86,7 +47,7 @@ module Repoman end end else - say_status "comparing", "looking for existing asset names" + say_status "comparing", "looking at existing asset names" discovered_assets.delete_if do |asset| result = false if File.exists?(asset.configuration.folder) @@ -96,7 +57,7 @@ module Repoman result end - say_status "comparing", "looking for existing asset paths" + say_status "comparing", "looking at existing asset paths" discovered_assets.delete_if do |asset| result = false existing_asset = existing_assets.detect do |existing_asset| @@ -140,6 +101,56 @@ module Repoman end + end + + class Add < Thor + namespace :add + include Thor::Actions + include Repoman::ThorHelper + include Repoman::GenerateHelper + include Repoman::AddHelper + include ::Repoman::ActionHelper + + # adds :quiet, :skip, :pretent, :force + add_runtime_options! + + method_option :filter, :type => :array, :aliases => "-f", :desc => "List of regex folder name filters" + method_option :refresh, :type => :boolean, :aliases => "-r", :desc => "Refresh existing blank attributes" + + desc "assets FOLDER", "generate multiple config files by searching a folder, one level deep, for git repositories" + def assets(folder) + + say_status "collecting", "collecting top level folder names" + discovered_assets = [] + filters = options[:filter] || ['.*'] + # Thor does not allow comma separated array options, fix that here + filters = filters.first.to_s.split(',') if filters.length == 1 + Dir.glob( File.join(folder, '*/') ).each do |repo_folder| + logger.debug "filters: #{filters.inspect}" + next unless filters.find {|filter| repo_folder.match(/#{filter}/)} + next unless File.exists?(File.join(repo_folder, '.git/')) + + # check existing assets for path match, if found, use existing name instead of the generated name + existing = existing_assets.detect do |existing_asset| + existing_asset.path && repo_folder && (File.expand_path(existing_asset.path) == File.expand_path(repo_folder)) + end + + if (existing) + name = existing.name + else + name = ::Repoman::RepoAsset.path_to_name(repo_folder) + end + + asset = ::Repoman::RepoAsset.new(name) + asset.path = File.expand_path(repo_folder) + + discovered_assets << asset + end + + process_discovered_assets(discovered_assets) + + end + private # where to start looking, required by the template method
add:assets logic in a helper in prep for 'add:asset'
robertwahler_repo_manager
train
beae8524133b0781a27c5a952b7e348be9f9240c
diff --git a/dempsy-framework.core/src/main/java/net/dempsy/threading/OrderedPerContainerThreadingModel.java b/dempsy-framework.core/src/main/java/net/dempsy/threading/OrderedPerContainerThreadingModel.java index <HASH>..<HASH> 100644 --- a/dempsy-framework.core/src/main/java/net/dempsy/threading/OrderedPerContainerThreadingModel.java +++ b/dempsy-framework.core/src/main/java/net/dempsy/threading/OrderedPerContainerThreadingModel.java @@ -11,6 +11,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -184,8 +185,22 @@ public class OrderedPerContainerThreadingModel implements ThreadingModel { public final ContainerJobMetadata container; public ContainerWorker(final ContainerJobMetadata container) { - this.queue = new LinkedBlockingQueue<>(); this.container = container; + final Container c = container.container; + if(c.containerInternallyQueuesMessages()) + throw new IllegalArgumentException( + "Cannot use an " + OrderedPerContainerThreadingModel.class.getSimpleName() + " with a " + c.getClass().getSimpleName() + + " container, as is being done for the cluster \"" + c.getClusterId().clusterName + + "\" because it internally queues messages, defeating the only reason to use this threading model."); + final int maxPendingMessagesPerContainer = c.getMaxPendingMessagesPerContainer(); + if(maxPendingMessagesPerContainer <= 0) { + LOGGER.warn( + "The container for \"{}\" has no limit set on the number of maximum queued messages. If the processing thread hangs up the messages will queue indefinitely potentially causing the process to run out of memory.", + c.getClusterId().clusterName); + this.queue = new LinkedBlockingQueue<>(); + } else + this.queue = new ArrayBlockingQueue<>(maxPendingMessagesPerContainer); + chain( // this used to use the nameSupplier but the name is too long in `htop` // to understand what's going on so it's been switched to simple "c-"
Prevent a blocked (in an mp call) thread from causing the filling of an unbounded queue in a OrderedPerContainerThreadingModel.
Dempsy_dempsy
train
429bdbfebc2c970ccab17220df6b109cdfd540dd
diff --git a/resolwe/flow/managers/dispatcher.py b/resolwe/flow/managers/dispatcher.py index <HASH>..<HASH> 100644 --- a/resolwe/flow/managers/dispatcher.py +++ b/resolwe/flow/managers/dispatcher.py @@ -439,13 +439,11 @@ class Manager(object): # Both of these imports are here only to get the packages' paths. import resolwe.flow.executors as executor_package - import resolwe.flow.managers.protocol as protocol_module exec_dir = os.path.dirname(inspect.getsourcefile(executor_package)) dest_dir = self._get_per_data_dir('RUNTIME_DIR', data_id) dest_package_dir = os.path.join(dest_dir, 'executors') shutil.copytree(exec_dir, dest_package_dir) - shutil.copy(protocol_module.__file__, dest_package_dir) dir_mode = self.settings_actual.get('FLOW_EXECUTOR', {}).get('RUNTIME_DIR_MODE', 0o755) os.chmod(dest_dir, dir_mode)
Remove unnecessary manager special case file copy for executor
genialis_resolwe
train
28adbca62b5ee03367efc52cb79ebf5542ca4563
diff --git a/src/Internal/Calculator/NativeCalculator.php b/src/Internal/Calculator/NativeCalculator.php index <HASH>..<HASH> 100644 --- a/src/Internal/Calculator/NativeCalculator.php +++ b/src/Internal/Calculator/NativeCalculator.php @@ -51,6 +51,12 @@ class NativeCalculator extends Calculator */ public function add(string $a, string $b) : string { + $result = $a + $b; + + if (is_int($result)) { + return (string) $result; + } + if ($a === '0') { return $b; } @@ -59,12 +65,6 @@ class NativeCalculator extends Calculator return $a; } - $result = $a + $b; - - if (is_int($result)) { - return (string) $result; - } - $this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg); if ($aNeg === $bNeg) { @@ -93,6 +93,12 @@ class NativeCalculator extends Calculator */ public function mul(string $a, string $b) : string { + $result = $a * $b; + + if (is_int($result)) { + return (string) $result; + } + if ($a === '0' || $b === '0') { return '0'; } @@ -113,12 +119,6 @@ class NativeCalculator extends Calculator return $this->neg($a); } - $result = $a * $b; - - if (is_int($result)) { - return (string) $result; - } - $this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg); $result = $this->doMul($aDig, $bDig);
Always try to perform native addition/multiplication first We now do this before any other check; this is less costly for the common case where the operation is actually feasible using native integers.
brick_math
train
1b840fb1b7a8bb9eb3a15ec6fa03dc58ec870af2
diff --git a/prometheus_client/core.py b/prometheus_client/core.py index <HASH>..<HASH> 100644 --- a/prometheus_client/core.py +++ b/prometheus_client/core.py @@ -181,7 +181,7 @@ REGISTRY = CollectorRegistry(auto_describe=True) '''The default registry.''' _METRIC_TYPES = ('counter', 'gauge', 'summary', 'histogram', - 'gaugehistogram', 'untyped', 'info', 'stateset') + 'gaugehistogram', 'unknown', 'info', 'stateset') class Metric(object): @@ -200,6 +200,8 @@ class Metric(object): if unit and not name.endswith("_" + unit): raise ValueError("Metric name not suffixed by unit: " + name) self.unit = unit + if typ == 'untyped': + typ = 'unknown' if typ not in _METRIC_TYPES: raise ValueError('Invalid metric type: ' + typ) self.type = typ @@ -228,12 +230,12 @@ class Metric(object): self.type, self.unit, self.samples) -class UntypedMetricFamily(Metric): - '''A single untyped metric and its samples. +class UnknownMetricFamily(Metric): + '''A single unknwon metric and its samples. For use by custom collectors. ''' def __init__(self, name, documentation, value=None, labels=None): - Metric.__init__(self, name, documentation, 'untyped') + Metric.__init__(self, name, documentation, 'unknown') if labels is not None and value is not None: raise ValueError('Can only specify at most one of value and labels.') if labels is None: @@ -250,6 +252,8 @@ class UntypedMetricFamily(Metric): ''' self.samples.append(Sample(self.name, dict(zip(self._labelnames, labels)), value, timestamp)) +# For backward compatibility. +UntypedMetricFamily = UnknownMetricFamily class CounterMetricFamily(Metric): '''A single counter and its samples. 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 @@ -82,6 +82,8 @@ def generate_latest(registry=core.REGISTRY): # A gauge histogram is really a gauge, # but this captures the strucutre better. mtype = 'histogram' + elif mtype == 'unknown': + mtype = 'untyped' output.append('# HELP {0} {1}'.format( mname, metric.documentation.replace('\\', r'\\').replace('\n', r'\n'))) output.append('\n# TYPE {0} {1}\n'.format(mname, mtype)) diff --git a/tests/openmetrics/test_exposition.py b/tests/openmetrics/test_exposition.py index <HASH>..<HASH> 100644 --- a/tests/openmetrics/test_exposition.py +++ b/tests/openmetrics/test_exposition.py @@ -150,12 +150,12 @@ cc_created{a="\\\\x\\n\\""} 123.456 yield metric self.registry.register(MyCollector()) - self.assertEqual(b'# HELP nonnumber Non number\n# TYPE nonnumber untyped\nnonnumber 123.0\n# EOF\n', generate_latest(self.registry)) + self.assertEqual(b'# HELP nonnumber Non number\n# TYPE nonnumber unknown\nnonnumber 123.0\n# EOF\n', generate_latest(self.registry)) def test_timestamp(self): class MyCollector(object): def collect(self): - metric = Metric("ts", "help", 'untyped') + metric = Metric("ts", "help", 'unknown') metric.add_sample("ts", {"foo": "a"}, 0, 123.456) metric.add_sample("ts", {"foo": "b"}, 0, -123.456) metric.add_sample("ts", {"foo": "c"}, 0, 123) @@ -166,7 +166,7 @@ cc_created{a="\\\\x\\n\\""} 123.456 self.registry.register(MyCollector()) self.assertEqual(b'''# HELP ts help -# TYPE ts untyped +# TYPE ts unknown ts{foo="a"} 0.0 123.456 ts{foo="b"} 0.0 -123.456 ts{foo="c"} 0.0 123
OM changes untyped to unknown
prometheus_client_python
train
c46e1f3a8454477851ec78b003422510bb2729c0
diff --git a/test/image_test.rb b/test/image_test.rb index <HASH>..<HASH> 100644 --- a/test/image_test.rb +++ b/test/image_test.rb @@ -213,7 +213,7 @@ class ImageTest < Test::Unit::TestCase def test_tempfile_at_path_after_format image = Image.open(TIFF_IMAGE_PATH) image.format('png') - assert_equal image.path, image.instance_eval("@tempfile.path") + assert File.exists?(image.path) image.destroy! end
Just ensure the path is correct in JRuby
minimagick_minimagick
train
40b88f30883e0cab79f97deeac6e647cd272e902
diff --git a/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py b/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py index <HASH>..<HASH> 100644 --- a/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py +++ b/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py @@ -25,10 +25,10 @@ import numpy as np from numpy.polynomial import Polynomial import sys +from emirdrp.processing.wavecal.set_wv_parameters import set_wv_parameters from emirdrp.products import RectWaveCoeff from emirdrp.core import EMIR_NAXIS1 -from emirdrp.core import EMIR_NAXIS1_ENLARGED from emirdrp.core import EMIR_NBARS from numina.array.display.pause_debugplot import DEBUGPLOT_CODES @@ -112,6 +112,15 @@ def rectwv_coeff_to_ds9(rectwv_coeff, if limits not in ['boundaries', 'frontiers']: raise ValueError('Unexpect limits=' + str(limits)) + # retrieve relevant wavelength calibration parameters + grism_name = rectwv_coeff.tags['grism'] + filter_name = rectwv_coeff.tags['filter'] + wv_parameters = set_wv_parameters(filter_name, grism_name) + naxis1_enlarged = wv_parameters['naxis1_enlarged'] + crpix1_enlarged = wv_parameters['crpix1_enlarged'] + crval1_enlarged = wv_parameters['crval1_enlarged'] + cdelt1_enlarged = wv_parameters['cdelt1_enlarged'] + ds9_output = '# Region file format: DS9 version 4.1\n' \ 'global color=green dashlist=2 4 width=2 ' \ 'font="helvetica 10 normal roman" select=1 ' \ @@ -153,15 +162,10 @@ def rectwv_coeff_to_ds9(rectwv_coeff, ds9_output += \ 'line {0} {1} {2} {3}'.format( 1, ydum, - EMIR_NAXIS1_ENLARGED, ydum + naxis1_enlarged, ydum ) ds9_output += ' # color={0}\n'.format(colorbox) - ds9_output += 'text {0} {1} {{{2}}} # color={3} ' \ - 'font="helvetica 10 bold ' \ - 'roman"\n'.format(EMIR_NAXIS1_ENLARGED / 2 + 0.5, - (ydum_lower + ydum_upper) / 2, - islitlet, - colorbox) + ydum_label = (ydum_lower + ydum_upper) / 2.0 else: if limits == 'frontiers': pol_lower = Polynomial( @@ -195,14 +199,23 @@ def rectwv_coeff_to_ds9(rectwv_coeff, ) ds9_output += ' # color={0}\n'.format(colorbox) # slitlet label - yc_lower = pol_lower(EMIR_NAXIS1 / 2 + 0.5) - yc_upper = pol_upper(EMIR_NAXIS1 / 2 + 0.5) - ds9_output += 'text {0} {1} {{{2}}} # color={3} ' \ - 'font="helvetica 10 bold ' \ - 'roman"\n'.format(EMIR_NAXIS1 / 2 + 0.5, - (yc_lower + yc_upper) / 2, - islitlet, - colorbox) + ydum_lower = pol_lower(EMIR_NAXIS1 / 2 + 0.5) + ydum_upper = pol_upper(EMIR_NAXIS1 / 2 + 0.5) + ydum_label = (ydum_lower + ydum_upper) / 2.0 + # slitlet label + xdum_label = EMIR_NAXIS1 / 2 + 0.5 + if rectified: + crpix1_linear = 1.0 + crval1_linear = dumdict['crval1_linear'] + cdelt1_linear = dumdict['cdelt1_linear'] + wave_center = crval1_linear + \ + (xdum_label - crpix1_linear) * cdelt1_linear + xdum_label = (wave_center - crval1_enlarged) / cdelt1_enlarged + xdum_label += crpix1_enlarged + ds9_output += 'text {0} {1} {{{2}}} # color={3} ' \ + 'font="helvetica 10 bold ' \ + 'roman"\n'.format(xdum_label, ydum_label, + islitlet, colorbox) return ds9_output
Place ds9 region labels centered in wavelength direction
guaix-ucm_pyemir
train
0cad8cd0d41d4a15d4fd003eebb12ebc79e63f70
diff --git a/spec/mtgox/client_spec.rb b/spec/mtgox/client_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mtgox/client_spec.rb +++ b/spec/mtgox/client_spec.rb @@ -18,30 +18,49 @@ describe MtGox::Client do end end - describe '#asks' do - before do + describe 'depth methods' do + before :each do stub_get('/code/data/getDepth.php'). to_return(:status => 200, :body => fixture('depth.json')) end - - it "should fetch open asks" do - asks = @client.asks - a_get('/code/data/getDepth.php').should have_been_made - asks.last.should == [45, 593.28] + + describe '#asks' do + it "should fetch open asks" do + asks = @client.asks + a_get('/code/data/getDepth.php').should have_been_made + asks.last.should == [45, 593.28] + end + + it "should be sorted in price-ascending order" do + asks = @client.asks + asks.sort_by {|x| x[0]}.should == asks + end + end - end - - describe '#bids' do - before do - stub_get('/code/data/getDepth.php'). - to_return(:status => 200, :body => fixture('depth.json')) + + describe "#bids" do + it "should fetch open bids" do + bids = @client.bids + a_get('/code/data/getDepth.php').should have_been_made + bids.last.should == [19.1, 1] + end + + it "should be sorted in price-descending order" do + bids = @client.bids + bids.sort_by {|x| x[0]}.reverse.should == bids + end + end - - it "should fetch open bids" do - bids = @client.bids - a_get('/code/data/getDepth.php').should have_been_made - bids.last.should == [19.1, 1] + + describe "#offers" do + it "should fetch both bids and asks, making only 1 network request" do + offers = @client.offers + a_get('/code/data/getDepth.php').should have_been_made.once + offers.asks.last.should == [45, 593.28] + offers.bids.last.should == [19.1, 1] + end end + end describe '#trades' do @@ -58,5 +77,10 @@ describe MtGox::Client do trades.last.amount.should == 1.37 trades.last.tid.should == "129606" end + + it "should be sorted in chronological order" do + trades = @client.trades + trades.sort_by(&:date).should == trades + end end end
added #offers to spec, and added specs for ordering conditions I added in the YARD docs
sferik_mtgox
train
b9eaca79684fa3fd4a6a423de5c1701e747b5ab5
diff --git a/test/spec/spec_helper.rb b/test/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/test/spec/spec_helper.rb +++ b/test/spec/spec_helper.rb @@ -35,7 +35,11 @@ module PoiseServiceHelper def service_resource_hints(hints, &block) hints ||= block.call if block before do - PoiseService::Providers::Base.remove_class_variable(:@@service_resource_hints) rescue nil + begin + PoiseService::ServiceProviders::Base.remove_class_variable(:@@service_resource_hints) + rescue NameError + # This space left intentionally blank. + end allow(Chef::Platform::ServiceHelpers).to receive(:service_resource_providers).and_return(Array(hints)) end end
Now with <I>% less rescue nil. Same classic flavor.
poise_poise-service
train
711d10037165625470079783a5caa7ce49ae7a89
diff --git a/lib/danger/ci_source/circle.rb b/lib/danger/ci_source/circle.rb index <HASH>..<HASH> 100644 --- a/lib/danger/ci_source/circle.rb +++ b/lib/danger/ci_source/circle.rb @@ -7,7 +7,6 @@ module Danger class CircleCI < CI def self.validates?(env) return false unless env["CIRCLE_BUILD_NUM"] - return false unless env["CI_PULL_REQUEST"] return false unless env["CIRCLE_PROJECT_USERNAME"] return false unless env["CIRCLE_PROJECT_REPONAME"] diff --git a/spec/lib/danger/ci_sources/circle_spec.rb b/spec/lib/danger/ci_sources/circle_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/danger/ci_sources/circle_spec.rb +++ b/spec/lib/danger/ci_sources/circle_spec.rb @@ -29,11 +29,11 @@ describe Danger::CISource::CircleCI do expect(t.pull_request_id).to be nil end - it 'doesnt validate when circle env var is found and it has no PR url' do + it 'does validate when circle env var is found and it has no PR url' do env = { "CIRCLE_BUILD_NUM" => "true", "CIRCLE_PROJECT_USERNAME" => "orta", "CIRCLE_PROJECT_REPONAME" => "thing" } - expect(Danger::CISource::CircleCI.validates?(env)).to be false + expect(Danger::CISource::CircleCI.validates?(env)).to be true end it 'doesnt validate when circle ci is not found' do
Allow Circle CI to pass validation withut a PR check, so that we can ask for the metadata a bit later
danger_danger
train
0795c5bae39cda6ca2e0b6ab5dc72215ac95a33a
diff --git a/lib/api.js b/lib/api.js index <HASH>..<HASH> 100644 --- a/lib/api.js +++ b/lib/api.js @@ -864,7 +864,7 @@ api.prepareRequest = function(req) ops: {}, noscan: 1, ip: req.ip, - host: req.hostname, + host: (req.hostname || "").toLowerCase(), path: path, apath: apath, secure: req.secure,
option s.host is lowecase
vseryakov_backendjs
train
c8ab23641c20ec8376cc0d293884ce12ca80583d
diff --git a/bittrex/bittrex.py b/bittrex/bittrex.py index <HASH>..<HASH> 100644 --- a/bittrex/bittrex.py +++ b/bittrex/bittrex.py @@ -107,6 +107,18 @@ class Bittrex(object): :rtype : dict """ return self.api_query('getmarketsummaries') + + def get_marketsummary(self, market): + """ + Used to get the last 24 hour summary of all active exchanges in specific coin + + :param market: String literal for the market(ex: XRP) + :type market: str + + :return: Summaries of active exchanges of a coin in JSON + :rtype : dict + """ + return self.api_query('getmarketsummary', {'market': market}) def get_orderbook(self, market, depth_type, depth=20): """ @@ -275,6 +287,8 @@ class Bittrex(object): :rtype : dict """ return self.api_query('getbalances', {}) + + def get_balance(self, currency): """
Added get_marketsummary
ericsomdahl_python-bittrex
train
c66cfb9a7586203b6f289b3393253c14756984b2
diff --git a/ratcave/camera.py b/ratcave/camera.py index <HASH>..<HASH> 100644 --- a/ratcave/camera.py +++ b/ratcave/camera.py @@ -203,6 +203,13 @@ class Camera(PhysicalGraph, HasUniforms, mixins.NameLabelMixin, mixins.Observabl def __repr__(self): return "<Camera(name='{self.name}', position_rel={self.position}, position_glob={self.position_global}, rotation={self.rotation})".format(self=self) + def __enter__(self): + self.uniforms.send() + return self + + def __exit__(self, *args): + pass + def update(self): super(Camera, self).update() self.projection.update() diff --git a/ratcave/light.py b/ratcave/light.py index <HASH>..<HASH> 100644 --- a/ratcave/light.py +++ b/ratcave/light.py @@ -12,5 +12,12 @@ class Light(PhysicalGraph, HasUniforms, mixins.NameLabelMixin, mixins.Observable def __repr__(self): return "<Light(name='{self.name}', position_rel={self.position}, position_glob={self.position_global}, rotation={self.rotation})".format(self=self) + def __enter__(self): + self.uniforms.send() + return self + + def __exit__(self, *args): + pass + def reset_uniforms(self): self.uniforms['light_position'] = self.model_matrix_global[:3, 3] \ No newline at end of file
Uniform sending can now be done through the context manager interface for Cameras and Lights.
ratcave_ratcave
train
c3f447f8396249315531e66250a4360476032800
diff --git a/src/Bllim/Datatables/Datatables.php b/src/Bllim/Datatables/Datatables.php index <HASH>..<HASH> 100644 --- a/src/Bllim/Datatables/Datatables.php +++ b/src/Bllim/Datatables/Datatables.php @@ -244,8 +244,8 @@ class Datatables $count++; $i--; continue; } - $temp = explode(' as ', $this->columns[$i]); - $last_columns[$count] = trim(array_pop($temp)); + preg_match('#^(\S*?)\s+as\s+(\S*?)$#si',$this->columns[$i],$matches); + $last_columns[$count] = empty($matches) ? $this->columns[$i] : $matches[2]; $count++; } @@ -376,8 +376,9 @@ class Datatables { if (Input::get('bSearchable_'.$i) == "true") { - $column = explode(' as ', $copy_this->columns[$i]); - $column = array_shift($column); + + preg_match('#^(\S*?)\s+as\s+(\S*?)$#si',$copy_this->columns[$i],$matches); + $column = empty($matches) ? $copy_this->columns[$i] : $matches[1]; $keyword = '%'.Input::get('sSearch').'%'; if(Config::get('datatables.search.use_wildcards', false)) { @@ -458,7 +459,7 @@ class Datatables private function count() { //Get columns to temp var. - $query_type = get_class($this->query) == 'Illuminate\Database\Query\Builder' ? 'fluent' : 'eloquent'; + $query_type = get_class($this->query) == 'Illuminate\Database\Query\Builder' ? 'fluent' : 'eloquent'; $columns = $query_type == 'eloquent' ? $this->query->getQuery()->columns : $this->query->columns; $this->count_all = $this->query->count(); @@ -477,10 +478,11 @@ class Datatables private function getColumnName($str) { - if(strpos($str,' as ')) + preg_match('#^(\S*?)\s+as\s+(\S*?)$#si',$str,$matches); + + if(!empty($matches)) { - $array = explode(' as ', $str); - return array_pop($array); + return $matches[2]; } elseif(strpos($str,'.')) {
help to fix #<I> exploding all possible as [as,AS,aS,As] without using strtolower
yajra_laravel-datatables
train
fa6658aa0a54ceef58e7a01a68b0af1f9a7a83e4
diff --git a/aws/data_source_aws_iam_user_test.go b/aws/data_source_aws_iam_user_test.go index <HASH>..<HASH> 100644 --- a/aws/data_source_aws_iam_user_test.go +++ b/aws/data_source_aws_iam_user_test.go @@ -4,6 +4,7 @@ import ( "fmt" "testing" + "github.com/aws/aws-sdk-go/service/iam" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) @@ -15,8 +16,9 @@ func TestAccAWSDataSourceIAMUser_basic(t *testing.T) { userName := fmt.Sprintf("test-datasource-user-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, + PreCheck: func() { testAccPreCheck(t) }, + ErrorCheck: testAccErrorCheck(t, iam.EndpointsID), + Providers: testAccProviders, Steps: []resource.TestStep{ { Config: testAccAwsDataSourceIAMUserConfig(userName), @@ -40,8 +42,9 @@ func TestAccAWSDataSourceIAMUser_tags(t *testing.T) { userName := fmt.Sprintf("test-datasource-user-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, + PreCheck: func() { testAccPreCheck(t) }, + ErrorCheck: testAccErrorCheck(t, iam.EndpointsID), + Providers: testAccProviders, Steps: []resource.TestStep{ { Config: testAccAwsDataSourceIAMUserConfig_tags(userName),
tests/ds/iam_user: Add ErrorCheck
terraform-providers_terraform-provider-aws
train
571a5605886279e55948c62134d8846d87fefe12
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -3,13 +3,13 @@ from distutils.core import setup setup( name='hapipy', - version='2.1.6', + version='2.1.7', description="A python wrapper around HubSpot's APIs", long_description = open('README.md').read(), author='Adrian Mott', author_email='amott@hubspot.com', url='https://github.com/HubSpot/hapipy', - download_url='https://github.com/HubSpot/hapipy/tarball/v2.1.6', + download_url='https://github.com/HubSpot/hapipy/tarball/v2.1.7', license='LICENSE.txt', packages=['hapi'], install_requires=[
Adding pycurl to setup.py.
HubSpot_hapipy
train
4695b21eeb8922866b74fe97266ac74dacc3e0ca
diff --git a/src/components/VSelect/VSelect.js b/src/components/VSelect/VSelect.js index <HASH>..<HASH> 100644 --- a/src/components/VSelect/VSelect.js +++ b/src/components/VSelect/VSelect.js @@ -355,9 +355,7 @@ export default { // to avoid a unnecessary label transition this.genSelectedItems() - this.$vuetify.load(() => { - this.content = this.$refs.menu.$refs.content - }) + this.content = this.$refs.menu.$refs.content }, beforeDestroy () {
fix: prevent race condition when VSelect is destroyed after mount See #<I> See 5cc9cfdc
vuetifyjs_vuetify
train
812b1e277d844fa48307bcd7c692a6f395c85fbb
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/delegate/DelegateTask.java b/modules/activiti-engine/src/main/java/org/activiti/engine/delegate/DelegateTask.java index <HASH>..<HASH> 100644 --- a/modules/activiti-engine/src/main/java/org/activiti/engine/delegate/DelegateTask.java +++ b/modules/activiti-engine/src/main/java/org/activiti/engine/delegate/DelegateTask.java @@ -17,6 +17,7 @@ import java.util.Date; import java.util.Set; import org.activiti.engine.ActivitiObjectNotFoundException; +import org.activiti.engine.task.DelegationState; import org.activiti.engine.task.IdentityLink; import org.activiti.engine.task.IdentityLinkType; @@ -84,6 +85,9 @@ public interface DelegateTask extends VariableScope { /** Returns the event name which triggered the task listener to fire for this task. */ String getEventName(); + + /** The current {@link org.activiti.engine.task.DelegationState} for this task. */ + DelegationState getDelegationState(); /** Adds the given user as a candidate user to this task. */ void addCandidateUser(String userId);
Add getDelegationState() in DelegateTask.
Activiti_Activiti
train
72693f3e425134f58fe351845e0a46290e3b2e20
diff --git a/src/Services/BaseFileService.php b/src/Services/BaseFileService.php index <HASH>..<HASH> 100644 --- a/src/Services/BaseFileService.php +++ b/src/Services/BaseFileService.php @@ -845,6 +845,136 @@ abstract class BaseFileService extends BaseRestService ], ], ], + 'post' => [ + 'tags' => [$name], + 'summary' => 'create' . $capitalized . 'Content() - Create some folders and/or files.', + 'operationId' => 'create' . $capitalized . 'Content', + 'x-publishedEvents' => [ + $name . '.create', + $name . '.content_created' + ], + 'parameters' => [ + [ + 'name' => 'body', + 'description' => 'Array of folders and/or files.', + 'schema' => ['$ref' => '#/definitions/FolderRequest'], + 'in' => 'body', + ], + [ + 'name' => 'url', + 'description' => 'The full URL of the file to upload.', + 'type' => 'string', + 'in' => 'query', + ], + [ + 'name' => 'extract', + 'description' => 'Extract an uploaded zip file into the folder.', + 'type' => 'boolean', + 'in' => 'query', + 'default' => false, + ], + [ + 'name' => 'clean', + 'description' => 'Option when \'extract\' is true, clean the current folder before extracting files and folders.', + 'type' => 'boolean', + 'in' => 'query', + 'default' => false, + ], + [ + 'name' => 'check_exist', + 'description' => 'If true, the request fails when the file or folder to create already exists.', + 'type' => 'boolean', + 'in' => 'query', + 'default' => false, + ], + [ + 'name' => 'X-HTTP-METHOD', + 'description' => 'Override request using POST to tunnel other http request, such as DELETE.', + 'enum' => ['GET', 'PUT', 'PATCH', 'DELETE'], + 'type' => 'string', + 'in' => 'header', + ], + ], + 'responses' => [ + '200' => [ + 'description' => 'Success', + 'schema' => ['$ref' => '#/definitions/FolderResponse'] + ], + 'default' => [ + 'description' => 'Error', + 'schema' => ['$ref' => '#/definitions/Error'] + ] + ], + 'description' => 'Post data as an array of folders and/or files. Folders are created if they do not exist', + ], + 'patch' => [ + 'tags' => [$name], + 'summary' => 'update' . $capitalized . 'ContainerProperties() - Update container properties.', + 'operationId' => 'update' . $capitalized . 'ContainerProperties', + 'x-publishedEvents' => [ + $name . '.update', + $name . '.container_updated' + ], + 'parameters' => [ + [ + 'name' => 'body', + 'description' => 'Array of container properties.', + 'schema' => ['$ref' => '#/definitions/FolderRequest'], + 'in' => 'body', + ], + ], + 'responses' => [ + '200' => [ + 'description' => 'Folder', + 'schema' => ['$ref' => '#/definitions/Folder'] + ], + 'default' => [ + 'description' => 'Error', + 'schema' => ['$ref' => '#/definitions/Error'] + ] + ], + 'description' => 'Post body as an array of folder properties.', + ], + 'delete' => [ + 'tags' => [$name], + 'summary' => 'delete' . + $capitalized . + 'Content() - Delete some container contents.', + 'operationId' => 'delete' . $capitalized . 'Content', + 'x-publishedEvents' => [ + $name . '.delete', + $name . '.content_deleted' + ], + 'parameters' => [ + [ + 'name' => 'force', + 'description' => 'Set to true to force delete on a non-empty folder.', + 'type' => 'boolean', + 'in' => 'query', + ], + [ + 'name' => 'content_only', + 'description' => 'Set to true to only delete the content of the container.', + 'type' => 'boolean', + 'in' => 'query', + ], + ], + 'responses' => [ + '200' => [ + 'description' => 'Success', + 'schema' => ['$ref' => '#/definitions/FolderResponse'] + ], + 'default' => [ + 'description' => 'Error', + 'schema' => ['$ref' => '#/definitions/Error'] + ] + ], + 'description' => + 'Set \'content_only\' to true to delete the sub-folders and files contained, but not the container. ' . + 'Set \'force\' to true to delete a non-empty folder. ' . + 'Alternatively, to delete by a listing of sub-folders and files, ' . + 'use the POST request with X-HTTP-METHOD = DELETE header and post listing.', + ], ], '/' . $name . '/{folder_path}/' => [ 'parameters' => [
DF-<I> #resolve #comment swagger doc updated for root of file services
dreamfactorysoftware_df-core
train
661b8a9603d6ae63c4059b1404e811220f63898e
diff --git a/src/DefaultEditor.js b/src/DefaultEditor.js index <HASH>..<HASH> 100644 --- a/src/DefaultEditor.js +++ b/src/DefaultEditor.js @@ -150,16 +150,8 @@ class DefaultEditor extends Component { <Section name={_('Size and Spacing')}> <BoxGap label={_('Bar Width')} attr="bargap" /> <BoxGap label={_('Box Width')} attr="boxgap" /> - <BoxGap - label={_('Bar Padding')} - attr="bargroupgap" - showArrows={false} - /> - <BoxGap - label={_('Box Padding')} - attr="boxgroupgap" - showArrows={false} - /> + <BoxGap label={_('Bar Padding')} attr="bargroupgap" /> + <BoxGap label={_('Box Padding')} attr="boxgroupgap" /> </Section> <Section name={_('Lines')}>
remove unncessary showArrows. This is now taken care of by component
plotly_react-chart-editor
train
8919430801beca81fea1f53f6e8ac208d80f406c
diff --git a/spec/websocket/driver/draft75_examples.rb b/spec/websocket/driver/draft75_examples.rb index <HASH>..<HASH> 100644 --- a/spec/websocket/driver/draft75_examples.rb +++ b/spec/websocket/driver/draft75_examples.rb @@ -43,6 +43,28 @@ shared_examples_for "draft-75 protocol" do driver.parse [0x6c, 0x6f, 0xff].pack("C*") expect(@message).to eq "Hello" end + + describe "when a message listener raises an error" do + before do + @messages = [] + + driver.on :message do |msg| + @messages << msg.data + raise "an error" + end + end + + it "is not trapped by the parser" do + buffer = [0x00, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0xff].pack('C*') + expect { driver.parse buffer }.to raise_error(RuntimeError, "an error") + end + + it "parses text frames without dropping input" do + driver.parse [0x00, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0xff, 0x00, 0x57].pack("C*") rescue nil + driver.parse [0x6f, 0x72, 0x6c, 0x64, 0xff].pack("C*") rescue nil + expect(@messages).to eq(["Hello", "World"]) + end + end end describe :frame do
Add tests for exception safety in the Draft<I> parser.
faye_websocket-driver-ruby
train