hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
467db8691335ab6d3b66bffa6b0648fa6b68cb93
diff --git a/spec/features/auth_app_spec.rb b/spec/features/auth_app_spec.rb index <HASH>..<HASH> 100644 --- a/spec/features/auth_app_spec.rb +++ b/spec/features/auth_app_spec.rb @@ -48,6 +48,7 @@ feature 'Posting workflows', js: true do and_by 'select new posting' do within(:gridpanel, 'posting_window', match: :first) do + wait_for_ajax expect(posting_grid.row_count).to eq 2 posting_grid.select_row(2) press('Select') diff --git a/spec/features/data_import_spec.rb b/spec/features/data_import_spec.rb index <HASH>..<HASH> 100644 --- a/spec/features/data_import_spec.rb +++ b/spec/features/data_import_spec.rb @@ -70,7 +70,7 @@ feature 'under Applications menu, Reports using Data Import', js: true do #hacky: assumes only 1 combobox without label within(:gridpanel, 'report_select', match: :first, wait: 5) do # hacky, hardcoding netzkecombobox dropdown arrow name - arrow = find(:input, 'nodename')['componentid'] + '-trigger-picker' + arrow = find(:input, 'nodename')['data-componentid'] + '-trigger-picker' find(:xpath, ".//div[@id='#{arrow}']").click find(:xpath, "//li[text()='Data Import Job (csv)']").click end @@ -137,7 +137,7 @@ feature 'under Applications menu, Reports using Data Import', js: true do #hacky: assumes only 1 combobox without label within(:gridpanel, 'report_select', match: :first) do # hacky, hardcoding netzkecombobox dropdown arrow name - arrow = find(:input, 'nodename')['componentid'] + '-trigger-picker' + arrow = find(:input, 'nodename')['data-componentid'] + '-trigger-picker' find(:xpath, ".//div[@id='#{arrow}']").click find(:xpath, "//li[text()='Data Import Job (csv)']").click end diff --git a/spec/features/reporting_spec.rb b/spec/features/reporting_spec.rb index <HASH>..<HASH> 100644 --- a/spec/features/reporting_spec.rb +++ b/spec/features/reporting_spec.rb @@ -94,7 +94,7 @@ DELOREAN #hacky: assumes only 1 combobox without label within(:gridpanel, 'report_select', match: :first) do # hacky, hardcoding netzkecombobox dropdown arrow name - arrow = find(:input, 'nodename')['componentid'] + '-trigger-picker' + arrow = find(:input, 'nodename')['data-componentid'] + '-trigger-picker' find(:xpath, ".//div[@id='#{arrow}']").click find(:xpath, "//li[text()='#{node_name}']").click end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -61,6 +61,7 @@ Capybara.register_driver :headless_chrome do |app| desired_capabilities: capabilities end +# Capybara.javascript_driver = :chrome Capybara.javascript_driver = :headless_chrome ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
Fix the rest of feature tests: use correct componentid in combobox dropdown
arman000_marty
train
25b46b2df32116a2ca7875f719f4ca45f9b4c1e2
diff --git a/schemaDocument.go b/schemaDocument.go index <HASH>..<HASH> 100644 --- a/schemaDocument.go +++ b/schemaDocument.go @@ -171,7 +171,7 @@ func (d *JsonSchemaDocument) parseSchema(documentNode interface{}, currentSchema if isKind(dv, reflect.Map) { newSchema := &jsonSchema{property: KEY_DEFINITIONS, parent: currentSchema, ref: currentSchema.ref} currentSchema.definitions[dk] = newSchema - err := d.parseSchema(m[KEY_DEFINITIONS], newSchema) + err := d.parseSchema(dv, newSchema) if err != nil { return errors.New(err.Error()) }
Parse individual definition values as subschemas
xeipuuv_gojsonschema
train
9569f12b6fa16fe42836d5c3f93edb55f343485a
diff --git a/lib/cloud_crowd/models/job.rb b/lib/cloud_crowd/models/job.rb index <HASH>..<HASH> 100644 --- a/lib/cloud_crowd/models/job.rb +++ b/lib/cloud_crowd/models/job.rb @@ -107,7 +107,9 @@ module CloudCrowd # When the WorkUnits are all finished, gather all their outputs together # before removing them from the database entirely. def gather_outputs_from_work_units - outs = self.work_units.complete.map {|wu| wu.parsed_output } + units = self.work_units.complete + is_json = units.first.output_is_json? + outs = units.map {|u| is_json ? JSON.parse(u.output) : u.output } self.work_units.complete.destroy_all outs end diff --git a/lib/cloud_crowd/models/work_unit.rb b/lib/cloud_crowd/models/work_unit.rb index <HASH>..<HASH> 100644 --- a/lib/cloud_crowd/models/work_unit.rb +++ b/lib/cloud_crowd/models/work_unit.rb @@ -58,13 +58,14 @@ module CloudCrowd }) end - def parsed_output - output_is_json? ? JSON.parse(output) : output - end - - # FIXME! + # Is the output of this work unit in JSON format? def output_is_json? - ['{', '[', '('].include? output[0..0] + @output_is_json if defined?(@output_is_json) + JSON.parse(output) + rescue JSON::ParserError + @output_is_json = false + else + @output_is_json = true end # The JSON representation of a WorkUnit contains common elements of its job. diff --git a/test/unit/test_job.rb b/test/unit/test_job.rb index <HASH>..<HASH> 100644 --- a/test/unit/test_job.rb +++ b/test/unit/test_job.rb @@ -46,9 +46,9 @@ class JobTest < Test::Unit::TestCase end should "create jobs with a SPLITTING status for actions that have a split method defined" do - job = CloudCrowd::Job.create_from_request({'inputs' => ['1'], 'action' => 'pdf_to_images'}) - assert job.splittable? - assert job.splitting? + # job = CloudCrowd::Job.create_from_request({'inputs' => ['1'], 'action' => 'pdf_to_images'}) + # assert job.splittable? + # assert job.splitting? end should "fire a callback when a job has finished, successfully or not" do
got a working output_is_json? method -- efficiency leaves something to be desired
documentcloud_cloud-crowd
train
5ce7e20ba6e81e4403779e892194cd321b3a0c2b
diff --git a/src/plugins/map/test.js b/src/plugins/map/test.js index <HASH>..<HASH> 100644 --- a/src/plugins/map/test.js +++ b/src/plugins/map/test.js @@ -27,6 +27,30 @@ describe(".map(function(){})", function() { }); }); + it("accepts return of single element", function(){ + var els = list.find('li').map(function(node){ + return node; + }).each(function(node, i){ + expect(i).to.equal(parseInt(node.innerHTML)); + }); + }); + + it("accepts return of array of elements", function(){ + var els = list.find('li').map(function(node, i){ + return [node]; + }).each(function(node, i){ + expect(i).to.equal(parseInt(node.innerHTML)); + }); + }); + + it("accepts return of umbrella instance", function(){ + var els = list.find('li').map(function(node, i){ + return u(node); + }).each(function(node, i){ + expect(i).to.equal(parseInt(node.innerHTML)); + }); + }); + it("can remove an element", function() { var final = u([1, 2, 3, 4]).map(function(node, i){ return i === 0 ? false : node; diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -1476,6 +1476,30 @@ describe(".map(function(){})", function() { }); }); + it("accepts return of single element", function(){ + var els = list.find('li').map(function(node){ + return node; + }).each(function(node, i){ + expect(i).to.equal(parseInt(node.innerHTML)); + }); + }); + + it("accepts return of array of elements", function(){ + var els = list.find('li').map(function(node, i){ + return [node]; + }).each(function(node, i){ + expect(i).to.equal(parseInt(node.innerHTML)); + }); + }); + + it("accepts return of umbrella instance", function(){ + var els = list.find('li').map(function(node, i){ + return u(node); + }).each(function(node, i){ + expect(i).to.equal(parseInt(node.innerHTML)); + }); + }); + it("can remove an element", function() { var final = u([1, 2, 3, 4]).map(function(node, i){ return i === 0 ? false : node;
Added tests for returning an Umbrella instance
franciscop_umbrella
train
56c4f28bd4be00590ab6e83953ac420a3d3b4d49
diff --git a/lxd/storage/drivers/generic_vfs.go b/lxd/storage/drivers/generic_vfs.go index <HASH>..<HASH> 100644 --- a/lxd/storage/drivers/generic_vfs.go +++ b/lxd/storage/drivers/generic_vfs.go @@ -879,7 +879,10 @@ func genericVFSBackupUnpack(d Driver, sysOS *sys.OS, vol Volume, snapshots []str } } else { // For custom volumes unmount now, there is no post hook as there is no backup.yaml to generate. - d.UnmountVolume(vol, false, op) + _, err = d.UnmountVolume(vol, false, op) + if err != nil { + return nil, nil, err + } } return postHook, revertExternal.Fail, nil
lxd/storage/drivers/generic/vfs: Catch unmount errors in genericVFSBackupUnpack
lxc_lxd
train
1212867c89ee4c62f0d18ee8d961c07258215393
diff --git a/uw_sws_graderoster/models.py b/uw_sws_graderoster/models.py index <HASH>..<HASH> 100644 --- a/uw_sws_graderoster/models.py +++ b/uw_sws_graderoster/models.py @@ -49,7 +49,7 @@ class GradeRosterItem(models.Model): tree = kwargs.get('data') if tree is None: - return super(GradeRosterItem, self).__init__() + return super(GradeRosterItem, self).__init__(*args, **kwargs) for el in tree.xpath(".//xhtml:a[@rel='student']/*[@class='reg_id']", namespaces=nsmap): @@ -149,7 +149,7 @@ class GradeRoster(models.Model): tree = kwargs.get('data') if tree is None: - return super(GradeRoster, self).__init__() + return super(GradeRoster, self).__init__(*args, **kwargs) pws = PWS() people = {self.instructor.uwregid: self.instructor}
fix model calls to super __init__
uw-it-aca_uw-restclients-graderoster
train
95729cc002014ebf2ef25c0def7f84eb6e3cdcd8
diff --git a/folium/features.py b/folium/features.py index <HASH>..<HASH> 100644 --- a/folium/features.py +++ b/folium/features.py @@ -696,13 +696,14 @@ class RegularPolygonMarker(MacroFeature): name='dvf_js') class VegaPopup(MacroFeature): - def __init__(self, data, width=300, height=300): + def __init__(self, data, width="100%", height="100%"): """TODO : docstring here""" super(VegaPopup, self).__init__() self.plugin_name = 'VegaPopup' self.data = data - self.width = "{}px".format(width) if isinstance(width,int) or isinstance(width,float) else "{}".format(width) - self.height = "{}px".format(height) if isinstance(height,int) or isinstance(height,float) else "{}".format(height) + + self.width = _parse_size(width) + self.height = _parse_size(height) self._template = Template(u""" {% macro script(this, kwargs) %}
Changed VegaPopup width and height handling
python-visualization_folium
train
6ddd1badfb377cd8105235a03a1fe05e93e6b5b0
diff --git a/src/main/java/hudson/plugins/emailext/plugins/content/BuildLogExcerptContent.java b/src/main/java/hudson/plugins/emailext/plugins/content/BuildLogExcerptContent.java index <HASH>..<HASH> 100644 --- a/src/main/java/hudson/plugins/emailext/plugins/content/BuildLogExcerptContent.java +++ b/src/main/java/hudson/plugins/emailext/plugins/content/BuildLogExcerptContent.java @@ -1,7 +1,7 @@ /* * The MIT License * - * Copyright (c) 20011, CloudBees, Inc., Nicolas De Loof + * Copyright (c) 2011, CloudBees, Inc., Nicolas De Loof * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -67,17 +67,17 @@ public class BuildLogExcerptContent implements EmailContent { } public <P extends AbstractProject<P, B>, B extends AbstractBuild<P, B>> String getContent(AbstractBuild<P, B> build, ExtendedEmailPublisher publisher, EmailType emailType, Map<String, ?> args) throws IOException, InterruptedException { - BufferedReader reader = null; try { - reader = new BufferedReader(new FileReader(build.getLogFile())); - return getContent(reader, args); + BufferedReader reader = new BufferedReader(new FileReader(build.getLogFile())); + try { + return getContent(reader, args); + } finally { + reader.close(); + } } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); return ""; // TODO: Indicate there was an error instead? } - finally { - IOUtils.closeQuietly(reader); - } } String getContent(BufferedReader reader, Map<String, ?> args) throws IOException { @@ -85,7 +85,7 @@ public class BuildLogExcerptContent implements EmailContent { Pattern start = Pattern.compile((String)args.get("start")); Pattern end = Pattern.compile((String)args.get("end")); - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); String line = null; boolean started = false; while ((line = reader.readLine()) != null) {
fix according to mfriedenhagen's comment
jenkinsci_email-ext-plugin
train
809d09d4f49b566ff47fe6c0fe07e1a00b6e29c8
diff --git a/tensorboard/plugins/pr_curve/summary.py b/tensorboard/plugins/pr_curve/summary.py index <HASH>..<HASH> 100644 --- a/tensorboard/plugins/pr_curve/summary.py +++ b/tensorboard/plugins/pr_curve/summary.py @@ -176,7 +176,7 @@ def op( combined_data = tf.stack([tp, fp, tn, fn, precision, recall]) return tf.summary.tensor_summary( - name=tag, + name='pr_curves', tensor=combined_data, collections=collections, summary_metadata=summary_metadata) diff --git a/tensorboard/plugins/pr_curve/summary_test.py b/tensorboard/plugins/pr_curve/summary_test.py index <HASH>..<HASH> 100644 --- a/tensorboard/plugins/pr_curve/summary_test.py +++ b/tensorboard/plugins/pr_curve/summary_test.py @@ -60,15 +60,15 @@ class PrCurveTest(tf.test.TestCase): # Verify that the metadata was correctly written. accumulator = multiplexer.GetAccumulator('foo') tag_content_dict = accumulator.PluginTagToContent('pr_curves') - self.assertListEqual(['tag_bar/tag_bar'], list(tag_content_dict.keys())) + self.assertListEqual(['tag_bar/pr_curves'], list(tag_content_dict.keys())) # Parse the data within the JSON string and set the proto's fields. plugin_data = pr_curve_pb2.PrCurvePluginData() - json_format.Parse(tag_content_dict['tag_bar/tag_bar'], plugin_data) + json_format.Parse(tag_content_dict['tag_bar/pr_curves'], plugin_data) self.assertEqual(10, plugin_data.num_thresholds) # Test the summary contents. - tensor_events = accumulator.Tensors('tag_bar/tag_bar') + tensor_events = accumulator.Tensors('tag_bar/pr_curves') self.assertEqual(1, len(tensor_events)) tensor_event = tensor_events[0] self.assertEqual(1, tensor_event.step)
Make tensor_summary accept 'pr_curves' as a name (#<I>) Previously, the call to tensor_summary within the PR Curve summary op accepted the tag as the name parameter. This should be the name of the plugin instead. The pattern followed by existing ops is to create a name-scope of tag specified by the user and then create a summary with the name of the plugin.
tensorflow_tensorboard
train
a6e3be35c3d8d0ac718f13eba0ce5bc980ae3cb5
diff --git a/source/net/fortuna/ical4j/model/parameter/Range.java b/source/net/fortuna/ical4j/model/parameter/Range.java index <HASH>..<HASH> 100644 --- a/source/net/fortuna/ical4j/model/parameter/Range.java +++ b/source/net/fortuna/ical4j/model/parameter/Range.java @@ -33,6 +33,7 @@ package net.fortuna.ical4j.model.parameter; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterFactoryImpl; +import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.Strings; /** @@ -68,10 +69,15 @@ public class Range extends Parameter { super(RANGE, ParameterFactoryImpl.getInstance()); this.value = Strings.unquote(aValue); - // value must be one of finite list.. - if (!VALUE_THISANDPRIOR.equals(value) - && !VALUE_THISANDFUTURE.equals(value)) { - throw new IllegalArgumentException("Invalid value [" + value + "]"); + // allow arbitrary ranges for Lotus Notes.. + // eg. X-LOTUS-RECURID;RANGE=ALL:20101006T203000Z + + if (!CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_NOTES_COMPATIBILITY)) { + // value must be one of finite list.. + if (!VALUE_THISANDPRIOR.equals(value) + && !VALUE_THISANDFUTURE.equals(value)) { + throw new IllegalArgumentException("Invalid value [" + value + "]"); + } } }
Allow arbitrary range value for Lotus Notes to support X- properties.. potential for review later
ical4j_ical4j
train
cc88d6fda762ae005ea034dffa72fe9fa59c32ec
diff --git a/django_prometheus/tests/end2end/testapp/settings.py b/django_prometheus/tests/end2end/testapp/settings.py index <HASH>..<HASH> 100644 --- a/django_prometheus/tests/end2end/testapp/settings.py +++ b/django_prometheus/tests/end2end/testapp/settings.py @@ -180,3 +180,11 @@ USE_TZ = True # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = "/static/" + +LOGGING = { + "version": 1, + "disable_existing_loggers": False, + "handlers": {"console": {"class": "logging.StreamHandler"}}, + "root": {"handlers": ["console"], "level": "INFO"}, + "loggers": {"django": {"handlers": ["console"], "level": "INFO"}}, +}
Configure logging in end 2 end test app
korfuri_django-prometheus
train
b6772fca979f07b3fd927e5b26e8171e61b5e922
diff --git a/lib/statsd.js b/lib/statsd.js index <HASH>..<HASH> 100644 --- a/lib/statsd.js +++ b/lib/statsd.js @@ -1,6 +1,14 @@ 'use strict'; var StatsD = require('hot-shots'); +/** + * Maximum size of a metrics batch used by default. + * + * @const + * @type {number} + */ +var DEFAULT_MAX_BATCH_SIZE = 1450; + var nameCache = {}; function normalizeName(name) { // See https://github.com/etsy/statsd/issues/110 @@ -50,9 +58,9 @@ function makeStatsD(options, logger) { if (options.batch) { if (typeof options.batch === 'boolean') { - options.batch = { max_size: 1500, max_delay: 1000 }; + options.batch = { max_size: DEFAULT_MAX_BATCH_SIZE, max_delay: 1000 }; } - statsdOptions.maxBufferSize = options.batch.max_size || 1500; + statsdOptions.maxBufferSize = options.batch.max_size || DEFAULT_MAX_BATCH_SIZE; statsdOptions.bufferFlushInterval = options.batch.max_delay || 1000; }
Metrics: Decreased the default maximum batch size
wikimedia_service-runner
train
246d5bd2a9ef0f1562057607b9282a78bfe952c0
diff --git a/robe-admin/src/main/java/io/robe/admin/hibernate/entity/Language.java b/robe-admin/src/main/java/io/robe/admin/hibernate/entity/Language.java index <HASH>..<HASH> 100644 --- a/robe-admin/src/main/java/io/robe/admin/hibernate/entity/Language.java +++ b/robe-admin/src/main/java/io/robe/admin/hibernate/entity/Language.java @@ -1,6 +1,8 @@ package io.robe.admin.hibernate.entity; import io.robe.hibernate.entity.BaseEntity; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; @@ -8,15 +10,12 @@ import javax.persistence.*; @Table public class Language extends BaseEntity { - public enum Type { - TR, - EN; - } - + @NotEmpty @Enumerated(EnumType.STRING) @Column(name = "code", nullable = false) private Type code; - + @Length(min = 2, max = 30) + @NotEmpty @Column(name = "name", nullable = false,length = 30) private String name; @@ -35,4 +34,9 @@ public class Language extends BaseEntity { public void setCode(Type lang) { this.code = lang; } + + public enum Type { + TR, + EN; + } } diff --git a/robe-admin/src/main/java/io/robe/admin/hibernate/entity/MailTemplate.java b/robe-admin/src/main/java/io/robe/admin/hibernate/entity/MailTemplate.java index <HASH>..<HASH> 100644 --- a/robe-admin/src/main/java/io/robe/admin/hibernate/entity/MailTemplate.java +++ b/robe-admin/src/main/java/io/robe/admin/hibernate/entity/MailTemplate.java @@ -1,6 +1,8 @@ package io.robe.admin.hibernate.entity; import io.robe.hibernate.entity.BaseEntity; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; @@ -9,11 +11,16 @@ import javax.persistence.*; @Table public class MailTemplate extends BaseEntity { + @Length(min = 1, max = 32) @Column(name = "code", length = 32) private String code; + + @NotEmpty @Enumerated(EnumType.STRING) @Column(name = "lang", nullable = false) private Type lang; + + @NotEmpty @Column(name = "mailTemplate", nullable = false) @Lob private char[] template; diff --git a/robe-admin/src/main/java/io/robe/admin/hibernate/entity/SystemParameter.java b/robe-admin/src/main/java/io/robe/admin/hibernate/entity/SystemParameter.java index <HASH>..<HASH> 100644 --- a/robe-admin/src/main/java/io/robe/admin/hibernate/entity/SystemParameter.java +++ b/robe-admin/src/main/java/io/robe/admin/hibernate/entity/SystemParameter.java @@ -1,6 +1,8 @@ package io.robe.admin.hibernate.entity; import io.robe.hibernate.entity.BaseEntity; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.Column; import javax.persistence.Entity; @@ -10,8 +12,13 @@ import javax.persistence.Table; @Table public class SystemParameter extends BaseEntity { + @Length(min = 1, max = 32) + @NotEmpty @Column(unique = true,nullable = false, name = "PARAMETER_KEY",length = 32) private String key; + + @Length(min = 2, max = 32) + @NotEmpty @Column(name = "PARAMETER_VALUE",nullable = false, length = 32) private String value;
Hibernate validators added to entities
robeio_robe
train
0b9fb87b45736d68c874e557f16689aa79caa18a
diff --git a/lib/reveal-ck/templates/processor.rb b/lib/reveal-ck/templates/processor.rb index <HASH>..<HASH> 100644 --- a/lib/reveal-ck/templates/processor.rb +++ b/lib/reveal-ck/templates/processor.rb @@ -1,7 +1,7 @@ # # Setup Slim require 'slim' -::Slim::Engine.set_default_options pretty: true +::Slim::Engine.set_options pretty: true require 'tilt'
[dependencies, slim] Start using set_options When I jumped versions of slim, I saw that what I was using was deprecated: ``` set_default_options has been deprecated, use set_options ```
jedcn_reveal-ck
train
6bfaef81d066ce4cfac8c138481f604e94e14076
diff --git a/lib/neography/rest.rb b/lib/neography/rest.rb index <HASH>..<HASH> 100644 --- a/lib/neography/rest.rb +++ b/lib/neography/rest.rb @@ -547,6 +547,12 @@ module Neography when 4 then {:method => "DELETE", :to => "/index/node/#{args[1]}/#{args[2]}/#{get_id(args[3])}" } when 3 then {:method => "DELETE", :to => "/index/node/#{args[1]}/#{get_id(args[2])}" } end + when :remove_relationship_from_index + case args.size + when 5 then {:method => "DELETE", :to => "/index/relationship/#{args[1]}/#{args[2]}/#{args[3]}/#{get_id(args[4])}" } + when 4 then {:method => "DELETE", :to => "/index/relationship/#{args[1]}/#{args[2]}/#{get_id(args[3])}" } + when 3 then {:method => "DELETE", :to => "/index/relationship/#{args[1]}/#{get_id(args[2])}" } + end when :delete_node {:method => "DELETE", :to => "/node/#{get_id(args[1])}"} else diff --git a/spec/integration/rest_batch_spec.rb b/spec/integration/rest_batch_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/rest_batch_spec.rb +++ b/spec/integration/rest_batch_spec.rb @@ -310,6 +310,24 @@ describe Neography::Rest do @neo.get_node_index(index, key, value3).should be_nil end + it "can remove a relationship from an index in batch" do + index = generate_text(6) + key = generate_text(6) + value1 = generate_text + value2 = generate_text + + node1 = @neo.create_node + node2 = @neo.create_node + relationship1 = @neo.create_unique_relationship(index, key, value1, "friends", node1, node2) + relationship2 = @neo.create_unique_relationship(index, key, value2, "friends", node2, node1) + + batch_result = @neo.batch [:remove_relationship_from_index, index, key, relationship1], + [:remove_relationship_from_index, index, key, relationship2] + + @neo.get_relationship_index(index, key, value1).should be_nil + @neo.get_relationship_index(index, key, value2).should be_nil + end + end describe "referenced batch" do
adding remove_relationship_from_index as batch operation
maxdemarzi_neography
train
6fb141e2a9e728499f8782310560bfaef7a5ed6c
diff --git a/ec2/spark_ec2.py b/ec2/spark_ec2.py index <HASH>..<HASH> 100755 --- a/ec2/spark_ec2.py +++ b/ec2/spark_ec2.py @@ -24,10 +24,12 @@ from __future__ import with_statement import hashlib import logging import os +import os.path import pipes import random import shutil import string +from stat import S_IRUSR import subprocess import sys import tarfile @@ -349,6 +351,7 @@ def launch_cluster(conn, opts, cluster_name): if opts.identity_file is None: print >> stderr, "ERROR: Must provide an identity file (-i) for ssh connections." sys.exit(1) + if opts.key_pair is None: print >> stderr, "ERROR: Must provide a key pair name (-k) to use on instances." sys.exit(1) @@ -1007,6 +1010,18 @@ def real_main(): DeprecationWarning ) + if opts.identity_file is not None: + if not os.path.exists(opts.identity_file): + print >> stderr,\ + "ERROR: The identity file '{f}' doesn't exist.".format(f=opts.identity_file) + sys.exit(1) + + file_mode = os.stat(opts.identity_file).st_mode + if not (file_mode & S_IRUSR) or not oct(file_mode)[-2:] == '00': + print >> stderr, "ERROR: The identity file must be accessible only by you." + print >> stderr, 'You can fix this with: chmod 400 "{f}"'.format(f=opts.identity_file) + sys.exit(1) + if opts.ebs_vol_num > 8: print >> stderr, "ebs-vol-num cannot be greater than 8" sys.exit(1)
[SPARK-<I>][EC2] Check the mode of private key Check the mode of private key file.
apache_spark
train
6be72558e47355d59091d5684f3c4ed853476404
diff --git a/openjscad.js b/openjscad.js index <HASH>..<HASH> 100644 --- a/openjscad.js +++ b/openjscad.js @@ -886,8 +886,11 @@ OpenJsCad.Processor.prototype = { if (obj !== null) { var csg = OpenJsCad.Processor.convertToSolid(obj); - // don't reset zoom if toggling between valid objects - this.viewer.setCsg(csg, !this.hasValidCurrentObject); + // // reset zoom unless toggling between valid objects + // this.viewer.setCsg(csg, !this.hasValidCurrentObject); + this.isFirstRender_ = typeof this.isFirstRender_ == 'undefined' ? true : false; + // (re-)set zoom only on very first rendering action + this.viewer.setCsg(csg, this.isFirstRender_); this.hasValidCurrentObject = true; this.supportedFormatsForCurrentObject().forEach(function(format) {
(re)set zoom only on very first render
jscad_csg.js
train
1fe10fe38cc5779ce89361a131268525aa492e1f
diff --git a/src/scripts/user/user.store.js b/src/scripts/user/user.store.js index <HASH>..<HASH> 100644 --- a/src/scripts/user/user.store.js +++ b/src/scripts/user/user.store.js @@ -62,7 +62,7 @@ let UserStore = Reflux.createStore({ hello.init({google: config.auth.google.clientID}); this.checkUser(); }, - + /** * Check User * @@ -100,6 +100,10 @@ let UserStore = Reflux.createStore({ signIn() { this.update({loading: true}); hello('google').login({scope: 'email,openid'}, (res) => { + if (res.error) { + this.update({loading: false}); + return; + } this.update({token: res.authResponse.access_token}); hello(res.network).api('/me').then((profile) => { scitran.verifyUser((err, res) => {
added error handling for canceled sign in
OpenNeuroOrg_openneuro
train
43a08851d3ffcf65683716f5c267ec818d50a974
diff --git a/doctor/types.py b/doctor/types.py index <HASH>..<HASH> 100644 --- a/doctor/types.py +++ b/doctor/types.py @@ -80,22 +80,22 @@ class SuperType(object): if the subclass does not define a `description` attribute. """ #: The description of what the type represents. - description: str = None + description = None # type: str #: An example value for the type. example = None #: Indicates if the value of this type is allowed to be None. - nullable: bool = False + nullable = False # type: bool #: An optional name of where to find the request parameter if it does not #: match the variable name in your logic function. - param_name: str = None + param_name = None # type: str #: An optional callable to parse a request paramter before it gets validated #: by a type. It should accept a single value paramter and return the #: parsed value. - parser: typing.Callable = None + parser = None # type: typing.Callable def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
Reverting inline type declaration. This is only supported in later versions of python 3.
upsight_doctor
train
0c1b10d42c0d3ee550c15d724ef5e8d9fd9e8208
diff --git a/numbers/greatestCommonDivisor.js b/numbers/greatestCommonDivisor.js index <HASH>..<HASH> 100644 --- a/numbers/greatestCommonDivisor.js +++ b/numbers/greatestCommonDivisor.js @@ -1,7 +1,7 @@ /** ## Greatest common divisor ## - isNatural(anyInteger) + greatestCommonDivisor(anyInteger) returns a natural number diff --git a/numbers/isPowerOfTwo.js b/numbers/isPowerOfTwo.js index <HASH>..<HASH> 100644 --- a/numbers/isPowerOfTwo.js +++ b/numbers/isPowerOfTwo.js @@ -9,11 +9,17 @@ - Test if a series of bits needs padding. - - Efficently test the outout of a function that should only return values that are powers of two (say memory sizes) + - Efficiently test the output of a function that should only return values that are powers of two (say for memory sizes) */ module.exports = function isPowerOfTwo(naturalNumber) { - return (naturalNumber & (naturalNumber - 1)) === 0; + // Bitwise AND (&) compares the bits of two numbers. + // Powers of two always have only one bit set. + // Subtracting one forces all lower order bits to get flipped. + // Then the AND (&) ensures no other bits match between the two values, + // thus proving only one bit was ever flipped. + + return naturalNumber && (naturalNumber & (naturalNumber - 1)) === 0; }; diff --git a/test/numbers/numbers.js b/test/numbers/numbers.js index <HASH>..<HASH> 100644 --- a/test/numbers/numbers.js +++ b/test/numbers/numbers.js @@ -6,19 +6,23 @@ var grape = require('grape'), math = require('../../'); grape('For powers of two', function(t) { - t.plan(6); + t.plan(8); t.ok(math.numbers.isPowerOfTwo(256)); t.ok(math.numbers.isPowerOfTwo(4096)); - t.ok(math.numbers.isPowerOfTwo(0)); + t.notOk(math.numbers.isPowerOfTwo(0)); t.ok(math.numbers.isPowerOfTwo(1)); t.notOk(math.numbers.isPowerOfTwo(7)); - t.notOk(math.numbers.isPowerOfTwo(-3)); + t.notOk(math.numbers.isPowerOfTwo(-4)); + + t.notOk(math.numbers.isPowerOfTwo(undefined)); + + t.notOk(math.numbers.isPowerOfTwo(null)); }); grape('For natural numbers', function(t) {
Fixed comments. Fixed unit tests for powerOfTwo
KoryNunn_math
train
3e85b623b8cc7b5b789842a89de6b698a34496c5
diff --git a/includes/class-freemius.php b/includes/class-freemius.php index <HASH>..<HASH> 100644 --- a/includes/class-freemius.php +++ b/includes/class-freemius.php @@ -6741,14 +6741,18 @@ $extra_install_params['license_key'] = $license_key; } + $args = $this->get_install_data_for_api( $extra_install_params, false, false ); + // Install the plugin. $install = $this->get_api_user_scope()->call( "/plugins/{$this->get_id()}/installs.json", 'post', - $this->get_install_data_for_api( $extra_install_params, false, false ) + $args ); if ( $this->is_api_error($install) ) { + $install = $this->apply_filters( 'after_install_failure', $install, $args ); + $this->_admin_notices->add( sprintf( __fs( 'could-not-activate-x', $this->_slug ), $this->get_plugin_name() ) . ' ' . __fs( 'contact-us-with-error-message', $this->_slug ) . ' ' . '<b>' . $install->error->message . '</b>',
[connect] Added `after_install_failure` filter to connection with an existing context user.
Freemius_wordpress-sdk
train
f600f69729ba202ce589000fe7272f3137782433
diff --git a/lib/Integrations/ACF.php b/lib/Integrations/ACF.php index <HASH>..<HASH> 100644 --- a/lib/Integrations/ACF.php +++ b/lib/Integrations/ACF.php @@ -15,7 +15,7 @@ class ACF { public function __construct() { add_filter('timber_post_get_meta', array( $this, 'post_get_meta' ), 10, 2); add_filter('timber_post_get_meta_field', array( $this, 'post_get_meta_field' ), 10, 3); - add_filter('timber_post_get_meta_object_field', array( $this, 'post_get_meta_object' ), 10, 3); + add_filter('timber/post/meta_object_field', array( $this, 'post_meta_object' ), 10, 3); add_filter('timber/term/meta', array( $this, 'term_get_meta' ), 10, 3); add_filter('timber/term/meta/field', array( $this, 'term_get_meta_field' ), 10, 4); add_filter('timber_user_get_meta_field_pre', array( $this, 'user_get_meta_field' ), 10, 3); @@ -30,7 +30,7 @@ class ACF { return get_field($field_name, $post_id); } - public function post_get_meta_object( $value, $post_id, $field_name ) { + public function post_meta_object( $value, $post_id, $field_name ) { return get_field_object($field_name, $post_id); } diff --git a/lib/Post.php b/lib/Post.php index <HASH>..<HASH> 100644 --- a/lib/Post.php +++ b/lib/Post.php @@ -703,11 +703,15 @@ class Post extends Core implements CoreInterface { } /** - * @param string $field_name + * Gets the field object data from Advanced Custom Fields. + * This includes metadata on the field like whether it's conditional or not. + * + * @since 1.6.0 + * @param string $field_name of the field you want to lookup. * @return mixed */ - public function get_field_object( $field_name ) { - $value = apply_filters('timber_post_get_meta_object_field', null, $this->ID, $field_name, $this); + public function field_object( $field_name ) { + $value = apply_filters('timber/post/meta_object_field', null, $this->ID, $field_name, $this); $value = $this->convert($value, __CLASS__); return $value; } diff --git a/readme.txt b/readme.txt index <HASH>..<HASH> 100644 --- a/readme.txt +++ b/readme.txt @@ -37,6 +37,7 @@ _Twig is the template language powering Timber; if you need a little background - Please add any usage changes here so theme developers are informed of changes. - You can now easily access all of a MenuItem's master object properties through `{{ item.master_object }}` What's a master object? It's when a Menu Item has been created directly from a Post or Term in the WP Admin #1577 #1572 - Enabled methods for getting media from posts, you can now do `{{ post.video }}`, `{{ post.audio }}` and `{{ post.gallery }}` to retrieve media include in the body of a post #1583 (thanks @marciojc) +- You can now get ACF's field object data: `{{ post.field_object('my_field').key }}` #1597 #1599 (thanks @palmiak) = 1.5.2 = diff --git a/tests/test-timber-integrations.php b/tests/test-timber-integrations.php index <HASH>..<HASH> 100644 --- a/tests/test-timber-integrations.php +++ b/tests/test-timber-integrations.php @@ -71,6 +71,18 @@ class TestTimberIntegrations extends Timber_UnitTestCase { $this->assertEquals( 'blue', Timber::compile_string( $str, array( 'term' => $term ) ) ); } + + function testACFFieldObject() { + $fp_id = $this->factory->post->create(array('post_content' => 'a:10:{s:4:"type";s:4:"text";s:12:"instructions";s:0:"";s:8:"required";i:0;s:17:"conditional_logic";i:0;s:7:"wrapper";a:3:{s:5:"width";s:2:"50";s:5:"class";s:8:"thingerz";s:2:"id";s:0:"";}s:13:"default_value";s:0:"";s:11:"placeholder";s:0:"";s:7:"prepend";s:0:"";s:6:"append";s:0:"";s:9:"maxlength";s:0:"";}', 'post_title' => 'Thinger', 'post_name' => 'field_5a43eae2cde80')); + $pid = $this->factory->post->create(); + update_field( 'thinger', 'foo', $pid ); + update_field( '_thinger', 'field_5a43eae2cde80', $pid ); + $post = new TimberPost($pid); + $template = '{{ post.meta("thinger") }} / {{ post.field_object("thinger").key }}'; + $str = Timber::compile_string($template, array( 'post' => $post )); + $this->assertEquals('foo / field_thinger', $str); + } + function testACFInit() { $acf = new ACF(); $this->assertInstanceOf( 'Timber\Integrations\ACF', $acf ); @@ -138,4 +150,5 @@ class TestTimberIntegrations extends Timber_UnitTestCase { $this->assertNull($success); } + }
ref #<I> -- add doc block; renamed function to simply `field_object`; added test to cover
timber_timber
train
9a96896bbda37613bd8b29ac658427366e5d49be
diff --git a/engineio/async_eventlet.py b/engineio/async_eventlet.py index <HASH>..<HASH> 100644 --- a/engineio/async_eventlet.py +++ b/engineio/async_eventlet.py @@ -7,6 +7,7 @@ from eventlet.websocket import WebSocketWSGI as _WebSocketWSGI class WebSocketWSGI(_WebSocketWSGI): def __init__(self, *args, **kwargs): + super(WebSocketWSGI, self).__init__(*args, **kwargs) self._sock = None def __call__(self, environ, start_response): diff --git a/engineio/asyncio_socket.py b/engineio/asyncio_socket.py index <HASH>..<HASH> 100644 --- a/engineio/asyncio_socket.py +++ b/engineio/asyncio_socket.py @@ -176,7 +176,7 @@ class AsyncSocket(socket.Socket): while True: p = None try: - p = await ws.wait() + p = await asyncio.wait_for(ws.wait(), self.server.ping_timeout) except: break if p is None: diff --git a/engineio/socket.py b/engineio/socket.py index <HASH>..<HASH> 100755 --- a/engineio/socket.py +++ b/engineio/socket.py @@ -180,15 +180,11 @@ class Socket(object): break if not packets: # empty packet list returned -> connection closed - if not self.closed: # pragma: no cover - self.close(wait=True, abort=True) break try: for pkt in packets: ws.send(pkt.encode(always_bytes=False)) except: - if not self.closed: # pragma: no cover - self.close(wait=True, abort=True) break writer_task = self.server.start_background_task(writer) @@ -203,7 +199,7 @@ class Socket(object): except Exception as e: # if the socket is already closed, we can assume this is a # downstream error of that - if not self.closed: + if not self.closed: # pragma: no cover self.server.logger.info( '%s: Unexpected error "%s", closing connection', self.sid, str(e)) @@ -227,8 +223,7 @@ class Socket(object): self.queue.put(None) # unlock the writer task so that it can exit writer_task.join() - if not self.closed: - self.close(wait=True, abort=True) + self.close(wait=True, abort=True) if reraise_exc: raise reraise_exc
detect lost connections (asyncio)
miguelgrinberg_python-engineio
train
8ee68667086da4070db989273e5911f47a5e664e
diff --git a/client/state/happychat/selectors.js b/client/state/happychat/selectors.js index <HASH>..<HASH> 100644 --- a/client/state/happychat/selectors.js +++ b/client/state/happychat/selectors.js @@ -145,7 +145,7 @@ export const getHappychatTimeline = createSelector( * @return {Boolean} Whether the user is able to send messages */ export const canUserSendMessages = state => ( - isHappychatAvailable( state ) && + isHappychatClientConnected( state ) && ! includes( [ HAPPYCHAT_CHAT_STATUS_BLOCKED, diff --git a/client/state/happychat/test/selectors.js b/client/state/happychat/test/selectors.js index <HASH>..<HASH> 100644 --- a/client/state/happychat/test/selectors.js +++ b/client/state/happychat/test/selectors.js @@ -92,23 +92,21 @@ describe( 'selectors', () => { HAPPYCHAT_CHAT_STATUS_NEW, ]; - it( 'should return false if Happychat is unavailable', () => { + it( 'should return false if Happychat is not connected', () => { const state = deepFreeze( { happychat: { connectionStatus: 'uninitialized', - isAvailable: false, chatStatus: HAPPYCHAT_CHAT_STATUS_NEW } } ); expect( canUserSendMessages( state ) ).to.be.false; } ); - it( "should return false if Happychat is available but the chat status doesn't allow messaging", () => { + it( "should return false if Happychat is connected but the chat status doesn't allow messaging", () => { messagingDisabledChatStatuses.forEach( status => { const state = deepFreeze( { happychat: { connectionStatus: 'connected', - isAvailable: true, chatStatus: status } } ); @@ -116,30 +114,30 @@ describe( 'selectors', () => { } ); } ); - it( 'should return true if Happychat is available but client is not connected', () => { + it( 'should return true if Happychat is connected and the chat status allows messaging', () => { messagingEnabledChatStatuses.forEach( status => { const state = deepFreeze( { happychat: { - connectionStatus: 'uninitialized', - isAvailable: true, + connectionStatus: 'connected', chatStatus: status } } ); - expect( canUserSendMessages( state ) ).to.be.false; + expect( canUserSendMessages( state ) ).to.be.true; } ); } ); - it( 'should return true if Happychat is available and the chat status allows messaging', () => { - messagingEnabledChatStatuses.forEach( status => { - const state = deepFreeze( { - happychat: { - connectionStatus: 'connected', - isAvailable: true, - chatStatus: status - } - } ); - expect( canUserSendMessages( state ) ).to.be.true; + it( 'should return true even when isAvailable is false', () => { + // This test is here to prevent a code regression — isAvailable is supposed to + // determine whether Happychat is capable of starting new chats, and should not be + // a factor when determining if a user should be able to send messages to the service. + const state = deepFreeze( { + happychat: { + connectionStatus: 'connected', + chatStatus: HAPPYCHAT_CHAT_STATUS_NEW, + isAvailable: false, + } } ); + expect( canUserSendMessages( state ) ).to.be.true; } ); } );
Happychat: Stop misusing isAvailable (#<I>) * Stop using `isHappychatAvailable` to determine if messages should be sendable. * Update happychat seletor tests so canUserSendMessages doesn't care about isAvailable * Add test to protect against regressions
Automattic_wp-calypso
train
a68941fc5598e653a8e56400b26f04d702461013
diff --git a/nianalysis/archive/xnat.py b/nianalysis/archive/xnat.py index <HASH>..<HASH> 100644 --- a/nianalysis/archive/xnat.py +++ b/nianalysis/archive/xnat.py @@ -545,6 +545,10 @@ class XNATArchive(Archive): if subject_ids is not None: subject_ids = [('{}_{:03d}'.format(project_id, s) if isinstance(s, int) else s) for s in subject_ids] + # Add processed visit IDs to list of visit ids to filter + if visit_ids is not None: + visit_ids = visit_ids + [i + self.PROCESSED_SUFFIX + for i in visit_ids] subjects = [] sessions = defaultdict(list) with self._login() as xnat_login:
implicitly include processed sessions when filtering visit ids
MonashBI_arcana
train
765bffc94406c57475d2bb5840f36078d52435ba
diff --git a/src/LaravelDebugbar.php b/src/LaravelDebugbar.php index <HASH>..<HASH> 100644 --- a/src/LaravelDebugbar.php +++ b/src/LaravelDebugbar.php @@ -71,6 +71,13 @@ class LaravelDebugbar extends DebugBar protected $booted = false; /** + * True when enabled, false disabled an null for still unknown + * + * @var bool + */ + protected $enabled = null; + + /** * True when this is a Lumen application * * @var bool @@ -95,7 +102,8 @@ class LaravelDebugbar extends DebugBar */ public function enable() { - $this->app['config']->set('debugbar.enabled', true); + $this->enabled = true; + if (!$this->booted) { $this->boot(); } @@ -580,10 +588,6 @@ class LaravelDebugbar extends DebugBar } } - - // Stop further rendering (on subrequests etc) - $this->disable(); - return $response; } @@ -593,7 +597,11 @@ class LaravelDebugbar extends DebugBar */ public function isEnabled() { - return value($this->app['config']->get('debugbar.enabled')); + if ($this->enabled === null) { + $this->enabled = value($this->app['config']->get('debugbar.enabled')); + } + + return $this->enabled; } /** @@ -697,7 +705,7 @@ class LaravelDebugbar extends DebugBar */ public function disable() { - $this->app['config']->set('debugbar.enabled', false); + $this->enabled = false; } /**
Dont update config Should fix config caching + concurrent requests.
barryvdh_laravel-debugbar
train
bdb52460d53c8a8388027f5cdc7ccfb1636f1258
diff --git a/nunjucks/src/runtime.js b/nunjucks/src/runtime.js index <HASH>..<HASH> 100644 --- a/nunjucks/src/runtime.js +++ b/nunjucks/src/runtime.js @@ -275,7 +275,7 @@ function asyncEach(arr, dimen, iter, cb) { iter(item[0], item[1], item[2], i, len, next); break; default: - item.push(i, next); + item.push(i, len, next); iter.apply(this, item); } }, cb); @@ -321,7 +321,7 @@ function asyncAll(arr, dimen, func, cb) { func(item[0], item[1], item[2], i, len, done); break; default: - item.push(i, done); + item.push(i, len, done); func.apply(this, item); } } diff --git a/tests/compiler.js b/tests/compiler.js index <HASH>..<HASH> 100644 --- a/tests/compiler.js +++ b/tests/compiler.js @@ -358,6 +358,11 @@ }, '[1,2][3,4][5,6]'); + equal( + '{% ' + block + ' a, b, c, d in arr %}[{{ a }},{{ b }},{{ c }},{{ d }}]{% ' + end + '%}', + { arr: [[1, 2, 3, 4], [5, 6, 7, 8]] }, + '[1,2,3,4][5,6,7,8]'); + equal('{% ' + block + ' x, y in points %}{{ loop.index }}{% ' + end + ' %}', { points: [[1, 2], [3, 4], [5, 6]]
Fix bug when looping over arrays of more than 3 dimensions
mozilla_nunjucks
train
732dee451bb9304e039abdec291457639ad7163e
diff --git a/lib/main.js b/lib/main.js index <HASH>..<HASH> 100644 --- a/lib/main.js +++ b/lib/main.js @@ -75,8 +75,9 @@ module.exports = function(cordovaOptions) { stealCordova.build = function(buildResult){ return stealCordova.initIfNeeded().then(function(){ - var bundlesPath = buildResult.configuration.bundlesPath; - return stealCordova.copyProductionFiles(bundlesPath); + var config = buildResult.configuration; + var destPath = config.dest || config.bundlesPath; + return stealCordova.copyProductionFiles(destPath); }).then(function(){ return runCli({}, { command: ["build"],
Support Steal <I> This makes it so that we support steal <I>. Steal <I> has a new destPath which is the entire dist/ folder. We want to make that folder now and not just the dist/bundles folder.
stealjs_steal-cordova
train
6c065f59d981ac3bf7c9372fc06d3388635aa22f
diff --git a/green/test/test_cmdline.py b/green/test/test_cmdline.py index <HASH>..<HASH> 100644 --- a/green/test/test_cmdline.py +++ b/green/test/test_cmdline.py @@ -80,7 +80,7 @@ class TestMain(unittest.TestCase): cwd = os.getcwd() path = os.path.abspath(__file__) os.chdir(os.path.dirname(os.path.dirname(os.path.dirname(path)))) - config.sys.argv = ['', '--completions'] + config.sys.argv = ['', '--completions', 'green'] cmdline.main(testing=True) os.chdir(cwd) self.assertIn('green.test', self.s.getvalue())
Fixed a cmdline test so that it doesn't pull examples/ into the coverage list.
CleanCut_green
train
64f6be8563484f758bb7fe8d9fb0600a294a96f3
diff --git a/lib/ec2/ec2.js b/lib/ec2/ec2.js index <HASH>..<HASH> 100644 --- a/lib/ec2/ec2.js +++ b/lib/ec2/ec2.js @@ -529,7 +529,7 @@ libEc2.runInstanceFromAmi = function(argv, context, callback) { }; return raEc2.assignFqdnToInstance(params, context, function(err, result) { - if (err) { return die(err, callback, 'runInstanceFromAmi.assignFqdnToInstances'); } + if (err) { console.error(sg.inspect(params)); return die(err, callback, 'runInstanceFromAmi.assignFqdnToInstances'); } return callback(err, instances, launchConfig); }); } @@ -782,9 +782,9 @@ libEc2.assignFqdnToInstance = function(argv, context, callback) { if (!fqdn) { return callback(sg.toError("Need --fqdn")); } // Allow caller to tell us multiple accts to search - var extraAccts = ''+argvExtract(argv, 'extra-accts,accts') || []; if (_.isString(extraAccts)) { extraAccts = extraAccts.split(','); } - var extraRoles = ''+argvExtract(argv, 'extra-roles,roles') || []; if (_.isString(extraRoles)) { extraRoles = extraRoles.split(','); } - var extraSessions = ''+argvExtract(argv, 'extra-sessions,sessions') || []; if (_.isString(extraSessions)) { extraSessions = extraSessions.split(','); } + var extraAccts = argvExtract(argv, 'extra-accts,accts') || []; if (!_.isArray(extraAccts)) { extraAccts = ''+extraAccts.split(','); } + var extraRoles = argvExtract(argv, 'extra-roles,roles') || []; if (!_.isArray(extraRoles)) { extraRoles = ''+extraRoles.split(','); } + var extraSessions = argvExtract(argv, 'extra-sessions,sessions') || []; if (!_.isArray(extraSessions)) { extraSessions = ''+extraSessions.split(','); } // Ensure that we have an equal number of extra accts, roles, sessions _.each(extraAccts, function(acct, index) { @@ -805,7 +805,6 @@ libEc2.assignFqdnToInstance = function(argv, context, callback) { var addresses, resourceRecordSets = []; return sg.__runll([function(next) { - return raEc2.getAddresses(argv, context, function(err, addresses_) { if (err) { return die(err, callback, 'libEc2.assignFqdnToInstance.getAddresses'); } addresses = addresses_;
Fixed undefined bug in assignFqdnToInstance
briancsparks_js-aws
train
506d7a1250eed154a9c2e5ff39df82d7c8becf58
diff --git a/Resources/public/js/cpterms.js b/Resources/public/js/cpterms.js index <HASH>..<HASH> 100644 --- a/Resources/public/js/cpterms.js +++ b/Resources/public/js/cpterms.js @@ -85,6 +85,19 @@ }, onDrag: function ( $item, position, _super, event ) { + // change placeholder according to the mouse offset + var $target = $( event.target ).closest( ".section" ), + $relative_position = this.getRelativePosition( event, $target ); + + var left = settings.sortable.offsetXChild + 'px'; + + if ( $relative_position.X > settings.sortable.offsetXChild ) { + $( '.placeholder', $item.closest('.tos') ).css( 'margin-left', left ); + } else { + $( '.placeholder', $item.closest('.tos') ).css( 'margin-left', '0px' ); + } + + _super( $item, position ); }, onDragStart: function( $item, container, _super, event ) {
moved placeholder to signify 'as'
coopers-peele_CPTermsBundle
train
c171fdcff389eea9ca171f2bf099198220a787af
diff --git a/pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py b/pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py index <HASH>..<HASH> 100644 --- a/pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py +++ b/pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py @@ -30,6 +30,11 @@ from google.cloud.pubsub_v1.subscriber.message import Message logger = logging.getLogger(__name__) +def _callback_completed(future): + """Simple callback that just logs a `Future`'s result.""" + logger.debug('Result: %s', future.result()) + + class Policy(base.BasePolicy): """A consumer class based on :class:`threading.Thread`. @@ -144,4 +149,4 @@ class Policy(base.BasePolicy): logger.debug(self._callback) message = Message(msg.message, msg.ack_id, self._request_queue) future = self._executor.submit(self._callback, message) - logger.debug('Result: %s' % future.result()) + future.add_done_callback(_callback_completed)
Move debug logging call in Future.add_done_callback (#<I>)
googleapis_google-cloud-python
train
51f7cda698d59e33313a543dd3c74b6240f7af40
diff --git a/coalaip/models.py b/coalaip/models.py index <HASH>..<HASH> 100644 --- a/coalaip/models.py +++ b/coalaip/models.py @@ -180,7 +180,7 @@ class LazyLoadableModel(PostInitImmutable): "@type ('{self_type})'").format(loaded_type=loaded_type, self_type=self.ld_type) ) - if loaded_context and loaded_context != self.ld_context: + if loaded_context and list(loaded_context) != list(self.ld_context): raise ModelDataError( ("Loaded context ('{loaded_ctx}') differs from entity's " "context ('{self_ctx}')").format(loaded_ctx=loaded_context,
fix: Compare expected and loaded context both as lists Fix ModelDataErrors being thrown when the loaded context is deserialized as a list and the expected context is a tuple.
COALAIP_pycoalaip
train
fd91d6a556b6c94ff594b1ea743baa899421bd88
diff --git a/elasticutils/__init__.py b/elasticutils/__init__.py index <HASH>..<HASH> 100644 --- a/elasticutils/__init__.py +++ b/elasticutils/__init__.py @@ -4,6 +4,7 @@ from threading import local from operator import itemgetter from pyes import ES, exceptions +from pyes.es import thrift_enable try: from statsd import statsd @@ -26,6 +27,11 @@ def get_es(): if not hasattr(_local, 'es'): timeout = getattr(settings, 'ES_TIMEOUT', 1) dump = getattr(settings, 'ES_DUMP_CURL', False) + if (not thrift_enable and + not settings.ES_HOSTS[0].split(':')[1].startswith('92')): + raise ValueError('ES_HOSTS is not set to a valid port starting ' + 'with 9200-9299 range. Other ports are valid ' + 'if using pythrift.') _local.es = ES(settings.ES_HOSTS, default_indexes=[settings.ES_INDEXES['default']], timeout=timeout, dump_curl=dump)
Give users a clue why they are getting an annoying pythrift error
mozilla_elasticutils
train
972282495d81d16ad4038f5c1e74dbe2d81fb243
diff --git a/kie-ci/src/main/java/org/kie/scanner/embedder/MavenEmbedderUtils.java b/kie-ci/src/main/java/org/kie/scanner/embedder/MavenEmbedderUtils.java index <HASH>..<HASH> 100644 --- a/kie-ci/src/main/java/org/kie/scanner/embedder/MavenEmbedderUtils.java +++ b/kie-ci/src/main/java/org/kie/scanner/embedder/MavenEmbedderUtils.java @@ -49,10 +49,10 @@ public class MavenEmbedderUtils { public static ComponentProvider buildComponentProvider(ClassLoader mavenClassLoader, ClassLoader parent, MavenRequest mavenRequest) throws MavenEmbedderException { if (enforceWiredComponentProvider || MavenEmbedderUtils.class.getClassLoader().getClass().toString().contains( "Bundle" )) { - log.info( "In OSGi: using programmatically wired maven parser" ); + log.debug( "In OSGi: using programmatically wired maven parser" ); return new WiredComponentProvider(); } - log.info( "Not in OSGi: using plexus based maven parser" ); + log.debug( "Not in OSGi: using plexus based maven parser" ); return new PlexusComponentProvider( mavenClassLoader, parent, mavenRequest ); }
[ENTESB-<I>] use DEBUG logging to inform about type of Maven parser * this message gets printed everytime a POM is read/parsed. That can be easily dozens of times for anything bigger than just simple examples. It may easily flood the logs.
kiegroup_drools
train
648ae50a1e57b81ab6e8917e62eaf458a4df10bc
diff --git a/.travis.yml b/.travis.yml index <HASH>..<HASH> 100644 --- a/.travis.yml +++ b/.travis.yml @@ -45,7 +45,7 @@ before_script: # Run tests script: - - pytest -n 2 --cov abilian abilian tests + - pytest --cov abilian abilian tests - sphinx-build -W -b html docs/ docs/_build/ - make lint diff --git a/abilian/services/auth/tests.py b/abilian/services/auth/tests.py index <HASH>..<HASH> 100644 --- a/abilian/services/auth/tests.py +++ b/abilian/services/auth/tests.py @@ -11,10 +11,10 @@ from flask import request, url_for from abilian.core.models.subjects import User from abilian.services.auth import views -from abilian.testing import BaseTestCase, TestConfig +from abilian.testing import BaseTestCase, TestConfig as BaseTestConfig -class AuthTestConfig(TestConfig): +class AuthTestConfig(BaseTestConfig): # Most views should not be protected by crsf. Let it fail if @csrf.exempt is # forgotten on a view. CSRF_ENABLED = True diff --git a/abilian/web/assets/__init__.py b/abilian/web/assets/__init__.py index <HASH>..<HASH> 100644 --- a/abilian/web/assets/__init__.py +++ b/abilian/web/assets/__init__.py @@ -44,8 +44,7 @@ def requirejs_config(): RESOURCES_DIR = pkg_resources.resource_filename('abilian.web', 'resources') -JQUERY = Bundle('jquery/js/jquery-1.11.3.js', - 'jquery/js/jquery-migrate-1.2.1.js') +JQUERY = Bundle('jquery/js/jquery-1.12.4.js') BOOTBOX_JS = Bundle('bootbox/bootbox.js')
Parallel tests = not a great idea.
abilian_abilian-core
train
af396c1e2ad0538477805a9924b26ed3930d1e75
diff --git a/wallet/wsapi/structs.go b/wallet/wsapi/structs.go index <HASH>..<HASH> 100644 --- a/wallet/wsapi/structs.go +++ b/wallet/wsapi/structs.go @@ -71,6 +71,10 @@ type chainRequest struct { Force bool `json:"force"` } +type identityKeyRequest struct { + Public string `json:"public"` +} + type importIdentityKeysRequest struct { Keys []struct { Secret string `json:"secret"` diff --git a/wallet/wsapi/wsapi.go b/wallet/wsapi/wsapi.go index <HASH>..<HASH> 100644 --- a/wallet/wsapi/wsapi.go +++ b/wallet/wsapi/wsapi.go @@ -253,6 +253,10 @@ func handleV2Request(j *factom.JSON2Request) (*factom.JSON2Response, *factom.JSO resp, jsonError = handleGetHeight(params) case "wallet-balances": resp, jsonError = handleWalletBalances(params) + case "identity-key": + resp, jsonError = handleIdentityKey(params) + case "all-identity-keys": + resp, jsonError = handleAllIdentityKeys(params) case "import-identity-keys": resp, jsonError = handleImportIdentityKeys(params) case "identity-keys-at-height": @@ -1032,6 +1036,42 @@ func handleGetHeight(params []byte) (interface{}, *factom.JSONError) { return resp, nil } +func handleIdentityKey(params []byte) (interface{}, *factom.JSONError) { + req := new(identityKeyRequest) + if err := json.Unmarshal(params, req); err != nil { + return nil, newInvalidParamsError() + } + + e, err := fctWallet.GetIdentityKey(req.Public) + if err != nil { + return nil, newCustomInternalError(err.Error()) + } + if e == nil { + return nil, newCustomInternalError("Wallet: identity key not found") + } + resp := new(identityKeyResponse) + resp.Public = e.PubString() + resp.Secret = e.SecString() + return resp, nil +} + +func handleAllIdentityKeys(params []byte) (interface{}, *factom.JSONError) { + resp := new(multiIdentityKeyResponse) + + keys, err := fctWallet.GetAllIdentityKeys() + if err != nil { + return nil, newCustomInternalError(err.Error()) + } + for _, v := range keys { + key := new(identityKeyResponse) + key.Public = v.PubString() + key.Secret = v.SecString() + resp.Keys = append(resp.Keys, key) + } + + return resp, nil +} + func handleImportIdentityKeys(params []byte) (interface{}, *factom.JSONError) { req := new(importIdentityKeysRequest) if err := json.Unmarshal(params, req); err != nil {
Added ability to list all identity keys or a specific identity key given the public key
FactomProject_factom
train
9a1b2a055fc85f91027b1715572c905e85af666f
diff --git a/src/Application/Context.php b/src/Application/Context.php index <HASH>..<HASH> 100644 --- a/src/Application/Context.php +++ b/src/Application/Context.php @@ -12,6 +12,27 @@ use Hook\Http\Router; class Context { protected static $app_key; + protected static $isTrustedAction = false; + + /** + * isTrusted + * + * @return bool + */ + public static function isTrusted() { + return static::$isTrustedAction; + } + + /** + * setTrusted + * + * @param bool $trusted + * + * @return string + */ + public static function setTrusted($trusted = true) { + static::$isTrustedAction = $trusted; + } /** * config diff --git a/src/Application/Routes.php b/src/Application/Routes.php index <HASH>..<HASH> 100644 --- a/src/Application/Routes.php +++ b/src/Application/Routes.php @@ -86,6 +86,10 @@ class Routes { echo json_encode(array('error' => $e->getMessage())); }); + $app->hook('slim.before.dispatch', function() use ($app) { + file_put_contents('php://stdout', "Hey!"); + }); + return $app; } diff --git a/src/Auth/Role.php b/src/Auth/Role.php index <HASH>..<HASH> 100644 --- a/src/Auth/Role.php +++ b/src/Auth/Role.php @@ -3,6 +3,7 @@ use Hook\Model\AppKey; use Hook\Model\AuthToken; use Hook\Application\Config; +use Hook\Application\Context; class Role { protected static $instance; @@ -29,7 +30,7 @@ class Role { public static function isAllowed($model, $action) { // commandline always have full-access - if (AppKey::current()->isCommandline()) { + if (Context::isTrusted() || AppKey::current()->isCommandline()) { return true; } diff --git a/src/Middlewares/AppMiddleware.php b/src/Middlewares/AppMiddleware.php index <HASH>..<HASH> 100644 --- a/src/Middlewares/AppMiddleware.php +++ b/src/Middlewares/AppMiddleware.php @@ -115,12 +115,20 @@ class AppMiddleware extends Slim\Middleware // // Register session handler // Session\Handler::register(Config::get('session.handler', 'database')); - // Compile all route modules - if ($custom_routes = Module::where('type', Module::TYPE_ROUTE)->get()) { - foreach ($custom_routes as $custom_route) { - $custom_route->compile(); - } + // Query and compile route module if found + $route_module_name = strtolower($app->request->getMethod()) . '_' . substr($app->request->getPathInfo(), 1) . '.php'; + $custom_route = Module::where('type', Module::TYPE_ROUTE)-> + where('name', $route_module_name)-> + first(); + + if ($custom_route) { + // Flag request as "trusted". + Context::setTrusted(true); + + // "Compile" the route to be available for the router + $custom_route->compile(); } + } else if (!\Hook\Controllers\ApplicationController::isRootOperation()) { $app->response->setStatus(403); $app->response->setBody(json_encode(array('error' => "Invalid credentials."))); diff --git a/src/Model/Module.php b/src/Model/Module.php index <HASH>..<HASH> 100644 --- a/src/Model/Module.php +++ b/src/Model/Module.php @@ -220,6 +220,7 @@ class Module extends Model // Expose handy aliases for modules // $aliases = ''; + $aliases.= 'use Hook\Application\Context;'; $aliases.= 'use Hook\Model\Module;'; $aliases.= 'use Hook\Model\File;'; $aliases.= 'use Hook\Model\Auth;';
custom routes are now 'trusted' as default. they are not affected by CRUD definitions by role.
doubleleft_hook
train
1dd0ac1761aa4fafcf07a3789084b8c181afb69e
diff --git a/src/main/java/com/lambdaworks/redis/protocol/CommandHandler.java b/src/main/java/com/lambdaworks/redis/protocol/CommandHandler.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/lambdaworks/redis/protocol/CommandHandler.java +++ b/src/main/java/com/lambdaworks/redis/protocol/CommandHandler.java @@ -135,6 +135,11 @@ public class CommandHandler<K, V> extends ChannelDuplexHandler implements RedisC while (!queue.isEmpty()) { RedisCommand<K, V, ?> command = queue.peek(); + + if (debugEnabled) { + logger.debug("{} Queue contains: {} commands", logPrefix(), queue.size()); + } + if (!rsm.decode(buffer, command, command.getOutput())) { return; } @@ -184,10 +189,6 @@ public class CommandHandler<K, V> extends ChannelDuplexHandler implements RedisC // commands are ok to stay within the queue, reconnect will retrigger them channel.write(command, channel.voidPromise()); channel.flush(); - - if (!channel.isActive() && !queue.contains(command)) { - return write(command); - } } } else { @@ -298,7 +299,7 @@ public class CommandHandler<K, V> extends ChannelDuplexHandler implements RedisC commandBuffer.clear(); if (debugEnabled) { - logger.debug("{} executeQueuedCommands {} command(s) queued", logPrefix(), queue.size()); + logger.debug("{} executeQueuedCommands {} command(s) queued", logPrefix(), tmp.size()); } synchronized (stateLock) {
Remove double-requeue on channel-inactive
lettuce-io_lettuce-core
train
845f2f7e9c0da55cba502487b8fb2a1cf7df018e
diff --git a/lib/httpimagestore/configuration/s3.rb b/lib/httpimagestore/configuration/s3.rb index <HASH>..<HASH> 100644 --- a/lib/httpimagestore/configuration/s3.rb +++ b/lib/httpimagestore/configuration/s3.rb @@ -36,10 +36,10 @@ module Configuration def self.parse(configuration, node) configuration.s3 and raise StatementCollisionError.new(node, 's3') - configuration.s3 = Struct.new(:key, :secret, :ssl, :client).new - configuration.s3.key = node.attribute('key') or raise NoAttributeError.new(node, 'key') - configuration.s3.secret = node.attribute('secret') or raise NoAttributeError.new(node, 'secret') - configuration.s3.ssl = + + key = node.attribute('key') or raise NoAttributeError.new(node, 'key') + secret = node.attribute('secret') or raise NoAttributeError.new(node, 'secret') + ssl = case node.attribute('ssl') when nil true @@ -51,13 +51,14 @@ module Configuration raise BadValueError.new(node, 'ssl', 'true or false') end - log.info "S3 client using '#{configuration.s3.key}' key and #{configuration.s3.ssl ? 'HTTPS' : 'HTTP'} connections" - configuration.s3.client = AWS::S3.new( - access_key_id: configuration.s3.key, - secret_access_key: configuration.s3.secret, + log.info "S3 client using '#{key}' key and #{ssl ? 'HTTPS' : 'HTTP'} connections" + + configuration.s3 = AWS::S3.new( + access_key_id: key, + secret_access_key: secret, logger: logger_for(AWS::S3), log_level: :debug, - use_ssl: configuration.s3.ssl + use_ssl: ssl ) end end @@ -97,7 +98,6 @@ module Configuration def client @configuration.global.s3 or raise S3NotConfiguredError - @configuration.global.s3.client or fail 'no S3 client' end def rendered_path(request_state) diff --git a/spec/configuration_s3_spec.rb b/spec/configuration_s3_spec.rb index <HASH>..<HASH> 100644 --- a/spec/configuration_s3_spec.rb +++ b/spec/configuration_s3_spec.rb @@ -17,12 +17,12 @@ else end it 'should provide S3 key and secret' do - subject.s3.key.should == ENV['AWS_ACCESS_KEY_ID'] - subject.s3.secret.should == ENV['AWS_SECRET_ACCESS_KEY'] + subject.s3.config.access_key_id.should == ENV['AWS_ACCESS_KEY_ID'] + subject.s3.config.secret_access_key.should == ENV['AWS_SECRET_ACCESS_KEY'] end it 'should use SSL by default' do - subject.s3.ssl.should be_true + subject.s3.config.use_ssl.should be_true end it 'should allow disabling SSL' do @@ -30,11 +30,11 @@ else s3 key="#{ENV['AWS_ACCESS_KEY_ID']}" secret="#{ENV['AWS_SECRET_ACCESS_KEY']}" ssl=false EOF - subject.s3.ssl.should be_false + subject.s3.config.use_ssl.should be_false end it 'should provide S3 client' do - subject.s3.client.should be_a AWS::S3 + subject.s3.should be_a AWS::S3 end describe 'error handling' do
got rid of unneeded s3 config fields
jpastuszek_httpimagestore
train
9596da7f6509676fa2df1ae6cf09884f0c340980
diff --git a/salt/serializers/toml.py b/salt/serializers/toml.py index <HASH>..<HASH> 100644 --- a/salt/serializers/toml.py +++ b/salt/serializers/toml.py @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- -""" +''' salt.serializers.toml ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implements TOML serializer. It's just a wrapper around pytoml module. -""" +''' from __future__ import absolute_import @@ -27,12 +27,12 @@ __all__ = ['deserialize', 'serialize', 'available'] def deserialize(stream_or_string, **options): - """ + ''' Deserialize any string or stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower pytoml module. - """ + ''' try: if not isinstance(stream_or_string, (bytes, six.string_types)): @@ -47,12 +47,12 @@ def deserialize(stream_or_string, **options): def serialize(obj, **options): - """ + ''' Serialize Python data to TOML. :param obj: the data structure to serialize. :param options: options given to lower pytoml module. - """ + ''' try: if 'file_out' in options:
change all docstrings to single quotes
saltstack_salt
train
8d72bd42dc972405585cc8af2cce57d35f4095d7
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ [![Build Status](https://travis-ci.org/zrrrzzt/generate-pincode.svg?branch=master)](https://travis-ci.org/zrrrzzt/generate-pincode) [![Coverage Status](https://coveralls.io/repos/zrrrzzt/generate-pincode/badge.svg?branch=master&service=github)](https://coveralls.io/github/zrrrzzt/generate-pincode?branch=master) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) + # generate-pincode Node.js module for generating random pincodes. @@ -23,4 +24,11 @@ console.log(pin) ## Related -- [generate-pincode-cli](https://github.com/zrrrzzt/generate-pincode-cli) CLI of this module \ No newline at end of file +- [generate-pincode-cli](https://github.com/zrrrzzt/generate-pincode-cli) CLI of this module + + +## License + +[MIT](LICENSE) + +![Robohash image of generate-pincode](https://robots.kebabstudios.party/generate-pincode.png "Robohash image of generate-pincode") \ No newline at end of file diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,10 @@ 'use strict' -module.exports = function generatePincode (pinLength) { - var pinCodeArray = [] +const shuffle = require('knuth-shuffle').knuthShuffle + +module.exports = pinLength => { + const seed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + let pinCodeArray = [] if (!pinLength) { throw new Error('Missing required param: pinLength') @@ -11,8 +14,9 @@ module.exports = function generatePincode (pinLength) { throw new Error('pinLength is not a whole number') } - for (var i = 0; i < pinLength; i++) { - pinCodeArray.push(Math.floor(Math.random() * 10)) + for (let i = 0; i < pinLength; i++) { + const random = shuffle(seed.slice(0)) + pinCodeArray.push(random[0]) } return pinCodeArray.join('') diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "generate-pincode", "description": "Generate random pincode", - "version": "4.0.0", + "version": "4.0.1", "license": "MIT", "author": { "name": "Geir Gåsodden", @@ -20,7 +20,7 @@ "url": "http://github.com/zrrrzzt/generate-pincode/issues" }, "engines": { - "node": ">=4.6.2" + "node": ">=4.8.4" }, "scripts": { "test": "standard && nsp check && tap --reporter=spec test/*.js", @@ -33,5 +33,8 @@ "nsp": "2.7.0", "standard": "10.0.3", "tap": "10.7.0" + }, + "dependencies": { + "knuth-shuffle": "1.0.1" } } diff --git a/test/testInputs.js b/test/testInputs.js index <HASH>..<HASH> 100644 --- a/test/testInputs.js +++ b/test/testInputs.js @@ -1,7 +1,7 @@ 'use strict' -var tap = require('tap') -var gpc = require('../index') +const tap = require('tap') +const gpc = require('../index') tap.throws( function () { diff --git a/test/testOutputs.js b/test/testOutputs.js index <HASH>..<HASH> 100644 --- a/test/testOutputs.js +++ b/test/testOutputs.js @@ -1,7 +1,7 @@ 'use strict' -var tap = require('tap') -var gpc = require('../index') +const tap = require('tap') +const gpc = require('../index') tap.equal( gpc(6).length, 6,
Implements knuth-shuffle
zrrrzzt_generate-pincode
train
d169fb811b66f105d953162177b3ef1f01e8ef86
diff --git a/web/src/main/javascript/expression-atlas-heatmap-highcharts/src/DataForHighcharts.js b/web/src/main/javascript/expression-atlas-heatmap-highcharts/src/DataForHighcharts.js index <HASH>..<HASH> 100644 --- a/web/src/main/javascript/expression-atlas-heatmap-highcharts/src/DataForHighcharts.js +++ b/web/src/main/javascript/expression-atlas-heatmap-highcharts/src/DataForHighcharts.js @@ -44,6 +44,33 @@ var comparatorByProperty = _.curry( } ); +var rankColumnsByWhereTheyAppearFirst = function(expressions){ + return ( + _.chain(expressions) + .map(function(row){ + return ( + row.map(function(e){ + return ( + +e.hasOwnProperty("value") + ); + }) + ); + }) + .thru(_.spread(_.zip)) + .map(function(column){ + return ( + column + .map(function(e,ix){ + return e*(ix+1); + }) + .filter(_.identity) + ); + }) + .map(_.min) + .value() + ); +}; + var rankColumnsByExpression = function(expressions){ return ( _.chain(expressions) @@ -323,6 +350,7 @@ var combineRanks = function(ranksAndTheirWeighings){ var calculateColumnRank = function(expressions){ return ( combineRanks([ + [rankColumnsByWhereTheyAppearFirst(expressions), 1], [rankColumnsByExpression(expressions), 1e3], [rankColumnsByThreshold(0.4,expressions), 1e6] ])
Add a small ranking by which experiment the column first appears in to resolve ties and present better the cases where each tissue is only in one experiment, e.g. putting the two blueprint experiments together in http://localhost:<I>/gxa/genes/ENSG<I>
ebi-gene-expression-group_atlas
train
5b7d0f445e4aa79f03d8ed4259e14bef5795cc5e
diff --git a/src/main/resources/core/scripts/selenium-browserbot.js b/src/main/resources/core/scripts/selenium-browserbot.js index <HASH>..<HASH> 100644 --- a/src/main/resources/core/scripts/selenium-browserbot.js +++ b/src/main/resources/core/scripts/selenium-browserbot.js @@ -1153,6 +1153,8 @@ BrowserBot.prototype._findElementUsingFullXPath = function(xpath, inDocument, in } // If not, fall back to slower JavaScript implementation + // DGF set xpathdebug = true (using getEval, if you like) to turn on JS XPath debugging + //xpathdebug = true; var context = new ExprContext(inDocument); var xpathObj = xpathParse(xpath); var xpathResult = xpathObj.evaluate(context); diff --git a/src/main/resources/core/xpath/misc.js b/src/main/resources/core/xpath/misc.js index <HASH>..<HASH> 100644 --- a/src/main/resources/core/xpath/misc.js +++ b/src/main/resources/core/xpath/misc.js @@ -189,10 +189,7 @@ function Log() {}; Log.lines = []; Log.write = function(s) { - if (logging__) { - this.lines.push(xmlEscapeText(s)); - this.show(); - } + LOG.debug("xpath logging: " + s); }; // Writes the given XML with every tag on a new line. diff --git a/src/main/resources/core/xpath/xpath.js b/src/main/resources/core/xpath/xpath.js index <HASH>..<HASH> 100644 --- a/src/main/resources/core/xpath/xpath.js +++ b/src/main/resources/core/xpath/xpath.js @@ -236,6 +236,9 @@ function xpathReduce(stack, ahead) { } var matchexpr = mapExpr(cand.match, function(m) { return m.expr; }); + if (xpathdebug) { + Log.write('about to run ' + cand.rule[3].toString()); + } cand.expr = cand.rule[3].apply(null, matchexpr); stack.push(cand); @@ -1462,6 +1465,7 @@ function makeLocationExpr6(rel, slash, step) { function makeLocationExpr7(rel, dslash, step) { rel.appendStep(makeAbbrevStep(dslash.value)); + rel.appendStep(step); return rel; } diff --git a/src/main/resources/tests/TestXPathLocators.html b/src/main/resources/tests/TestXPathLocators.html index <HASH>..<HASH> 100644 --- a/src/main/resources/tests/TestXPathLocators.html +++ b/src/main/resources/tests/TestXPathLocators.html @@ -124,6 +124,14 @@ Copyright 2004 ThoughtWorks, Inc <td>xpath=//*[text()="right"]</td> <td>&nbsp;</td> </tr> + + <tr><td colspan="3"><i>test for SEL-444</i></td></tr> + + <tr> + <td>verifyValue</td> + <td>xpath=//div[@id='nested1']/div[1]//input[2]</td> + <td>nested3b</td> + </tr> </tbody> </table> diff --git a/src/main/resources/tests/html/test_locators.html b/src/main/resources/tests/html/test_locators.html index <HASH>..<HASH> 100644 --- a/src/main/resources/tests/html/test_locators.html +++ b/src/main/resources/tests/html/test_locators.html @@ -62,6 +62,13 @@ Copyright 2006 ThoughtWorks, Inc <div>div4</div> </div> + <div id="nested1"> + <div id="nested2"> + <input id="nested3a" type="button" value="nested3a"> + <input id="nested3b" type="button" value="nested3b"> + </div> + </div> + <div id="targetTest"> <span name="target">target</span> <a href="#target">referreing URI</a>
SEL-<I>. Fixed xpath.js so it can logs to the Selenium log; added a bit of logging. This code has a LOT of code paths; in this case, there was an error in makeLocationExpr7! r<I>
SeleniumHQ_selenium
train
907f741c7b71568cfb0de8ec77f388b9bd8ae2b5
diff --git a/tests/TypeParseTest.php b/tests/TypeParseTest.php index <HASH>..<HASH> 100644 --- a/tests/TypeParseTest.php +++ b/tests/TypeParseTest.php @@ -356,6 +356,9 @@ class TypeParseTest extends TestCase ); } + /** + * @return void + */ public function testCallableOrInt() { $this->assertSame( @@ -469,8 +472,11 @@ class TypeParseTest extends TestCase /** * @dataProvider providerTestValidCallMapType * - * @param string $expected - * @param array<int|string, string> $arr + * @param string $return_type + * @param string $param_type_1 + * @param string $param_type_2 + * @param string $param_type_3 + * @param string $param_type_4 * * @return void */ @@ -507,7 +513,7 @@ class TypeParseTest extends TestCase } /** - * @return void + * @return array<string, array<int|string, string>> */ public function providerTestValidCallMapType() {
Fix Psalm errors in TypeParseTest
vimeo_psalm
train
6528796b2c49ceb2b9475a8332c7e1a1bb6a3b43
diff --git a/salt/utils/xmlutil.py b/salt/utils/xmlutil.py index <HASH>..<HASH> 100644 --- a/salt/utils/xmlutil.py +++ b/salt/utils/xmlutil.py @@ -1,10 +1,11 @@ -# -*- coding: utf-8 -*- """ Various XML utilities """ # Import Python libs -from __future__ import absolute_import, print_function, unicode_literals + +import re +from xml.etree import ElementTree def _conv_name(x): @@ -99,3 +100,37 @@ def to_dict(xmltree, attr=False): return _to_full_dict(xmltree) else: return _to_dict(xmltree) + + +def get_xml_node(node, xpath): + """ + Get an XML node using a path (super simple xpath showing complete node ancestry). + This also creates the missing nodes. + + The supported XPath can contain elements filtering using [@attr='value']. + + Args: + node: an Element object + xpath: simple XPath to look for. + """ + if not xpath.startswith("./"): + xpath = "./{}".format(xpath) + res = node.find(xpath) + if res is None: + parent_xpath = xpath[: xpath.rfind("/")] + parent = node.find(parent_xpath) + if parent is None: + parent = get_xml_node(node, parent_xpath) + segment = xpath[xpath.rfind("/") + 1 :] + # We may have [] filter in the segment + matcher = re.match( + r"""(?P<tag>[^[]+)(?:\[@(?P<attr>\w+)=["'](?P<value>[^"']+)["']])?""", + segment, + ) + attrib = ( + {matcher.group("attr"): matcher.group("value")} + if matcher.group("attr") and matcher.group("value") + else {} + ) + res = ElementTree.SubElement(parent, matcher.group("tag"), attrib) + return res
Add xmlutil.get_xml_node() helper function This function helps getting ElementTree XML nodes and creating the missing parents if needed.
saltstack_salt
train
34afa842ddca765860140bb9ca709388b584f206
diff --git a/repositories/RedisRepo.php b/repositories/RedisRepo.php index <HASH>..<HASH> 100644 --- a/repositories/RedisRepo.php +++ b/repositories/RedisRepo.php @@ -11,6 +11,13 @@ class RedisRepo { /** @var Redis\Database The Redis database to use for queries */ protected $redisDatabase = null; + /** + * The list of key patterns this repository uses + * It is recommended that you add all key patterns to this list to make it easier to eventually flush them, if we want to + * + * @var array + */ + protected $keyPatterns = array(); /** * @param Redis\Database $redisDatabase The database to use for queries @@ -19,4 +26,45 @@ class RedisRepo { $this->redisDatabase = $redisDatabase; } + + /** + * Adds key patterns to the list + * + * @param string|array $keyPatterns The key pattern or list of key patterns to add + */ + protected function addKeyPatterns($keyPatterns) + { + // The key patterns must be an array, so create one if necessary + if(is_string($keyPatterns)) + { + $keyPatterns = array($keyPatterns); + } + + foreach($keyPatterns as $keyPattern) + { + if(!in_array($keyPattern, $this->keyPatterns)) + { + $this->keyPatterns[] = $keyPattern; + } + } + } + + /** + * Deletes all the key patterns + * + * @return bool True if successful, otherwise false + */ + protected function deleteKeyPatterns() + { + // Loops through our key patterns, gets all keys that match them, then deletes each of them + $lua = "local keyPatterns = {'" . implode("','", $this->keyPatterns) . "'} + for i, keyPattern in ipairs(keyPatterns) do + for j, key in ipairs(redis.call('keys', keyPattern)) do + redis.call('del', key) + end + end"; + $this->redisDatabase->getPHPRedis()->eval($lua); + + return $this->redisDatabase->getPHPRedis()->getLastError() === null; + } } \ No newline at end of file
Added methods to register key patterns and delete those patterns in the case we want to flush a particular Redis repo
opulencephp_Opulence
train
b5c7fb747c9d8b430f0dece7adb32126f18d135c
diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java index <HASH>..<HASH> 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java @@ -743,7 +743,7 @@ public final class Settings { try { value = Integer.parseInt(Settings.getString(key)); } catch (NumberFormatException ex) { - LOGGER.trace("Could not convert property '{}' to an int.", key, ex); + LOGGER.trace("Could not convert property '{}={}' to an int.", key, Settings.getString(key)); value = defaultValue; } return value;
updated log message to assist in debugging an issue
jeremylong_DependencyCheck
train
04d2bb8c35e8a6937e5f529aac1897ba08c92430
diff --git a/kmatch/kmatch.py b/kmatch/kmatch.py index <HASH>..<HASH> 100644 --- a/kmatch/kmatch.py +++ b/kmatch/kmatch.py @@ -37,14 +37,25 @@ class K(object): :type suppress_key_errors: bool :raises: ValueError on an invalid pattern or regex """ - self._pattern = deepcopy(p) + self._raw_pattern = deepcopy(p) + self._compiled_pattern = deepcopy(p) self._suppress_key_errors = suppress_key_errors # Validate the pattern is in the appropriate format - self._validate(self._pattern) + self._validate(self._compiled_pattern) # Compile any regexs in the pattern - self._compile(self._pattern) + self._compile(self._compiled_pattern) + + @property + def pattern(self): + """ + Gets the kmatch pattern. + + :returns: The kmatch pattern dictionary originally provided to the K object + :rtype: dict + """ + return self._raw_pattern def _is_operator(self, p): return len(p) == 2 and p[0] in self._OPERATOR_MAP and isinstance(p[1], (list, tuple)) @@ -119,12 +130,13 @@ class K(object): def match(self, value): """ - Matches the value to the pattern + Matches the value to the pattern. :param value: The value to be matched :type value: dict :returns: True if the value matches the pattern, False otherwise + :rtype: bool :raises: KeyError if key from pattern does not exist in input value and the suppress_key_errors class variable is False """ - return self._match(self._pattern, value) + return self._match(self._compiled_pattern, value) diff --git a/kmatch/tests/tests.py b/kmatch/tests/tests.py index <HASH>..<HASH> 100644 --- a/kmatch/tests/tests.py +++ b/kmatch/tests/tests.py @@ -4,6 +4,15 @@ from mock import patch from kmatch import K +class KPatternTest(TestCase): + """ + Tests the pattern function in K. + """ + def test_pattern(self): + k = K(['=~', 'hi', 'hi']) + self.assertEquals(k.pattern, ['=~', 'hi', 'hi']) + + class KMatchTest(TestCase): """ Tests the match function in K. @@ -235,20 +244,20 @@ class KInitTest(TestCase): def test_unnested(self, mock_compile): k = K(['=~', 'field', 'hi']) self.assertEquals(mock_compile.call_count, 1) - self.assertEquals(k._pattern, ['=~', 'field', 'hi_compiled']) + self.assertEquals(k._compiled_pattern, ['=~', 'field', 'hi_compiled']) @patch('kmatch.kmatch.re.compile', spec_set=True, side_effect=lambda x: '{0}_compiled'.format(x)) def test_nested_list_of_single_dict(self, mock_compile): k = K(['!', ['=~', 'field', 'hi']]) self.assertEquals(mock_compile.call_count, 1) - self.assertEquals(k._pattern, ['!', ['=~', 'field', 'hi_compiled']]) + self.assertEquals(k._compiled_pattern, ['!', ['=~', 'field', 'hi_compiled']]) @patch('kmatch.kmatch.re.compile', spec_set=True, side_effect=lambda x: '{0}_compiled'.format(x)) def test_nested_list_of_lists(self, mock_compile): k = K(['&', [['=~', 'f', 'hi'], ['=~', 'f', 'hello']]]) self.assertEquals(mock_compile.call_count, 2) self.assertEquals( - k._pattern, + k._compiled_pattern, ['&', [['=~', 'f', 'hi_compiled'], ['=~', 'f', 'hello_compiled']]]) @patch('kmatch.kmatch.re.compile', spec_set=True, side_effect=lambda x: '{0}_compiled'.format(x)) @@ -265,7 +274,7 @@ class KInitTest(TestCase): ]] ]]) self.assertEquals(mock_compile.call_count, 5) - self.assertEquals(k._pattern, ['&', [ + self.assertEquals(k._compiled_pattern, ['&', [ ['=~', 'f', 'hi_compiled'], ['=~', 'f', 'hello_compiled'], ['|', [ diff --git a/kmatch/version.py b/kmatch/version.py index <HASH>..<HASH> 100644 --- a/kmatch/version.py +++ b/kmatch/version.py @@ -1 +1 @@ -__version__ = '0.1' +__version__ = '0.1.1'
added pattern property for obtaining kmatch pattern
ambitioninc_kmatch
train
30ae9c071faf7d5ba15f9331bf00764195c029d5
diff --git a/lib/function/matrix/cross.js b/lib/function/matrix/cross.js index <HASH>..<HASH> 100644 --- a/lib/function/matrix/cross.js +++ b/lib/function/matrix/cross.js @@ -18,15 +18,19 @@ function factory (type, config, load, typed) { * a1 * b2 - a2 * b1 * ] * + * If one of the input vectors has a dimension greater than 1, the output + * vector will be a 1x3 (2-dimensional) matrix. + * * Syntax: * * math.cross(x, y) * * Examples: * - * math.cross([1, 1, 0], [0, 1, 1]); // Returns [1, -1, 1] - * math.cross([3, -3, 1], [4, 9, 2]); // Returns [-15, -2, 39] - * math.cross([2, 3, 4], [5, 6, 7]); // Returns [-3, 6, -3] + * math.cross([1, 1, 0], [0, 1, 1]); // Returns [1, -1, 1] + * math.cross([3, -3, 1], [4, 9, 2]); // Returns [-15, -2, 39] + * math.cross([2, 3, 4], [5, 6, 7]); // Returns [-3, 6, -3] + * math.cross([[1, 2, 3]], [[4], [5], [6]]); // Returns [[-3, 6, -3]] * * See also: * @@ -66,6 +70,8 @@ function factory (type, config, load, typed) { * @private */ function _cross(x, y) { + var highestDimension = Math.max(array.size(x).length, array.size(y).length); + x = array.squeeze(x); y = array.squeeze(y); @@ -77,11 +83,17 @@ function factory (type, config, load, typed) { '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])'); } - return [ + var product = [ subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0])) ]; + + if (highestDimension > 1) { + return [product]; + } else { + return product; + } } }
Change dimensionality of vector returned by cross() If one of the input vectors/matrices has a dimension greater than 1, the output vector will be a 1x3 matrix. Otherwise, the result will be a flat 3-component vector. Closes #<I>
josdejong_mathjs
train
c3a17de326409398e003a4456c1343f15158f785
diff --git a/peer.go b/peer.go index <HASH>..<HASH> 100644 --- a/peer.go +++ b/peer.go @@ -1029,6 +1029,25 @@ func (p *peer) QueueInventory(invVect *btcwire.InvVect) { p.outputInvChan <- invVect } +// Connected returns whether or not the peer is currently connected. +func (p *peer) Connected() bool { + return atomic.LoadInt32(&p.connected) != 0 && + atomic.LoadInt32(&p.disconnect) == 0 +} + +// Disconnect disconnects the peer by closing the connection. It also sets +// a flag so the impending shutdown can be detected. +func (p *peer) Disconnect() { + // did we win the race? + if atomic.AddInt32(&p.disconnect, 1) != 1 { + return + } + close(p.quit) + if atomic.LoadInt32(&p.connected) != 0 { + p.conn.Close() + } +} + // Start begins processing input and output messages. It also sends the initial // version message for outbound connections to start the negotiation process. func (p *peer) Start() error { @@ -1057,19 +1076,6 @@ func (p *peer) Start() error { return nil } -// Disconnect disconnects the peer by closing the connection. It also sets -// a flag so the impending shutdown can be detected. -func (p *peer) Disconnect() { - // did we win the race? - if atomic.AddInt32(&p.disconnect, 1) != 1 { - return - } - close(p.quit) - if atomic.LoadInt32(&p.connected) != 0 { - p.conn.Close() - } -} - // Shutdown gracefully shuts down the peer by disconnecting it and waiting for // all goroutines to finish. func (p *peer) Shutdown() { @@ -1209,8 +1215,3 @@ func (p *peer) logError(fmt string, args ...interface{}) { log.Debugf(fmt, args...) } } - -func (p *peer) Connected() bool { - return atomic.LoadInt32(&p.connected) != 0 && - atomic.LoadInt32(&p.disconnect) == 0 -}
Comment Connected function in peer. While here, also rearrange the functions slightly to logically group them.
btcsuite_btcd
train
055f1dccb3548828db4453519199e6f8fde75c17
diff --git a/server/opts_test.go b/server/opts_test.go index <HASH>..<HASH> 100644 --- a/server/opts_test.go +++ b/server/opts_test.go @@ -101,12 +101,7 @@ func TestTLSConfigFile(t *testing.T) { } // Now check TLSConfig a bit more closely // CipherSuites - ciphers := []uint16{ - // tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - // tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - } + ciphers := defaultCipherSuites() if !reflect.DeepEqual(tlsConfig.CipherSuites, ciphers) { t.Fatalf("Got incorrect cipher suite list: [%+v]", tlsConfig.CipherSuites) }
Allow test to use correct default ciphers
nats-io_gnatsd
train
7f92bb7976281653e96dc326494ed77bab2615da
diff --git a/packages/editor/src/editor.js b/packages/editor/src/editor.js index <HASH>..<HASH> 100644 --- a/packages/editor/src/editor.js +++ b/packages/editor/src/editor.js @@ -101,6 +101,53 @@ export function enableEditor({ space, uiWrapper, config }) { id: 'component-delete', label: 'Delete', }, + // @todo why no work? + // { + // command: 'core:component-prev', + // id: 'component-prev', + // label: 'Prev', + // }, + + { + id: 'device-mobile', + label: 'Mobile', + togglable: true, + command: { + run: editor => editor.setDevice('Mobile'), + stop: editor => editor.setDevice('Full'), + }, + }, + { + id: 'device-tablet', + label: 'Tablet', + togglable: true, + command: { + run: editor => editor.setDevice('Tablet'), + stop: editor => editor.setDevice('Full'), + }, + }, + { + id: 'device-desktop', + label: 'Desktop', + togglable: true, + command: { + run: editor => editor.setDevice('Desktop'), + stop: editor => editor.setDevice('Full'), + }, + }, + { + id: 'trigger-anim-in', + label: 'Trigger Anim In', + command: { + run: editor => { + const component = editor.getSelected(); + if (component.is('bolt-animate')) { + const el = component.getEl(); + el.triggerAnimIn(); + } + }, + }, + }, { id: 'show-json', className: 'btn-show-json', @@ -141,6 +188,14 @@ export function enableEditor({ space, uiWrapper, config }) { appendTo: editorSlots.blocks, blocks: [], }, + deviceManager: { + devices: [ + { name: 'Mobile', width: '400px' }, + { name: 'Tablet', width: '700px' }, + { name: 'Desktop', width: '1100px' }, + { name: 'Full', width: '100%' }, + ], + }, styleManager: { type: null }, assetManager: { assets: [ @@ -166,10 +221,24 @@ export function enableEditor({ space, uiWrapper, config }) { stylePrefix: `${stylePrefix}canvas-`, styles: config.styles, }, + // rte: { + // actions: false, + // }, }; const editor = grapesjs.init(editorConfig); + editor.TraitManager.addType('drupal-media-manager', { + createInput({ trait }) { + const el = document.createElement('div'); + el.innerHTML = ` +<button>Upload to Drupal Media Manager</button> + `; + + return el; + }, + }); + /** * @param {Object} opt * @param {string} opt.slotName @@ -238,6 +307,7 @@ export function enableEditor({ space, uiWrapper, config }) { editor.on('component:selected', (/** @type {grapesjs.Component} */ model) => { const name = model.getName().toLowerCase(); const slotControls = model.getSlotControls && model.getSlotControls(); + window.x = model; renderSlotControls({ slotControls }); }); @@ -257,9 +327,11 @@ export function enableEditor({ space, uiWrapper, config }) { config.scripts.forEach(script => { const scriptEl = canvasDoc.createElement('script'); scriptEl.src = script; + scriptEl.async = true; canvasDoc.body.appendChild(scriptEl); }); + // helpful to access current editor instance in console with `editor` window['editor'] = editor; // eslint-disable-line dot-notation let dropzoneSelector = ''; @@ -269,7 +341,7 @@ export function enableEditor({ space, uiWrapper, config }) { if (!dropzones) return; dropzones.forEach(el => { const isEmpty = el.children.length === 0; - el.style.outline = 'dotted green 2px'; + el.style.outline = 'dotted green 1px'; }); } diff --git a/packages/micro-journeys/src/interactive-pathway.js b/packages/micro-journeys/src/interactive-pathway.js index <HASH>..<HASH> 100644 --- a/packages/micro-journeys/src/interactive-pathway.js +++ b/packages/micro-journeys/src/interactive-pathway.js @@ -65,7 +65,7 @@ class BoltInteractivePathway extends withLitHtml() { */ getTitle() { /** @type {HTMLElement} */ - const pathwayTitleEl = this.querySelector('[slot="pathway-title"]'); + const pathwayTitleEl = this.renderRoot.querySelector('.c-bolt-interactive-pathway__nav-item--active'); return pathwayTitleEl ? pathwayTitleEl.innerText : ''; }
fix(micro-journeys): show pathways title in non-shadow dom
bolt-design-system_bolt
train
b84a01aa631320295eee63726efc19b74aa636da
diff --git a/lib/swaggerise.js b/lib/swaggerise.js index <HASH>..<HASH> 100644 --- a/lib/swaggerise.js +++ b/lib/swaggerise.js @@ -11,7 +11,7 @@ module.exports = function swaggerize(item) { /** * Allows you describe an app our router route. * @paramSchema metaData ./lib/schemas/meta-data.json - * @param {string[]} [metaData.tags] - A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](swagger.io/specification/#operationObject) must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. See {@link http://swagger.io/specification/#tagObject Tag Object}. + * @param {string[]} [metaData.tags] - A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](swagger.io/specification/#operationObject) must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. See {@link http://swagger.io/specification/#tagObject Tag Object}. (Generated) * @return {void} */ function describe(metaData) { diff --git a/utility/metadata-schema-to-js-doc/inject-schema.js b/utility/metadata-schema-to-js-doc/inject-schema.js index <HASH>..<HASH> 100644 --- a/utility/metadata-schema-to-js-doc/inject-schema.js +++ b/utility/metadata-schema-to-js-doc/inject-schema.js @@ -147,8 +147,8 @@ function addGeneratedComment(options, callback) { var searchString = util.format('* @paramSchema %s %s', options.paramName, options.schemaPath); var pramNameRegExString = options.paramName + '\\..+'; var paramNameWithOrWithoutBrackets = '((\\[' + pramNameRegExString + '\\])|(' + pramNameRegExString + '))'; - var regEx = new RegExp('^\\s*\\*\\s@param\\s((\\{.*\\}\\s' + paramNameWithOrWithoutBrackets + ')|' + paramNameWithOrWithoutBrackets + ')\\s((\\s)|(.))*\\(Generated\\)', 'i'); - _.remove(options.lines, function (line, index) { + var regEx = new RegExp('^\\s*\\*\\s@param\\s((\\{.*\\}\\s' + paramNameWithOrWithoutBrackets + ')|' + paramNameWithOrWithoutBrackets + ')\\s.*\\(Generated\\)', 'i'); + _.remove(options.lines, function (line) { return regEx.test(line); }); options.lines.forEach(function (line, index) {
code to remove generated properties before generating more ones.
eXigentCoder_swagger-spec-express
train
012065c41de6bd0adbacc616fe461c086ef5ec52
diff --git a/addon/properties/attachments/content/content.js b/addon/properties/attachments/content/content.js index <HASH>..<HASH> 100644 --- a/addon/properties/attachments/content/content.js +++ b/addon/properties/attachments/content/content.js @@ -4,13 +4,13 @@ const { computed } = Ember; -const internal = (prop) => { +export const internal = (prop) => { return computed(function() { return this._internal[prop]; }).readOnly(); }; -export default Ember.Object.extend({ +export const Content = Ember.Object.extend({ _internal: null, diff --git a/addon/properties/attachments/content/string-content.js b/addon/properties/attachments/content/string-content.js index <HASH>..<HASH> 100644 --- a/addon/properties/attachments/content/string-content.js +++ b/addon/properties/attachments/content/string-content.js @@ -1,16 +1,10 @@ import Ember from 'ember'; -import Content from './content'; +import { Content, internal } from './content'; const { computed } = Ember; -const internal = (prop) => { - return computed(function() { - return this._internal[prop]; - }).readOnly(); -} - export default Content.extend({ data: internal('data'),
cleanup --HG-- branch : feature/attachments
ampatspell_ember-cli-sofa
train
7ed835ae5acf2ba1c5648beb0fab65d2b7088d42
diff --git a/src/components/diff/diff__doublepane-divider.js b/src/components/diff/diff__doublepane-divider.js index <HASH>..<HASH> 100644 --- a/src/components/diff/diff__doublepane-divider.js +++ b/src/components/diff/diff__doublepane-divider.js @@ -304,7 +304,7 @@ DoubleEditorDivider.getPathForRange = function (range, visibleRangeOriginal, vis templateData.rightYTo ), util.format('%s %s', - templateData.xModifiedTo, + templateData.xModifiedFrom, templateData.leftYTo ), util.format('%s %s L %s %s Z',
fix(diff): fix connector path Former-commit-id: <I>f<I>cbde1fc<I>db7c<I>adf1a<I>b
JetBrains_ring-ui
train
f030afbdc54785cc85e71425d7bba87862aec19c
diff --git a/src/extensions/scratch3_wedo2/index.js b/src/extensions/scratch3_wedo2/index.js index <HASH>..<HASH> 100644 --- a/src/extensions/scratch3_wedo2/index.js +++ b/src/extensions/scratch3_wedo2/index.js @@ -787,9 +787,7 @@ class WeDo2 { _checkBatteryLevel () { this._ble.read( BLEService.DEVICE_SERVICE, - BLECharacteristic.LOW_VOLTAGE_ALERT, - false, - this._onMessage // will ignore result + BLECharacteristic.LOW_VOLTAGE_ALERT ); }
Removing extra params from a BLE read in WeDo2.
LLK_scratch-vm
train
4fb7617d4148efc8c979698cc0f9c83bf390a090
diff --git a/src/libs/Auth.php b/src/libs/Auth.php index <HASH>..<HASH> 100644 --- a/src/libs/Auth.php +++ b/src/libs/Auth.php @@ -458,10 +458,11 @@ class Auth * * @param string $token token * @param array $password new password + * @param string $ip ip address making the request * * @return boolean success */ - public function forgotStep2($token, array $password) + public function forgotStep2($token, array $password, $pi) { $this->app[ 'errors' ]->setCurrentContext( 'auth.forgot' ); @@ -478,13 +479,17 @@ class Auth $success = $user->set( 'user_password', $password ); $user->enforcePermissions(); - if( $success ) + if ($success) { Database::delete( 'UserLinks', [ 'uid' => $user->id(), 'link_type' => USER_LINK_FORGOT_PASSWORD ] ); + $user->sendEmail('password-changed', [ + 'ip' => $ip ]); + } + return $success; } diff --git a/tests/AuthTest.php b/tests/AuthTest.php index <HASH>..<HASH> 100644 --- a/tests/AuthTest.php +++ b/tests/AuthTest.php @@ -377,10 +377,10 @@ class AuthTest extends \PHPUnit_Framework_TestCase 'uid' => self::$user->id(), 'link_type' => USER_LINK_FORGOT_PASSWORD ] ) ); - $this->assertFalse( self::$auth->forgotStep2( 'blah', [ 'password', 'password' ] ) ); + $this->assertFalse(self::$auth->forgotStep2('blah', ['password', 'password'], '127.0.0.1')); $oldUserPassword = self::$user->user_password; - $this->assertTrue( self::$auth->forgotStep2( $link->link, [ 'testpassword2', 'testpassword2' ] ) ); + $this->assertTrue(self::$auth->forgotStep2($link->link, ['testpassword2', 'testpassword2'], '127.0.0.1')); self::$user->load(); $this->assertNotEquals( $oldUserPassword, self::$user->user_password ); $this->assertEquals( 0, UserLink::totalRecords( [
send user an email notifying them when their password has been changed via forgot password
infusephp_auth
train
40a1c8342b336e8bfd7cad3a17a0f5168e901d2b
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,26 @@ or maven : <version>1.2.2</version> </dependency> ``` + +Development snapshot are available on sonatype nexus repository +```script + <repositories> + <repository> + <id>sonatype-nexus-snapshots</id> + <name>Sonatype Nexus Snapshots</name> + <url>https://oss.sonatype.org/content/repositories/snapshots</url> + </repository> + </repositories> + + <dependencies> + <dependency> + <groupId>org.mariadb.jdbc</groupId> + <artifactId>mariadb-java-client</artifactId> + <version>1.3.0-SNAPSHOT</version> + </dependency> + </dependencies> +``` + ## Documentation For a Getting started guide, API docs, recipes, etc. see the [documentation page](https://mariadb.com/kb/en/mariadb/about-the-mariadb-java-client/)! diff --git a/pom.xml b/pom.xml index <HASH>..<HASH> 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ <artifactId>mariadb-java-client</artifactId> <packaging>jar</packaging> <name>mariadb-java-client</name> - <version>1.2.2</version> + <version>1.3.0-SNAPSHOT</version> <description>JDBC driver for MariaDB and MySQL</description> <url>https://mariadb.com/kb/en/mariadb/about-mariadb-connector-j/</url> <properties> @@ -262,7 +262,6 @@ <token>@qualifier</token> <value>${parsedVersion.qualifier}</value> </replacement> - parsedVersion.qualifier </replacements> </configuration> </plugin> diff --git a/src/main/java/org/mariadb/jdbc/MySQLDatabaseMetaData.java b/src/main/java/org/mariadb/jdbc/MySQLDatabaseMetaData.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mariadb/jdbc/MySQLDatabaseMetaData.java +++ b/src/main/java/org/mariadb/jdbc/MySQLDatabaseMetaData.java @@ -61,6 +61,7 @@ import java.util.Comparator; import java.util.List; public class MySQLDatabaseMetaData implements DatabaseMetaData { + private final static String DRIVER_NAME = "MariaDB connector/J"; private String url; private MySQLConnection connection; private String databaseProductName = "MySQL"; @@ -488,20 +489,20 @@ public class MySQLDatabaseMetaData implements DatabaseMetaData { public String getDriverName() throws SQLException { - return "mariadb-jdbc"; // TODO: get from constants file + return DRIVER_NAME; } public String getDriverVersion() throws SQLException { - return String.format("%d.%d",getDriverMajorVersion(),getDriverMinorVersion()); + return Version.version; } public int getDriverMajorVersion() { - return 1; + return Version.majorVersion; } public int getDriverMinorVersion() { - return 1; + return Version.minorVersion; } diff --git a/src/main/java/org/mariadb/jdbc/Version.java b/src/main/java/org/mariadb/jdbc/Version.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mariadb/jdbc/Version.java +++ b/src/main/java/org/mariadb/jdbc/Version.java @@ -1,10 +1,10 @@ package org.mariadb.jdbc; public final class Version { - public static final String version = "1.2.2"; + public static final String version = "1.3.0-SNAPSHOT"; public static final int majorVersion = 1; - public static final int minorVersion = 2; - public static final int patchVersion = 2; - public static final String qualifier = ""; + public static final int minorVersion = 3; + public static final int patchVersion = 0; + public static final String qualifier = "SNAPSHOT"; } \ No newline at end of file diff --git a/src/test/java/org/mariadb/jdbc/DateTest.java b/src/test/java/org/mariadb/jdbc/DateTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/mariadb/jdbc/DateTest.java +++ b/src/test/java/org/mariadb/jdbc/DateTest.java @@ -233,13 +233,15 @@ public class DateTest extends BaseTest{ ps.executeUpdate(); ResultSet rs = connection.createStatement().executeQuery("select * from dtest"); rs.next(); + assertEquals(d.getHours(), rs.getTime(1).getHours()); + /* Check that time is correct, up to seconds precision */ - assertEquals(d.getHours(),rs.getTime(1).getHours()); - assertEquals(d.getMinutes(),rs.getTime(1).getMinutes()); if (isMariadbServer()) { + assertEquals(d.getMinutes(),rs.getTime(1).getMinutes()); assertEquals(d.getSeconds(), rs.getTime(1).getSeconds()); } else { //mysql 1 seconde precision + Assert.assertTrue(Math.abs(d.getMinutes() - rs.getTime(1).getMinutes()) <= 1); Assert.assertTrue(Math.abs(d.getSeconds() - rs.getTime(1).getSeconds())<=1); } }
[CONJ-<I>] Correct driver metadata version
MariaDB_mariadb-connector-j
train
1a26aee249ea722cdca550118f1f92524fd957c0
diff --git a/Gruntfile.circle.js b/Gruntfile.circle.js index <HASH>..<HASH> 100644 --- a/Gruntfile.circle.js +++ b/Gruntfile.circle.js @@ -31,28 +31,28 @@ module.exports = function gruntConfig(grunt) { }, [ // note: packages are ordered on approximate flakiness of their respective // test suites - `example-phone`, - `ciscospark`, - `plugin-phone`, - `http-core`, - `spark-core`, - `plugin-wdm`, - `plugin-mercury`, - `plugin-locus`, - `generator-ciscospark`, + // `example-phone`, + // `ciscospark`, + // `plugin-phone`, + // `http-core`, + // `spark-core`, + // `plugin-wdm`, + // `plugin-mercury`, + // `plugin-locus`, + // `generator-ciscospark`, `common`, `helper-html`, - `jsdoctrinetest`, - `*`, - `!test-helper*`, - `!bin*`, - `!xunit-with-logs` + `jsdoctrinetest` + // `*`, + // `!test-helper*`, + // `!bin*`, + // `!xunit-with-logs` ]); const CIRCLE_NODE_TOTAL = parseInt(process.env.CIRCLE_NODE_TOTAL || 1, 10); const CIRCLE_NODE_INDEX = parseInt(process.env.CIRCLE_NODE_INDEX || 0, 10); const packs = [ - `plugin-wdm`, + // `plugin-wdm`, `common`, `helper-html`, `jsdoctrinetest`
chore(build): further limit built/tested code during experimentation
webex_spark-js-sdk
train
e89addd00e3726ca0fec21ce58d60d581308cc0d
diff --git a/cmd/cli/new/template/makefile.go b/cmd/cli/new/template/makefile.go index <HASH>..<HASH> 100644 --- a/cmd/cli/new/template/makefile.go +++ b/cmd/cli/new/template/makefile.go @@ -8,6 +8,12 @@ init: go get -u github.com/golang/protobuf/proto go get -u github.com/golang/protobuf/protoc-gen-go go get github.com/micro/micro/v3/cmd/protoc-gen-micro + go get github.com/micro/micro/v3/cmd/protoc-gen-openapi + +.PHONY: api +api: + protoc --openapi_out=. --proto_path=. proto/{{.Alias}}.proto + .PHONY: proto proto: protoc --proto_path=. --micro_out=. --go_out=:. proto/{{.Alias}}.proto diff --git a/service/runtime/kubernetes/client/client_test.go b/service/runtime/kubernetes/client/client_test.go index <HASH>..<HASH> 100644 --- a/service/runtime/kubernetes/client/client_test.go +++ b/service/runtime/kubernetes/client/client_test.go @@ -8,8 +8,8 @@ import ( "github.com/micro/micro/v3/service/runtime" - "github.com/micro/micro/v3/test/fakes" "github.com/micro/micro/v3/service/runtime/kubernetes/api" + "github.com/micro/micro/v3/test/fakes" . "github.com/onsi/gomega" ) diff --git a/service/runtime/manager/manager.go b/service/runtime/manager/manager.go index <HASH>..<HASH> 100644 --- a/service/runtime/manager/manager.go +++ b/service/runtime/manager/manager.go @@ -15,9 +15,9 @@ import ( "github.com/micro/micro/v3/service/client" "github.com/micro/micro/v3/service/logger" "github.com/micro/micro/v3/service/runtime" + kclient "github.com/micro/micro/v3/service/runtime/kubernetes/client" "github.com/micro/micro/v3/service/runtime/source/git" "github.com/micro/micro/v3/service/store" - kclient "github.com/micro/micro/v3/service/runtime/kubernetes/client" "github.com/micro/micro/v3/util/namespace" ) diff --git a/service/server/grpc/util.go b/service/server/grpc/util.go index <HASH>..<HASH> 100644 --- a/service/server/grpc/util.go +++ b/service/server/grpc/util.go @@ -18,10 +18,10 @@ package grpc import ( "context" - "io" "fmt" - "strings" + "io" "os" + "strings" "sync" "google.golang.org/grpc/codes"
add make api command to makefile (#<I>)
micro_micro
train
67cf9193ba792049eda26c0fb4f4fb0c4e66b78b
diff --git a/fluent_comments/static/fluent_comments/js/ajaxcomments.js b/fluent_comments/static/fluent_comments/js/ajaxcomments.js index <HASH>..<HASH> 100644 --- a/fluent_comments/static/fluent_comments/js/ajaxcomments.js +++ b/fluent_comments/static/fluent_comments/js/ajaxcomments.js @@ -37,7 +37,7 @@ .each(function(){ var $form = $(this); var object_id = parseInt($form.attr('data-object-id')); // Supported in all jQuery versions. - $form.wrap('<div class="js-comments-form-orig-position"></div>').parent().attr('id', 'comment-form-orig-position-' + object_id); + $form.wrap('<div class="js-comments-form-orig-position" id="comments-form-orig-position-' + object_id + '"></div>'); }); // HACK HACK HACK @@ -170,8 +170,7 @@ if(event) event.preventDefault(); - var object_id = data['object_id']; - var $form = $('#comment-form-' + object_id); + var $form = $(event.target).closest('form.js-comments-form'); resetForm($form); }
Fix "Cancel Reply" link for new multiple-form per page support. Closes #<I>
django-fluent_django-fluent-comments
train
b3db3e906b3eadcfc85d75bc493cc7177f89acfe
diff --git a/sqlalchemy_postgres_autocommit/databases.py b/sqlalchemy_postgres_autocommit/databases.py index <HASH>..<HASH> 100644 --- a/sqlalchemy_postgres_autocommit/databases.py +++ b/sqlalchemy_postgres_autocommit/databases.py @@ -6,7 +6,12 @@ from sqlalchemy import orm class Database: def __init__(self, database_url): self.engine = engine.create_engine(database_url, isolation_level="AUTOCOMMIT") - self.Session = orm.sessionmaker(bind=self.engine, autocommit=True, autoflush=False) + self.Session = orm.sessionmaker( + bind=self.engine, + class_=Session, + autocommit=True, + autoflush=False, + ) # Keep track of which DBAPI connection(s) had autocommit turned off for # a particular transaction object. self.transaction_connections = {} @@ -42,3 +47,11 @@ class Database: def get_dbapi_connection(self, connection: engine.Connection) -> extensions.connection: return connection.connection.connection + + +class Session(orm.Session): + def commit(self): + if self.transaction is not None or not self.autocommit: + super().commit() + else: + self.flush()
Don't raise exception when committing without transaction. Flush instead. It makes integrating with third-party libraries easier, because you can simply call session.commit() instead of session.flush(). Without this change calling .commit() outside of transaction would raise: sqlalchemy.exc.InvalidRequestError: No transaction is begun.
socialwifi_sqlalchemy-postgres-autocommit
train
e786742192883eab012635a972b7f6a6fa3786ec
diff --git a/src/Stream.php b/src/Stream.php index <HASH>..<HASH> 100644 --- a/src/Stream.php +++ b/src/Stream.php @@ -73,8 +73,10 @@ class Stream implements StreamInterface public function __toString() { try { - $this->seek(0); - return (string) stream_get_contents($this->stream); + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); } catch (\Throwable $e) { trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); return ''; @@ -191,7 +193,7 @@ class Stream implements StreamInterface public function seek($offset, $whence = SEEK_SET) { $whence = (int) $whence; - + if (!isset($this->stream)) { throw new \RuntimeException('Stream is detached'); } diff --git a/tests/StreamTest.php b/tests/StreamTest.php index <HASH>..<HASH> 100644 --- a/tests/StreamTest.php +++ b/tests/StreamTest.php @@ -68,6 +68,24 @@ class StreamTest extends TestCase $stream->close(); } + public function testConvertsToStringNonSeekableStream() + { + $handle = popen('echo foo', 'r'); + $stream = new Stream($handle); + self::assertFalse($stream->isSeekable()); + self::assertSame('foo', trim((string) $stream)); + } + + public function testConvertsToStringNonSeekablePartiallyReadStream() + { + $handle = popen('echo bar', 'r'); + $stream = new Stream($handle); + $firstLetter = $stream->read(1); + self::assertFalse($stream->isSeekable()); + self::assertSame('b', $firstLetter); + self::assertSame('ar', trim((string) $stream)); + } + public function testGetsContents() { $handle = fopen('php://temp', 'w+');
Converting a non-seekable stream to a string (#<I>) * Add cast to string for non-seekable streams * Add tests of cast to string of non-seekable streams * Replace this with self
guzzle_psr7
train
a5d3e7c8ca71b3c6e1dc2146cac8e39d7126d9b6
diff --git a/memmap_test.go b/memmap_test.go index <HASH>..<HASH> 100644 --- a/memmap_test.go +++ b/memmap_test.go @@ -241,8 +241,8 @@ func TestWriteCloseTime(t *testing.T) { time.Sleep(2 * time.Second) case "darwin": time.Sleep(1 * time.Second) - default: - time.Sleep(10 * time.Millisecond) + default: // depending on the FS, this may work with < 1 second, on my old ext3 it does not + time.Sleep(1 * time.Second) } _, err = f.Write([]byte("test"))
fix for OsFs w/ lower timestamp resolution
spf13_afero
train
f6a01cfe8372164fd1ecf4b041a5b466e980a94f
diff --git a/dcrsqlite/apisource.go b/dcrsqlite/apisource.go index <HASH>..<HASH> 100644 --- a/dcrsqlite/apisource.go +++ b/dcrsqlite/apisource.go @@ -306,8 +306,15 @@ func (db *wiredDB) GetRawTransactionWithPrevOutAddresses(txid string) (*apitypes for i := range tx.Vin { vin := &tx.Vin[i] - prevOutAddresses[i] = txhelpers.OutPointAddressesFromString( + if vin.IsCoinBase() /* || vin.IsStakeBase() */ { + continue + } + var err error + prevOutAddresses[i], err = txhelpers.OutPointAddressesFromString( vin.Txid, vin.Vout, vin.Tree, db.client, db.params) + if err != nil { + log.Warnf("failed to get outpoint address from txid: %v", err) + } } msgTx := txhelpers.MsgTxFromHex(txhex) diff --git a/txhelpers/txhelpers.go b/txhelpers/txhelpers.go index <HASH>..<HASH> 100644 --- a/txhelpers/txhelpers.go +++ b/txhelpers/txhelpers.go @@ -113,7 +113,7 @@ func BlockConsumesOutpointWithAddresses(block *dcrutil.Block, addrs map[string]T // txrr, err := c.GetRawTransactionVerbose(&prevOut.Hash) prevTx, err := c.GetRawTransaction(&prevOut.Hash) if err != nil { - fmt.Printf("Unable to get raw transaction for %s", prevOut.Hash.String()) + fmt.Printf("Unable to get raw transaction for %s\n", prevOut.Hash.String()) continue } @@ -122,7 +122,7 @@ func BlockConsumesOutpointWithAddresses(block *dcrutil.Block, addrs map[string]T _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { - fmt.Printf("ExtractPkScriptAddrs: %v", err.Error()) + fmt.Printf("ExtractPkScriptAddrs: %v\n", err.Error()) continue } @@ -186,20 +186,18 @@ func BlockReceivesToAddresses(block *dcrutil.Block, addrs map[string]TxAction, // OutPointAddresses gets the addresses payed to by a transaction output. func OutPointAddresses(outPoint *wire.OutPoint, c RawTransactionGetter, - params *chaincfg.Params) []string { + params *chaincfg.Params) ([]string, error) { // The addresses are encoded in the pkScript, so we need to get the // raw transaction, and the TxOut that contains the pkScript. prevTx, err := c.GetRawTransaction(&outPoint.Hash) if err != nil { - fmt.Printf("Unable to get raw transaction for %s", outPoint.Hash.String()) - return nil + return nil, fmt.Errorf("unable to get raw transaction for %s", outPoint.Hash.String()) } txOuts := prevTx.MsgTx().TxOut if len(txOuts) <= int(outPoint.Index) { - fmt.Printf("PrevOut index (%d) is beyond the TxOuts slice (length %d)", + return nil, fmt.Errorf("PrevOut index (%d) is beyond the TxOuts slice (length %d)", outPoint.Index, len(txOuts)) - return nil } // For the TxOut of interest, extract the list of addresses @@ -207,8 +205,7 @@ func OutPointAddresses(outPoint *wire.OutPoint, c RawTransactionGetter, _, txAddrs, _, err := txscript.ExtractPkScriptAddrs( txOut.Version, txOut.PkScript, params) if err != nil { - fmt.Printf("ExtractPkScriptAddrs: %v", err.Error()) - return nil + return nil, fmt.Errorf("ExtractPkScriptAddrs: %v", err.Error()) } addresses := make([]string, 0, len(txAddrs)) @@ -216,17 +213,16 @@ func OutPointAddresses(outPoint *wire.OutPoint, c RawTransactionGetter, addr := txAddr.EncodeAddress() addresses = append(addresses, addr) } - return addresses + return addresses, nil } // OutPointAddressesFromString is the same as OutPointAddresses, but it takes // the outpoint as the tx string, vout index, and tree. func OutPointAddressesFromString(txid string, index uint32, tree int8, - c RawTransactionGetter, params *chaincfg.Params) []string { + c RawTransactionGetter, params *chaincfg.Params) ([]string, error) { hash, err := chainhash.NewHashFromStr(txid) if err != nil { - fmt.Printf("Invalid hash %s", txid) - return nil + return nil, fmt.Errorf("Invalid hash %s", txid) } outPoint := wire.NewOutPoint(hash, index, tree)
Avoid attempting to fetch non-existent coinbase prevout. return error from OutPointAddressesFromString and OutPointAddresses, log it in GetRawTransactionWithPrevOutAddresses
decred_dcrdata
train
f326a50118c97f6bdd6e5635ad481aa3c6c7a05b
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -54,7 +54,7 @@ function Hook (modules, options, onrequire) { debug('processing %s module require(\'%s\'): %s', core ? 'core' : 'non-core', request, filename) // return known patched modules immediately - if (self.cache.hasOwnProperty(filename)) { + if (Object.prototype.hasOwnProperty.call(self.cache, filename) === true) { debug('returning already patched cached module: %s', filename) return self.cache[filename] } @@ -130,7 +130,7 @@ function Hook (modules, options, onrequire) { } // only call onrequire the first time a module is loaded - if (!self.cache.hasOwnProperty(filename)) { + if (Object.prototype.hasOwnProperty.call(self.cache, filename) === false) { // ensure that the cache entry is assigned a value before calling // onrequire, in case calling onrequire requires the same module. self.cache[filename] = exports
refactor: don't access Object.prototype methods on target object
elastic_require-in-the-middle
train
dcf57bd2cc93c121d7e090a7a825e05d9ce1bb5d
diff --git a/plugins/guests/linux/cap/mount_nfs.rb b/plugins/guests/linux/cap/mount_nfs.rb index <HASH>..<HASH> 100644 --- a/plugins/guests/linux/cap/mount_nfs.rb +++ b/plugins/guests/linux/cap/mount_nfs.rb @@ -26,7 +26,7 @@ module VagrantPlugins end mount_command = "mount -o '#{mount_opts.join(",")}' #{ip}:'#{hostpath}' #{expanded_guest_path}" - retryable(:on => Vagrant::Errors::LinuxNFSMountFailed, :tries => 5, :sleep => 2) do + retryable(:on => Vagrant::Errors::LinuxNFSMountFailed, :tries => 5, :sleep => 3) do machine.communicate.sudo(mount_command, :error_class => Vagrant::Errors::LinuxNFSMountFailed) end
guests/linux: increase sleep time btween NFS mount retries
hashicorp_vagrant
train
f7b1c7a816c12d67dc3bc45d340c548f712594a0
diff --git a/core/DataTable/Filter/CalculateEvolutionFilter.php b/core/DataTable/Filter/CalculateEvolutionFilter.php index <HASH>..<HASH> 100755 --- a/core/DataTable/Filter/CalculateEvolutionFilter.php +++ b/core/DataTable/Filter/CalculateEvolutionFilter.php @@ -8,6 +8,7 @@ */ namespace Piwik\DataTable\Filter; +use Piwik\Common; use Piwik\DataTable; use Piwik\DataTable\Row; use Piwik\Site; @@ -122,6 +123,8 @@ class CalculateEvolutionFilter extends ColumnCallbackAddColumnPercentage $value = self::getPercentageValue($value, $divisor, $this->quotientPrecision); $value = self::appendPercentSign($value); + $value = Common::forceDotAsSeparatorForDecimalPoint($value); + return $value; }
refs #<I> fix evolution filter did cast a float to string resulting in wrong sorting results
matomo-org_matomo
train
20ce8b71ab41ef223a787068e80242838a719faa
diff --git a/plugin/pkg/scheduler/algorithm/predicates/predicates.go b/plugin/pkg/scheduler/algorithm/predicates/predicates.go index <HASH>..<HASH> 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/predicates.go +++ b/plugin/pkg/scheduler/algorithm/predicates/predicates.go @@ -28,6 +28,7 @@ import ( "k8s.io/kubernetes/pkg/client/cache" qosutil "k8s.io/kubernetes/pkg/kubelet/qos/util" "k8s.io/kubernetes/pkg/labels" + utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" @@ -161,7 +162,7 @@ func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []api.Volume, namespace if err != nil { // if the PVC is not found, log the error and count the PV towards the PV limit // generate a random volume ID since its required for de-dup - glog.Error(err) + utilruntime.HandleError(fmt.Errorf("Unable to look up PVC info for %s/%s, assuming PVC matches predicate when counting limits: %v", namespace, pvcName, err)) source := rand.NewSource(time.Now().UnixNano()) generatedID := "missingPVC" + strconv.Itoa(rand.New(source).Intn(1000000)) filteredVolumes[generatedID] = true @@ -178,7 +179,7 @@ func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []api.Volume, namespace // if the PV is not found, log the error // and count the PV towards the PV limit // generate a random volume ID since its required for de-dup - glog.Error(err) + utilruntime.HandleError(fmt.Errorf("Unable to look up PV info for %s/%s/%s, assuming PV matches predicate when counting limits: %v", namespace, pvcName, pvName, err)) source := rand.NewSource(time.Now().UnixNano()) generatedID := "missingPV" + strconv.Itoa(rand.New(source).Intn(1000000)) filteredVolumes[generatedID] = true diff --git a/plugin/pkg/scheduler/algorithm/predicates/predicates_test.go b/plugin/pkg/scheduler/algorithm/predicates/predicates_test.go index <HASH>..<HASH> 100644 --- a/plugin/pkg/scheduler/algorithm/predicates/predicates_test.go +++ b/plugin/pkg/scheduler/algorithm/predicates/predicates_test.go @@ -1411,7 +1411,7 @@ func TestEBSVolumeCountConflicts(t *testing.T) { { VolumeSource: api.VolumeSource{ PersistentVolumeClaim: &api.PersistentVolumeClaimVolumeSource{ - ClaimName: "deletedPV", + ClaimName: "pvcWithDeletedPV", }, }, }, @@ -1549,8 +1549,8 @@ func TestEBSVolumeCountConflicts(t *testing.T) { Spec: api.PersistentVolumeClaimSpec{VolumeName: "someNonEBSVol"}, }, { - ObjectMeta: api.ObjectMeta{Name: "deletedPV"}, - Spec: api.PersistentVolumeClaimSpec{VolumeName: "deletedPV"}, + ObjectMeta: api.ObjectMeta{Name: "pvcWithDeletedPV"}, + Spec: api.PersistentVolumeClaimSpec{VolumeName: "pvcWithDeletedPV"}, }, }
Improving error messages and naming to be clear
kubernetes_kubernetes
train
6fe86b50bbea4731a470fbd7a7cc6ed3b9260441
diff --git a/lib/spring/test/acceptance_test.rb b/lib/spring/test/acceptance_test.rb index <HASH>..<HASH> 100644 --- a/lib/spring/test/acceptance_test.rb +++ b/lib/spring/test/acceptance_test.rb @@ -465,11 +465,11 @@ module Spring test "changing the Gemfile works when spring calls into itself" do File.write(app.path("script.rb"), <<-RUBY.strip_heredoc) gemfile = Rails.root.join("Gemfile") - File.write(gemfile, "\#{gemfile.read}gem 'devise'\\n") + File.write(gemfile, "\#{gemfile.read}gem 'text'\\n") Bundler.with_clean_env do system(#{app.env.inspect}, "bundle install") end - output = `\#{Rails.root.join('bin/rails')} runner 'require "devise"; puts "done";'` + output = `\#{Rails.root.join('bin/rails')} runner 'require "text"; puts "done";'` exit output.include? "done\n" RUBY
Don't use devise in test Latest version of devise doesn't like Ruby <I>, so this is failing.
rails_spring
train
dde66cf02492e1c16aacabb9a3d2769efed96848
diff --git a/src/main/java/org/gwtbootstrap3/extras/notify/client/ui/NotifySettings.java b/src/main/java/org/gwtbootstrap3/extras/notify/client/ui/NotifySettings.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/gwtbootstrap3/extras/notify/client/ui/NotifySettings.java +++ b/src/main/java/org/gwtbootstrap3/extras/notify/client/ui/NotifySettings.java @@ -31,6 +31,8 @@ import org.gwtbootstrap3.extras.notify.client.event.NotifyClosedHandler; import org.gwtbootstrap3.extras.notify.client.event.NotifyShowHandler; import org.gwtbootstrap3.extras.notify.client.event.NotifyShownHandler; +import com.google.gwt.core.client.JavaScriptObject; + /** * This class represent basic Notify's settings, that you can use to customize display of each Notify. * <p/> @@ -43,7 +45,21 @@ import org.gwtbootstrap3.extras.notify.client.event.NotifyShownHandler; * @author Xiaodong SUN * @see #makeDefault() */ -public class NotifySettings { +public class NotifySettings extends JavaScriptObject { + + /** + * Default constructor + */ + protected NotifySettings() {} + + /** + * Creates a new instance of {@link NotifySettings}. + * + * @return a new instance of {@link NotifySettings}. + */ + public static NotifySettings newSettings() { + return JavaScriptObject.createObject().cast(); + } /** * Set element name or class or ID to append Notify to. Default is 'body'. @@ -102,7 +118,7 @@ public class NotifySettings { } /** - * If <code>true</code> the <code>data-grow="dismiss"</code> element in the template + * If <code>true</code> the <code>data-notify="dismiss"</code> element in the template * will be hidden. * * @param customType Style name to set
Added new static access for Bootstrap notify settings
gwtbootstrap3_gwtbootstrap3-extras
train
9b6530996565e1509125883e508e802ae7bb3a0b
diff --git a/src/Package_Command.php b/src/Package_Command.php index <HASH>..<HASH> 100644 --- a/src/Package_Command.php +++ b/src/Package_Command.php @@ -4,6 +4,7 @@ use Composer\Composer; use Composer\Config; use Composer\Config\JsonConfigSource; use Composer\DependencyResolver\Pool; +use Composer\DependencyResolver\Request; use Composer\EventDispatcher\Event; use Composer\Factory; use Composer\IO\NullIO; @@ -19,6 +20,7 @@ use Composer\Repository\CompositeRepository; use Composer\Repository\ComposerRepository; use Composer\Repository\RepositoryManager; use Composer\Util\Filesystem; +use Composer\Util\HttpDownloader; use WP_CLI\ComposerIO; use WP_CLI\Extractor; use WP_CLI\Utils; @@ -81,7 +83,7 @@ class Package_Command extends WP_CLI_Command { const PACKAGE_INDEX_URL = 'https://wp-cli.org/package-index/'; const SSL_CERTIFICATE = '/rmccue/requests/library/Requests/Transport/cacert.pem'; - private $pool = false; + private $version_selector = false; /** * Default author data used while creating default WP-CLI packages composer.json. @@ -676,8 +678,14 @@ class Package_Command extends WP_CLI_Command { $config->merge( $config_args ); $config->setConfigSource( new JsonConfigSource( $this->get_composer_json() ) ); + $io = new NullIO(); try { - $package_index = new ComposerRepository( [ 'url' => self::PACKAGE_INDEX_URL ], new NullIO(), $config ); + if ( $this->is_composer_v2() ) { + $http_downloader = new HttpDownloader( $io, $config ); + $package_index = new ComposerRepository( [ 'url' => self::PACKAGE_INDEX_URL ], $io, $config, $http_downloader ); + } else { + $package_index = new ComposerRepository( [ 'url' => self::PACKAGE_INDEX_URL ], $io, $config ); + } } catch ( Exception $e ) { WP_CLI::error( $e->getMessage() ); } @@ -995,9 +1003,9 @@ class Package_Command extends WP_CLI_Command { * @return PackageInterface|null */ private function find_latest_package( PackageInterface $package, Composer $composer, $php_version, $minor_only = false ) { - // find the latest version allowed in this pool + // Find the latest version allowed in this pool/repository set. $name = $package->getPrettyName(); - $version_selector = new VersionSelector( $this->get_pool( $composer ) ); + $version_selector = $this->get_version_selector( $composer ); $stability = $composer->getPackage()->getMinimumStability(); $flags = $composer->getPackage()->getStabilityFlags(); if ( isset( $flags[ $name ] ) ) { @@ -1014,15 +1022,31 @@ class Package_Command extends WP_CLI_Command { if ( null === $target_version && $minor_only ) { $target_version = '^' . $package->getVersion(); } + + if ( $this->is_composer_v2() ) { + return $version_selector->findBestCandidate( $name, $target_version, $best_stability ); + } + return $version_selector->findBestCandidate( $name, $target_version, $php_version, $best_stability ); } - private function get_pool( Composer $composer ) { - if ( ! $this->pool ) { - $this->pool = new Pool( $composer->getPackage()->getMinimumStability(), $composer->getPackage()->getStabilityFlags() ); - $this->pool->addRepository( new CompositeRepository( $composer->getRepositoryManager()->getRepositories() ) ); + private function get_version_selector( Composer $composer ) { + if ( ! $this->version_selector ) { + if ( $this->is_composer_v2() ) { + $repository_set = new Repository\RepositorySet( + $composer->getPackage()->getMinimumStability(), + $composer->getPackage()->getStabilityFlags() + ); + $repository_set->addRepository( new CompositeRepository( $composer->getRepositoryManager()->getRepositories() ) ); + $this->version_selector = new VersionSelector( $repository_set ); + } else { + $pool = new Pool( $composer->getPackage()->getMinimumStability(), $composer->getPackage()->getStabilityFlags() ); + $pool->addRepository( new CompositeRepository( $composer->getRepositoryManager()->getRepositories() ) ); + $this->version_selector = new VersionSelector( $pool ); + } } - return $this->pool; + + return $this->version_selector; } /** @@ -1317,4 +1341,13 @@ class Package_Command extends WP_CLI_Command { } ); } + + /** + * Check whether we are dealing with Composer version 2.0.0+. + * + * @return bool + */ + private function is_composer_v2() { + return version_compare( Composer::getVersion(), '2.0.0', '>=' ); + } }
Fix version selector usage for Composer v2
wp-cli_package-command
train
a82787fb8a63209ac1a32fbe9cd6e5b21a5b78c2
diff --git a/lib/vcr/middleware/rack.rb b/lib/vcr/middleware/rack.rb index <HASH>..<HASH> 100644 --- a/lib/vcr/middleware/rack.rb +++ b/lib/vcr/middleware/rack.rb @@ -3,8 +3,13 @@ module VCR class Rack include Common + def initialize(*args) + @mutex = Mutex.new + super + end + def call(env) - Thread.exclusive do + @mutex.synchronize do VCR.use_cassette(*cassette_arguments(env)) do @app.call(env) end
Use a mutex rather than Thread.exclusive. I'm getting errors from the rack middleware cuke on <I> w/ the Thread.exclusive.
vcr_vcr
train
01440395176bdbb2662480f03b27851cb860f385
diff --git a/python/pyspark/mllib/linalg/__init__.py b/python/pyspark/mllib/linalg/__init__.py index <HASH>..<HASH> 100644 --- a/python/pyspark/mllib/linalg/__init__.py +++ b/python/pyspark/mllib/linalg/__init__.py @@ -301,11 +301,14 @@ class DenseVector(Vector): return DenseVector, (self.array.tostring(),) def numNonzeros(self): + """ + Number of nonzero elements. This scans all active values and count non zeros + """ return np.count_nonzero(self.array) def norm(self, p): """ - Calculte the norm of a DenseVector. + Calculates the norm of a DenseVector. >>> a = DenseVector([0, -1, 2, -3]) >>> a.norm(2) @@ -397,10 +400,16 @@ class DenseVector(Vector): return np.dot(diff, diff) def toArray(self): + """ + Returns an numpy.ndarray + """ return self.array @property def values(self): + """ + Returns a list of values + """ return self.array def __getitem__(self, item): @@ -479,8 +488,8 @@ class SparseVector(Vector): :param size: Size of the vector. :param args: Active entries, as a dictionary {index: value, ...}, - a list of tuples [(index, value), ...], or a list of strictly i - ncreasing indices and a list of corresponding values [index, ...], + a list of tuples [(index, value), ...], or a list of strictly + increasing indices and a list of corresponding values [index, ...], [value, ...]. Inactive entries are treated as zeros. >>> SparseVector(4, {1: 1.0, 3: 5.5}) @@ -521,11 +530,14 @@ class SparseVector(Vector): raise TypeError("indices array must be sorted") def numNonzeros(self): + """ + Number of nonzero elements. This scans all active values and count non zeros. + """ return np.count_nonzero(self.values) def norm(self, p): """ - Calculte the norm of a SparseVector. + Calculates the norm of a SparseVector. >>> a = SparseVector(4, [0, 1], [3., -4.]) >>> a.norm(1) @@ -797,7 +809,7 @@ class Vectors(object): values (sorted by index). :param size: Size of the vector. - :param args: Non-zero entries, as a dictionary, list of tupes, + :param args: Non-zero entries, as a dictionary, list of tuples, or two sorted lists containing indices and values. >>> Vectors.sparse(4, {1: 1.0, 3: 5.5})
[SPARK-<I>] [DOCUMENTATION, MLLIB, PYSPARK] Added documentation for few APIs There are some missing API docs in pyspark.mllib.linalg.Vector (including DenseVector and SparseVector). We should add them based on their Scala counterparts.
apache_spark
train
7eb34bfd085b2ed7d700e2e480dfd5d5a32d1546
diff --git a/tags2sdists/checkoutdir.py b/tags2sdists/checkoutdir.py index <HASH>..<HASH> 100644 --- a/tags2sdists/checkoutdir.py +++ b/tags2sdists/checkoutdir.py @@ -71,7 +71,7 @@ class CheckoutDir(object): self.wrapper.prepare() # zest.releaser requirement. self.package = self.wrapper.vcs.name - def missing_tags(self, existing_sdists=None): + def missing_tags(self, existing_sdists=None, build_all=False): """Return difference between existing sdists and available tags.""" if existing_sdists is None: existing_sdists = [] @@ -86,7 +86,7 @@ class CheckoutDir(object): if tag.is_prerelease: logger.warn("Pre-release marker in tag: %s, ignoring", tag) continue - if tag in existing_sdists: + if tag in existing_sdists and not build_all: logger.debug( "Tag %s is already available, not looking further", tag ) diff --git a/tags2sdists/script.py b/tags2sdists/script.py index <HASH>..<HASH> 100644 --- a/tags2sdists/script.py +++ b/tags2sdists/script.py @@ -34,6 +34,14 @@ def main(): default=False, help="Show minimal output", ) + parser.add_option( + "-a", + "--build-all", + action="store_true", + dest="build_all", + default=False, + help="Build all releases (=don't stop if the newest tag is found)", + ) (options, args) = parser.parse_args() if len(args) != 2: @@ -67,7 +75,8 @@ def main(): # directory in our sdists dir :-) continue for tag in checkout_dir.missing_tags( - existing_sdists=package_dir.packages[package] + existing_sdists=package_dir.packages[package], + build_all=options.build_all, ): tarball = checkout_dir.create_sdist(tag) package_dir.add_tarball(tarball, package)
Added --build-all option: don't stop if the latest tag is found The default behaviour helps with mis-behaving old tags, but if all the packages are clean, --build-all make sure also bugfix releases for older versions are build.
lizardsystem_tags2sdists
train
b2667fbcdf6c112910e25f96163de977dc156af7
diff --git a/src/php/Qafoo/Analyzer/Command/Serve.php b/src/php/Qafoo/Analyzer/Command/Serve.php index <HASH>..<HASH> 100644 --- a/src/php/Qafoo/Analyzer/Command/Serve.php +++ b/src/php/Qafoo/Analyzer/Command/Serve.php @@ -21,14 +21,22 @@ class Serve extends Command InputOption::VALUE_REQUIRED, 'Port to start webserver on', 8080 + ) + ->addOption( + 'hostname', + null, // -h is already used for help + InputOption::VALUE_REQUIRED, + 'Hostname used to listen to', + 'localhost' ); } protected function execute(InputInterface $input, OutputInterface $output) { $port = (int) $input->getOption('port'); + $hostname = $input->getOption('hostname'); $baseDir = realpath(__DIR__ . '/../../../../../'); - $output->writeln("Starting webserver on http://localhost:$port/"); - passthru("/usr/bin/env php -S localhost:$port -t $baseDir $baseDir/bin/serve.php"); + $output->writeln("Starting webserver on http://$hostname:$port/"); + passthru("/usr/bin/env php -S $hostname:$port -t $baseDir $baseDir/bin/serve.php"); } }
Allow setting the hostname via a -h flag This should make it possible to use the app from i.e. inside a (docker) container for easy running... ``` docker run -it --rm -v $(pwd):/app -w /app -p <I>:<I> php:7-cli bin/analyze serve --hostname <I> ```
Qafoo_QualityAnalyzer
train
24ccf3e8ef3cdc4efbe5124eddae8cb7787edf6c
diff --git a/src/sap.ui.core/src/sap/ui/model/odata/v4/ODataListBinding.js b/src/sap.ui.core/src/sap/ui/model/odata/v4/ODataListBinding.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.core/src/sap/ui/model/odata/v4/ODataListBinding.js +++ b/src/sap.ui.core/src/sap/ui/model/odata/v4/ODataListBinding.js @@ -206,14 +206,7 @@ sap.ui.define([ } else { // absolute path this.oCache.read(iStart, iLength, function () { bDataRequested = true; - try { - that.fireDataRequested(); - } catch (e) { - jQuery.sap.log.warning("Call to 'dataRequested' event handler failed: " - + (e.message || e.toString()), - e.stack, // may be undefined: only supported in Chrome, FF - sClassName); - } + that.fireDataRequested(); }).then(createContexts.bind(undefined, getBasePath)).then(function () { //fire dataReceived after change event fired in createContexts() if (bDataRequested) { diff --git a/src/sap.ui.core/test/sap/ui/core/qunit/odata/v4/ODataListBinding.qunit.js b/src/sap.ui.core/test/sap/ui/core/qunit/odata/v4/ODataListBinding.qunit.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.core/test/sap/ui/core/qunit/odata/v4/ODataListBinding.qunit.js +++ b/src/sap.ui.core/test/sap/ui/core/qunit/odata/v4/ODataListBinding.qunit.js @@ -831,10 +831,6 @@ sap.ui.require([ this.oLogMock.expects("error") .withExactArgs("Failed to get contexts for /service/EMPLOYEES with start index 0 and " + "length 10", oError, "sap.ui.model.odata.v4.ODataListBinding"); - this.oLogMock.expects("warning") - .withExactArgs("Call to 'dataRequested' event handler failed: Expected Error in event" - + " handler", - /*stack trace*/ sinon.match.any, "sap.ui.model.odata.v4.ODataListBinding"); this.oSandbox.stub(Cache, "create", function (oRequestor, sUrl, mQueryOptions) { return { @@ -846,10 +842,6 @@ sap.ui.require([ }); oListBinding = this.oModel.bindList("/EMPLOYEES"); - oListBinding.attachDataRequested(function (oEvent) { - // do not break if event handler throws an error - throw new Error("Expected Error in event handler"); - }); oListBinding.attachDataReceived(function (oEvent) { assert.strictEqual(oEvent.getSource(), oListBinding, "oEvent.getSource()"); assert.strictEqual(oEvent.getParameter("error"), oError,
[INTERNAL] sap.ui.model.odata.v4.ODataListBinding: remove try/catch around fireDataRequested() After a discussion we decided not to catch errors resulting in the application code (event handler) PS1: PP SBE, PBU: remove try/catch after internal discussion Change-Id: Ia<I>d<I>c<I>fe<I>a<I>ea<I>de JIRA: FLPUISERVICES<I>-<I>
SAP_openui5
train
a8e6e4d4c161e6bb742f1ff6d50cfeb0352c0bc1
diff --git a/SingularityService/src/main/java/com/hubspot/singularity/mesos/SingularityMesosOfferScheduler.java b/SingularityService/src/main/java/com/hubspot/singularity/mesos/SingularityMesosOfferScheduler.java index <HASH>..<HASH> 100644 --- a/SingularityService/src/main/java/com/hubspot/singularity/mesos/SingularityMesosOfferScheduler.java +++ b/SingularityService/src/main/java/com/hubspot/singularity/mesos/SingularityMesosOfferScheduler.java @@ -1,9 +1,9 @@ package com.hubspot.singularity.mesos; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -16,8 +16,8 @@ import org.apache.mesos.Protos.Offer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Optional; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Provider; @@ -130,9 +130,9 @@ public class SingularityMesosOfferScheduler { while (!pendingTaskIdToTaskRequest.isEmpty() && addedTaskInLastLoop && canScheduleAdditionalTasks(taskCredits)) { addedTaskInLastLoop = false; - List<String> acceptedTasks = new ArrayList<>(); - for (SingularityTaskRequestHolder taskRequestHolder : pendingTaskIdToTaskRequest.values()) { + for (Iterator<SingularityTaskRequestHolder> iterator = pendingTaskIdToTaskRequest.values().iterator(); iterator.hasNext();) { + SingularityTaskRequestHolder taskRequestHolder = iterator.next(); Map<SingularityOfferHolder, Double> scorePerOffer = new HashMap<>(); double minScore = minScore(taskRequestHolder.getTaskRequest(), offerMatchAttemptsPerTask, System.currentTimeMillis()); @@ -172,14 +172,13 @@ public class SingularityMesosOfferScheduler { } bestOffer.addMatchedTask(task); addedTaskInLastLoop = true; - acceptedTasks.add(task.getTaskRequest().getPendingTask().getPendingTaskId().getId()); + iterator.remove(); if (useTaskCredits && taskCredits == 0) { LOG.info("Used all available task credits, not scheduling any more tasks"); break; } } } - acceptedTasks.forEach(pendingTaskIdToTaskRequest::remove); } if (useTaskCredits) { @@ -296,6 +295,7 @@ public class SingularityMesosOfferScheduler { private double scoreNonLongRunningTask(SingularityTaskRequest taskRequest, double longRunningMemUsedScore, double memTotalScore, double longRunningCpusUsedScore, double cpusTotalScore) { Optional<SingularityDeployStatistics> statistics = deployManager.getDeployStatistics(taskRequest.getRequest().getId(), taskRequest.getDeploy().getId()); + final double epsilon = 0.0001; double freeResourceWeight = 0.75; double usedResourceWeight = 0.25; @@ -304,7 +304,7 @@ public class SingularityMesosOfferScheduler { final double maxNonLongRunningUsedResourceWeight = configuration.getMaxNonLongRunningUsedResourceWeight(); usedResourceWeight = Math.min((double) TimeUnit.MILLISECONDS.toSeconds(statistics.get().getAverageRuntimeMillis().get()) / configuration.getConsiderNonLongRunningTaskLongRunningAfterRunningForSeconds(), 1) * maxNonLongRunningUsedResourceWeight; - if (usedResourceWeight == maxNonLongRunningUsedResourceWeight) { + if (Math.abs(usedResourceWeight - maxNonLongRunningUsedResourceWeight) < epsilon) { return scoreLongRunningTask(longRunningMemUsedScore, memTotalScore, longRunningCpusUsedScore, cpusTotalScore); } freeResourceWeight = 1 - usedResourceWeight;
switch to iterator and properly compare floats
HubSpot_Singularity
train
5790474cb5a44b8d0072c72180bc646e6ec15874
diff --git a/base-server.js b/base-server.js index <HASH>..<HASH> 100644 --- a/base-server.js +++ b/base-server.js @@ -1081,7 +1081,7 @@ module.exports = BaseServer * @callback authenticator * @param {string} userId User ID. * @param {any} credentials The client credentials. - * @param {Client} client Client object. + * @param {ServerClient} client Client object. * @return {boolean|Promise<boolean>} `true` if credentials was correct */
Fix class name in JSDoc
logux_server
train
0c3e2f0081805cf29c63f3463f4c32386b3aa85f
diff --git a/Kwf_js/EyeCandy/List/Plugins/Carousel.js b/Kwf_js/EyeCandy/List/Plugins/Carousel.js index <HASH>..<HASH> 100644 --- a/Kwf_js/EyeCandy/List/Plugins/Carousel.js +++ b/Kwf_js/EyeCandy/List/Plugins/Carousel.js @@ -1,5 +1,4 @@ Kwf.EyeCandy.List.Plugins.Carousel = Ext.extend(Kwf.EyeCandy.List.Plugins.Abstract, { - numberShown: 5, //animationConfig: { duration: 0.25 }, //fadeAnimationConfig: { duration: 0.25 }, //optional, by default animationConfig will be used useFade: true, //if elements will be faded in/out in addition to the moving @@ -7,6 +6,11 @@ Kwf.EyeCandy.List.Plugins.Carousel = Ext.extend(Kwf.EyeCandy.List.Plugins.Abstra _moveActive: false, init: function() { + var firstChild = this.list.items.length > 0 ? this.list.items[0] : null; + if (!firstChild) return false; + + var numberShown = Math.floor(this.list.el.getWidth()/firstChild.el.getWidth()); + Ext.applyIf(this, { animationConfig: { duration: 0.25 } }); @@ -21,33 +25,47 @@ Kwf.EyeCandy.List.Plugins.Carousel = Ext.extend(Kwf.EyeCandy.List.Plugins.Abstra this.moveElement = this.moveElement.child(this.moveElementSelector); } - if (this.list.items.length > this.numberShown) { - for(var i=this.numberShown; i<this.list.getItems().length; ++i) { + if (this.list.items.length > numberShown) { + for(var i=numberShown; i<this.list.getItems().length; ++i) { this.list.getItem(i).el.hide(); } } + + Ext.fly(window).on('resize', function() { + this.updateButtons(); + }, this) }, render: function() { - if (this.list.items.length > this.numberShown) { - this.list.el.createChild({ - tag: 'a', - cls: 'carouselPrevious', - href: '#' - }).on('click', function(ev) { - ev.stopEvent(); - this.onMovePrevious(); - }, this); - this.list.el.createChild({ - tag: 'a', - cls: 'carouselNext', - href: '#' - }).on('click', function(ev) { - ev.stopEvent(); - this.onMoveNext(); - }, this); - } + this.list.el.createChild({ + tag: 'a', + cls: 'carouselPrevious', + href: '#' + }).on('click', function(ev) { + ev.stopEvent(); + this.onMovePrevious(); + }, this); + this.list.el.createChild({ + tag: 'a', + cls: 'carouselNext', + href: '#' + }).on('click', function(ev) { + ev.stopEvent(); + this.onMoveNext(); + }, this); + + this.updateButtons(); }, + updateButtons: function() { + var numberShown = Math.floor(this.list.el.getWidth()/this.list.items[0].el.getWidth()); + if (this.list.items.length > numberShown) { + this.list.el.child('a.carouselPrevious').removeClass('deactivated'); + this.list.el.child('a.carouselNext').removeClass('deactivated'); + } else { + this.list.el.child('a.carouselPrevious').addClass('deactivated'); + this.list.el.child('a.carouselNext').addClass('deactivated'); + } + }, onMoveNext: function() { if (this._moveActive) return; this._moveActive = true;
Added responsive function for carousel - calculating the item to show on container width - hidding arrows if count equal or less item count
koala-framework_koala-framework
train
d243f3c4e54aa89c570102e7d69aea44c3bd5f0a
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index <HASH>..<HASH> 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1932,7 +1932,7 @@ class NDFrame(PandasObject): #---------------------------------------------------------------------- # Attribute access - def __finalize__(self, other, method=None): + def __finalize__(self, other, method=None, **kwargs): """ propagate metadata from other to self @@ -3404,7 +3404,7 @@ class NDFrame(PandasObject): """ return self.where(~cond, np.nan) - def shift(self, periods=1, freq=None, axis=0, **kwds): + def shift(self, periods=1, freq=None, axis=0, **kwargs): """ Shift index by desired number of periods with an optional time freq @@ -3430,10 +3430,10 @@ class NDFrame(PandasObject): return self block_axis = self._get_block_manager_axis(axis) - if freq is None and not len(kwds): + if freq is None and not len(kwargs): new_data = self._data.shift(periods=periods, axis=block_axis) else: - return self.tshift(periods, freq, **kwds) + return self.tshift(periods, freq, **kwargs) return self._constructor(new_data).__finalize__(self) @@ -3473,7 +3473,7 @@ class NDFrame(PandasObject): return new_obj.__finalize__(self) - def tshift(self, periods=1, freq=None, axis=0, **kwds): + def tshift(self, periods=1, freq=None, axis=0, **kwargs): """ Shift the time index, using the index's frequency if available @@ -3512,7 +3512,7 @@ class NDFrame(PandasObject): if periods == 0: return self - offset = _resolve_offset(freq, kwds) + offset = _resolve_offset(freq, kwargs) if isinstance(offset, string_types): offset = datetools.to_offset(offset) @@ -3894,28 +3894,28 @@ class NDFrame(PandasObject): @Appender(_shared_docs['pct_change'] % _shared_doc_kwargs) def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None, - **kwds): + **kwargs): # TODO: Not sure if above is correct - need someone to confirm. - axis = self._get_axis_number(kwds.pop('axis', self._stat_axis_name)) + axis = self._get_axis_number(kwargs.pop('axis', self._stat_axis_name)) if fill_method is None: data = self else: data = self.fillna(method=fill_method, limit=limit) rs = (data.div(data.shift(periods=periods, freq=freq, - axis=axis, **kwds)) - 1) + axis=axis, **kwargs)) - 1) if freq is None: mask = com.isnull(_values_from_object(self)) np.putmask(rs.values, mask, np.nan) return rs - def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwds): + def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwargs): grouped = self.groupby(level=level, axis=axis) if hasattr(grouped, name) and skipna: - return getattr(grouped, name)(**kwds) + return getattr(grouped, name)(**kwargs) axis = self._get_axis_number(axis) method = getattr(type(self), name) - applyf = lambda x: method(x, axis=axis, skipna=skipna, **kwds) + applyf = lambda x: method(x, axis=axis, skipna=skipna, **kwargs) return grouped.aggregate(applyf) @classmethod diff --git a/pandas/core/index.py b/pandas/core/index.py index <HASH>..<HASH> 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -415,7 +415,7 @@ class Index(IndexOpsMixin, PandasObject): quote_strings=True) return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype) - def to_series(self): + def to_series(self, **kwargs): """ Create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index
add back some kwargs usage, closes GH<I>
pandas-dev_pandas
train
30186a95118ffd9d98ddab4c7f5743afe654ad43
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -39,7 +39,7 @@ cmdclass = {'clean': CleanCommand} setup( name='loky', - version='0.3.0', + version='0.4.0.dev', description=("A robust implementation of " "concurrent.futures.ProcessPoolExecutor"), url='https://github.com/tommoral/loky/',
CLN switch back master to dev version
tomMoral_loky
train
576ee4d3099131e12aa56f7562de416393ad86f4
diff --git a/promql/engine.go b/promql/engine.go index <HASH>..<HASH> 100644 --- a/promql/engine.go +++ b/promql/engine.go @@ -29,6 +29,7 @@ import ( "github.com/go-kit/kit/log/level" opentracing "github.com/opentracing/opentracing-go" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/common/model" "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/pkg/timestamp" "github.com/prometheus/prometheus/pkg/value" @@ -1494,6 +1495,9 @@ func (ev *evaluator) aggregation(op ItemType, grouping []string, without bool, p var valueLabel string if op == itemCountValues { valueLabel = param.(string) + if !model.LabelName(valueLabel).IsValid() { + ev.errorf("invalid label name %q", valueLabel) + } if !without { grouping = append(grouping, valueLabel) } diff --git a/promql/engine_test.go b/promql/engine_test.go index <HASH>..<HASH> 100644 --- a/promql/engine_test.go +++ b/promql/engine_test.go @@ -23,6 +23,7 @@ import ( "github.com/go-kit/kit/log" "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/storage" + "github.com/prometheus/prometheus/util/testutil" ) func TestQueryConcurrency(t *testing.T) { @@ -267,11 +268,12 @@ load 10s } cases := []struct { - Query string - Result Value - Start time.Time - End time.Time - Interval time.Duration + Query string + Result Value + Start time.Time + End time.Time + Interval time.Duration + ShouldError bool }{ // Instant queries. { @@ -326,6 +328,10 @@ load 10s End: time.Unix(10, 0), Interval: 5 * time.Second, }, + { + Query: `count_values("wrong label!", metric)`, + ShouldError: true, + }, } for _, c := range cases { @@ -340,6 +346,10 @@ load 10s t.Fatalf("unexpected error creating query: %q", err) } res := qry.Exec(test.Context()) + if c.ShouldError { + testutil.NotOk(t, res.Err, "expected error for the query %q", c.Query) + continue + } if res.Err != nil { t.Fatalf("unexpected error running query: %q", res.Err) }
Label name check for 'count_values' (#<I>)
prometheus_prometheus
train
b0183dcb8e295e3c5938d8343f906b1b6d6d3b70
diff --git a/src/Queryyetsimple/Di/Container.php b/src/Queryyetsimple/Di/Container.php index <HASH>..<HASH> 100644 --- a/src/Queryyetsimple/Di/Container.php +++ b/src/Queryyetsimple/Di/Container.php @@ -208,10 +208,12 @@ class Container implements IContainer, ArrayAccess if (is_int($key)) { continue; } + $this->alias($key, $item); } } else { $value = (array) $value; + foreach ($value as $item) { $this->alias[$item] = $alias; } @@ -457,11 +459,7 @@ class Container implements IContainer, ArrayAccess if ($validArgs < $required) { throw new ContainerInvalidArgumentException( - sprintf( - 'There are %d required args,but %d gived.', - $required, - $validArgs - ) + sprintf('There are %d required args,but %d gived.', $required, $validArgs) ); } @@ -552,6 +550,7 @@ class Container implements IContainer, ArrayAccess protected function parseParameterClass(ReflectionParameter $param) { $classObject = $param->getClass(); + if (!$classObject || !($classObject instanceof ReflectionClass)) { return false; } @@ -574,7 +573,10 @@ class Container implements IContainer, ArrayAccess case $result = $this->parseClassNotExists($argsclass): break; default: - throw new InvalidArgumentException(sprintf('Class or interface %s is not register in container', $argsclass)); + throw new InvalidArgumentException( + sprintf('Class or interface %s is not register in container', $argsclass) + ); + break; } @@ -604,13 +606,23 @@ class Container implements IContainer, ArrayAccess if (class_exists($itemMake)) { $result = $this->make($itemMake); if (!is_object($result)) { - throw new InvalidArgumentException(sprintf('Class or interface %s is register in container is not object.', $argsclass)); + throw new InvalidArgumentException( + sprintf( + 'Class or interface %s is register in container is not object.', + $argsclass + ) + ); } return $result; } - throw new InvalidArgumentException(sprintf('Class or interface %s is not register in container', $argsclass)); + throw new InvalidArgumentException( + sprintf( + 'Class or interface %s is not register in container', + $argsclass + ) + ); } /** @@ -627,8 +639,14 @@ class Container implements IContainer, ArrayAccess } $result = $this->make($argsclass); + if (!is_object($result)) { - throw new InvalidArgumentException(sprintf('Class or interface %s is register in container is not object.', $argsclass)); + throw new InvalidArgumentException( + sprintf( + 'Class or interface %s is register in container is not object.', + $argsclass + ) + ); } return $result; @@ -701,7 +719,9 @@ class Container implements IContainer, ArrayAccess $reflection = new ReflectionClass($injection); if (!$reflection->isInstantiable()) { - throw new InvalidArgumentException(sprintf('Class %s is not instantiable.', $injection)); + throw new InvalidArgumentException( + sprintf('Class %s is not instantiable.', $injection) + ); } $param = []; @@ -723,11 +743,7 @@ class Container implements IContainer, ArrayAccess */ protected function newInstanceArgs($classname, $args) { - try { - return (new ReflectionClass($classname))->newInstanceArgs($args); - } catch (ReflectionException $e) { - return (new ReflectionClass($classname))->newInstanceWithoutConstructor(); - } + return (new ReflectionClass($classname))->newInstanceArgs($args); } /** diff --git a/tests/Di/ContainerTest.php b/tests/Di/ContainerTest.php index <HASH>..<HASH> 100644 --- a/tests/Di/ContainerTest.php +++ b/tests/Di/ContainerTest.php @@ -347,6 +347,61 @@ class ContainerTest extends TestCase $container->remove(Test8::class); $this->assertFalse($container->exists(Test8::class)); } + + public function testNotInstantiable() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Class Tests\Di\Test9 is not instantiable.' + ); + + $container = new Container(); + + $this->assertSame('world9', $container->make(Test9::class)->hello()); + } + + public function testUnsupportedCallbackTypes() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Unsupported callback types.' + ); + + $container = new Container(); + + $container->call(false); + } + + public function testMakeServiceBool() + { + $container = new Container(); + + $container->bind('foo', false); + + $this->assertFalse($container->make('foo')); + } + + public function testBindArrayAsAlias() + { + $container = new Container(); + + $container->bind(['foo' => 'bar'], false); + + $this->assertFalse($container->make('foo')); + $this->assertFalse($container->make('bar')); + } + + public function testParseReflectionException() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Class Tests\Di\TestNotFound does not exist' + ); + + $container = new Container(); + + $container->call([new Test10(), 'hello']); + } } class Test1 @@ -444,3 +499,23 @@ class Test8 implements ITest8 return ['call handle']; } } + +class Test9 +{ + protected function __construct() + { + } + + public function hello() + { + return 'world9'; + } +} + +class Test10 +{ + public function hello(TestNotFound $test) + { + return 'test10'; + } +}
di component tests coverage to <I>%
hunzhiwange_framework
train
4ed83131d5f9e84a98d14dc4482ba1ff7e8895e3
diff --git a/pandas/core/ops.py b/pandas/core/ops.py index <HASH>..<HASH> 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -408,8 +408,10 @@ Parameters ---------- other : Series or scalar value fill_value : None or float value, default None (NaN) - Fill missing (NaN) values with this value. If both Series are - missing, the result will be missing + Fill existing missing (NaN) values, and any new element needed for + successful Series alignment, with this value before computation. + If data in both corresponding Series locations is missing + the result will be missing level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level @@ -418,6 +420,30 @@ Returns ------- result : Series +Examples +-------- +>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd']) +>>> a +a 1.0 +b 1.0 +c 1.0 +d NaN +dtype: float64 +>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e']) +>>> b +a 1.0 +b NaN +d 1.0 +e NaN +dtype: float64 +>>> a.add(b, fill_value=0) +a 2.0 +b 1.0 +c 1.0 +d 1.0 +e NaN +dtype: float64 + See also -------- Series.{reverse} @@ -433,8 +459,10 @@ other : Series, DataFrame, or constant axis : {0, 1, 'index', 'columns'} For Series input, axis to match Series index on fill_value : None or float value, default None - Fill missing (NaN) values with this value. If both DataFrame locations are - missing, the result will be missing + Fill existing missing (NaN) values, and any new element needed for + successful DataFrame alignment, with this value before computation. + If data in both corresponding DataFrame locations is missing + the result will be missing level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level @@ -446,6 +474,33 @@ Mismatched indices will be unioned together Returns ------- result : DataFrame + +Examples +-------- +>>> a = pd.DataFrame([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'], + columns=['one']) +>>> a + one +a 1.0 +b 1.0 +c 1.0 +d NaN +>>> b = pd.DataFrame(dict(one=[1, np.nan, 1, np.nan], + two=[np.nan, 2, np.nan, 2]), + index=['a', 'b', 'd', 'e']) +>>> b + one two +a 1.0 NaN +b NaN 2.0 +d 1.0 NaN +e NaN 2.0 +>>> a.add(b, fill_value=0) + one two +a 2.0 NaN +b 1.0 2.0 +c 1.0 NaN +d 1.0 NaN +e NaN 2.0 """ _flex_doc_FRAME = """ @@ -460,8 +515,10 @@ other : Series, DataFrame, or constant axis : {{0, 1, 'index', 'columns'}} For Series input, axis to match Series index on fill_value : None or float value, default None - Fill missing (NaN) values with this value. If both DataFrame - locations are missing, the result will be missing + Fill existing missing (NaN) values, and any new element needed for + successful DataFrame alignment, with this value before computation. + If data in both corresponding DataFrame locations is missing + the result will be missing level : int or name Broadcast across a level, matching Index values on the passed MultiIndex level @@ -474,6 +531,33 @@ Returns ------- result : DataFrame +Examples +-------- +>>> a = pd.DataFrame([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'], + columns=['one']) +>>> a + one +a 1.0 +b 1.0 +c 1.0 +d NaN +>>> b = pd.DataFrame(dict(one=[1, np.nan, 1, np.nan], + two=[np.nan, 2, np.nan, 2]), + index=['a', 'b', 'd', 'e']) +>>> b + one two +a 1.0 NaN +b NaN 2.0 +d 1.0 NaN +e NaN 2.0 +>>> a.add(b, fill_value=0) + one two +a 2.0 NaN +b 1.0 2.0 +c 1.0 NaN +d 1.0 NaN +e NaN 2.0 + See also -------- DataFrame.{reverse} @@ -545,7 +629,6 @@ def _make_flex_doc(op_name, typ): base_doc = _flex_doc_PANEL else: raise AssertionError('Invalid typ argument.') - doc = base_doc.format(desc=op_desc['desc'], op_name=op_name, equiv=equiv, reverse=op_desc['reverse']) return doc
DOC: Clarify and add fill_value example in arithmetic ops (#<I>)
pandas-dev_pandas
train
e2e8bbbfdeda299f173c19c6c8fdd9725125d4e9
diff --git a/tests/integration/states/git.py b/tests/integration/states/git.py index <HASH>..<HASH> 100644 --- a/tests/integration/states/git.py +++ b/tests/integration/states/git.py @@ -197,6 +197,62 @@ class GitTest(integration.ModuleCase, integration.SaltReturnAssertsMixIn): finally: shutil.rmtree(name, ignore_errors=True) + def test_latest_fast_forward(self): + ''' + Test running git.latest state a second time after changes have been + made to the remote repo. + ''' + def _head(cwd): + return self.run_function('git.rev_parse', [cwd, 'HEAD']) + + repo_url = 'https://{0}/saltstack/salt-test-repo.git'.format(self.__domain) + mirror_dir = os.path.join(integration.TMP, 'salt_repo_mirror') + mirror_url = 'file://' + mirror_dir + admin_dir = os.path.join(integration.TMP, 'salt_repo_admin') + clone_dir = os.path.join(integration.TMP, 'salt_repo') + + try: + # Mirror the repo + self.run_function('git.clone', + [mirror_dir, repo_url, None, '--mirror']) + + # Make sure the directory for the mirror now exists + self.assertTrue(os.path.exists(mirror_dir)) + + # Clone the mirror twice, once to the admin location and once to + # the clone_dir + ret = self.run_state('git.latest', name=mirror_url, target=admin_dir) + self.assertSaltTrueReturn(ret) + ret = self.run_state('git.latest', name=mirror_url, target=clone_dir) + self.assertSaltTrueReturn(ret) + + # Make a change to the repo by editing the file in the admin copy + # of the repo and committing. + head_pre = _head(admin_dir) + with open(os.path.join(admin_dir, 'LICENSE'), 'a') as fp_: + fp_.write('Hello world!') + self.run_function('git.commit', [admin_dir, 'Added a line', '-a']) + # Make sure HEAD is pointing to a new SHA so we know we properly + # committed our change. + head_post = _head(admin_dir) + self.assertNotEqual(head_pre, head_post) + + # Push the change to the mirror + # NOTE: the test will fail if the salt-test-repo's default branch + # is changed. + self.run_function('git.push', [admin_dir, 'origin', 'develop']) + + # Re-run the git.latest state on the clone_dir + ret = self.run_state('git.latest', name=mirror_url, target=clone_dir) + self.assertSaltTrueReturn(ret) + + # Make sure that the clone_dir now has the correct SHA + self.assertEqual(head_post, _head(clone_dir)) + + finally: + for path in (mirror_dir, admin_dir, clone_dir): + shutil.rmtree(path, ignore_errors=True) + def test_present(self): ''' git.present
Add integration test for #<I>
saltstack_salt
train
e4d50db8e0a227d82b59fa4a0bb8c51fd5c824e2
diff --git a/lib/walker.js b/lib/walker.js index <HASH>..<HASH> 100644 --- a/lib/walker.js +++ b/lib/walker.js @@ -125,6 +125,12 @@ class Walker { for (const script of scripts) { const stat = await fs.stat(script); if (stat.isFile()) { + if (!isDotJS(script)) { + log.warn('Non-javascript file is specified in \'scripts\'.', [ + 'Pkg will probably fail to parse. Specify *.js in glob.', + script ]); + } + this.append({ file: script, marker: marker,
show a warning that css gets into 'scripts'. addresses #<I>
zeit_pkg
train
94b402d50f12413da4a4e70e028bd626117d39fe
diff --git a/src/Queries/BaseQuery.php b/src/Queries/BaseQuery.php index <HASH>..<HASH> 100644 --- a/src/Queries/BaseQuery.php +++ b/src/Queries/BaseQuery.php @@ -359,26 +359,30 @@ abstract class BaseQuery $oldFields = $results[$keyByValue]->fields; foreach ($oldFields as $field => $oldValue) { // пропускаем служебные поля. - if (in_array($field, ['_was_multiplied', 'PROPERTIES'])) { + if (in_array($field, ['_were_multiplied', 'PROPERTIES'])) { continue; } + $alreadyMultiplied = !empty($oldFields['_were_multiplied'][$field]); + // мультиплицируем только несовпадающие значения полей $newValue = $item[$field]; if ($oldValue !== $newValue) { - // если еще не мультиплицироваи объект то все поля надо превратить в массивы - if (empty($oldFields['_was_multiplied'])) { + // если еще не мультиплицировали поле, то его надо превратить в массив. + if (!$alreadyMultiplied) { $oldFields[$field] = [ $oldFields[$field] ]; + $oldFields['_were_multiplied'][$field] = true; } - // в любом случае добавляем новое значение полю - $oldFields[$field][] = $newValue; + // добавляем новое значению поле если такого еще нет. + if (empty($oldFields[$field]) || (is_array($oldFields[$field]) && !in_array($newValue, $oldFields[$field]))) { + $oldFields[$field][] = $newValue; + } } } - $oldFields['_was_multiplied'] = true; $results[$keyByValue]->fields = $oldFields; } } diff --git a/tests/ElementQueryTest.php b/tests/ElementQueryTest.php index <HASH>..<HASH> 100644 --- a/tests/ElementQueryTest.php +++ b/tests/ElementQueryTest.php @@ -131,7 +131,7 @@ class ElementQueryTest extends TestCase $expected = [ 1 => ['ID' => 1, 'PROPERTY_FOO_VALUE' => 'foo'], - 2 => ['ID' => 2, 'PROPERTY_FOO_VALUE' => ['bar', 'bar2', 'bar3'], '_was_multiplied' => true], + 2 => ['ID' => 2, 'PROPERTY_FOO_VALUE' => ['bar', 'bar2', 'bar3'], '_were_multiplied' => ['PROPERTY_FOO_VALUE' => true]], ]; foreach ($items as $k => $item) { $this->assertSame($expected[$k], $item->fields);
Fix multiple multimple props in Iblock 1
arrilot_bitrix-models
train
4b16d49adb2e0e032fc428bc3af34ab9eeac722d
diff --git a/js/colorpicker.js b/js/colorpicker.js index <HASH>..<HASH> 100644 --- a/js/colorpicker.js +++ b/js/colorpicker.js @@ -357,7 +357,7 @@ var igv = (function (igv) { $(this.container).offset( { left: (track_size.width - size.width)/2, top: track_origin.top } ); - this.headerBlurb.text(this.trackView.track.name); + //this.headerBlurb.text(this.trackView.track.name); this.previousTrackColorTile.css( { "background-color" : this.trackView.track.color } );
Remove track name from color picker header
igvteam_igv.js
train
0ca18df1994d249e9fa695ad7a306d9ff93fcc25
diff --git a/tests/unit/accounts/test_services.py b/tests/unit/accounts/test_services.py index <HASH>..<HASH> 100644 --- a/tests/unit/accounts/test_services.py +++ b/tests/unit/accounts/test_services.py @@ -366,6 +366,46 @@ class TestDatabaseUserService: user = UserFactory.create() assert not user_service.check_totp_value(user.id, b"123456") + def test_check_totp_global_rate_limited(self, user_service, metrics): + resets = pretend.stub() + limiter = pretend.stub(test=lambda: False, resets_in=lambda: resets) + user_service.ratelimiters["global"] = limiter + + with pytest.raises(TooManyFailedLogins) as excinfo: + user_service.check_totp_value(uuid.uuid4(), b"123456", tags=["foo"]) + + assert excinfo.value.resets_in is resets + assert metrics.increment.calls == [ + pretend.call("warehouse.authentication.two_factor.start", tags=["foo"]), + pretend.call( + "warehouse.authentication.two_factor.ratelimited", + tags=["foo", "ratelimiter:global"], + ), + ] + + def test_check_totp_value_user_rate_limited(self, user_service, metrics): + user = UserFactory.create() + resets = pretend.stub() + limiter = pretend.stub( + test=pretend.call_recorder(lambda uid: False), + resets_in=pretend.call_recorder(lambda uid: resets), + ) + user_service.ratelimiters["user"] = limiter + + with pytest.raises(TooManyFailedLogins) as excinfo: + user_service.check_totp_value(user.id, b"123456") + + assert excinfo.value.resets_in is resets + assert limiter.test.calls == [pretend.call(user.id)] + assert limiter.resets_in.calls == [pretend.call(user.id)] + assert metrics.increment.calls == [ + pretend.call("warehouse.authentication.two_factor.start", tags=[]), + pretend.call( + "warehouse.authentication.two_factor.ratelimited", + tags=["ratelimiter:user"], + ), + ] + class TestTokenService: def test_verify_service(self): diff --git a/warehouse/accounts/services.py b/warehouse/accounts/services.py index <HASH>..<HASH> 100644 --- a/warehouse/accounts/services.py +++ b/warehouse/accounts/services.py @@ -257,6 +257,28 @@ class DatabaseUserService: tags = tags if tags is not None else [] self._metrics.increment("warehouse.authentication.two_factor.start", tags=tags) + # The very first thing we want to do is check to see if we've hit our + # global rate limit or not, assuming that we've been configured with a + # global rate limiter anyways. + if not self.ratelimiters["global"].test(): + logger.warning("Global failed login threshold reached.") + self._metrics.increment( + "warehouse.authentication.two_factor.ratelimited", + tags=tags + ["ratelimiter:global"], + ) + raise TooManyFailedLogins(resets_in=self.ratelimiters["global"].resets_in()) + + # Now, check to make sure that we haven't hitten a rate limit on a + # per user basis. + if not self.ratelimiters["user"].test(user_id): + self._metrics.increment( + "warehouse.authentication.two_factor.ratelimited", + tags=tags + ["ratelimiter:user"], + ) + raise TooManyFailedLogins( + resets_in=self.ratelimiters["user"].resets_in(user_id) + ) + totp_secret = self.get_totp_secret(user_id) if totp_secret is None:
rate limit TOTP submission (#<I>) * rate limit TOTP submission * reorder rate limit checking, we already have user so no need to interleve db call between RL checks
pypa_warehouse
train
9e2488266a23485615ad7f854edb5371d5687704
diff --git a/lib/sputnik.js b/lib/sputnik.js index <HASH>..<HASH> 100644 --- a/lib/sputnik.js +++ b/lib/sputnik.js @@ -42,6 +42,9 @@ var Sputnik = function Sputnik (options) { this.anyBegin = []; this.anyEnd = []; + // Keep track of preventions + this.preventions = {}; + } /** diff --git a/lib/stage.js b/lib/stage.js index <HASH>..<HASH> 100644 --- a/lib/stage.js +++ b/lib/stage.js @@ -48,12 +48,24 @@ var Stage = function Stage (sputnik, name) { // Add the stage to the sputniks object sputnik.stages[name] = this; + // Things this stage prevents + this._prevent = []; + + // Indicate this stage was attempted to start, but prevented + this.prevented = false; + } Stage.prototype.begin = function begin (warnDuplicate) { if (typeof warnDuplicate == 'undefined') warnDuplicate = true; + // Do not start this stage if we're being prevented somewhere + if (this.sputnik.preventions[this.name]) { + this.prevented = true; + return; + } + if (!this.begun) { // Execute the any functions @@ -138,12 +150,17 @@ Stage.prototype.caller = function caller () { */ Stage.prototype.end = function end () { + var i; + this.stopTimeout(); + // Only do this once if (this.open) { + this.open = false; this.evaluate(); this.doQueue('after'); + } } @@ -186,7 +203,7 @@ Stage.prototype.doQueue = function doQueue (queueType) { for (var nr in q) { var p = q[nr]; - p.fnc(); + p.fnc.call(this); } // now remove them @@ -198,13 +215,71 @@ Stage.prototype.doQueue = function doQueue (queueType) { for (var i in this.sputnik.anyEnd) { this.sputnik.anyEnd[i](this); } + + // Now, un-prevent other stages + for (i = 0; i < this._prevent.length; i++) { + this.unprevent(this._prevent[i]); + } + } return true; } /** - * Execute a function before or after this stage + * Prevent another stage from running while this stage is busy + */ +Stage.prototype.prevent = function prevent (stageName) { + + if (typeof this.sputnik.preventions[stageName] == 'undefined') { + this.sputnik.preventions[stageName] = []; + } + + // Indicate the given stage needs to wait for this stage to end + if (this.sputnik.preventions[stageName].indexOf(this.name) == -1) { + this.sputnik.preventions[stageName].push(this.name); + } + + // Also store this in our own var + if (this._prevent.indexOf(stageName) == -1) { + this._prevent.push(stageName); + } + +} + +/** + * Unprevent a stage + */ +Stage.prototype.unprevent = function unprevent (stageName) { + + var p = this.sputnik.preventions[stageName], id, xStage; + + if (typeof p != 'undefined' && p instanceof Array) { + + id = p.indexOf(this.name); + + // If the id was found, remove it + if (id > -1) p.splice(id, 1); + + if (!p || !p.length) { + this.sputnik.preventions[stageName] = false; + } + } + + // If the stage is no longer being prevented by anything... + if (!this.sputnik.preventions[stageName]) { + + xStage = this.sputnik.getStage(stageName); + + // And it hasn't tried to started once before, begin it now + if (xStage.prevented) xStage.begin(); + + } + +} + +/** + * Execute a function before, after or during this stage */ Stage.prototype.when = function when (when, fnc, order) {
Add a "prevent" function, to make a stage wait to begin for another stage to end
skerit_sputnik
train
9c3b545d0898cd1d1cca526746cb4fcd87e02e1f
diff --git a/cnxarchive/tests/test_database.py b/cnxarchive/tests/test_database.py index <HASH>..<HASH> 100644 --- a/cnxarchive/tests/test_database.py +++ b/cnxarchive/tests/test_database.py @@ -1221,6 +1221,12 @@ INSERT INTO trees (parent_id, documentid, is_collated) WHERE module_ident = %s''', (new_module_ident,)) self.assertEqual(cursor.fetchone()[0], 0) + # Make sure there's no fulltext index info + cursor.execute('''SELECT count(*) + FROM modulefti WHERE module_ident = %s''', + (new_module_ident,)) + self.assertEqual(cursor.fetchone()[0], 0) + # Copy files for m42119 except *.html and index.cnxml cursor.execute('''\ SELECT f.file, m.filename, f.media_type @@ -1280,6 +1286,15 @@ INSERT INTO trees (parent_id, documentid, is_collated) html = index_htmls[0][0][:] self.assertIn('<html', html) + # Test that the generated index.cnxml.html was processed for fulltext search + cursor.execute('''SELECT module_idx, fulltext + FROM modulefti WHERE module_ident = %s''', + (new_module_ident,)) + idx, fulltext = cursor.fetchall()[0] + self.assertEqual(len(idx), 3545) + self.assertIn('Introduction to Science and the Realm of Physics, ' + 'Physical Quantities, and Units', fulltext) + @testing.db_connect def test_module_files_from_html(self, cursor): # Insert abstract with cnxml -- (this is tested elsewhere) @@ -1307,6 +1322,12 @@ INSERT INTO trees (parent_id, documentid, is_collated) WHERE module_ident = %s''', (new_module_ident,)) self.assertEqual(cursor.fetchone()[0], 0) + # Make sure there's no fulltext index info + cursor.execute('''SELECT count(*) + FROM modulefti WHERE module_ident = %s''', + (new_module_ident,)) + self.assertEqual(cursor.fetchone()[0], 0) + # Copy files for m42119 except *.html and *.cnxml cursor.execute(''' SELECT f.file, m.filename, f.media_type @@ -1369,6 +1390,15 @@ INSERT INTO trees (parent_id, documentid, is_collated) cnxml = index_cnxmls[0][0][:] self.assertIn('<document', cnxml) + # Test that the inserted index.cnxml.html was processed for fulltext search + cursor.execute('''SELECT module_idx, fulltext + FROM modulefti WHERE module_ident = %s''', + (new_module_ident,)) + idx, fulltext = cursor.fetchall()[0] + self.assertEqual(len(idx), 3556) + self.assertIn('Introduction to Science and the Realm of Physics, ' + 'Physical Quantities, and Units', fulltext) + @testing.db_connect def test_module_files_overwrite_index_html(self, cursor): # Insert a new version of an existing module @@ -1454,6 +1484,27 @@ INSERT INTO trees (parent_id, documentid, is_collated) self.assertEqual(custom_content, html) @testing.db_connect + def test_collated_fulltext_indexing_triggers(self, cursor): + """Verify that inserting a collated file association builds + the necessary indexes. This is used when a book is cooked. + """ + + cursor.execute('INSERT INTO collated_file_associations (context, item, fileid) ' + 'VALUES(18,19,108)') + # Verify that the inserted file has been indexed + cursor.execute('SELECT length(module_idx) ' + 'FROM collated_fti ' + 'WHERE context = 18 AND item = 19') + self.assertEqual(cursor.fetchone()[0], 55) + + cursor.execute('SELECT lexeme ' + 'FROM collated_fti_lexemes ' + 'WHERE context = 18 AND item = 19') + lexemes = cursor.fetchall() + self.assertEqual(len(lexemes), 55) + self.assertIn(('følger',), lexemes) + + @testing.db_connect def test_tree_to_json(self, cursor): """Verify the results of the ``tree_to_json_for_legacy`` sql function. This is used during a cnx-publishing publication.
add tests for fulltext indexing triggers
openstax_cnx-archive
train
a633a7b315763541175a0ac7749870cc8ae0296c
diff --git a/sgactions/browsers/Chrome/main.js b/sgactions/browsers/Chrome/main.js index <HASH>..<HASH> 100644 --- a/sgactions/browsers/Chrome/main.js +++ b/sgactions/browsers/Chrome/main.js @@ -47,7 +47,7 @@ var sendToBackground = function(msg) { window.addEventListener("message", function(e) { // TODO: Figure out why Firefox does not like looking at e.source - //if (e.source != window) return; // Must be from this page. + // if (e.source != window) return; // Must be from this page. if (!e.data.sgactions) return; // Must be sgactions. var msg = e.data.sgactions; diff --git a/sgactions/browsers/Chrome/page/core.js b/sgactions/browsers/Chrome/page/core.js index <HASH>..<HASH> 100644 --- a/sgactions/browsers/Chrome/page/core.js +++ b/sgactions/browsers/Chrome/page/core.js @@ -23,7 +23,6 @@ SGActions = { msg.src = 'page'; msg.dst = msg.dst || 'native'; // Send it to main.js (the content-script). - console.log('Posting', msg) window.postMessage({sgactions: msg}, '*') }, diff --git a/sgactions/browsers/Firefox/background.js b/sgactions/browsers/Firefox/background.js index <HASH>..<HASH> 100644 --- a/sgactions/browsers/Firefox/background.js +++ b/sgactions/browsers/Firefox/background.js @@ -19,39 +19,42 @@ exports.onUnload = function(reason) { } var proc = null; +var buffer = ''; var handleInput = function(data) { - if (!this.buffer) { - this.buffer = data + if (!buffer) { + buffer = data } else { - this.buffer += data + buffer += data } - while (this.buffer) { - var parts = this.buffer.match(/^([^\n\r]*)[\n\r]+(.*)$/) + while (buffer) { + + var parts = buffer.match(/^([^\n\r]*)[\n\r]+([\s\S]*)$/) if (!parts) { return } var raw = parts[1]; - this.buffer = parts[2] || ''; + buffer = parts[2] || ''; var msg = JSON.parse(raw) - console.error('DECODED:') - console.error(msg) // Dispatch it to the worker. - var id = msg.dst.tab_id; - var worker = workers[msg.dst.tab_id] + var id = msg.dst.tab_id + var worker = workers[id] msg.dst = msg.dst.next worker.port.emit('message', msg) + //console.error("DISPATCHED TO WORKER " + id) + } } var connectToNative = function() { + // TODO: FIX THIS. proc = spawn('/home/mikeb-local/dev/sgactions/sgactions/browsers/Chrome/native.sh', [self.id, 'Firefox'], { env: env, stdio: ['pipe', 'pipe', 2], @@ -72,7 +75,6 @@ var sendToNative = function(msg) { connectToNative() } var encoded = JSON.stringify(msg) - //console.error("sending message to native " + encoded.length) emit(proc.stdin, 'data', encoded + '\n') } diff --git a/sgactions/browsers/chrome_native/core.py b/sgactions/browsers/chrome_native/core.py index <HASH>..<HASH> 100644 --- a/sgactions/browsers/chrome_native/core.py +++ b/sgactions/browsers/chrome_native/core.py @@ -122,7 +122,6 @@ def main(): try: if _line_based: - log('reading from stdin') raw_msg = sys.stdin.readline() if not raw_msg: print >> sys.stderr, '[SGActions] native port closed' @@ -133,7 +132,7 @@ def main(): print >> sys.stderr, '[SGActions] native port closed' break size, = struct.unpack('I', raw_size) - print >> sys.stderr, '[SGActions] msg of size', raw_size + print >> sys.stderr, '[SGActions] reading message of size', raw_size raw_msg = sys.stdin.read(size) msg = json.loads(raw_msg) except Exception as e: diff --git a/sgactions/dispatch.py b/sgactions/dispatch.py index <HASH>..<HASH> 100644 --- a/sgactions/dispatch.py +++ b/sgactions/dispatch.py @@ -5,7 +5,10 @@ import sys import traceback import urlparse -#from metatools.imports import load_entrypoint +# HACK: Just for Mark Media for today. +sys.path.append('/home/mikeb-local/dev/metatools') + +from metatools.imports import load_entrypoint from . import utils from . import tickets
Fix message parsing so that we can receive multiple messages
vfxetc_sgactions
train
4bb779bd885fef7cb2f58f6524a0394fce432485
diff --git a/spec/sign_spec.rb b/spec/sign_spec.rb index <HASH>..<HASH> 100644 --- a/spec/sign_spec.rb +++ b/spec/sign_spec.rb @@ -229,7 +229,7 @@ describe 'dco sign' do stash_path = File.join(temp_path, '.git/logs/refs/stash') if File.exist?(stash_path) sleep(5) - command("erase #{temp_path}") + command("cmd.exe /c \"erase #{temp_path}\"") end expect(subject.exitstatus).to eq 0
Probably still won't work.
coderanger_dco
train
c0c4ada23b6e941acc9f4930d4a1dd90a41bd21a
diff --git a/lib/cli.js b/lib/cli.js index <HASH>..<HASH> 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -1,4 +1,5 @@ var fs = require('fs'); +var path = require('path'); Cli = (function() { @@ -18,7 +19,8 @@ Cli = (function() { CliObject.prototype.generateFileObject = function() { var filename = this.args.slice(2); - var templateName = filename.toString().split('/templates/').reverse()[0].replace('.handlebars', ''); + var templateName = filename.toString().split(path.sep + 'templates' + path.sep).reverse()[0].replace('.handlebars', ''); + var templateName = templateName.replace(path.sep, '/'); var template = fs.readFileSync(filename.toString(), 'utf8'); return {'name': templateName, 'content': template}; }; diff --git a/tests/cli.spec.js b/tests/cli.spec.js index <HASH>..<HASH> 100644 --- a/tests/cli.spec.js +++ b/tests/cli.spec.js @@ -1,4 +1,5 @@ require('../lib/cli'); +var path = require('path'); describe("CommandLineParser Tests", function() { @@ -25,31 +26,36 @@ describe("CommandLineParser Tests", function() { it("halt not invoked when valid filepath passed in", function() { var haltSpy = spyOn(Cli.prototype, 'haltProcessWithUsage'); - var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', 'file-system/app/templates/foo.handlebars']}); + var tpl = path.join('file-system', 'app', 'templates', 'foo.handlebars'); + var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', tpl]}); sut.parseCommandLineArgs(); expect(haltSpy).not.toHaveBeenCalledWith(); }); it("returns templateName without handlebars extension when valid filepath passed in", function() { - var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', 'file-system/app/templates/foo.handlebars']}); + var tpl = path.join('file-system', 'app', 'templates', 'foo.handlebars'); + var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', tpl]}); result = sut.parseCommandLineArgs(); expect(result['name']).toEqual('foo'); }); it("returns template content when valid filepath passed in and it exists on the filesystem", function() { - var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', 'file-system/app/templates/foo.handlebars']}); + var tpl = path.join('file-system', 'app', 'templates', 'foo.handlebars'); + var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', tpl]}); result = sut.parseCommandLineArgs(); expect(result['content']).toEqual('{{outlet}}\n'); }); it("returns templateName without handlebars extension for nested template", function() { - var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', 'file-system/app/templates/tables/index.handlebars']}); + var tpl = path.join('file-system', 'app', 'templates', 'tables', 'index.handlebars'); + var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', tpl]}); result = sut.parseCommandLineArgs(); expect(result['name']).toEqual('tables/index'); }); it("returns template content for nested template", function() { - var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', 'file-system/app/templates/tables/index.handlebars']}); + var tpl = path.join('file-system', 'app', 'templates', 'tables', 'index.handlebars'); + var sut = new Cli({args:['node', 'node_modules/django-ember-precompile/bin/django-ember-precompile', tpl]}); result = sut.parseCommandLineArgs(); expect(result['content']).toEqual('{{outlet}}\n'); });
change to use path.sep instead of hardcoded path separator
toranb_django-ember-precompile
train
86f9f4fccc6af40826f3f29eaf5cc9b90dc1b5b2
diff --git a/tests/integration/test_dot_venv.py b/tests/integration/test_dot_venv.py index <HASH>..<HASH> 100644 --- a/tests/integration/test_dot_venv.py +++ b/tests/integration/test_dot_venv.py @@ -90,3 +90,25 @@ def test_venv_file_with_path(PipenvInstance, pypi): venv_loc = Path(p.pipenv('--venv').out.strip()) assert venv_loc.joinpath('.project').exists() assert venv_loc == Path(venv_path.name) + + +@pytest.mark.dotvenv +def test_venv_file_with_relative_path(PipenvInstance, pypi): + """Tests virtualenv creation when a .venv file exists at the project root + and contains a relative path. + """ + with temp_environ(), PipenvInstance(chdir=True, pypi=pypi) as p: + if 'PIPENV_VENV_IN_PROJECT' in os.environ: + del os.environ['PIPENV_VENV_IN_PROJECT'] + + file_path = os.path.join(p.path, '.venv') + venv_path = 'foo/test-venv' + with open(file_path, 'w') as f: + f.write(venv_path) + + c = p.pipenv('install') + assert c.return_code == 0 + + venv_loc = Path(p.pipenv('--venv').out.strip()).resolve() + assert venv_loc.joinpath(".project").exists() + assert venv_loc == Path(venv_path).resolve()
add test for venv file with a relative path
pypa_pipenv
train
8f92b6b2cb2e4ec3af8783eb6bf4ff06f5a352cf
diff --git a/salt/client/ssh/__init__.py b/salt/client/ssh/__init__.py index <HASH>..<HASH> 100644 --- a/salt/client/ssh/__init__.py +++ b/salt/client/ssh/__init__.py @@ -63,7 +63,7 @@ SSH_SHIM = '''/bin/sh << 'EOF' then if [ $(cat /tmp/.salt/version) != {0} ] then - {{0}} rm -rf /tmp/.salt && {{0}} install -m 1777 -d /tmp/.salt + {{0}} rm -rf /tmp/.salt && install -m 1700 -d /tmp/.salt if [ $? -ne 0 ]; then exit 1 fi @@ -78,10 +78,15 @@ SSH_SHIM = '''/bin/sh << 'EOF' echo "Python too old" >&2 exit 1 fi - echo "{1}" - install -m 1700 -d /tmp/.salt - echo "deploy" - exit 1 + if [ -f /tmp/.salt/salt-thin.tgz ] + then + [ $({{1}} /etc/fstab | cut -f1 -d' ') == {{2}} ] && {{0}} tar xzvf /tmp/.salt/salt-thin.tgz -C /tmp/.salt + else + install -m 1700 -d /tmp/.salt + echo "{1}" + echo "deploy" + exit 1 + fi fi echo "{1}" {{0}} $PYTHON $SALT --local --out json -l quiet {{1}} @@ -424,9 +429,6 @@ class Single(object): self.shell.send( thin, '/tmp/.salt/salt-thin.tgz') - self.shell.exec_cmd( - 'tar xzvf /tmp/.salt/salt-thin.tgz -C /tmp/.salt' - ) return True def run(self, deploy_attempted=False):
Add untaring the thin tarball into the shim Also add hooks in to checksum the thin tarball
saltstack_salt
train
9a9889f54048acb57ac928b8b68e9ac6f5d5714e
diff --git a/src/ufoLib2/objects/glyph.py b/src/ufoLib2/objects/glyph.py index <HASH>..<HASH> 100644 --- a/src/ufoLib2/objects/glyph.py +++ b/src/ufoLib2/objects/glyph.py @@ -1,4 +1,5 @@ import attr +from copy import deepcopy from typing import Union, List, Any, Dict, Optional from ufoLib2.objects.anchor import Anchor from ufoLib2.objects.guideline import Guideline @@ -145,6 +146,28 @@ class Glyph(object): guideline = Guideline(**guideline) self._guidelines.append(guideline) + def copyDataFromGlyph(self, glyph): + """Deep-copy everything from the other glyph, except for the name. + Existing glyph data is overwritten. + + This method was added for compatibility with the defcon API, and + it may be removed in the future. + """ + self.width = glyph.width + self.height = glyph.height + self.unicodes = list(glyph.unicodes) + self.image = deepcopy(glyph.image) + self.note = glyph.note + self.lib = deepcopy(glyph.lib) + self.anchors = deepcopy(glyph.anchors) + self.guidelines = deepcopy(glyph.guidelines) + # NOTE: defcon's copyDataFromGlyph appends instead of overwrites here, + # but we do the right thing, for consistency with the rest. + self.clearContours() + self.clearComponents() + pointPen = self.getPointPen() + glyph.drawPoints(pointPen) + # ----------- # Pen methods # -----------
glyph: add copyDataFromGlyph method like in defcon I need to use this in glyphsLib so that I can do things like: new_glyph = font.newGlyph(b) new_glyph.copyDataFromGlyph(another_glyph)
fonttools_ufoLib2
train
55536d8453e048492553ff8d5a868d40f5692848
diff --git a/lib/outputlib.php b/lib/outputlib.php index <HASH>..<HASH> 100644 --- a/lib/outputlib.php +++ b/lib/outputlib.php @@ -2722,7 +2722,7 @@ class moodle_core_renderer extends moodle_renderer_base { foreach ($list->items as $listitem) { if ($listitem instanceof html_list) { - $output .= $this->output_start_tag('li'); + $output .= $this->output_start_tag('li', array()); $output .= $this->htmllist($listitem); $output .= $this->output_end_tag('li'); } else if ($listitem instanceof html_list_item) { diff --git a/lib/simpletest/testoutputlib.php b/lib/simpletest/testoutputlib.php index <HASH>..<HASH> 100644 --- a/lib/simpletest/testoutputlib.php +++ b/lib/simpletest/testoutputlib.php @@ -910,7 +910,7 @@ class moodle_core_renderer_test extends UnitTestCase { // Empty link object: link MUST have a text value $link = new html_link(); $popupaction = new popup_action('click', 'http://test.com', 'my_popup'); - $link->add_action_object($popupaction); + $link->add_action($popupaction); $this->expectException(); $html = $this->renderer->link_to_popup($link); } @@ -921,7 +921,7 @@ class moodle_core_renderer_test extends UnitTestCase { $link->url = 'http://test.com'; $link->title = 'Popup window'; $popupaction = new popup_action('click', 'http://test.com', 'my_popup'); - $link->add_action_object($popupaction); + $link->add_action($popupaction); $html = $this->renderer->link_to_popup($link); $expectedattributes = array('title' => 'Popup window', 'href' => 'http://test.com');
MDL-<I> Updated unit tests
moodle_moodle
train