hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
b2de090542e889da80860739b35cc5509b15d4f3
diff --git a/lib/reader.rb b/lib/reader.rb index <HASH>..<HASH> 100644 --- a/lib/reader.rb +++ b/lib/reader.rb @@ -229,6 +229,7 @@ module Authorization if block_given? @current_rule = rule yield + raise DSLError, "has_permission_on block content specifies no privileges" if rule.privileges.empty? # TODO ensure? @current_rule = nil end
Additional sanity checks on DSL syntax. By glongman
stffn_declarative_authorization
train
db728d0d32b3b94c45770216d4f269f8a93aa378
diff --git a/lib/active_mocker/generate.rb b/lib/active_mocker/generate.rb index <HASH>..<HASH> 100644 --- a/lib/active_mocker/generate.rb +++ b/lib/active_mocker/generate.rb @@ -106,7 +106,7 @@ class Generate end def delete_mocks - FileUtils.rm Dir.glob(File.join(mock_dir, '*.rb')) + FileUtils.rm Dir.glob(File.join(mock_dir, "*_#{mock_append_name.underscore}.rb")) end def mock_dir
Will only delete files in the mocks directory if they end with the mock_append_name.
zeisler_active_mocker
train
2885f925a2401d2609336f01bf59bd988cbd5368
diff --git a/lib/gimme/method_resolver.rb b/lib/gimme/method_resolver.rb index <HASH>..<HASH> 100644 --- a/lib/gimme/method_resolver.rb +++ b/lib/gimme/method_resolver.rb @@ -3,21 +3,31 @@ module Gimme class MethodResolver def self.resolve_sent_method(double,sym,args,raises_no_method_error=true) cls = double.cls - sym = args.shift if sym == :send + sym = args.shift if sym == :send if cls && raises_no_method_error - if cls.private_methods.include?(sym.to_s) + if cls.private_methods.include?(named(sym)) raise NoMethodError.new("#{sym} is a private method of your #{cls} test double, so stubbing/verifying it might not be a great idea. If you want to try to stub or verify this method anyway, then you can - invoke give! or verify! to suppress this error.") - elsif !cls.instance_methods.include?(sym.to_s) - raise NoMethodError.new("Your test double of #{cls} may not know how to respond to the '#{sym}' method. + invoke give! or verify! to suppress this error.") + elsif !cls.instance_methods.include?(named(sym)) + raise NoMethodError.new("Your test double of #{cls} may not know how to respond to the '#{sym}' method. If you're confident that a real #{cls} will know how to respond to '#{sym}', then you can - invoke give! or verify! to suppress this error.") + invoke give! or verify! to suppress this error.") end end sym end + + if RUBY_VERSION >= "1.9.2" + def self.named(sym) + sym + end + else + def self.named(sym) + sym.to_s + end + end end -end \ No newline at end of file +end
Check for existing method based on the Ruby version.
searls_gimme
train
657c1c1bf7f675a6ed1fa4f810b11ee16b096893
diff --git a/lib/cxxproject/buildingblocks/linkable.rb b/lib/cxxproject/buildingblocks/linkable.rb index <HASH>..<HASH> 100644 --- a/lib/cxxproject/buildingblocks/linkable.rb +++ b/lib/cxxproject/buildingblocks/linkable.rb @@ -98,8 +98,8 @@ module Cxxproject when HasLibraries::SEARCH_PATH tmp, prefix = adapt_path(elem[1], d, prefix) libraries << tmp - libraries << @tcs[:ENV][:LIB_SEPARATOR] libraries << @tcs[:ENV][:LIB_SEPARATOR][target_os] + libraries << File::PATH_SEPARATOR end end end diff --git a/lib/cxxproject/toolchain/provider.rb b/lib/cxxproject/toolchain/provider.rb index <HASH>..<HASH> 100644 --- a/lib/cxxproject/toolchain/provider.rb +++ b/lib/cxxproject/toolchain/provider.rb @@ -109,7 +109,6 @@ module Cxxproject :ENV => { :LIB_VAR=> {:UNIX => 'LD_LIBRARY_PATH', :OSX => 'DYLD_LIBRARY_PATH', :WINDOWS => ''}, - :LIB_SEPARATOR => {:UNIX => ":", :OSX => ':', :WINDOWS => ''} }, :CONSOLE_HIGHLIGHTER => ColorizingFormatter.new }
Use File::PATH_SEPARATOR
marcmo_cxxproject
train
3ac4e4502903e4d8731dc9ce59a830074b0632b1
diff --git a/lib/active_scaffold/data_structures/association.rb b/lib/active_scaffold/data_structures/association.rb index <HASH>..<HASH> 100644 --- a/lib/active_scaffold/data_structures/association.rb +++ b/lib/active_scaffold/data_structures/association.rb @@ -63,11 +63,7 @@ module ActiveScaffold::DataStructures def readonly? return false unless @type == :active_record - if scope_values.key? :readonly - scope_values[:readonly] - else - through? - end + scope_values[:readonly] end delegate :name, :klass, :foreign_key, :==, to: :@association diff --git a/lib/active_scaffold/helpers/form_column_helpers.rb b/lib/active_scaffold/helpers/form_column_helpers.rb index <HASH>..<HASH> 100644 --- a/lib/active_scaffold/helpers/form_column_helpers.rb +++ b/lib/active_scaffold/helpers/form_column_helpers.rb @@ -213,8 +213,9 @@ module ActiveScaffold end def column_show_add_new(column, associated, record) - value = (column.association.collection? && !column.association.readonly?) || column.association.singular? - value &&= false unless column.association.klass.authorized_for?(:crud_type => :create) + assoc = column.association + value = (assoc.collection? && !assoc.readonly? && !assoc.through?) || assoc.singular? + value &&= false unless assoc.klass.authorized_for?(:crud_type => :create) value end
readonly not return true for through association
activescaffold_active_scaffold
train
45e4f72394949128764d46e13d1f3c5ba06b9b31
diff --git a/Type/CaptchaType.php b/Type/CaptchaType.php index <HASH>..<HASH> 100644 --- a/Type/CaptchaType.php +++ b/Type/CaptchaType.php @@ -110,7 +110,7 @@ class CaptchaType extends AbstractType )); $persistOptions = array(); - foreach (array('phrase', 'width', 'height', 'distortion', 'quality') as $key) { + foreach (array('phrase', 'width', 'height', 'distortion', 'length', 'quality') as $key) { $persistOptions[$key] = $options[$key]; }
[CaptchaType] Adding length to the persisted options to work with as_url (see #<I>)
Gregwar_CaptchaBundle
train
5afdf2945b345502d781831955014759a8a611c5
diff --git a/util/batch/general/system.py b/util/batch/general/system.py index <HASH>..<HASH> 100644 --- a/util/batch/general/system.py +++ b/util/batch/general/system.py @@ -80,7 +80,6 @@ class NodesState(): - class NodeSetup: def __init__(self, memory=None, node_kind=None, nodes=None, cpus=None, nodes_max=float('inf'), nodes_leave_free=0, total_cpus_min=1, total_cpus_max=float('inf'), check_for_better=False, walltime=None): @@ -258,8 +257,6 @@ class NodeSetupIncompleteError(Exception): - - class BatchSystem(): def __init__(self, commands, queues, max_walltime={}, module_renaming={}, node_infos={}): @@ -274,7 +271,6 @@ class BatchSystem(): self.node_infos = node_infos - @property def mpi_command(self): return self.commands['mpirun'] @@ -388,6 +384,7 @@ class BatchSystem(): command = self.mpi_command.format(command=command, cpus=cpus) return command + ## best node setups def speed(self, node_kind, nodes, cpus): @@ -477,7 +474,6 @@ class BatchSystem(): assert cpus is None or best_cpus == cpus or best_cpus == 0 return (best_nodes, best_cpus) - def best_cpu_configurations(self, memory_required, node_kind=None, nodes=None, cpus=None, nodes_max=float('inf'), nodes_leave_free=0, total_cpus_max=float('inf'), walltime=None): @@ -567,6 +563,7 @@ class BatchSystem(): raise NotImplementedError() + class Job(): def __init__(self, batch_system, output_dir, force_load=False, max_job_name_len=80, exceeded_walltime_error_message=None): @@ -588,14 +585,14 @@ class Job(): ## load option file if existing or forced if force_load or os.path.exists(option_file_expanded): - self.__options = util.options.Options(option_file_expanded, mode='r+', replace_environment_vars_at_get=True) + self.__options = util.options.OptionsFile(option_file_expanded, mode='r+', replace_environment_vars_at_get=True) logger.debug('Job {} loaded.'.format(option_file_expanded)) ## make new job options file otherwise else: os.makedirs(output_dir_expanded, exist_ok=True) - self.__options = util.options.Options(option_file_expanded, mode='w-', replace_environment_vars_at_get=True) + self.__options = util.options.OptionsFile(option_file_expanded, mode='w-', replace_environment_vars_at_get=True) self.options['/job/output_file'] = os.path.join(output_dir, 'job_output.txt') self.options['/job/option_file'] = os.path.join(output_dir, 'job_options.txt') @@ -629,7 +626,6 @@ class Job(): return job_str - @property def options(self): return self.__options
API: util.options: 'Options' renamed in 'OptionsFile'
jor-_util
train
5a30305fbc1b923c687f049c65c66ad20fef153b
diff --git a/lib/compact_index/versions_file.rb b/lib/compact_index/versions_file.rb index <HASH>..<HASH> 100644 --- a/lib/compact_index/versions_file.rb +++ b/lib/compact_index/versions_file.rb @@ -49,7 +49,7 @@ class CompactIndex::VersionsFile def parse_gems_for_create(gems) fixed_format_gems = gems.map do |k,v| - numbers = v.map { |x| x[:number] } + numbers = v.map { |x| [x[:number], x[:platform] ] } { name: k, versions: numbers, checksum: v.first[:checksum] } end fixed_format_gems.sort! { |a,b| a[:name] <=> b[:name] } diff --git a/spec/versions_file_spec.rb b/spec/versions_file_spec.rb index <HASH>..<HASH> 100644 --- a/spec/versions_file_spec.rb +++ b/spec/versions_file_spec.rb @@ -31,7 +31,7 @@ describe CompactIndex::VersionsFile do ], "gem2" => [ build_version(number: "1.0.1"), - build_version(number: "1.0.2-arch") + build_version(number: "1.0.2", platform: 'arch') ] } end @@ -141,7 +141,7 @@ describe CompactIndex::VersionsFile do it "receive extra gems" do extra_gems = {"gem3" => [ build_version( { created_at: gem_time, number: "1.0.1" } ), - build_version( { created_at: gem_time, number: "1.0.2-arch" } ) + build_version( { created_at: gem_time, number: "1.0.2", platform: 'arch' } ) ]} expect( versions_file.contents(extra_gems)
Fix parse_gems_for_create to also handle separate platform and version
bundler_compact_index
train
4b149e219b62defc34f755f8ad28720c7cdcc9e5
diff --git a/src/Behat/Mink/Driver/SahiDriver.php b/src/Behat/Mink/Driver/SahiDriver.php index <HASH>..<HASH> 100644 --- a/src/Behat/Mink/Driver/SahiDriver.php +++ b/src/Behat/Mink/Driver/SahiDriver.php @@ -422,7 +422,7 @@ JS; JS; $value = $this->evaluateScript($function); - if ('' === $value) { + if ('' === $value || false === $value) { return array(); } else { return explode(',', $value);
Fix bug with multiselects
minkphp_MinkSahiDriver
train
530307b895441e0250c4d71e664c5fb78f02ab27
diff --git a/mopidy_youtube/apis/youtube_bs4api.py b/mopidy_youtube/apis/youtube_bs4api.py index <HASH>..<HASH> 100644 --- a/mopidy_youtube/apis/youtube_bs4api.py +++ b/mopidy_youtube/apis/youtube_bs4api.py @@ -211,6 +211,7 @@ class bs4API(scrAPI): "search_query": '"' + id + '"', "sp": "EgIQAQ%3D%3D", "app": "desktop", + "persist_app": 1, } for id in ids # This may be more exact: @@ -237,6 +238,7 @@ class bs4API(scrAPI): "search_query": '"' + id + '"', "sp": "EgIQAw%3D%3D", "app": "desktop", + "persist_app": 1, } for id in ids ]
add a couple more "persist_app": 1, I'm going to pay for doing this using the GitHub web interface, I'm sure...
mopidy_mopidy-youtube
train
d84149677893e83a402db72378267551c131280d
diff --git a/mhctools/base_commandline_predictor.py b/mhctools/base_commandline_predictor.py index <HASH>..<HASH> 100644 --- a/mhctools/base_commandline_predictor.py +++ b/mhctools/base_commandline_predictor.py @@ -47,6 +47,7 @@ class BaseCommandlinePredictor(BasePredictor): input_fasta_flag, length_flag, allele_flag, + peptide_mode_flags=["-p"], tempdir_flag=None, extra_flags=[], max_sequences_per_fasta_file=10**4, @@ -80,6 +81,10 @@ class BaseCommandlinePredictor(BasePredictor): allele_flag : str How to specify the allele we want predictions for (e.g. "-a") + peptide_mode_flags : list of str + How to switch from the default FASTA subsequences input mode to + where peptides are explicitly given one per line of a text file. + tempdir_flag : str, optional How to specify the predictor's temporary directory (e.g. "-tdir") diff --git a/mhctools/iedb.py b/mhctools/iedb.py index <HASH>..<HASH> 100644 --- a/mhctools/iedb.py +++ b/mhctools/iedb.py @@ -154,7 +154,6 @@ class IedbBasePredictor(BasePredictor): self.prediction_method) def _get_iedb_request_params(self, sequence, allele): - params = { "method": seq_to_str(self.prediction_method), "length": seq_to_str(self.default_peptide_lengths), @@ -164,13 +163,17 @@ class IedbBasePredictor(BasePredictor): } return params - def predict_peptides(self, peptides, source_sequence_names=None, offsets=None): + def _prepare_peptides_inputs(): if source_sequence_names is None: source_sequence_names = [None] * len(peptides) if offsets is None: offsets = [0] * len(peptides) assert len(peptides) == len(source_sequence_names) == len(offsets) + def predict_peptides(self, peptides, source_sequence_names=None, offsets=None): + peptides, source_sequence_names, offsets = \ + self._prepare_peptides_inputs(peptides, source_sequence_names, offsets) + binding_predictions = [] for peptide, name, offset in zip(peptides, source_sequence_names, offsets): peptide_binding_predictions = self.predict_subsequences(
working on Netmhc input mode
openvax_mhctools
train
025f6a780e672b372df8e637a96c02d4821c7892
diff --git a/spyderlib/widgets/sourcecode/syntaxhighlighters.py b/spyderlib/widgets/sourcecode/syntaxhighlighters.py index <HASH>..<HASH> 100644 --- a/spyderlib/widgets/sourcecode/syntaxhighlighters.py +++ b/spyderlib/widgets/sourcecode/syntaxhighlighters.py @@ -817,26 +817,6 @@ class HtmlSH(BaseWebSH): """HTML Syntax Highlighter""" PROG = re.compile(make_html_patterns(), re.S) -#============================================================================== -# CSS highlighter -#============================================================================== - -def make_css_patterns(): - """Strongly inspired from idlelib.ColorDelegator.make_pat """ - tags = any("builtin", [r"^[^{}/*:;]+$", - r"(?<=}\/).*?(?={)", - r"[^}]+?(?={)"]) - keywords = any("keyword", [r"[\w-]+?(?=:)"]) - string = any("string", [r"(?<=:).+?(?=;)"]) - comment = any("comment", [r"/\*(.*?)\*/"]) - multiline_comment_start = any("multiline_comment_start", [r"\/\*"]) - multiline_comment_end = any("multiline_comment_end", [r"\*\/"]) - return "|".join([tags, keywords, string, comment, - multiline_comment_start, multiline_comment_end]) - -class CssSH(BaseWebSH): - """CSS Syntax Highlighter""" - PROG = re.compile(make_css_patterns(), re.S) #============================================================================== # Pygments based omni-parser @@ -915,6 +895,10 @@ class IniSH(PygmentsSH): class XmlSH(PygmentsSH): """XML highlighter""" _lang_name = 'xml' + +class CssSH(PygmentsSH): + """CSS Syntax Highlighter""" + _lang_name = 'css' class MatlabSH(PygmentsSH): """Matlab highlighter"""
Editor: CSS syntax highlighter was buggy (multiline comments) and replaced by a pygments lexer (CSS syntax highlighting in Spyder will thus require pygments) Update Issue <I> Status: Fixed
spyder-ide_spyder
train
5ba79aadbd43176b74a4f25ab3a13c9390ff9235
diff --git a/lib/commands/context.js b/lib/commands/context.js index <HASH>..<HASH> 100644 --- a/lib/commands/context.js +++ b/lib/commands/context.js @@ -1,7 +1,7 @@ import { iosCommands, IOSPerformanceLog, NATIVE_WIN, WEBVIEW_WIN } from 'appium-ios-driver'; import { createRemoteDebugger, RemoteDebugger } from 'appium-remote-debugger'; import { errors, isErrorType } from 'appium-base-driver'; -import { util } from 'appium-support'; +import { util, timing } from 'appium-support'; import log from '../logger'; import { retryInterval } from 'asyncbox'; import _ from 'lodash'; @@ -105,6 +105,11 @@ commands.setContext = async function setContext (name, callback, skipReadyCheck) return context === NATIVE_WIN || context === null; } + // allow the full context list to be passed in + if (name && name.id) { + name = name.id; + } + log.debug(`Attempting to set context to '${name || NATIVE_WIN}' from '${this.curContext ? this.curContext : NATIVE_WIN}'`); if (alreadyInContext(name, this.curContext) || alreadyInContext(_.replace(name, WEBVIEW_BASE, ''), this.curContext)) { @@ -248,15 +253,42 @@ extensions.listWebFrames = async function listWebFrames (useUrl = true) { /** * Get the contexts available, with information about the url and title of each * webview + * + * @param {Object} opts - Options set, which can include `waitForWebviewMs` to + * specify the period to poll for available webviews * @returns {Array} List of Context objects */ -extensions.mobileGetContexts = async function mobileGetContexts () { +extensions.mobileGetContexts = async function mobileGetContexts (opts = {}) { + let { + waitForWebviewMs = 0, + } = opts; + + // make sure it is a number, so the duration check works properly + if (!_.isNumber(waitForWebviewMs)) { + waitForWebviewMs = parseInt(waitForWebviewMs, 10); + if (isNaN(waitForWebviewMs)) { + waitForWebviewMs = 0; + } + } + const curOpt = this.opts.fullContextList; + // `appium-ios-driver#getContexts` returns the full list of contexts + // if this option is on + this.opts.fullContextList = true; + + const timer = new timing.Timer().start(); try { - // `appium-ios-driver#getContexts` returns the full list of contexts - // if this option is on - this.opts.fullContextList = true; - return await this.getContexts(); + let contexts; + do { + contexts = await this.getContexts(); + + if (contexts.length >= 2) { + log.debug(`Found webview context after ${timer.getDuration().asMilliSeconds.toFixed(0)}ms`); + return contexts; + } + log.debug(`No webviews found in ${timer.getDuration().asMilliSeconds.toFixed(0)}ms`); + } while (timer.getDuration().asMilliSeconds < waitForWebviewMs); + return contexts; } finally { // reset the option so there are no side effects this.opts.fullContextList = curOpt; diff --git a/test/functional/basic/basic-e2e-specs.js b/test/functional/basic/basic-e2e-specs.js index <HASH>..<HASH> 100644 --- a/test/functional/basic/basic-e2e-specs.js +++ b/test/functional/basic/basic-e2e-specs.js @@ -299,9 +299,8 @@ describe('XCUITestDriver - basics -', function () { describe('contexts -', function () { before(async function () { - const el = await driver.elementByAccessibilityId('Web View'); - await driver.execute('mobile: scroll', {element: el, toVisible: true}); - await el.click(); + await driver.execute('mobile: scroll', {direction: 'down'}); + await driver.elementByAccessibilityId('Web View').click(); }); after(async function () { await driver.back(); @@ -309,12 +308,8 @@ describe('XCUITestDriver - basics -', function () { }); it('should start a session, navigate to url, get title', async function () { - const contexts = await retryInterval(100, 1000, async function () { - // on some systems (like Travis) it takes a while to load the webview - const contexts = await driver.contexts(); - contexts.length.should.be.at.least(2); - return contexts; - }); + // on some systems (like Travis) it takes a while to load the webview + const contexts = await driver.execute('mobile: getContexts', {waitForWebviewMs: 30000}); await driver.context(contexts[1]); await driver.get(GUINEA_PIG_PAGE);
feat: add option for wait duration for mobile context list (#<I>) * feat: add option for wait duration for mobile context list * return an array * make sure getting contexts happens once
appium_appium-xcuitest-driver
train
0bc4a38e48969513c524ff4795daecf2576725cf
diff --git a/__tests__/src/getPropLiteralValue-test.js b/__tests__/src/getPropLiteralValue-test.js index <HASH>..<HASH> 100644 --- a/__tests__/src/getPropLiteralValue-test.js +++ b/__tests__/src/getPropLiteralValue-test.js @@ -80,6 +80,15 @@ describe('getLiteralPropValue', () => { assert.equal(expected, actual); }); + it('should convert "TrUE" to boolean type', () => { + const prop = extractProp('<div foo="TrUE" />'); + + const expected = true; + const actual = getLiteralPropValue(prop); + + assert.equal(expected, actual); + }); + it('should convert "false" to boolean type', () => { const prop = extractProp('<div foo="false" />'); @@ -89,6 +98,15 @@ describe('getLiteralPropValue', () => { assert.equal(expected, actual); }); + it('should convert "FaLsE" to boolean type', () => { + const prop = extractProp('<div foo="FaLsE" />'); + + const expected = false; + const actual = getLiteralPropValue(prop); + + assert.equal(expected, actual); + }); + it('should return String null when value is null', () => { const prop = extractProp('<div foo={null} />'); diff --git a/src/values/Literal.js b/src/values/Literal.js index <HASH>..<HASH> 100644 --- a/src/values/Literal.js +++ b/src/values/Literal.js @@ -7,9 +7,10 @@ export default function extractValueFromLiteral(value) { const { value: extractedValue } = value; - if (extractedValue === 'true') { + const normalizedStringValue = typeof extractedValue === 'string' && extractedValue.toLowerCase(); + if (normalizedStringValue === 'true') { return true; - } else if (extractedValue === 'false') { + } else if (normalizedStringValue === 'false') { return false; }
Normalize literal string value before converting to boolean (#<I>) Fixes #<I>
evcohen_jsx-ast-utils
train
584fb319b311ea9013f0dad52b102df065c8d0cb
diff --git a/lib/atdis/models/event.rb b/lib/atdis/models/event.rb index <HASH>..<HASH> 100644 --- a/lib/atdis/models/event.rb +++ b/lib/atdis/models/event.rb @@ -3,14 +3,14 @@ module ATDIS class Event < Model set_field_mappings ({ id: String, - date: DateTime, + timestamp: DateTime, description: String, event_type: String, status: String }) # Mandatory parameters - validates :id, :date, :description, presence_before_type_cast: {spec_section: "4.3.4"} + validates :id, :timestamp, :description, presence_before_type_cast: {spec_section: "4.3.4"} end # TODO Check that :id is unique within an authority diff --git a/spec/atdis/models/event_spec.rb b/spec/atdis/models/event_spec.rb index <HASH>..<HASH> 100644 --- a/spec/atdis/models/event_spec.rb +++ b/spec/atdis/models/event_spec.rb @@ -2,7 +2,7 @@ require "spec_helper" describe ATDIS::Models::Event do it ".attribute_names" do - ATDIS::Models::Event.attribute_names.should == ["id", "date", "description", "event_type", "status"] + ATDIS::Models::Event.attribute_names.should == ["id", "timestamp", "description", "event_type", "status"] end it ".id" do @@ -10,7 +10,7 @@ describe ATDIS::Models::Event do end it ".date" do - ATDIS::Models::Event.interpret(date: "2013-06-18").date.should == DateTime.new(2013,6,18) + ATDIS::Models::Event.interpret(timestamp: "2013-06-18").timestamp.should == DateTime.new(2013,6,18) end it ".description" do
Attribute has been renamed as per the spec
openaustralia_atdis
train
a03d49cbf16940707f4734e8440d106304bafd68
diff --git a/lib/jets/controller/rendering.rb b/lib/jets/controller/rendering.rb index <HASH>..<HASH> 100644 --- a/lib/jets/controller/rendering.rb +++ b/lib/jets/controller/rendering.rb @@ -72,7 +72,8 @@ class Jets::Controller end def actual_host - headers["host"] + # actually host is in headers["origin"] when cloudfront is in front + headers["origin"] || headers["host"] end end
use headers origin for actual host in case of cloudfront in front
tongueroo_jets
train
7c9796e693939c651a6eb5a3d50ac94a7bbcc58c
diff --git a/lib/ecwid_api/error.rb b/lib/ecwid_api/error.rb index <HASH>..<HASH> 100644 --- a/lib/ecwid_api/error.rb +++ b/lib/ecwid_api/error.rb @@ -4,7 +4,7 @@ module EcwidApi class ResponseError < Error def initialize(response) if response.respond_to?(:reason_phrase) - super("#{response.reason_phrase} (#{response.status})") + super "#{response.reason_phrase} (#{response.status})\n#{response.body}" else super "The Ecwid API responded with an error (#{response.status})" end
Adds the response body when an Exception occurs
davidbiehl_ecwid_api
train
335f9e683b91cd68d7e33c2b64cd586202fe8387
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -26,7 +26,10 @@ module.exports.pitch = function(remainingRequest) { // Change the request from an /abolute/path.js to a relative ./path.js // This prevents [chunkhash] values from changing when running webpack // builds in different directories. - var newRequestPath = "." + path.sep + path.basename(remainingRequest); + const newRequestPath = remainingRequest.replace( + this.resourcePath, + '.' + path.sep + path.relative(this.context, this.resourcePath) + ); this.cacheable && this.cacheable(); if(!this.query) throw new Error("query parameter is missing"); return accesorString(this.query.substr(1)) + " = " +
fix(remainingRequest): resolve issue when multiple variables are exposed for the same request. (#<I>) The previous commit for more consistent hashes naively overwrote the entire request, assuming there weren't additional loaders to be run against the file. This modifies the changes to the request to only change the path to the imported file rather than changing the entire remainingRequest.
webpack-contrib_expose-loader
train
c3aba3fc096bc2207d9d944cc0d56239066332c6
diff --git a/lib/rails-footnotes.rb b/lib/rails-footnotes.rb index <HASH>..<HASH> 100644 --- a/lib/rails-footnotes.rb +++ b/lib/rails-footnotes.rb @@ -32,6 +32,9 @@ module Footnotes delegate :lock_top_right, :to => Filter delegate :lock_top_right=, :to => Filter + + delegate :font_size, :to => Filter + delegate :font_size=, :to => Filter end def self.run! diff --git a/lib/rails-footnotes/filter.rb b/lib/rails-footnotes/filter.rb index <HASH>..<HASH> 100644 --- a/lib/rails-footnotes/filter.rb +++ b/lib/rails-footnotes/filter.rb @@ -4,6 +4,7 @@ module Footnotes @@multiple_notes = false @@klasses = [] @@lock_top_right = false + @@font_size = '11px' # Default link prefix is textmate @@prefix = 'txmt://open?url=file://%s&amp;line=%d&amp;column=%d' @@ -18,7 +19,8 @@ module Footnotes # :prefix => Prefix appended to FootnotesLinks # :multiple_notes => Set to true if you want to open several notes at the same time # :lock_top_right => Lock a btn to toggle notes to the top right of the browser - cattr_accessor :no_style, :notes, :prefix, :multiple_notes, :lock_top_right + # :font_size => CSS font-size property + cattr_accessor :no_style, :notes, :prefix, :multiple_notes, :lock_top_right, :font_size class << self include Footnotes::EachWithRescue @@ -154,7 +156,7 @@ module Footnotes insert_text :before, /<\/head>/i, <<-HTML <!-- Footnotes Style --> <style type="text/css"> - #footnotes_debug {font-size: 11px; font-family: Consolas, monaco, monospace; font-weight: normal; margin: 2em 0 1em 0; text-align: center; color: #444; line-height: 16px; background: #fff;} + #footnotes_debug {font-size: #{@@font_size}; font-family: Consolas, monaco, monospace; font-weight: normal; margin: 2em 0 1em 0; text-align: center; color: #444; line-height: 16px; background: #fff;} #footnotes_debug th, #footnotes_debug td {color: #444; line-height: 18px;} #footnotes_debug a {color: #9b1b1b; font-weight: inherit; text-decoration: none; line-height: 18px;} #footnotes_debug table {text-align: center;}
add font_size option <I>px font is hard for some people to read
josevalim_rails-footnotes
train
9e3ea2913569be2cd8cb4e1ae37a67e4b0f93397
diff --git a/Makefile b/Makefile index <HASH>..<HASH> 100644 --- a/Makefile +++ b/Makefile @@ -148,10 +148,10 @@ gui_test_suite: compile testdata # commit rights. See issue https://github.com/AIFDR/inasafe/issues/232 testdata: @echo - @echo "-----------------------------------------------------------" + @echo "------------------------------------------------------------" @echo "Updating inasafe_data - public test and demo data repository" - @echo "You should update the hash to check out a specific data version" - @echo "-----------------------------------------------------------" + @echo "Update the hash to check out a specific data version " + @echo "------------------------------------------------------------" @scripts/update-test-data.sh 15f70d17c6cacd4c6a6c256c537729e0bda5ca03 2>&1 | tee tmp_warnings.txt; [ $${PIPESTATUS[0]} -eq 0 ] && rm -f tmp_warnings.txt || echo "Stored update warnings in tmp_warnings.txt"; #check and show if there was an error retrieving the test data diff --git a/safe/impact_functions/core.py b/safe/impact_functions/core.py index <HASH>..<HASH> 100644 --- a/safe/impact_functions/core.py +++ b/safe/impact_functions/core.py @@ -361,8 +361,8 @@ def get_thresholds(layer): """ if 'thresholds' in layer.keywords: - s = layer.keywords['thresholds'] - thresholds = [float(x) for x in s.split(',')] + t_list = layer.keywords['thresholds'] + thresholds = [float(x) for x in t_list] thresholds.sort() else: thresholds = [] diff --git a/safe/storage/raster.py b/safe/storage/raster.py index <HASH>..<HASH> 100644 --- a/safe/storage/raster.py +++ b/safe/storage/raster.py @@ -530,20 +530,16 @@ class Raster(Layer): resolution = keywords['resolution'] try: - # FIXME (Ole): It seams float never - # raises an exception. I am sure it used to, - # this has to be rewritten more explicitly res = float(resolution) - except ValueError: - # Assume resolution is a string of the form: + except TypeError: + # Assume resolution is a tuple of the form: # (0.00045228819716044, 0.00045228819716044) msg = ('Unknown format for resolution keyword: %s' - % resolution) - verify((resolution.startswith('(') and - resolution.endswith(')')), msg) + % str(resolution)) + verify(isinstance(resolution, tuple), msg) - dx, dy = [float(s) for s in resolution[1:-1].split(',')] + dx, dy = [float(s) for s in resolution] if not isotropic: res = (dx, dy) else: diff --git a/safe/storage/utilities.py b/safe/storage/utilities.py index <HASH>..<HASH> 100644 --- a/safe/storage/utilities.py +++ b/safe/storage/utilities.py @@ -267,6 +267,7 @@ def read_keywords(filename, sublayer=None, all_blocks=False): first_keywords = None for line in fid.readlines(): # Remove trailing (but not preceeding!) whitespace + # FIXME: Can be removed altogether text = line.rstrip() # Ignore blank lines
Fixed functionality to work with keyword values that can be python structures
inasafe_inasafe
train
dc008faea1e4b1e38a0858ae582874ea95e637b0
diff --git a/tests/units/test_lib.rb b/tests/units/test_lib.rb index <HASH>..<HASH> 100644 --- a/tests/units/test_lib.rb +++ b/tests/units/test_lib.rb @@ -32,7 +32,7 @@ class TestLib < Test::Unit::TestCase assert(a.first.is_a?(String)) assert_equal(10, a.size) - a = @lib.log_commits :count => 20, :since => "#{Date.today.year - 2007} years ago" + a = @lib.log_commits :count => 20, :since => "#{Date.today.year - 2006} years ago" assert(a.first.is_a?(String)) assert_equal(20, a.size) diff --git a/tests/units/test_log.rb b/tests/units/test_log.rb index <HASH>..<HASH> 100644 --- a/tests/units/test_log.rb +++ b/tests/units/test_log.rb @@ -40,7 +40,7 @@ class TestLog < Test::Unit::TestCase l = @git.log.since("2 seconds ago") assert_equal(0, l.size) - l = @git.log.since("#{Date.today.year - 2007} years ago") + l = @git.log.since("#{Date.today.year - 2006} years ago") assert_equal(30, l.size) end
Fix tests failing if run between Nov 7 <I>:<I>:<I> -<I> and Jan 1 <I>:<I>:<I> -<I>
ruby-git_ruby-git
train
74b0e9ea8750ac41e9970b23a7a8253f07b7963a
diff --git a/lib/twirp/version.rb b/lib/twirp/version.rb index <HASH>..<HASH> 100644 --- a/lib/twirp/version.rb +++ b/lib/twirp/version.rb @@ -1,3 +1,3 @@ module Twirp - VERSION = "0.4.1" + VERSION = "0.5.0" end
bump to version <I> => Twirp::ClientJSON
twitchtv_twirp-ruby
train
52f5a65fb0a987368a36f85abb75e4aee9cdda51
diff --git a/bosh-stemcell/spec/stemcells/stig_spec.rb b/bosh-stemcell/spec/stemcells/stig_spec.rb index <HASH>..<HASH> 100644 --- a/bosh-stemcell/spec/stemcells/stig_spec.rb +++ b/bosh-stemcell/spec/stemcells/stig_spec.rb @@ -71,6 +71,7 @@ describe 'Stig test case verification', { stemcell_image: true, stig_check: true V-38515 V-38514 V-38619 + V-38490 } expected_stig_test_cases = expected_base_stig_test_cases diff --git a/bosh-stemcell/spec/support/os_image_linux_kernel_modules_shared_examples.rb b/bosh-stemcell/spec/support/os_image_linux_kernel_modules_shared_examples.rb index <HASH>..<HASH> 100644 --- a/bosh-stemcell/spec/support/os_image_linux_kernel_modules_shared_examples.rb +++ b/bosh-stemcell/spec/support/os_image_linux_kernel_modules_shared_examples.rb @@ -1,32 +1,39 @@ shared_examples_for 'a Linux kernel module configured OS image' do - context 'prevent bluetooth module to be loaded (stig: V-38682)' do + context 'prevent bluetooth module from being loaded (stig: V-38682)' do describe file('/etc/modprobe.d/blacklist.conf') do it { should be_file } it { should contain 'install bluetooth /bin/true' } end end - context 'prevent tipc module to be loaded (stig: V-38517)' do + context 'prevent tipc module from being loaded (stig: V-38517)' do describe file('/etc/modprobe.d/blacklist.conf') do it { should contain 'install tipc /bin/true' } end end - context 'prevent sctp module to be loaded (stig: V-38515)' do + context 'prevent sctp module from being loaded (stig: V-38515)' do describe file('/etc/modprobe.d/blacklist.conf') do it { should contain 'install sctp /bin/true' } end end - context 'prevent dccp module to be loaded (stig: V-38514)' do + context 'prevent dccp module from being loaded (stig: V-38514)' do describe file('/etc/modprobe.d/blacklist.conf') do it { should contain 'install dccp /bin/true' } end end - context 'prevent bluetooth service to be enabled (stig: V-38691)' do + context 'prevent bluetooth service from being enabled (stig: V-38691)' do describe service('bluetooth') do it { should_not be_enabled } end end + + context 'prevent USB module from being loaded (stig: V-38490)' do + describe file('/etc/modprobe.d/blacklist.conf') do + it { should contain 'install usb-storage /bin/true' } + end + end + end diff --git a/stemcell_builder/stages/system_kernel_modules/apply.sh b/stemcell_builder/stages/system_kernel_modules/apply.sh index <HASH>..<HASH> 100755 --- a/stemcell_builder/stages/system_kernel_modules/apply.sh +++ b/stemcell_builder/stages/system_kernel_modules/apply.sh @@ -6,6 +6,7 @@ base_dir=$(readlink -nf $(dirname $0)/../..) source $base_dir/lib/prelude_apply.bash echo '# prevent blacklisted modules from being loaded +install usb-storage /bin/true install bluetooth /bin/true install tipc /bin/true install sctp /bin/true
Prevent loading from USB as per stig V-<I> [#<I>](<URL>)
cloudfoundry_bosh
train
8710d248a815c5ffa59ed13b717892edf830bf93
diff --git a/Core/MVC/Symfony/View/Builder/InvisibleContentViewBuilder.php b/Core/MVC/Symfony/View/Builder/InvisibleContentViewBuilder.php index <HASH>..<HASH> 100644 --- a/Core/MVC/Symfony/View/Builder/InvisibleContentViewBuilder.php +++ b/Core/MVC/Symfony/View/Builder/InvisibleContentViewBuilder.php @@ -51,18 +51,6 @@ class InvisibleContentViewBuilder extends ContentViewBuilder } /** - * Tests if the builder matches the given argument. - * - * @param mixed $argument Anything the builder can decide against. Example: a controller's request string. - * - * @return bool true if the ViewBuilder matches the argument, false otherwise. - */ - public function matches( $argument ) - { - return parent::matches( $argument ); - } - - /** * Builds the View based on $parameters. * * @param array $parameters
Remove superfluous method override
netgen_site-bundle
train
88879b420de49dfaeab9dced9b8df85546fdf289
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ deps = { "eth-bloom>=1.0.3,<2.0.0", "eth-keys>=0.2.1,<0.4.0", "eth-typing>=2.2.0,<3.0.0", - "eth-utils>=1.7.0,<2.0.0", + "eth-utils>=1.8.0,<2.0.0", "lru-dict>=1.1.6", "mypy_extensions>=0.4.1,<1.0.0", "py-ecc>=1.4.7,<5.0.0", @@ -23,10 +23,10 @@ deps = { # Installing these libraries may make the evm perform better than # using the default fallbacks though. 'eth-extra': [ - "coincurve>=10.0.0,<11.0.0", + "coincurve>=13.0.0,<14.0.0", "eth-hash[pysha3];implementation_name=='cpython'", "eth-hash[pycryptodome];implementation_name=='pypy'", - "plyvel>=1.0.5,<1.2.0", + "plyvel>=1.2.0,<2", ], 'test': [ "factory-boy==2.11.1", @@ -39,9 +39,9 @@ deps = { "pytest-xdist==1.31.0", ], 'lint': [ - "flake8==3.5.0", - "flake8-bugbear==18.8.0", - "mypy==0.701", + "flake8==3.8.2", + "flake8-bugbear==20.1.4", + "mypy==0.750", ], 'benchmark': [ "termcolor>=1.1.0,<2.0.0",
setup: update to package versions that have Python <I> wheels. Minimal set of dependencies that otherwise break the virtualenv, detailed here: <URL>. <I> is installed now anyway, but this has been suggested in <URL>
ethereum_py-evm
train
d8111e4c9f0b501a257d595e7ced1b3d45a65852
diff --git a/packages/ludumpad-client/src/app.js b/packages/ludumpad-client/src/app.js index <HASH>..<HASH> 100644 --- a/packages/ludumpad-client/src/app.js +++ b/packages/ludumpad-client/src/app.js @@ -304,3 +304,17 @@ function sendData () { oldData = currentData socket.emit('ld:input-update', currentData) } + +function log (msg) { + if (typeof msg !== 'string') msg = JSON.stringify(msg) + if (socket) socket.emit('ld:debug', msg) + console.log(msg) +} + +window.onerror = function (msg, url, line, col, error) { + let extra = '' + if (col) extra += '\ncolumn: ' + col + if (error) extra += '\nerror: ' + error + const errStr = `Error: ${msg}\nurl: ${url}\nline: ${line}${extra}` + log(errStr) +} diff --git a/packages/ludumpad-server/src/ld-controller.js b/packages/ludumpad-server/src/ld-controller.js index <HASH>..<HASH> 100644 --- a/packages/ludumpad-server/src/ld-controller.js +++ b/packages/ludumpad-server/src/ld-controller.js @@ -34,6 +34,9 @@ export default class LDController { }) this.on('ld:input-update', this.onInputUpdate.bind(this)) + this.on('ld:debug', msg => { + console.log(`> debug message from ${this.id} (player #${this.number + 1}): ${msg}`) + }) } onInputUpdate (data) {
Log errors on LudumPad controllers
dasilvacontin_ludumpad
train
d4900ee454c6faa0ac7c823b5519bab760591ac9
diff --git a/tests/packaging/release.py b/tests/packaging/release.py index <HASH>..<HASH> 100644 --- a/tests/packaging/release.py +++ b/tests/packaging/release.py @@ -563,6 +563,15 @@ _confirm_true = _confirm(True) _confirm_false = _confirm(False) +# This is shit but I'm too tired and angry right now to give a fuck. +def _run_all(c, mute=True): + try: + return all_(c) + except SystemExit: + if not mute: + raise + + class All(Spec): "all_" # mehhh @@ -576,7 +585,7 @@ class All(Spec): @_confirm_false def displays_status_output(self, _): with _mock_context(self) as c: - all_(c) + _run_all(c) output = sys.stdout.getvalue() for action in ( Changelog.NEEDS_RELEASE, @@ -590,13 +599,13 @@ class All(Spec): @patch('invocations.console.input', return_value='no') def prompts_before_taking_action(self, mock_input): with _mock_context(self) as c: - all_(c) + _run_all(c) eq_(mock_input.call_args[0][0], "Take the above actions? [Y/n] ") @_confirm_false def if_prompt_response_negative_no_action_taken(self, _): with _mock_context(self) as c: - all_(c) + _run_all(c) # TODO: move all action-y code into subroutines, then mock them and # assert they were never called? # Expect that only the status-y run() calls were made. @@ -608,7 +617,7 @@ class All(Spec): @_confirm_true def opens_EDITOR_with_changelog_when_it_needs_update(self, _): with _mock_context(self) as c: - all_(c) + _run_all(c) # Grab changelog path from the context config, why not path = c.config.packaging.changelog_file # TODO: real code should probs expand EDITOR explicitly so it can @@ -619,7 +628,7 @@ class All(Spec): @_confirm_true def opens_EDITOR_with_version_file_when_it_needs_update(self, _): with _mock_context(self) as c: - all_(c) + _run_all(c) path = "{0}/_version.py".format(FAKE_PACKAGE) # TODO: real code should probs expand EDITOR explicitly so it can # run w/o a shell wrap / require a full env? @@ -629,7 +638,7 @@ class All(Spec): @_confirm_true def commits_and_adds_git_tag_when_needs_cutting(self, _): with _mock_context(self) as c: - all_(c) + _run_all(c) version = "1.1.2" # as changelog has issues & prev was 1.1.1 # Ensure the commit necessity test happened. (Default mock_context # sets it up to result in a commit being necessary.) @@ -651,7 +660,7 @@ class All(Spec): # case, can't really make it public, as that risks clashing with # "real" members of the context/config...?) c._run[check] = Result("", exited=1) - all_(c) + _run_all(c) # Expect NO git commit commands = [x[0][0] for x in c.run.call_args_list] ok_(not any(x.startswith("git commit") for x in commands)) @@ -670,7 +679,7 @@ class All(Spec): @_confirm_true def no_changelog_update_needed_means_no_changelog_edit(self, _): with _mock_context(self) as c: - all_(c) + _run_all(c) # TODO: as with the 'took no actions at all' test above, # proving a negative sucks - eventually make this subroutine # assert based. Meh.
Update tests to account for non broken confirm() call. Sigh
pyinvoke_invocations
train
c78a447d78cc37330300e40f353c92330f1ee723
diff --git a/src/sap.ui.rta/src/sap/ui/rta/plugin/AddXMLAtExtensionPoint.js b/src/sap.ui.rta/src/sap/ui/rta/plugin/AddXMLAtExtensionPoint.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.rta/src/sap/ui/rta/plugin/AddXMLAtExtensionPoint.js +++ b/src/sap.ui.rta/src/sap/ui/rta/plugin/AddXMLAtExtensionPoint.js @@ -247,10 +247,9 @@ sap.ui.define([ /** * Retrieves the action data for addXMLAtExtensionPoint. - * @param {sap.ui.dt.ElementOverlay} oOverlay - Overlay containing the design time metadata - * @returns {object} Object with the action data from the design time metadata + * @returns {object} Object with the action data */ - Plugin.prototype.getAction = function() { + AddXMLAtExtensionPoint.prototype.getAction = function() { return { changeType: FLEX_CHANGE_TYPE }; };
[INTERNAL][FIX] sap.ui.rta: Fix typo in extension point plugin The function getAction of AddXMLAtExtensionPoint has overwritten the function of the whole base plugin, not only for itself. Change-Id: Ibfdfc8c8f<I>a<I>a<I>d<I>ba<I>fa<I>
SAP_openui5
train
fb5b3d0fda042d1094be9437a3c0c62e807776fc
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ install_requires = [ # For more details, see: # http://packages.python.org/distribute/setuptools.html#declaring-dependencies "nltk", "enum", "lxml", "networkx", "pygraphviz", - "brewer2mpl", "unidecode", "neonx" + "brewer2mpl", "unidecode", "neonx", "pydot" ] diff --git a/src/discoursegraphs/readwrite/dot.py b/src/discoursegraphs/readwrite/dot.py index <HASH>..<HASH> 100644 --- a/src/discoursegraphs/readwrite/dot.py +++ b/src/discoursegraphs/readwrite/dot.py @@ -9,7 +9,23 @@ This module contains code to convert document graphs to graphviz graphs import codecs from tempfile import NamedTemporaryFile -from networkx import write_dot +#~ from networkx import write_dot +from networkx.drawing.nx_pydot import to_pydot + + +def write_dot(G, output_file): + """Write NetworkX graph G to a Graphviz dot format file. + """ + try: + import pydot + except ImportError: + raise ImportError("write_dot() requires pydot", + "http://code.google.com/p/pydot/") + P=to_pydot(G) + + with codecs.open(output_file, mode='w', encoding='utf8') as out: + out.write(P.to_string()) + return def print_dot(docgraph, ignore_node_labels=False):
added pydot to dependencies
arne-cl_discoursegraphs
train
fb9e1abb920d4b5b77b9169c37d4e0dec09d5d1d
diff --git a/zipline/gens/tradesimulation.py b/zipline/gens/tradesimulation.py index <HASH>..<HASH> 100644 --- a/zipline/gens/tradesimulation.py +++ b/zipline/gens/tradesimulation.py @@ -153,10 +153,10 @@ class AlgorithmSimulator(object): if midnight_dt in algo.capital_changes: # process any capital changes that came overnight - perf_tracker.process_capital_changes( - algo.capital_changes[midnight_dt], - is_interday=True - ) + change = algo.capital_changes[midnight_dt] + log.info('Processing capital change of %s at %s' % + (change, midnight_dt)) + perf_tracker.process_capital_changes(change, is_interday=True) # Get the positions before updating the date so that prices are # fetched for trading close instead of midnight @@ -218,8 +218,11 @@ class AlgorithmSimulator(object): # process any capital changes that came between the last # and current minutes + change = algo.capital_changes[dt] + log.info('Processing capital change of %s at %s' % + (change, dt)) algo.perf_tracker.process_capital_changes( - algo.capital_changes[dt], + change, is_interday=False ) else:
LOG: Log the dt and amount when each capital change executes
quantopian_zipline
train
f50929a52f171bb26c1d2df5348374ac6990b5a7
diff --git a/lib/dnsimple/client/registrar.rb b/lib/dnsimple/client/registrar.rb index <HASH>..<HASH> 100644 --- a/lib/dnsimple/client/registrar.rb +++ b/lib/dnsimple/client/registrar.rb @@ -22,8 +22,7 @@ module Dnsimple end - def check(account_id, domain_name, attributes = {}, options = {}) - options = options.merge(attributes) + def check(account_id, domain_name, options = {}) response = client.get(Client.versioned("/%s/registrar/domains/%s/check" % [account_id, domain_name]), options) Dnsimple::Response.new(response, Struct::Availability.new(response["data"]))
This endpoint doesn't need attributes
dnsimple_dnsimple-ruby
train
fe43e3b89d0612836333629783012b72c18727ab
diff --git a/integration/all.sh b/integration/all.sh index <HASH>..<HASH> 100755 --- a/integration/all.sh +++ b/integration/all.sh @@ -1,5 +1,8 @@ -#!/bin/sh +#!/bin/bash +set -euo pipefail +IFS=$'\n\t' -./test-http.sh || exit -./test-merge.sh || exit -./test-delupd.sh || exit +go test -tags integration -v +./test-http.sh +./test-merge.sh +./test-delupd.sh diff --git a/model/puller.go b/model/puller.go index <HASH>..<HASH> 100644 --- a/model/puller.go +++ b/model/puller.go @@ -461,7 +461,7 @@ func (p *puller) handleBlock(b bqBlock) bool { of.temp = filepath.Join(p.repoCfg.Directory, defTempNamer.TempName(f.Name)) dirName := filepath.Dir(of.filepath) - _, err := os.Stat(dirName) + info, err := os.Stat(dirName) if err != nil { err = os.MkdirAll(dirName, 0777) } else { @@ -469,6 +469,8 @@ func (p *puller) handleBlock(b bqBlock) bool { if dirName != p.repoCfg.Directory { err = os.Chmod(dirName, 0777) } + // Change it back after creating the file, to minimize the time window with incorrect permissions + defer os.Chmod(dirName, info.Mode()) } if err != nil { l.Infof("mkdir: error: %q / %q: %v", p.repoCfg.ID, f.Name, err) @@ -632,7 +634,13 @@ func (p *puller) handleEmptyBlock(b bqBlock) { dirName := filepath.Dir(of.filepath) os.Chmod(of.filepath, 0666) if dirName != p.repoCfg.Directory { + info, err := os.Stat(dirName) + if err != nil { + l.Debugln("weird! can't happen?", err) + } os.Chmod(dirName, 0777) + // Change it back after deleting the file, to minimize the time window with incorrect permissions + defer os.Chmod(dirName, info.Mode()) } if p.versioner != nil { if debug { diff --git a/osutil/osutil.go b/osutil/osutil.go index <HASH>..<HASH> 100644 --- a/osutil/osutil.go +++ b/osutil/osutil.go @@ -7,17 +7,28 @@ package osutil import ( "os" + "path/filepath" "runtime" ) func Rename(from, to string) error { + // Make sure the destination directory is writeable + toDir := filepath.Dir(to) + if info, err := os.Stat(toDir); err == nil { + os.Chmod(toDir, 0777) + defer os.Chmod(toDir, info.Mode()) + } + + // On Windows, make sure the destination file is writeable (or we can't delete it) if runtime.GOOS == "windows" { - os.Chmod(to, 0666) // Make sure the file is user writeable + os.Chmod(to, 0666) err := os.Remove(to) if err != nil && !os.IsNotExist(err) { return err } } - defer os.Remove(from) // Don't leave a dangling temp file in case of rename error + + // Don't leave a dangling temp file in case of rename error + defer os.Remove(from) return os.Rename(from, to) }
Try not to leave directories behind with incorrect permissions
syncthing_syncthing
train
8d238259fffa6c63a05b5d5b4d75b4128c02ca31
diff --git a/lib/abstractor/abstractable.rb b/lib/abstractor/abstractable.rb index <HASH>..<HASH> 100644 --- a/lib/abstractor/abstractable.rb +++ b/lib/abstractor/abstractable.rb @@ -42,7 +42,7 @@ module Abstractor if options[:namespace_type] || options[:namespace_id] abstractor_abstractions_by_namespace(options).map(&:abstractor_abstraction_group).compact.uniq else - abstractor_abstraction_groups + abstractor_abstraction_groups.not_deleted end end diff --git a/spec/models/abstractor/imaging_spec.rb b/spec/models/abstractor/imaging_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/abstractor/imaging_spec.rb +++ b/spec/models/abstractor/imaging_spec.rb @@ -97,16 +97,22 @@ describe ImagingExam do end #reporting namespaced grouped abstractions - it 'can return abstractor abstractions in a namespace', focus: false do + it 'can return abstractor abstraction groups in a namespace', focus: false do @imaging_exam.abstract(namespace_type: @abstractor_subject_abstraction_schema_dat.namespace_type, namespace_id: @abstractor_subject_abstraction_schema_dat.namespace_id) expect(@imaging_exam.reload.abstractor_abstraction_groups_by_namespace(namespace_type: @abstractor_subject_abstraction_schema_recist_response.namespace_type, namespace_id: @abstractor_subject_abstraction_schema_recist_response.namespace_id).size).to eq(1) end - it 'can return abstractor abstractions (regardless of namespace)', focus: false do + it 'can return abstractor abstraction groups (regardless of namespace)', focus: false do @imaging_exam.abstract(namespace_type: @abstractor_subject_abstraction_schema_dat.namespace_type, namespace_id: @abstractor_subject_abstraction_schema_dat.namespace_id) expect(@imaging_exam.reload.abstractor_abstraction_groups_by_namespace.size).to eq(2) end + it 'can return abstractor abstraction groups (regardless of namespace) but not excluding soft deleted rows', focus: true do + @imaging_exam.abstract(namespace_type: @abstractor_subject_abstraction_schema_dat.namespace_type, namespace_id: @abstractor_subject_abstraction_schema_dat.namespace_id) + @imaging_exam.abstractor_abstraction_groups.first.soft_delete! + expect(@imaging_exam.reload.abstractor_abstraction_groups_by_namespace.size).to eq(1) + end + it "can report abstractions needing to be reviewed (regardless of namespace)", focus: false do @imaging_exam.abstract(namespace_type: @abstractor_subject_abstraction_schema_dat.namespace_type, namespace_id: @abstractor_subject_abstraction_schema_dat.namespace_id) expect(@imaging_exam.reload.abstractor_abstractions_by_abstractor_abstraction_status(Abstractor::Enum::ABSTRACTION_STATUS_NEEDS_REVIEW).size).to eq(6)
Soft deleted rows should not be included in abstraction groups. Closes #<I>
NUBIC_abstractor
train
6589a20a4eea74359e16a8d5a3dd679347151293
diff --git a/run_tests.py b/run_tests.py index <HASH>..<HASH> 100644 --- a/run_tests.py +++ b/run_tests.py @@ -75,18 +75,18 @@ def run_parallel_to_xml(suite, args): os.unlink(name) num_failures = 0 index = itertools.count() - + # Keep track of the running popen objects by keyword keyword_to_process = {} try: for keyword in suite: if keyword: keyword_to_process[keyword] = run_to_xml(keyword, str(next(index)), args) - + # We will periodically poll to see what is running, and every so many # loops we will announce it, so watching the Jenkins log isn't boring. loops = 0 - + while len(keyword_to_process) > 0: # Make a list of finished keywords finished = [] @@ -95,7 +95,7 @@ def run_parallel_to_xml(suite, args): # This keyword has finished! finished.append(keyword) status = process.returncode - + if status > 0: num_failures += 1 if status < len(pytest_errors): @@ -108,18 +108,18 @@ def run_parallel_to_xml(suite, args): # We got a signal num_failures += 1 log.info('Test keyword %s failed with code %d: abnormal exit', keyword, status) - + for keyword in finished: # Clean up the popen objects for finished test runs del keyword_to_process[keyword] - + if loops % 30 == 0: # Announce what is still running about every 5 minutes log.info('Still running at %d: %s', loops, str(list(keyword_to_process.keys()))) - + loops += 1 time.sleep(10) - + except: for process in keyword_to_process.values(): process.terminate() @@ -130,7 +130,7 @@ def run_parallel_to_xml(suite, args): for keyword in itertools.chain(*test_suites.values())) log.info('Starting other tests') process = run_to_xml(everything_else, str(next(index)), args) - + loops = 0 while process.poll() is None: if loops % 30 == 0: diff --git a/src/toil/cwl/cwltoil.py b/src/toil/cwl/cwltoil.py index <HASH>..<HASH> 100755 --- a/src/toil/cwl/cwltoil.py +++ b/src/toil/cwl/cwltoil.py @@ -478,7 +478,7 @@ class CWLJobWrapper(Job): resolved_cwljob = resolve_indirect(self.cwljob) if isinstance(resolved_cwljob, tuple): cwljob = resolved_cwljob[0] - # metadata = resolved_cwljob[1] + metadata = resolved_cwljob[1] else: cwljob = resolved_cwljob fill_in_defaults( @@ -487,7 +487,7 @@ class CWLJobWrapper(Job): self.runtime_context.basedir or "")) realjob = CWLJob(self.cwltool, cwljob, self.runtime_context) self.addChild(realjob) - return realjob.rv() + return realjob.rv(), metadata def _makeNestedTempDir(top, seed, levels=2): @@ -590,6 +590,7 @@ class CWLJob(Job): cwljob, metadata = resolved_cwljob else: cwljob = resolved_cwljob + metadata = {} fill_in_defaults( self.step_inputs, cwljob, self.runtime_context.make_fs_access("")) @@ -775,7 +776,7 @@ class CWLScatter(Job): "Must provide scatterMethod to scatter over multiple" " inputs.") - return outputs + return outputs, metadata class CWLGather(Job): @@ -834,7 +835,7 @@ class CWLGather(Job): outobj[k], metadata[k] = result else: outobj[k] = result - return outobj + return outobj, metadata class SelfJob(object): diff --git a/src/toil/job.py b/src/toil/job.py index <HASH>..<HASH> 100644 --- a/src/toil/job.py +++ b/src/toil/job.py @@ -927,7 +927,7 @@ class Job(BaseJob): :param fileHandle: An open, binary-mode file handle. :returns: """ - + def filter_main(module_name, class_name): try: if module_name == '__main__': @@ -949,13 +949,13 @@ class Job(BaseJob): # In Python 3 find_global isn't real and we are supposed to # subclass unpickler and override find_class. We can't just replace # it. But with cPickle in Pyhton 2 we can't subclass Unpickler. - + class FilteredUnpickler(pickle.Unpickler): def find_class(self, module, name): return filter_main(module, name) - + unpickler = FilteredUnpickler(fileHandle) - + runnable = unpickler.load() assert isinstance(runnable, BaseJob) runnable._config = config
fix: Propagate the metadata field in more steps
DataBiosphere_toil
train
68720584ba50e7bed1746e46e0f55ea687b5cf86
diff --git a/src/consumer/__tests__/instrumentationEvents.spec.js b/src/consumer/__tests__/instrumentationEvents.spec.js index <HASH>..<HASH> 100644 --- a/src/consumer/__tests__/instrumentationEvents.spec.js +++ b/src/consumer/__tests__/instrumentationEvents.spec.js @@ -183,6 +183,7 @@ describe('Consumer > Instrumentation Events', () => { payload: { numberOfBatches: expect.any(Number), duration: expect.any(Number), + nodeId: expect.any(String), }, }) }) @@ -207,7 +208,9 @@ describe('Consumer > Instrumentation Events', () => { id: expect.any(Number), timestamp: expect.any(Number), type: 'consumer.fetch_start', - payload: {}, + payload: { + nodeId: expect.any(String), + }, }) }) diff --git a/src/consumer/consumerGroup.js b/src/consumer/consumerGroup.js index <HASH>..<HASH> 100644 --- a/src/consumer/consumerGroup.js +++ b/src/consumer/consumerGroup.js @@ -308,7 +308,6 @@ module.exports = class ConsumerGroup { }) this.fetchManager = fetchManager({ - logger: this.logger, instrumentationEmitter: this.instrumentationEmitter, concurrency: this.concurrency, nodeIds: this.cluster.getNodeIds(), diff --git a/src/consumer/fetchManager.js b/src/consumer/fetchManager.js index <HASH>..<HASH> 100644 --- a/src/consumer/fetchManager.js +++ b/src/consumer/fetchManager.js @@ -11,26 +11,19 @@ const fetchManager = ({ instrumentationEmitter, nodeIds, fetch, concurrency = 1 let error const fetchNode = async (runnerId, nodeId) => { - if (!(runnerId in fetchers)) fetchers[runnerId] = {} - if (nodeId in fetchers[runnerId]) return fetchers[nodeId] + if (!fetchers[runnerId]) fetchers[runnerId] = {} + if (fetchers[runnerId][nodeId]) return fetchers[runnerId][nodeId] fetchers[runnerId][nodeId] = (async () => { const startFetch = Date.now() - instrumentationEmitter.emit(FETCH_START, {}) + instrumentationEmitter.emit(FETCH_START, { nodeId }) const batches = await fetch(nodeId, assignments[runnerId]) instrumentationEmitter.emit(FETCH, { - /** - * PR #570 removed support for the number of batches in this instrumentation event; - * The new implementation uses an async generation to deliver the batches, which makes - * this number impossible to get. The number is set to 0 to keep the event backward - * compatible until we bump KafkaJS to version 2, following the end of node 8 LTS. - * - * @since 2019-11-29 - */ - numberOfBatches: 0, + numberOfBatches: batches.length, duration: Date.now() - startFetch, + nodeId, }) batches.forEach(batch => {
refactor: minor changes before refactoring to single requests per broker due to blocking fetch request limitations
tulios_kafkajs
train
71b12b9473c2f737d789c7b373849864b9bfea79
diff --git a/php/utils-wp.php b/php/utils-wp.php index <HASH>..<HASH> 100644 --- a/php/utils-wp.php +++ b/php/utils-wp.php @@ -344,7 +344,7 @@ function wp_get_table_names( $args, $assoc_args = array() ) { if ( empty( $tables_sql ) ) { $tables_sql = $wpdb->prepare( 'SHOW TABLES LIKE %s', esc_like( $wpdb->get_blog_prefix() ) . '%' ); } else { - $tables_sql .= $wpdb->prepare( ' AND Tables_in_$wpdb->dbname LIKE %s', esc_like( $wpdb->get_blog_prefix() ) . '%' ); + $tables_sql .= sprintf( " AND %s LIKE '%s'", esc_sql_ident( 'Tables_in_' . $wpdb->dbname ), esc_like( $wpdb->get_blog_prefix() ) . '%' ); } $tables = $wpdb->get_col( $tables_sql, 0 ); // WPCS: unprepared SQL OK.
fix and make internally consistent building of sql
wp-cli_wp-cli
train
05d32517ef678989baad4411060a02b646d64e57
diff --git a/lib/astrails/safe.rb b/lib/astrails/safe.rb index <HASH>..<HASH> 100644 --- a/lib/astrails/safe.rb +++ b/lib/astrails/safe.rb @@ -1,5 +1,6 @@ require "aws/s3" require 'fileutils' +require 'benchmark' require 'tempfile' require 'extensions/mktmpdir' diff --git a/lib/astrails/safe/local.rb b/lib/astrails/safe/local.rb index <HASH>..<HASH> 100644 --- a/lib/astrails/safe/local.rb +++ b/lib/astrails/safe/local.rb @@ -19,7 +19,10 @@ module Astrails unless $DRY_RUN FileUtils.mkdir_p(path) unless File.directory?(path) - system "#{@backup.command}>#{@backup.path = full_path}" + benchmark = Benchmark.realtime do + system "#{@backup.command}>#{@backup.path = full_path}" + end + puts("command took " + sprintf("%.2f", benchmark) + " second(s).") if $_VERBOSE end end diff --git a/lib/astrails/safe/s3.rb b/lib/astrails/safe/s3.rb index <HASH>..<HASH> 100644 --- a/lib/astrails/safe/s3.rb +++ b/lib/astrails/safe/s3.rb @@ -20,11 +20,14 @@ module Astrails puts "Uploading #{bucket}:#{full_path}" if $_VERBOSE || $DRY_RUN unless $DRY_RUN || $LOCAL - AWS::S3::Bucket.create(bucket) - File.open(@backup.path) do |file| - AWS::S3::S3Object.store(full_path, file, bucket) + benchmark = Benchmark.realtime do + AWS::S3::Bucket.create(bucket) + File.open(@backup.path) do |file| + AWS::S3::S3Object.store(full_path, file, bucket) + end end puts "...done" if $_VERBOSE + puts("Upload took " + sprintf("%.2f", benchmark) + " second(s).") if $_VERBOSE end end
added code to measure time of operations and print it in verbose mode
astrails_safe
train
3b86237d3c3adea161e58353ca3b04e79c3f203e
diff --git a/rcli/display/__init__.py b/rcli/display/__init__.py index <HASH>..<HASH> 100644 --- a/rcli/display/__init__.py +++ b/rcli/display/__init__.py @@ -159,17 +159,6 @@ def timed_display(msg): print_header("completed in {:.2f}s".format(delta), False) -def line(char="\u2500", start="\u2500", end="\u2500"): - print(start, char * _ncols() - 2, end) - - -@contextlib.contextmanager -def box(): - line(start="\u250F", end="\u2513") - yield - line(start="\u2517", end="\u251B") - - def run_tasks(header, tasks): """Run a group of tasks with a header, footer and success/failure messages. diff --git a/rcli/display/box.py b/rcli/display/box.py index <HASH>..<HASH> 100644 --- a/rcli/display/box.py +++ b/rcli/display/box.py @@ -70,6 +70,9 @@ class Box: size=None, header="", header_style=None, + footer="", + footer_style=None, + sep_style=None, ): self._upper_left = upper_left self._upper_right = upper_right @@ -82,7 +85,10 @@ class Box: self._sep_right = sep_right self._size = size self._header = header - self.header_style = header_style + self._header_style = header_style + self._footer = footer + self._footer_style = footer_style + self._sep_style = sep_style def top(self, text=""): with Style.current(): @@ -91,7 +97,7 @@ class Box: self._horizontal, self._upper_left, f"{self._upper_right}{Style.reset}", - self.header_style(text) if self.header_style else text, + self._header_style(text) if self._header_style else text, ), flush=True, ) @@ -99,13 +105,14 @@ class Box: def sep(self, text=""): print(self._get_sep(text), sep="", flush=True) - def bottom(self): + def bottom(self, text=""): with Style.current(): print( self._line( self._horizontal, self._lower_left, f"{self._lower_right}{Style.reset}", + self._footer_style(text) if self._footer_style else text, ), flush=True, ) @@ -124,7 +131,10 @@ class Box: def _get_sep(self, text=""): return self._line( - self._sep_horizontal, self._sep_left, self._sep_right, text + self._sep_horizontal, + self._sep_left, + self._sep_right, + self._sep_style(text) if self._sep_style else text, ) def __enter__(self): @@ -135,7 +145,7 @@ class Box: def __exit__(self, *args, **kwargs): Box._stack.pop() - self.bottom() + self.bottom(self._footer) Box._depth -= 1 @staticmethod @@ -148,6 +158,7 @@ class Box: if "size" in kw: impl._size = kw["size"] impl._header = kw.get("header", "") + impl._footer = kw.get("footer", "") with impl, contextlib.redirect_stdout(impl._create_buffer()): yield impl @@ -166,6 +177,8 @@ Box.thick = Box.new_style( "\u2501", "\u252B", header_style=Style.bold, + footer_style=Style.bold, + sep_style=Style.bold, ) Box.info = Box.new_style( "\u250F",
Remove prototype functions and add footer support.
contains-io_rcli
train
947209a0286c3fa6cb047fc39eb7b9d8999a377c
diff --git a/packer.go b/packer.go index <HASH>..<HASH> 100644 --- a/packer.go +++ b/packer.go @@ -5,12 +5,21 @@ import ( "github.com/mitchellh/packer/packer" "github.com/mitchellh/packer/packer/plugin" "fmt" + "io/ioutil" "log" "os" "os/exec" ) func main() { + if os.Getenv("PACKER_LOG") == "" { + // If we don't have logging explicitly enabled, then disable it + log.SetOutput(ioutil.Discard) + } else { + // Logging is enabled, make sure it goes to stderr + log.SetOutput(os.Stderr) + } + defer plugin.CleanupClients() commands := map[string]string { diff --git a/packer/environment.go b/packer/environment.go index <HASH>..<HASH> 100644 --- a/packer/environment.go +++ b/packer/environment.go @@ -4,6 +4,7 @@ package packer import ( "errors" "fmt" + "log" "os" "sort" "strings" @@ -87,6 +88,8 @@ func (e *coreEnvironment) Builder(name string) (b Builder, err error) { // Executes a command as if it was typed on the command-line interface. // The return value is the exit code of the command. func (e *coreEnvironment) Cli(args []string) (result int, err error) { + log.Printf("Environment.Cli: %#v\n", args) + if len(args) == 0 || args[0] == "--help" || args[0] == "-h" { e.printHelp() return 1, nil @@ -115,6 +118,7 @@ func (e *coreEnvironment) Cli(args []string) (result int, err error) { // If we still don't have a command, show the help. if command == nil { + log.Printf("Environment.CLI: command not found: %s\n", args[0]) e.printHelp() return 1, nil }
packer: PACKER_LOG to toggle logging from an env var [GH-3]
hashicorp_packer
train
c3c7152c55f04ab846f2c5b0f8f0e2b8f7fd5fa7
diff --git a/pkg/proxy/ipvs/proxier.go b/pkg/proxy/ipvs/proxier.go index <HASH>..<HASH> 100644 --- a/pkg/proxy/ipvs/proxier.go +++ b/pkg/proxy/ipvs/proxier.go @@ -1009,7 +1009,7 @@ func (proxier *Proxier) syncProxyRules() { } if err := proxier.syncService(svcNameString, serv, true); err == nil { // check if service need skip endpoints that not in same host as kube-proxy - onlyLocal := svcInfo.SessionAffinityType == v1.ServiceAffinityClientIP && svcInfo.OnlyNodeLocalEndpoints + onlyLocal := svcInfo.SessionAffinityType == v1.ServiceAffinityClientIP || svcInfo.OnlyNodeLocalEndpoints activeIPVSServices[serv.String()] = true activeBindAddrs[serv.Address.String()] = true if err := proxier.syncEndpoint(svcName, onlyLocal, serv); err != nil {
Corrected condition. Fix for #<I>
kubernetes_kubernetes
train
5b5449b0aaa2dcca032da999875bc847cfd6ae08
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -476,6 +476,7 @@ class BuildExt(build_ext): self.compiler.linker_so.extend( ["-Wl,-rpath", os.path.join(JAVA_HOME, 'jre/lib/server')] ) + self.compiler.linker_so.append("-Wl,--no-as-needed") build_ext.build_extension(self, ext) def run(self):
Override --as-needed passed to ld by default on some popular distributions This fix cures the problem "undefined symbol: BIO_s_mem" which arises on some platforms when loading pipes, even though pipes seems to build properly.
crs4_pydoop
train
5b7b266f6f94ee5faa1d36e4a17c98ff5eef8436
diff --git a/bakery/tasks.py b/bakery/tasks.py index <HASH>..<HASH> 100644 --- a/bakery/tasks.py +++ b/bakery/tasks.py @@ -407,7 +407,8 @@ def fontaine_process(project, log): log.write('pyFontaine (fontaine/main.py)\n', prefix = 'Header: ') os.chdir(_out) files = glob.glob('*.ttf') - cmd = "python %s/venv/lib/python2.7/site-packages/fontaine/main.py --text '%s' > 'src/fontaine.txt'" % (ROOT, files) + for file in files: + cmd = "python %s/venv/lib/python2.7/site-packages/fontaine/main.py --text '%s' > 'src/fontaine.txt'" % (ROOT, file) run(cmd, cwd=_out, log=log) # TODO also save the totals for the dashboard.... # log.write('Running Fontaine on Results\n', prefix = 'Header: ')
Fix: pyFontaine report generation should be in a for loop
googlefonts_fontbakery
train
5f56253c3e5d55f1432b1a8ea69611c18b8f4807
diff --git a/internal/services/consumption/migration/consumption_budget_subscription.go b/internal/services/consumption/migration/consumption_budget_subscription.go index <HASH>..<HASH> 100644 --- a/internal/services/consumption/migration/consumption_budget_subscription.go +++ b/internal/services/consumption/migration/consumption_budget_subscription.go @@ -247,7 +247,7 @@ func (SubscriptionConsumptionBudgetV1ToV2) UpgradeFunc() pluginsdk.StateUpgrader return nil, fmt.Errorf("parsing %q: %+v", idRaw, err) } - oldSubscriptionId := rawState["subscription_id"].(string) + oldSubscriptionId := rawState["subscription_id"].(commonids.SubscriptionId) newSubscriptionId := commonids.NewSubscriptionID(id.SubscriptionId).ID() log.Printf("[DEBUG] Updating subscription_id from %q to %q", oldSubscriptionId, newSubscriptionId) rawState["subscription_id"] = newSubscriptionId
Fix type issue in migration logic (#<I>)
terraform-providers_terraform-provider-azurerm
train
302260b014e1d593ad01c528104d050c587c1ac8
diff --git a/core/raftlease/store.go b/core/raftlease/store.go index <HASH>..<HASH> 100644 --- a/core/raftlease/store.go +++ b/core/raftlease/store.go @@ -99,7 +99,21 @@ func (s *Store) ClaimLease(key lease.Key, req lease.Request) error { Lease: key.Lease, Holder: req.Holder, Duration: req.Duration, - }) + }, nil) + return errors.Trace(err) +} + +// ClaimLeaseAbort is like ClaimLease but allows cancelling the request early +func (s *Store) ClaimLeaseAbort(key lease.Key, req lease.Request, stop <-chan struct{}) error { + err := s.runOnLeader(&Command{ + Version: CommandVersion, + Operation: OperationClaim, + Namespace: key.Namespace, + ModelUUID: key.ModelUUID, + Lease: key.Lease, + Holder: req.Holder, + Duration: req.Duration, + }, stop) return errors.Trace(err) } @@ -113,7 +127,7 @@ func (s *Store) ExtendLease(key lease.Key, req lease.Request) error { Lease: key.Lease, Holder: req.Holder, Duration: req.Duration, - })) + }, nil)) } // ExpireLease is part of lease.Store. @@ -162,7 +176,7 @@ func (s *Store) pinOp(operation string, key lease.Key, entity string) error { ModelUUID: key.ModelUUID, Lease: key.Lease, PinEntity: entity, - })) + }, nil)) } // Advance is part of globalclock.Updater. @@ -175,7 +189,7 @@ func (s *Store) Advance(duration time.Duration) error { Operation: OperationSetTime, OldTime: s.prevTime, NewTime: newTime, - }) + }, nil) if globalclock.IsConcurrentUpdate(err) { // Someone else updated before us - get the new time. s.prevTime = s.fsm.GlobalTime() @@ -189,7 +203,7 @@ func (s *Store) Advance(duration time.Duration) error { return errors.Trace(err) } -func (s *Store) runOnLeader(command *Command) error { +func (s *Store) runOnLeader(command *Command, stop <-chan struct{}) error { bytes, err := command.Marshal() if err != nil { return errors.Trace(err) @@ -246,6 +260,8 @@ func (s *Store) runOnLeader(command *Command) error { } s.record(command.Operation, result, start) return err + case <-stop: + return errors.Errorf("command %q on %q for %q aborted", command.Operation, command.Lease, command.Holder) } } diff --git a/core/raftlease/store_test.go b/core/raftlease/store_test.go index <HASH>..<HASH> 100644 --- a/core/raftlease/store_test.go +++ b/core/raftlease/store_test.go @@ -85,6 +85,44 @@ func (s *storeSuite) TestClaim(c *gc.C) { ) } +func (s *storeSuite) TestClaimAborted(c *gc.C) { + s.handleHubRequest(c, + func() { + errChan := make(chan error) + stopChan := make(chan struct{}) + go func() { + errChan <- s.store.ClaimLeaseAbort( + lease.Key{"warframe", "vauban", "prime"}, + lease.Request{"vor", time.Second}, + stopChan, + ) + }() + // Without allowing the time to move forward, abort the request + close(stopChan) + + select { + case err := <-errChan: + c.Check(err, gc.ErrorMatches, `command "claim" on "prime" for "vor" aborted`) + case <-time.After(coretesting.LongWait): + c.Fatalf("timed out waiting for claim error") + } + }, + + raftlease.Command{ + Version: 1, + Operation: raftlease.OperationClaim, + Namespace: "warframe", + ModelUUID: "vauban", + Lease: "prime", + Holder: "vor", + Duration: time.Second, + }, + func(req raftlease.ForwardRequest) { + // We never send a response, to allow abort to trigger + }, + ) +} + func (s *storeSuite) TestClaimTimeout(c *gc.C) { s.handleHubRequest(c, func() {
Initial work to support aborting claims. Allow passing in a 'stop' channel, and allow it to return a 'cancelled' error.
juju_juju
train
a15ac8524ac1b3445685f52da34660070b410ed7
diff --git a/bokeh/server/tornado.py b/bokeh/server/tornado.py index <HASH>..<HASH> 100644 --- a/bokeh/server/tornado.py +++ b/bokeh/server/tornado.py @@ -52,7 +52,9 @@ class BokehTornado(TornadoApplication): else: route = key + p[0] relative_patterns.append((route, p[1], { "bokeh_application" : applications[key] })) - super(BokehTornado, self).__init__(extra_patterns + relative_patterns + toplevel_patterns, **settings) + all_patterns = extra_patterns + relative_patterns + toplevel_patterns + log.debug("Patterns are: %r", all_patterns) + super(BokehTornado, self).__init__(all_patterns, **settings) self._applications = applications self._sessions = dict() diff --git a/bokeh/server/urls.py b/bokeh/server/urls.py index <HASH>..<HASH> 100644 --- a/bokeh/server/urls.py +++ b/bokeh/server/urls.py @@ -15,6 +15,6 @@ toplevel_patterns = [ # These all get prefixed with the application route, so /foo/ws etc. per_app_patterns = [ - (r'/', DocHandler), + (r'/?', DocHandler), (r'/ws', WSHandler), ]
Allow both "/foo" and "/foo/" for application routes
bokeh_bokeh
train
a56b98333c42e693959e28c52114779b0e15433f
diff --git a/molgenis-data-annotators/src/main/java/org/molgenis/data/annotation/impl/DbnsfpVariantServiceAnnotator.java b/molgenis-data-annotators/src/main/java/org/molgenis/data/annotation/impl/DbnsfpVariantServiceAnnotator.java index <HASH>..<HASH> 100644 --- a/molgenis-data-annotators/src/main/java/org/molgenis/data/annotation/impl/DbnsfpVariantServiceAnnotator.java +++ b/molgenis-data-annotators/src/main/java/org/molgenis/data/annotation/impl/DbnsfpVariantServiceAnnotator.java @@ -49,18 +49,11 @@ public class DbnsfpVariantServiceAnnotator extends VariantAnnotator { private static final String NAME = "dbNSFP-Variant"; - // the dbnsfp service is dependant on these four values, - // without them no annotations can be returned - private static final String CHROMOSOME = "chrom"; - private static final String POSITION = "pos"; - private static final String REFERENCE = "ref"; - private static final String ALTERNATIVE = "alt"; - // FIXME the prefix for chromosome files, change this into runtime property private static final String CHROMOSOME_FILE = "/Users/mdehaan/bin/tools/dbnsfp/dbNSFP2.3_variant.chr"; // we want to know features, so take the first chromosome file and retrieve them from the header - private static final String[] FEATURES = determineFeatures(); + public static final String[] FEATURES = determineFeatures(); @Autowired AnnotationService annotatorService; @@ -95,7 +88,7 @@ public class DbnsfpVariantServiceAnnotator extends VariantAnnotator String chromosome = entity.getString(CHROMOSOME); - triplets[0] = entity.getString(POSITION); + triplets[0] = entity.getLong(POSITION).toString(); triplets[1] = entity.getString(REFERENCE); triplets[2] = entity.getString(ALTERNATIVE); @@ -124,16 +117,21 @@ public class DbnsfpVariantServiceAnnotator extends VariantAnnotator String line = ""; - while (bufferedReader.ready()) + fileReader: while (bufferedReader.ready()) { + line = bufferedReader.readLine(); + if(line.startsWith("#")){ + continue fileReader; + } + String[] lineSplit = line.split("\t"); charArrayReader: for (int i = 0; i < charArraysForThisChromosome.size(); i++) { Long position = Long.parseLong(charArraysForThisChromosome.get(i)[0]); - if (lineSplit[1].equals(position)) + if (lineSplit[1].equals(position.toString())) { String reference = charArraysForThisChromosome.get(i)[1]; String alternative = charArraysForThisChromosome.get(i)[2];
removed superclass constants. Made feature list public for test. Position check is now done with string.
molgenis_molgenis
train
e1f0b259b425f85761c3a8aad0ab7bdd96df6f65
diff --git a/lib/application.js b/lib/application.js index <HASH>..<HASH> 100644 --- a/lib/application.js +++ b/lib/application.js @@ -2077,33 +2077,38 @@ function setupStaticViews() { var self = this; - // Generate static file regex - this.views.static = []; - - fileModule.walkSync(this.mvcpath + 'views/' + this.paths.static, function(dirPath, dirs, files) { - for (var path,file,i=0; i < files.length; i++) { - file = files[i]; - path = (dirPath + '/' + file).replace(/\/+/g, '/'); - path = self.relPath(path, 'app/views/__static'); - if (self.regex.templateFile.test(path)) self.views.static.push(path); - } - }); + var staticPath = this.mvcpath + 'views/' + this.paths.static; + this.views.static = []; this.views.staticAsoc = {}; this.views.pathAsoc = {}; - - // Associate static paths with their respective templates - for (var key, i=0; i < this.views.static.length; i++) { - var file = this.views.static[i]; - key = file.replace(this.regex.templateFile, ''); - this.views.staticAsoc['/' + key] = file; - } + if (fs.existsSync(staticPath)) { + + fileModule.walkSync(staticPath, function(dirPath, dirs, files) { + for (var path,file,i=0; i < files.length; i++) { + file = files[i]; + path = (dirPath + '/' + file).replace(/\/+/g, '/'); + path = self.relPath(path, 'app/views/__static'); + if (self.regex.templateFile.test(path)) self.views.static.push(path); + } + }); + + // Associate static paths with their respective templates + for (var key, i=0; i < this.views.static.length; i++) { + var file = this.views.static[i]; + key = file.replace(this.regex.templateFile, ''); + this.views.staticAsoc['/' + key] = file; + } + + } + } // Configures View Partials function setupViewPartials() { + // Partial & template regexes var self = this, exts = this.templateExtensions, @@ -2111,38 +2116,44 @@ function setupViewPartials() { templateRegex = new RegExp('\\.(' + exts.join('|') + ')$'), layoutPath = self.mvcpath + 'views/' + self.paths.layout; - // Build partial views and add path associations + var viewsPath = this.mvcpath + 'views'; + var partialPaths = []; - fileModule.walkSync(this.mvcpath + 'views', function(dirPath, dirs, files) { - for (var path,file,i=0; i < files.length; i++) { - - file = files[i]; - path = dirPath + "/" + file; - - if (partialRegex.test(path)) { - - // Only build valid partial views - partialPaths.push(path); - buildPartialView.call(self, path); - watchPartial.call(self, path); - - } else if (templateRegex.test(file)) { - - // Build partial views for everything inside app.paths.layout - - if (path.indexOf(layoutPath) === 0) { + + if (fs.existsSync(viewsPath)) { + + fileModule.walkSync(viewsPath, function(dirPath, dirs, files) { + for (var path,file,i=0; i < files.length; i++) { + + file = files[i]; + path = dirPath + "/" + file; + + if (partialRegex.test(path)) { + + // Only build valid partial views partialPaths.push(path); buildPartialView.call(self, path); watchPartial.call(self, path); - } - // Only add valid templates to view associations - self.views.pathAsoc[self.relPath(path.replace(self.regex.templateFile, ''))] = path; + } else if (templateRegex.test(file)) { + // Build partial views for everything inside app.paths.layout + + if (path.indexOf(layoutPath) === 0) { + partialPaths.push(path); + buildPartialView.call(self, path); + watchPartial.call(self, path); + } + + // Only add valid templates to view associations + self.views.pathAsoc[self.relPath(path.replace(self.regex.templateFile, ''))] = path; + + } } - } - }); - + }); + + } + // Helper Partials Object.keys(this.helpers).forEach(function(alias) { var m, method, hkey, helper = self.helpers[alias];
Add ability to run bare apps These are apps with the smallest number of files possible. Any unncessessary files can safely be removed, to have the smallest application possible.
derdesign_protos
train
f410c13e329520976f3e730c1c5eab2da6f731b2
diff --git a/WebRequest/ChromiumMixin.py b/WebRequest/ChromiumMixin.py index <HASH>..<HASH> 100644 --- a/WebRequest/ChromiumMixin.py +++ b/WebRequest/ChromiumMixin.py @@ -127,7 +127,7 @@ class WebGetCrMixin(object): if hasattr(sup, '__del__'): sup.__del__() - def stepThroughJsWaf_cr(self, url, titleContains='', titleNotContains=''): + def stepThroughJsWaf_bare_chromium(self, url, titleContains='', titleNotContains=''): ''' Use Chromium to access a resource behind WAF protection. diff --git a/WebRequest/WebRequestClass.py b/WebRequest/WebRequestClass.py index <HASH>..<HASH> 100644 --- a/WebRequest/WebRequestClass.py +++ b/WebRequest/WebRequestClass.py @@ -117,6 +117,7 @@ class WebGetRobust( self.alt_cookiejar = alt_cookiejar self.__loadCookies() + def chunkReport(self, bytesSoFar, totalSize): if totalSize: percent = float(bytesSoFar) / totalSize @@ -856,7 +857,7 @@ class WebGetRobust( def stepThroughJsWaf(self, *args, **kwargs): # Shim to the underlying web browser of choice - return self.stepThroughJsWaf_selenium_pjs(*args, **kwargs) + return self.stepThroughJsWaf_bare_chromium(*args, **kwargs) # Compat for old code. diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setup( name="WebRequest", # Version number (initial): - version="0.0.2", + version="0.0.3", # Application author details: author="Connor Wolf ",
Ok, switch over to chromium unwrapping. TODO: Similar shit for firefox.
fake-name_WebRequest
train
379bba537a4824952c9c3a17d1b6474ef1e2c3a6
diff --git a/Datagrid/PropelDatagrid.php b/Datagrid/PropelDatagrid.php index <HASH>..<HASH> 100644 --- a/Datagrid/PropelDatagrid.php +++ b/Datagrid/PropelDatagrid.php @@ -346,10 +346,8 @@ abstract class PropelDatagrid implements PropelDatagridInterface foreach ($sort as $column => $order) { $method = 'orderBy'.ucfirst($column); - try { + if (method_exists($this->getQuery(), $method)) { $this->getQuery()->{$method}($order); - } catch (\Exception $e) { - throw new \Exception('There is no method "'.$method.'" to sort the datagrid on column "'.$column.'". Just create it in the "'.get_class($this->query).'" object.'); } } }
Fail silently when sorting on unknown column.
spyrit_PropelDatagridBundle
train
97e180258c4bb3d5a7d811e6045933feba43da68
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -208,8 +208,13 @@ class build_swig(Command): self.announce('swigging gphoto2 versions %s' % str(gp_versions), 2) # do -builtin and not -builtin swig_bis = [False] - swig_version = str(subprocess.check_output( - ['swig', '-version'], universal_newlines=True)) + cmd = ['swig', '-version'] + try: + swig_version = str(subprocess.check_output( + cmd, universal_newlines=True)) + except Exception: + error('ERROR: command "%s" failed', ' '.join(cmd)) + raise for line in swig_version.split('\n'): if 'Version' in line: swig_version = tuple(map(int, line.split()[-1].split('.')))
Better error message if swig is not installed
jim-easterbrook_python-gphoto2
train
57eb9b42d320c1abc0ea7b70528caef5a131916a
diff --git a/pyamg/krylov/tests/test_krylov.py b/pyamg/krylov/tests/test_krylov.py index <HASH>..<HASH> 100644 --- a/pyamg/krylov/tests/test_krylov.py +++ b/pyamg/krylov/tests/test_krylov.py @@ -90,10 +90,10 @@ class TestKrylov(TestCase): 'b': b, 'x0': x0, 'tol': 1e-16, 'maxiter': 2, 'reduction_factor': 0.98}) - from numpy.testing import dec - @dec.knownfailureif(True, 'MGS and Householder and scipy.sparse.linalg ' +\ - 'do not match for GMRES' +\ - 'see https://github.com/pyamg/pyamg/issues/158') + #from numpy.testing import dec + #@dec.knownfailureif(True, 'MGS and Householder and scipy.sparse.linalg ' +\ + # 'do not match for GMRES' +\ + # 'see https://github.com/pyamg/pyamg/issues/158') def test_gmres(self): # Ensure repeatability @@ -116,10 +116,17 @@ class TestKrylov(TestCase): maxiter=min(A.shape[0], maxiter)) (x2, flag2) = gmres_mgs(A, b, x0=x0, maxiter=min(A.shape[0], maxiter)) - assert_array_almost_equal(x/norm(x), x2/norm(x2), - err_msg='Householder GMRES and MGS\ - GMRES gave different\ - results for small matrix') + try: + assert_array_almost_equal(x/norm(x), x2/norm(x2), + err_msg='Householder GMRES and MGS\ + GMRES gave different\ + results for small matrix') + except AssertionError: + from nose import SkipTest + raise SkipTest('MGS and Householder and scipy.sparse.linalg' +\ + 'do not match for GMRES' +\ + 'see https://github.com/pyamg/pyamg/issues/158') + assert_equal(flag, flag2, err_msg='Householder GMRES and MGS GMRES returned\ different convergence flags for small\ @@ -146,9 +153,9 @@ class TestKrylov(TestCase): err_msg='CR and GMRES yield\ different answers') - from numpy.testing import dec - @dec.knownfailureif(True, 'Oblique projectors fail ' +\ - 'see https://github.com/pyamg/pyamg/issues/159') + #from numpy.testing import dec + #@dec.knownfailureif(True, 'Oblique projectors fail ' +\ + # 'see https://github.com/pyamg/pyamg/issues/159') def test_krylov(self): # Oblique projectors reduce the residual @@ -160,9 +167,14 @@ class TestKrylov(TestCase): (xNew, flag) = method(A, b, x0=x0, tol=case['tol'], maxiter=case['maxiter']) xNew = xNew.reshape(-1, 1) - assert_equal((norm(b - A*xNew)/norm(b - A*x0)) < - case['reduction_factor'], True, - err_msg='Oblique Krylov Method Failed Test') + try: + assert_equal((norm(b - A*xNew)/norm(b - A*x0)) < + case['reduction_factor'], True, + err_msg='Oblique Krylov Method Failed Test') + except AssertionError: + from nose import SkipTest + raise SkipTest('Oblique projectors fail ' +\ + 'see https://github.com/pyamg/pyamg/issues/159') # Oblique projectors reduce the residual, here we consider oblique # projectors for symmetric matrices
change to nose.SkipTest for so that nosetests works
pyamg_pyamg
train
bad0f657de2215947a3dbe4da203969f6c9a97aa
diff --git a/tsdb/engine/tsm1/cache.go b/tsdb/engine/tsm1/cache.go index <HASH>..<HASH> 100644 --- a/tsdb/engine/tsm1/cache.go +++ b/tsdb/engine/tsm1/cache.go @@ -86,7 +86,7 @@ func (a *entries) clone() Values { // dedupe returns a copy of all underlying Values. Values are deduped and sorted. func (a *entries) dedupe() Values { - return a.clone().Deduplicate() + return a.clone().Deduplicate(true) } // Cache maintains an in-memory store of Values for a set of keys. As data is added to the cache @@ -204,7 +204,7 @@ func (c *Cache) Values(key string) Values { if values == nil { return nil } - return values.Deduplicate() + return values.Deduplicate(true) } // evict instructs the cache to evict data up to and including the current checkpoint. diff --git a/tsdb/engine/tsm1/compact.go b/tsdb/engine/tsm1/compact.go index <HASH>..<HASH> 100644 --- a/tsdb/engine/tsm1/compact.go +++ b/tsdb/engine/tsm1/compact.go @@ -287,7 +287,7 @@ func NewWALKeyIterator(readers ...*WALSegmentReader) (KeyIterator, error) { // sort and dedup all the points for each key. for k, v := range series { order = append(order, k) - series[k] = v.Deduplicate() + series[k] = v.Deduplicate(true) } sort.Strings(order) diff --git a/tsdb/engine/tsm1/encoding.go b/tsdb/engine/tsm1/encoding.go index <HASH>..<HASH> 100644 --- a/tsdb/engine/tsm1/encoding.go +++ b/tsdb/engine/tsm1/encoding.go @@ -168,10 +168,10 @@ func DecodeBlock(block []byte, vals []Value) ([]Value, error) { } } -// Deduplicate returns a new Values slice with any values -// that have the same timestamp removed. The Value that appears -// last in the slice is the one that is kept. The returned slice is in ascending order -func (a Values) Deduplicate() Values { +// Deduplicate returns a new Values slice with any values that have the same timestamp removed. +// The Value that appears last in the slice is the one that is kept. The returned slice is then +// sorted in the requested order. +func (a Values) Deduplicate(ascending bool) Values { m := make(map[int64]Value) for _, val := range a { m[val.UnixNano()] = val @@ -181,8 +181,12 @@ func (a Values) Deduplicate() Values { for _, val := range m { other = append(other, val) } - sort.Sort(Values(other)) + if ascending { + sort.Sort(Values(other)) + } else { + sort.Sort(sort.Reverse(Values(other))) + } return other } diff --git a/tsdb/engine/tsm1/log.go b/tsdb/engine/tsm1/log.go index <HASH>..<HASH> 100644 --- a/tsdb/engine/tsm1/log.go +++ b/tsdb/engine/tsm1/log.go @@ -166,12 +166,12 @@ func (l *Log) Cursor(series string, fields []string, dec *tsdb.FieldCodec, ascen copy(c, fc) c = append(c, values...) - return newWALCursor(Values(c).Deduplicate(), ascending) + return newWALCursor(Values(c).Deduplicate(true), ascending) } } if l.cacheDirtySort[ck] { - values = Values(values).Deduplicate() + values = Values(values).Deduplicate(true) } // build a copy so writes afterwards don't change the result set @@ -586,7 +586,7 @@ func (l *Log) flush(flush flushType) error { } l.cache = make(map[string]Values) for k := range l.cacheDirtySort { - l.flushCache[k] = l.flushCache[k].Deduplicate() + l.flushCache[k] = l.flushCache[k].Deduplicate(true) } l.cacheDirtySort = make(map[string]bool) diff --git a/tsdb/engine/tsm1/tsm1.go b/tsdb/engine/tsm1/tsm1.go index <HASH>..<HASH> 100644 --- a/tsdb/engine/tsm1/tsm1.go +++ b/tsdb/engine/tsm1/tsm1.go @@ -1656,12 +1656,12 @@ func (e *Engine) DecodeAndCombine(newValues Values, block, buf []byte, nextTime }) values = append(values, newValues[:pos]...) remainingValues = newValues[pos:] - values = Values(values).Deduplicate() + values = Values(values).Deduplicate(true) } else { requireSort := Values(values).MaxTime() >= newValues.MinTime() values = append(values, newValues...) if requireSort { - values = Values(values).Deduplicate() + values = Values(values).Deduplicate(true) } }
Deduplicate supports requesting sort order
influxdata_influxdb
train
04169852cb8135066391239c4a6ce18bf8c94a80
diff --git a/DataFixtures/ORM/LoadProductStatusData.php b/DataFixtures/ORM/LoadProductStatusData.php index <HASH>..<HASH> 100755 --- a/DataFixtures/ORM/LoadProductStatusData.php +++ b/DataFixtures/ORM/LoadProductStatusData.php @@ -13,8 +13,8 @@ namespace WellCommerce\Bundle\ProductStatusBundle\DataFixtures\ORM; use Doctrine\Common\Persistence\ObjectManager; -use WellCommerce\Bundle\DoctrineBundle\DataFixtures\AbstractDataFixture; use WellCommerce\Bundle\CoreBundle\Helper\Sluggable; +use WellCommerce\Bundle\DoctrineBundle\DataFixtures\AbstractDataFixture; use WellCommerce\Bundle\ProductStatusBundle\Entity\ProductStatus; /**
Insight fixes (cherry picked from commit <I>ad<I>b<I>bbccd<I>a9eaf2f<I>dab<I>e<I>a)
WellCommerce_CouponBundle
train
472f271dd8cf430943c5431b9d9b4b6d7113a0cf
diff --git a/src/main/java/org/mutabilitydetector/unittesting/MutabilityAssert.java b/src/main/java/org/mutabilitydetector/unittesting/MutabilityAssert.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mutabilitydetector/unittesting/MutabilityAssert.java +++ b/src/main/java/org/mutabilitydetector/unittesting/MutabilityAssert.java @@ -26,6 +26,7 @@ import java.util.List; import org.hamcrest.Matcher; import org.mutabilitydetector.AnalysisResult; import org.mutabilitydetector.Configuration; +import org.mutabilitydetector.ConfigurationBuilder; import org.mutabilitydetector.Configurations; import org.mutabilitydetector.IsImmutable; import org.mutabilitydetector.MutabilityReason; @@ -602,6 +603,10 @@ import org.mutabilitydetector.MutableReasonDetail; * @see AnalysisResult * @see MutableReasonDetail * @see IsImmutable + * @see Configuration + * @see Configurations#OUT_OF_THE_BOX_CONFIGURATION + * @see ConfigurationBuilder + * @see MutabilityReason */ public final class MutabilityAssert {
Add more references to javadocs.
MutabilityDetector_MutabilityDetector
train
c085dc72cffc7e964488eccb65bfb01e4c4ec392
diff --git a/bosh-dev/lib/bosh/dev/emitable_example.rb b/bosh-dev/lib/bosh/dev/emitable_example.rb index <HASH>..<HASH> 100644 --- a/bosh-dev/lib/bosh/dev/emitable_example.rb +++ b/bosh-dev/lib/bosh/dev/emitable_example.rb @@ -6,7 +6,7 @@ module Bosh end def metric - 'bosh.ci.bat.duration' + 'ci.bosh.bat.duration' end def value diff --git a/bosh-dev/spec/bosh/dev/data_dog_reporter_spec.rb b/bosh-dev/spec/bosh/dev/data_dog_reporter_spec.rb index <HASH>..<HASH> 100644 --- a/bosh-dev/spec/bosh/dev/data_dog_reporter_spec.rb +++ b/bosh-dev/spec/bosh/dev/data_dog_reporter_spec.rb @@ -19,7 +19,7 @@ module Bosh end it 'should send a message to DataDog when an example passes' do - data_dog_client.should_receive(:emit_point).with('bosh.ci.bat.duration', 3.14, tags: %w[infrastructure:vsphere example:foo-bar-baz]) + data_dog_client.should_receive(:emit_point).with('ci.bosh.bat.duration', 3.14, tags: %w[infrastructure:vsphere example:foo-bar-baz]) sender.report_on(example) end end diff --git a/bosh-dev/spec/bosh/dev/emitable_example_spec.rb b/bosh-dev/spec/bosh/dev/emitable_example_spec.rb index <HASH>..<HASH> 100644 --- a/bosh-dev/spec/bosh/dev/emitable_example_spec.rb +++ b/bosh-dev/spec/bosh/dev/emitable_example_spec.rb @@ -8,7 +8,7 @@ module Bosh let(:example) do double(RSpec::Core::Example, metadata: { - full_description: 'Some context should, r3sult in some_behavior.', + full_description: 'Some context should, r3sult in:some_behavior.', execution_result: {run_time: run_time} }) end @@ -18,7 +18,7 @@ module Bosh EmitableExample.new(example) end - its(:metric) { should eq 'bosh.ci.bat.duration' } + its(:metric) { should eq 'ci.bosh.bat.duration' } its(:value) { should eq run_time } its(:options) { should eq(tags: %w[infrastructure:openstack example:some-context-should-r3sult-in-some-behavior]) } end
Change the BAT DataDog metric name [finish #<I>] * Also make sure that we test that our EmitableExample strips colons out of the example names.
cloudfoundry_bosh
train
85b191c4b9ad4a95dd76ef8f4f3b725f443a660b
diff --git a/tests/unit/utils/config_test.py b/tests/unit/utils/config_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/utils/config_test.py +++ b/tests/unit/utils/config_test.py @@ -218,6 +218,83 @@ class ConfigTestCase(TestCase): } self.assertDictEqual(expected, Requirements.serialize()) + class Requirements2(BaseRequirements): + title = 'Digital Ocean' + description = 'Digital Ocean Cloud VM configuration requirements.' + + personal_access_token = schema.StringItem( + title='Personal Access Token', + description='This is the API access token which can be generated ' + 'under the API/Application on your account', + required=True) + + ssh_key_file = schema.StringItem( + title='SSH Private Key', + description='The path to an SSH private key which will be used ' + 'to authenticate on the deployed VMs') + + ssh_key_names = schema.StringItem( + title='SSH Key Names', + description='The names of an SSH key being managed on ' + 'Digital Ocean account which will be used to ' + 'authenticate on the deployed VMs') + + requirements_definition = schema.AnyOfItem( + items=( + schema.RequirementsItem(requirements=['ssh_key_file']), + schema.RequirementsItem(requirements=['ssh_key_names']) + ), + )(flatten=True) + + expected = { + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Digital Ocean", + "description": "Digital Ocean Cloud VM configuration requirements.", + "type": "object", + "properties": { + "driver": { + "default": "digital_ocean", + "format": "hidden", + "type": "string", + "title": "driver" + }, + "personal_access_token": { + "type": "string", + "description": "This is the API access token which can be " + "generated under the API/Application on your account", + "title": "Personal Access Token" + }, + "ssh_key_file": { + "type": "string", + "description": "The path to an SSH private key which will " + "be used to authenticate on the deployed VMs", + "title": "SSH Private Key" + }, + "ssh_key_names": { + "type": "string", + "description": "The names of an SSH key being managed on Digital " + "Ocean account which will be used to authenticate " + "on the deployed VMs", + "title": "SSH Key Names" + } + }, + "anyOf": [ + {"required": ["ssh_key_file"]}, + {"required": ["ssh_key_names"]} + ], + "required": [ + "personal_access_token" + ], + "x-ordering": [ + "driver", + "personal_access_token", + "ssh_key_file", + "ssh_key_names", + ], + "additionalProperties": False + } + self.assertDictContainsSubset(expected, Requirements2.serialize()) + @skipIf(HAS_JSONSCHEMA is False, 'The \'jsonschema\' library is missing') def test_optional_requirements_config_validation(self): class BaseRequirements(schema.Schema):
Test case to make sure plain string requirements have the same outcome
saltstack_salt
train
3d6a37cecc0e13d821601c1bc592827155999cc9
diff --git a/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsDependencyProcessor.java b/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsDependencyProcessor.java index <HASH>..<HASH> 100755 --- a/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsDependencyProcessor.java +++ b/jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsDependencyProcessor.java @@ -55,6 +55,7 @@ public class JaxrsDependencyProcessor implements DeploymentUnitProcessor { public static final ModuleIdentifier RESTEASY_JAXB = ModuleIdentifier.create("org.jboss.resteasy.resteasy-jaxb-provider"); public static final ModuleIdentifier RESTEASY_JACKSON2 = ModuleIdentifier.create("org.jboss.resteasy.resteasy-jackson2-provider"); public static final ModuleIdentifier RESTEASY_JSON_P_PROVIDER = ModuleIdentifier.create("org.jboss.resteasy.resteasy-json-p-provider"); + public static final ModuleIdentifier RESTEASY_JSON_B_PROVIDER = ModuleIdentifier.create("org.jboss.resteasy.resteasy-json-binding-provider"); public static final ModuleIdentifier RESTEASY_JSAPI = ModuleIdentifier.create("org.jboss.resteasy.resteasy-jsapi"); public static final ModuleIdentifier RESTEASY_MULTIPART = ModuleIdentifier.create("org.jboss.resteasy.resteasy-multipart-provider"); public static final ModuleIdentifier RESTEASY_YAML = ModuleIdentifier.create("org.jboss.resteasy.resteasy-yaml-provider"); @@ -95,6 +96,7 @@ public class JaxrsDependencyProcessor implements DeploymentUnitProcessor { addDependency(moduleSpecification, moduleLoader, RESTEASY_JAXB, true, false); addDependency(moduleSpecification, moduleLoader, RESTEASY_JACKSON2, true, false); addDependency(moduleSpecification, moduleLoader, RESTEASY_JSON_P_PROVIDER, true, false); + addDependency(moduleSpecification, moduleLoader, RESTEASY_JSON_B_PROVIDER, true, false); //addDependency(moduleSpecification, moduleLoader, RESTEASY_JETTISON); addDependency(moduleSpecification, moduleLoader, RESTEASY_JSAPI, true, false); addDependency(moduleSpecification, moduleLoader, RESTEASY_MULTIPART, true, false);
[WFLY-<I>]:Add resteasy-json-binding-provider dependency to jaxrs deployment processor"
wildfly_wildfly
train
bbaa518488f3eb68e25880a171614daa3c1cccd0
diff --git a/fakejuju.py b/fakejuju.py index <HASH>..<HASH> 100644 --- a/fakejuju.py +++ b/fakejuju.py @@ -174,7 +174,15 @@ class FakeEnvironmentState: for containers in self.containers.values(): containers.discard(container_id) - def remove_machine(self, machine_id): + def remove_machine(self, machine_id, force=False): + if not force: + for units, unit_id, loop_machine_id in self.iter_unit_machines(): + if loop_machine_id != machine_id: + continue + logging.error( + 'no machines were destroyed: machine {} has unit "{}"' + ' assigned'.format(machine_id, unit_id)) + raise subprocess.CalledProcessError(1, 'machine assigned.') self.machines.remove(machine_id) self.containers.pop(machine_id, None) @@ -220,13 +228,17 @@ class FakeEnvironmentState: ('{}/{}'.format(service_name, str(len(machines))), self.add_machine())) - def remove_unit(self, to_remove): + def iter_unit_machines(self): for units in self.services.values(): for unit_id, machine_id in units: - if unit_id == to_remove: - self.remove_machine(machine_id) - units.remove((unit_id, machine_id)) - break + yield units, unit_id, machine_id + + def remove_unit(self, to_remove): + for units, unit_id, machine_id in self.iter_unit_machines(): + if unit_id == to_remove: + units.remove((unit_id, machine_id)) + self.remove_machine(machine_id) + break def destroy_service(self, service_name): for unit, machine_id in self.services.pop(service_name): @@ -768,7 +780,7 @@ class FakeBackend: if '/' in machine_id: model_state.remove_container(machine_id) else: - model_state.remove_machine(machine_id) + model_state.remove_machine(machine_id, parsed.force) if command == 'quickstart': parser = ArgumentParser() parser.add_argument('--constraints')
Refuse to remove machines with units.
juju_juju
train
7458f1e7861e5146da61cbff9393d72c88a3608c
diff --git a/airflow/providers/google/cloud/transfers/gcs_to_bigquery.py b/airflow/providers/google/cloud/transfers/gcs_to_bigquery.py index <HASH>..<HASH> 100644 --- a/airflow/providers/google/cloud/transfers/gcs_to_bigquery.py +++ b/airflow/providers/google/cloud/transfers/gcs_to_bigquery.py @@ -20,7 +20,6 @@ import json from typing import Optional, Sequence, Union -from airflow.exceptions import AirflowException from airflow.models import BaseOperator from airflow.providers.google.cloud.hooks.bigquery import BigQueryHook from airflow.providers.google.cloud.hooks.gcs import GCSHook @@ -274,10 +273,6 @@ class GCSToBigQueryOperator(BaseOperator): object_name=self.schema_object, ) schema_fields = json.loads(blob.decode("utf-8")) - elif self.schema_object is None and self.autodetect is False: - raise AirflowException( - 'At least one of `schema_fields`, `schema_object`, or `autodetect` must be passed.' - ) else: schema_fields = None
Remove check for at least one schema in GCSToBigquery (#<I>) For the case when updating an existing table or insert data to a particular partition, no schema is needed. Autodetect doesn't always work, e.g. cannot distinguish partition correctly. Other options requires forking the schema to airflow.
apache_airflow
train
9a66b8182d25a45ba667997611c38433483b7c57
diff --git a/test.py b/test.py index <HASH>..<HASH> 100644 --- a/test.py +++ b/test.py @@ -14,11 +14,16 @@ def identity(f, *a, **k): def f1(): "f1" +def getfname(func): + fname = os.path.basename(func.func_globals['__file__']) + return os.path.splitext(fname)[0] + '.py' + def test0(): - assert os.path.basename(identity.func_globals['__file__']) == 'test.py' + this = getfname(identity) + assert this == 'test.py', this print(identity.__doc__) def test1(): - assert os.path.basename(f1.func_globals['__file__']) == 'test.py' + this = getfname(f1) + assert this == 'test.py', this print(f1.__doc__) -
Fixed two tests of the decorator module
micheles_decorator
train
0fa75c089cb190cd0a3f780d17fa9a7ae9c5ee16
diff --git a/bumpr/helpers.py b/bumpr/helpers.py index <HASH>..<HASH> 100644 --- a/bumpr/helpers.py +++ b/bumpr/helpers.py @@ -4,9 +4,6 @@ from __future__ import print_function, unicode_literals import logging import shlex import subprocess -import sys - -IS_PY26 = sys.version_info[:2] == (2, 6) class BumprError(Exception): @@ -43,8 +40,6 @@ def execute(command, verbose=False, replacements=None, dryrun=False): commands.append([part.format(**replacements) for part in cmd]) else: command = command.format(**replacements) - if IS_PY26: - command = command.encode('utf8') commands = [shlex.split(cmd.strip()) for cmd in command.splitlines() if cmd.strip()] output = ''
Drop some py<I> specific code
noirbizarre_bumpr
train
6d780106502509b2598f4f1b9b2b647230ec8d7c
diff --git a/src/util.js b/src/util.js index <HASH>..<HASH> 100644 --- a/src/util.js +++ b/src/util.js @@ -70,13 +70,27 @@ function mixin(target, source, force) { } /** - * Get a globally unique ID + * Get a unique ID. * @method getId * @static */ function getId() { - // TODO: make better. - return 'getid-' + Math.random(); + var guid = 'guid', + domain = 12; + if (typeof crypto === 'object') { + var buffer = new Uint8Array(domain); + crypto.getRandomValues(buffer); + eachReverse(buffer, function(n) { + guid += '-' + n; + }); + } else { + while (domain > 0) { + guid += '-' + Math.ceil(255 * Math.random()); + domain -= 1; + } + } + + return guid; } /** @@ -204,8 +218,9 @@ function getURL(blob) { } /** - * Provide a source URL which to generate an AppContext compatible with - * the current instance of freedom. + * Provide a version of src where the 'isAppContext' function will return true. + * Used for creating app contexts which may not be able to determine that they + * need to start up as applications by themselves. * @method forceAppContext * @static */ @@ -217,8 +232,8 @@ function forceAppContext(src) { } /** - * Advertise freedom when running in a priviledged context for registration - * of context specific providers. + * When running in a priviledged context, honor a global + * 'freedomcfg' function to allow registration of additional API providers. * @method advertise * @static */
fix bug in getId() for better guid generation
freedomjs_freedom
train
bfc6ce95e4b4938afa6b3644cc35aea29cc60ead
diff --git a/src/flux-dispatcher.js b/src/flux-dispatcher.js index <HASH>..<HASH> 100644 --- a/src/flux-dispatcher.js +++ b/src/flux-dispatcher.js @@ -70,7 +70,6 @@ export class FluxDispatcher { this.typesPromises = new Map(); this.instanceDispatchers.forEach((dispatchers, type) => { - var typePromise = this.getOrCreateTypePromises(type); var promises = []; @@ -117,8 +116,16 @@ export class FluxDispatcher { return this.getOrCreateTypePromises(type.prototype).promise; }); + var def = Promise.defer(); + Promise.settle(typesPromises).then(() => { - handler(); + Promise.resolve(handler()).then((ret) => { + def.resolve(ret); + }).catch((err) => { + def.reject(err); + }); }); + + return def.promise; } -} \ No newline at end of file +} diff --git a/src/instance-dispatcher.js b/src/instance-dispatcher.js index <HASH>..<HASH> 100644 --- a/src/instance-dispatcher.js +++ b/src/instance-dispatcher.js @@ -53,11 +53,11 @@ export class Dispatcher { registerMetadata() { var metadata = Metadata.getOrCreateMetadata(Object.getPrototypeOf(this.instance)); - metadata.awaiters.forEach((types, methodName) => { + metadata.awaiters.forEach((types, methodName) => { if(this.instance[methodName] !== undefined && typeof this.instance[methodName] === 'function') { var methodImpl = this.instance[methodName]; - this.instance[methodName] = (...args) => { - FluxDispatcher.instance.waitFor(types, () => { + this.instance[methodName] = (...args) => { + return FluxDispatcher.instance.waitFor(types, () => { methodImpl.apply(this.instance, args); }); }; @@ -98,4 +98,4 @@ export class DispatcherProxy { this.instance[Symbols.instanceDispatcher].dispatch(event, payload); }); } -} \ No newline at end of file +}
fix(waitFor): @waitFor decorated handler will now properly handle dispatch
tfrydrychewicz_aurelia-flux
train
f5e359f70408d565ae8754e83cc4f9dd3b493b43
diff --git a/UntappdClient.js b/UntappdClient.js index <HASH>..<HASH> 100644 --- a/UntappdClient.js +++ b/UntappdClient.js @@ -151,7 +151,7 @@ var UntappdClient = function(debug) { that.getUserAuthenticationURL = function(returnRedirectionURL) { if (returnRedirectionURL===undefined || returnRedirectionURL===null) throw new Error("returnRedirectionURL cannot be undefined or null."); if (!hasId() || !hasSecret()) throw new Error("UntappdClient.getUserAuthenticationURL requires a ClientId/ClientSecret pair."); - return "http://untappd.com/oauth/authenticate/?client_id="+id+"&response_type=token&redirect_url="+returnRedirectionURL; + return "https://untappd.com/oauth/authenticate/?client_id="+id+"&response_type=token&redirect_url="+returnRedirectionURL; }; //this is for server-side, Step 1 - OAUTH Authentication
Switch Auth call to use SSL Received this email and was digging through our Hubot script to ensure everything would continue working. This appears to be the only instance where SSL is not being used. --- >As an Untappd API developer, we wanted to inform you that you will need to update your application to use our secure, HTTPS API endpoint (<URL>
arei_node-untappd
train
dfb57e33bcada12647fb916b6d971a541d2cbb9b
diff --git a/lib/simple_form/inputs/base.rb b/lib/simple_form/inputs/base.rb index <HASH>..<HASH> 100644 --- a/lib/simple_form/inputs/base.rb +++ b/lib/simple_form/inputs/base.rb @@ -100,7 +100,7 @@ module SimpleForm end def action_validators?(validator) - validator.options.include?(:on) ? ACTIONS[validator.options[:on]] == template.controller.action_name.to_sym : true + validator.options.include?(:on) ? ACTIONS[validator.options[:on].to_sym] == template.controller.action_name.to_sym : true end def attribute_required_by_default?
Feature #<I> re-fixed for ruby <I>
plataformatec_simple_form
train
cbf015164ceeec55bbd1b43726eb999cd0b9d42a
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -79,7 +79,7 @@ v0.9.0 (201x-xx-xx) they can also define the needed logic in their command classes by implementing `Predis\Command\PrefixableCommandInterface` just like before. -- The client can now send raw commands using the `Predis\Client::raw()` method. +- The client can now send raw commands using `Predis\Client::executeRaw()`. v0.8.5 (2013-xx-xx) diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ responses. Users must provide the arguments list as an array, following the comm defined by the [Redis documentation for commands](http://redis.io/commands): ```php -$response = $client->raw(['SET', 'foo', 'bar']); +$response = $client->executeRaw(['SET', 'foo', 'bar']); ``` diff --git a/examples/SendingRedisCommands.php b/examples/SendingRedisCommands.php index <HASH>..<HASH> 100644 --- a/examples/SendingRedisCommands.php +++ b/examples/SendingRedisCommands.php @@ -44,7 +44,9 @@ array ( // commands to Redis the usual way and the "raw" way is that in the latter case // their arguments are not filtered nor responses coming from Redis are parsed. -$response = $client->raw(array('MGET', 'uid:0001', 'uid:0002', 'uid:0003')); +$response = $client->executeRaw(array( + 'MGET', 'uid:0001', 'uid:0002', 'uid:0003' +)); var_export($response); echo PHP_EOL; /* OUTPUT: diff --git a/lib/Predis/Client.php b/lib/Predis/Client.php index <HASH>..<HASH> 100644 --- a/lib/Predis/Client.php +++ b/lib/Predis/Client.php @@ -263,7 +263,7 @@ class Client implements ClientInterface * @param bool $error Set to TRUE when Redis returned an error response. * @return mixed */ - public function raw(array $arguments, &$error = null) + public function executeRaw(array $arguments, &$error = null) { $error = false; diff --git a/tests/Predis/ClientTest.php b/tests/Predis/ClientTest.php index <HASH>..<HASH> 100644 --- a/tests/Predis/ClientTest.php +++ b/tests/Predis/ClientTest.php @@ -518,11 +518,11 @@ class ClientTest extends PredisTestCase $client = new Client($connection); - $this->assertSame('OK', $client->raw(array('SET', 'foo', 'bar'))); - $this->assertSame('bar', $client->raw(array('GET', 'foo'))); + $this->assertSame('OK', $client->executeRaw(array('SET', 'foo', 'bar'))); + $this->assertSame('bar', $client->executeRaw(array('GET', 'foo'))); $error = true; // $error is always populated by reference. - $this->assertSame('PONG', $client->raw(array('PING'), $error)); + $this->assertSame('PONG', $client->executeRaw(array('PING'), $error)); $this->assertFalse($error); } @@ -543,8 +543,8 @@ class ClientTest extends PredisTestCase $client = new Client($connection, array('prefix' => 'predis:')); - $this->assertSame('OK', $client->raw(array('SET', 'foo', 'bar'))); - $this->assertSame('bar', $client->raw(array('GET', 'foo'))); + $this->assertSame('OK', $client->executeRaw(array('SET', 'foo', 'bar'))); + $this->assertSame('bar', $client->executeRaw(array('GET', 'foo'))); } /** @@ -563,7 +563,7 @@ class ClientTest extends PredisTestCase $client = new Client($connection, array('exceptions' => true)); - $this->assertSame($message, $client->raw(array('PING'), $error)); + $this->assertSame($message, $client->executeRaw(array('PING'), $error)); $this->assertTrue($error); }
Rename Predis\Client::raw() to Predis\Client::executeRaw(). This is more consistent with Predis\Client::executeRaw() and its more explicit since simply "raw" as a method name was a bit too vague even despite being nicely short.
nrk_predis
train
298a22d96ca512ab3910303ae8f2913e608d0a64
diff --git a/pylint/message/message_handler_mix_in.py b/pylint/message/message_handler_mix_in.py index <HASH>..<HASH> 100644 --- a/pylint/message/message_handler_mix_in.py +++ b/pylint/message/message_handler_mix_in.py @@ -343,7 +343,7 @@ class MessagesHandlerMixIn: } return by_checker - def get_full_documentation(self): + def get_checkers_documentation(self): result = get_rst_title("Pylint global options and switches", "-") result += """ Pylint provides global options and switches. @@ -384,7 +384,7 @@ Below is a list of all checkers and their features. """output a full documentation in ReST format""" if not stream: stream = sys.stdout - print(self.get_full_documentation()[:-1], file=stream) + print(self.get_checkers_documentation()[:-1], file=stream) @staticmethod def _print_checker_doc(information, stream=None):
Refactor - Rename an overlapsing function in MessageHandlerMixIn BaseChecker and MessageHandlerMixIn can be the same instance.
PyCQA_pylint
train
09fd4edfd01c1744052f8db1c36f9641e865507b
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -80,7 +80,8 @@ class Data { this.fanout = fanout this.blockSizes = blockSizes || [] this.mtime = mtime || new Date(0) - this.mode = mode + this.mode = mode || mode === 0 ? (mode & 0xFFF) : undefined + this._originalMode = mode if (this.mode === undefined && type === 'file') { this.mode = DEFAULT_FILE_MODE @@ -151,8 +152,8 @@ class Data { let mode - if (!isNaN(parseInt(this.mode))) { - mode = this.mode + if (this.mode || this.mode === 0) { + mode = (this._originalMode & 0xFFFFF000) | (this.mode & 0xFFF) if (mode === DEFAULT_FILE_MODE && this.type === 'file') { mode = undefined diff --git a/test/unixfs-format.spec.js b/test/unixfs-format.spec.js index <HASH>..<HASH> 100644 --- a/test/unixfs-format.spec.js +++ b/test/unixfs-format.spec.js @@ -13,6 +13,8 @@ const directory = loadFixture('test/fixtures/directory.unixfs') const file = loadFixture('test/fixtures/file.txt.unixfs') const symlink = loadFixture('test/fixtures/symlink.txt.unixfs') const { Buffer } = require('buffer') +const protons = require('protons') +const unixfsData = protons(require('../src/unixfs.proto')).Data describe('unixfs-format', () => { it('defaults to file', () => { @@ -145,6 +147,20 @@ describe('unixfs-format', () => { expect(UnixFS.unmarshal(data.marshal())).to.have.deep.property('mtime', new Date(Math.round(mtime.getTime() / 1000) * 1000)) }) + it('does not overwrite unknown mode bits', () => { + const mode = 0xFFFFFFF // larger than currently defined mode bits + const buf = unixfsData.encode({ + Type: 0, + mode + }) + + const unmarshaled = UnixFS.unmarshal(buf) + const marshaled = unmarshaled.marshal() + + const entry = unixfsData.decode(marshaled) + expect(entry).to.have.property('mode', mode) + }) + // figuring out what is this metadata for https://github.com/ipfs/js-ipfs-data-importing/issues/3#issuecomment-182336526 it.skip('metadata', () => {})
fix: mask file mode (#<I>) Only expose documented bits to calling code but respect them when turning the entry into a protobuf.
ipfs_js-ipfs-unixfs
train
45603be3298366394fef05125d36f00c2fcccd04
diff --git a/lib/models/messaging_client.js b/lib/models/messaging_client.js index <HASH>..<HASH> 100644 --- a/lib/models/messaging_client.js +++ b/lib/models/messaging_client.js @@ -129,6 +129,7 @@ function MessagingClient(type) { context.sendRedundantly(data, function(err, result){ vennApiService.postLog(context.apiKey, sendLog); if(err) return callback( err ); + // TODO: Should result being undefined indicate an error was logged in sendLog and should this be propagated back? return callback( null, {"service": result} ); }) }) diff --git a/lib/models/messaging_service_status.js b/lib/models/messaging_service_status.js index <HASH>..<HASH> 100644 --- a/lib/models/messaging_service_status.js +++ b/lib/models/messaging_service_status.js @@ -5,7 +5,8 @@ var codes = { SUCCESS : 'MESSAGE_SENT', QUEUED : 'MESSAGE_QUEUED', LIMIT_EXCEEDED : 'LIMIT_EXCEEDED_ERROR', - SERVICE_DOWN : 'SERVICE_DOWN_ERROR' + SERVICE_DOWN : 'SERVICE_DOWN_ERROR', + DATA_REJECTED : 'DATA_REJECTED_ERROR' } function MessagingServiceStatus(service) { diff --git a/lib/models/providers/sms/twilio.js b/lib/models/providers/sms/twilio.js index <HASH>..<HASH> 100644 --- a/lib/models/providers/sms/twilio.js +++ b/lib/models/providers/sms/twilio.js @@ -71,8 +71,9 @@ function TwilioServiceStatus(response, success) { // There was an error when attempting to send message this.state.message = response.message + ': ' + response.moreInfo; - // See https://www.twilio.com/docs/statusors for status error codes + // See https://www.twilio.com/docs/errors for status error codes if (response.code == 20003 || response.code == 20005) this.state.code = this.StatusCodes.LIMIT_EXCEEDED; // should only be code 20005, but Twilio doesn't seem to follow its own documentation + else if (response.code == 21210) this.state.code = this.StatusCodes.DATA_REJECTED; else this.state.code = this.StatusCodes.DEFAULT; } } diff --git a/test/sms/twilio/error.js b/test/sms/twilio/error.js index <HASH>..<HASH> 100644 --- a/test/sms/twilio/error.js +++ b/test/sms/twilio/error.js @@ -2,6 +2,8 @@ var assert = require("assert") var nock = require("nock") var client = require("../../../lib/index").SMS; var MessagingUserStatus = require('../../../lib/models/messaging_user_status'); +var MessagingServiceStatus = require('../../../lib/models/messaging_service_status'); +var StatusCodes = (new MessagingServiceStatus()).StatusCodes; var UserCodes = (new MessagingUserStatus()).StatusCodes; describe('receive error from twilio', function () { @@ -104,4 +106,28 @@ describe('receive error from twilio', function () { done() }) }) + + it("when from number is formatted correctly but isn't a valid twilio number associated with your account", function (done) { + nock.cleanAll(); + nock('https://api.getvenn.io/v1') + .get('/keys/sms') + .reply(200, { + "twilio": { + "account_sid": "sldkfjdslkjf", + "auth_token": "sldkfjdslkjf" + } + }); + nock('https://api.twilio.com:443') + .post('/2010-04-01/Accounts/sldkfjdslkjf/Messages.json') + .reply(401, {'status': 401, 'message': "'From' phone number not verified", 'code': 21210, 'moreInfo': 'https://www.twilio.com/docs/errors/21210'}); + nock('https://api.getvenn.io/v1') + .get('/priority/sms') + .reply(200, [ "twilio"]); + + client.initialize(); + client.send({to:"15135549122", from: "12345678900", message:"message-13579"}, function(err, result){ + assert.equal(this.sendLog[0].code, StatusCodes.DATA_REJECTED); + done() + }) + }) }) \ No newline at end of file
Update Twilio service status handler to handle unregistered 'from' numbers. Test covers contents of sendLog. resolves #<I>
TeamLifecycle_venn-messaging-node
train
22b2328e26fd112d80cf131bd9b5093bd227f1c9
diff --git a/container/src/main/java/org/wildfly/swarm/container/Container.java b/container/src/main/java/org/wildfly/swarm/container/Container.java index <HASH>..<HASH> 100644 --- a/container/src/main/java/org/wildfly/swarm/container/Container.java +++ b/container/src/main/java/org/wildfly/swarm/container/Container.java @@ -34,6 +34,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.OptionalInt; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; @@ -106,21 +107,7 @@ public class Container { * @throws Exception If an error occurs performing classloading and initialization magic. */ public Container(boolean debugBootstrap) throws Exception { - System.setProperty(SwarmInternalProperties.VERSION, VERSION); - - try { - String stageFile = System.getProperty(SwarmProperties.PROJECT_STAGE_FILE); - if (stageFile != null) { - loadStageConfiguration(new URL(stageFile)); - } - - } catch (MalformedURLException e) { - System.err.println("[WARN] Failed to parse project stage URL reference, ignoring: " + e.getMessage()); - } - - createServer(debugBootstrap); - createShrinkWrapDomain(); - determineDeploymentType(); + this(debugBootstrap, new String[]{}); } /** @@ -143,9 +130,24 @@ public class Container { * @throws Exception If an error occurs performing classloading and initialization magic. */ public Container(boolean debugBootstrap, String... args) throws Exception { - this(debugBootstrap); + System.setProperty(SwarmInternalProperties.VERSION, VERSION); + + createServer(debugBootstrap); + createShrinkWrapDomain(); + determineDeploymentType(); + CommandLine cmd = CommandLine.parse(args); cmd.apply(this); + + try { + String stageFile = System.getProperty(SwarmProperties.PROJECT_STAGE_FILE); + if (stageFile != null) { + loadStageConfiguration(new URL(stageFile)); + } + + } catch (MalformedURLException e) { + System.err.println("[WARN] Failed to parse project stage URL reference, ignoring: " + e.getMessage()); + } } public Container withXmlConfig(URL url) { @@ -154,8 +156,9 @@ public class Container { } public Container withStageConfig(URL url) { + this.stageConfigUrl = Optional.of(url); if (null == System.getProperty(SwarmProperties.PROJECT_STAGE_FILE)) { - loadStageConfiguration(url); + loadStageConfiguration(stageConfigUrl.get()); } else { System.out.println("[INFO] Project stage superseded by external configuration " + System.getProperty(SwarmProperties.PROJECT_STAGE_FILE)); } @@ -195,7 +198,7 @@ public class Container { props.load(in); if (props.containsKey(BootstrapProperties.APP_ARTIFACT)) { System.setProperty(BootstrapProperties.APP_ARTIFACT, - props.getProperty(BootstrapProperties.APP_ARTIFACT)); + props.getProperty(BootstrapProperties.APP_ARTIFACT)); } Set<String> names = props.stringPropertyNames(); @@ -234,9 +237,9 @@ public class Container { if (!this.dependentFractions.isEmpty()) { this.dependentFractions.stream() .filter(dependentFraction -> - this.fractions.get(dependentFraction.getClass()) == null - || (this.fractions.get(dependentFraction.getClass()) != null - && this.defaultFractionTypes.contains(dependentFraction.getClass()))) + this.fractions.get(dependentFraction.getClass()) == null + || (this.fractions.get(dependentFraction.getClass()) != null + && this.defaultFractionTypes.contains(dependentFraction.getClass()))) .forEach(this::fraction); this.dependentFractions.clear(); } @@ -327,8 +330,16 @@ public class Container { public Container start(boolean eagerlyOpen) throws Exception { if (!this.running) { - setupXmlConfig(); - setupStageConfig(); + if (stageConfig.isPresent()) { + + System.out.println("[INFO] Starting container with stage config source : " + stageConfigUrl.get()); + this.server.setStageConfig(stageConfig.get()); + } + + if (xmlConfig.isPresent()) { + System.out.println("[INFO] Starting container with xml config source : " + xmlConfig.get()); + this.server.setXmlConfig(xmlConfig.get()); + } this.deployer = this.server.start(this, eagerlyOpen); this.running = true; @@ -337,7 +348,7 @@ public class Container { return this; } - private void setupStageConfig() throws Exception { + /* private void setupStageConfig() throws Exception { ProjectStage projectStage = stageConfig.isPresent() ? stageConfig.get() : null; // auto discover META-INF/project-stages.yml in default deployment @@ -368,7 +379,7 @@ public class Container { if (configURL != null) { this.server.setXmlConfig(configURL); } - } + }*/ /** * Stop the container, undeploying all deployments. @@ -794,6 +805,8 @@ public class Container { private Optional<URL> xmlConfig = Optional.empty(); + private Optional<URL> stageConfigUrl = Optional.empty(); + private Archive<?> defaultDeployment; private URL defaultDeploymentURL;
Consolidate ctor code path in Container.class
thorntail_thorntail
train
22aef0124e2a8f6d5fa7395410faf3f498ffc044
diff --git a/doc/05-repositories.md b/doc/05-repositories.md index <HASH>..<HASH> 100644 --- a/doc/05-repositories.md +++ b/doc/05-repositories.md @@ -229,22 +229,18 @@ In this case the short name of the channel is `pear2`, so the It is possible to alias all pear channel packages with custom name. Example: - You own private pear repository and going to use composer abilities to bring - dependencies from vcs or transit to composer repository scheme. - List of packages: +You own private pear repository and going to use composer abilities to bring dependencies from vcs or transit to composer repository scheme. +Your repository list of packages: * BasePackage, requires nothing * IntermediatePackage, depends on BasePackage * TopLevelPackage1 and TopLevelPackage2 both dependth on IntermediatePackage. - For composer it looks like: + +For composer it looks like: * "pear-pear.foobar.repo/IntermediatePackage" depends on "pear-pear.foobar.repo/BasePackage", * "pear-pear.foobar.repo/TopLevelPackage1" depends on "pear-pear.foobar.repo/IntermediatePackage", * "pear-pear.foobar.repo/TopLevelPackage2" depends on "pear-pear.foobar.repo/IntermediatePackage" - When you update one of your packages to composer naming scheme or made it - available through vcs your older dependencies would not see new version cause it would be named - like "foobar/IntermediatePackage". - Specifying 'vendor-alias' for pear repository you will get all its packages aliased with composer-like names. - Following example would take BasePackage, TopLevelPackage1 and TopLevelPackage2 packages from pear repository - and IntermediatePackage from github repository: + +When you update one of your packages to composer naming scheme or made it available through vcs, your older dependencies would not see new version, cause it would be named like "foobar/IntermediatePackage". Specifying 'vendor-alias' for pear repository, you will get all its packages aliased with composer-like names. Following example would take BasePackage, TopLevelPackage1 and TopLevelPackage2 packages from pear repository and IntermediatePackage from github repository: { "repositories": [ diff --git a/src/Composer/Package/Locker.php b/src/Composer/Package/Locker.php index <HASH>..<HASH> 100644 --- a/src/Composer/Package/Locker.php +++ b/src/Composer/Package/Locker.php @@ -211,7 +211,7 @@ class Locker } $name = $package->getPrettyName(); - $version = $package->getVersion(); + $version = $package->getPrettyVersion(); if (!$name || !$version) { throw new \LogicException(sprintf( diff --git a/src/Composer/Repository/PearRepository.php b/src/Composer/Repository/PearRepository.php index <HASH>..<HASH> 100644 --- a/src/Composer/Repository/PearRepository.php +++ b/src/Composer/Repository/PearRepository.php @@ -91,9 +91,13 @@ class PearRepository extends ArrayRepository $result = array(); foreach ($channelInfo->getPackages() as $packageDefinition) { foreach ($packageDefinition->getReleases() as $version => $releaseInfo) { - $normalizedVersion = $this->parseVersion($version); - if (!$normalizedVersion) { - continue; // skip packages with unparsable versions + try { + $normalizedVersion = $versionParser->normalize($version); + } catch (\UnexpectedValueException $e) { + if ($this->io->isVerbose()) { + $this->io->write('Could not load '.$packageDefinition->getPackageName().' '.$version.': '.$e->getMessage()); + } + continue; } $composerPackageName = $this->buildComposerPackageName($packageDefinition->getChannelName(), $packageDefinition->getPackageName()); @@ -175,24 +179,4 @@ class PearRepository extends ArrayRepository return "pear-{$channelName}/{$packageName}"; } - - /** - * Softened version parser. - * - * @param string $version - * @return null|string - */ - private function parseVersion($version) - { - if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?}i', $version, $matches)) { - $version = $matches[1] - .(!empty($matches[2]) ? $matches[2] : '.0') - .(!empty($matches[3]) ? $matches[3] : '.0') - .(!empty($matches[4]) ? $matches[4] : '.0'); - - return $version; - } - - return null; - } } diff --git a/tests/Composer/Test/Package/LockerTest.php b/tests/Composer/Test/Package/LockerTest.php index <HASH>..<HASH> 100644 --- a/tests/Composer/Test/Package/LockerTest.php +++ b/tests/Composer/Test/Package/LockerTest.php @@ -138,7 +138,7 @@ class LockerTest extends \PHPUnit_Framework_TestCase ->will($this->returnValue('pkg1')); $package1 ->expects($this->once()) - ->method('getVersion') + ->method('getPrettyVersion') ->will($this->returnValue('1.0.0-beta')); $package2 @@ -147,7 +147,7 @@ class LockerTest extends \PHPUnit_Framework_TestCase ->will($this->returnValue('pkg2')); $package2 ->expects($this->once()) - ->method('getVersion') + ->method('getPrettyVersion') ->will($this->returnValue('0.1.10')); $json
Revert Locker change, ignore PEAR packages whose version cannot be parsed.
mothership-ec_composer
train
ccf7723778676b2b1f8ce3844c4ccb7dd855ff0f
diff --git a/lib/adhearsion/voip/asterisk/commands.rb b/lib/adhearsion/voip/asterisk/commands.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/voip/asterisk/commands.rb +++ b/lib/adhearsion/voip/asterisk/commands.rb @@ -929,10 +929,10 @@ module Adhearsion end # allows setting of the callerid number of the call - def set_caller_id_number(caller_id) - return unless caller_id - raise ArgumentError, "Caller ID must be numerical" if caller_id.to_s !~ /^\d+$/ - response "SET CALLERID", caller_id + def set_caller_id_number(caller_id_num) + return unless caller_id_num + raise ArgumentError, "Caller ID must be numeric" if caller_id_num.to_s !~ /^\d+$/ + variable "CALLERID(num)" => caller_id_num end # allows the setting of the callerid name of the call diff --git a/spec/voip/asterisk/test_commands.rb b/spec/voip/asterisk/test_commands.rb index <HASH>..<HASH> 100644 --- a/spec/voip/asterisk/test_commands.rb +++ b/spec/voip/asterisk/test_commands.rb @@ -1668,7 +1668,7 @@ context "set_caller_id_number command" do test "should encapsulate the number with quotes" do caller_id = "14445556666" - mock_call.should_receive(:raw_response).once.with(%(SET CALLERID "#{caller_id}")).and_return true + mock_call.should_receive(:raw_response).once.with(%(SET VARIABLE "CALLERID(num)" "#{caller_id}")).and_return true mock_call.send(:set_caller_id_number, caller_id) end end
[#<I>] Allow :name and :caller_id to be used together on dial() method
adhearsion_adhearsion
train
6ebd308237c12138eaf40bd149e74267ebcb7e59
diff --git a/lib/sendwithus.rb b/lib/sendwithus.rb index <HASH>..<HASH> 100644 --- a/lib/sendwithus.rb +++ b/lib/sendwithus.rb @@ -28,7 +28,17 @@ module SendWithUs @debug = options[:debug] || false end + ## + # send a templated email! + + def send(email_name, email_to, data = {}) + data[:email_name] = email_name + data[:email_to] = email_to + return api_request("send", data) + end + private + ## # used to build the request path @@ -39,8 +49,6 @@ module SendWithUs return path end - private - ## # used to send the actual http request # ignores response and sends synchronously atm @@ -59,17 +67,6 @@ module SendWithUs return response end - - public - - ## - # send a templated email! - - def send(email_name, email_to, data = {}) - data[:email_name] = email_name - data[:email_to] = email_to - return api_request("send", data) - end end end
Move code around to stop using public/private unecessarily. Public marks all methods after it as public. Private does the same. Initially, methods are public, so I've reduced this to just one use of "private"
sendwithus_sendwithus_ruby
train
e0f6d476dbd980e4587502d0936505f7e675eb33
diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/model/Queue.java +++ b/core/src/main/java/hudson/model/Queue.java @@ -1365,14 +1365,18 @@ public class Queue extends ResourceController implements Saveable { * to the queue, and the task will never get executed. * * <p> - * This extension point is still a subject to change, as we are seeking more - * comprehensive Queue pluggability. See HUDSON-2072. + * The other use case is to add additional {@link Action}s to the task + * (for example {@link LabelAssignmentAction}) to tasks that are submitted to the queue. * * @since 1.316 */ public static abstract class QueueDecisionHandler implements ExtensionPoint { /** * Returns whether the new item should be scheduled. + * + * @param actions + * List of actions that are to be made available as {@link AbstractBuild#getActions()} + * upon the start of the build. This list is live, and can be mutated. */ public abstract boolean shouldSchedule(Task p, List<Action> actions); diff --git a/core/src/main/java/hudson/model/labels/LabelAssignmentAction.java b/core/src/main/java/hudson/model/labels/LabelAssignmentAction.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/model/labels/LabelAssignmentAction.java +++ b/core/src/main/java/hudson/model/labels/LabelAssignmentAction.java @@ -2,13 +2,26 @@ package hudson.model.labels; import hudson.model.Action; import hudson.model.Label; +import hudson.model.LoadBalancer; import hudson.model.Queue; +import hudson.model.Queue.QueueDecisionHandler; +import hudson.model.Queue.Task; import hudson.model.queue.SubTask; /** * {@link Action} that can be submitted to {@link Queue} that controls where * the task runs. * + * <h2>Where to insert {@link LabelAssignmentAction}s</h2> + * <p> + * If you control when the task gets submitted to the queue, you can associate this action + * to the task by passing it as a parameter to method like {@link Queue#schedule(Task, int, Action...)}. + * + * <p> + * If you want to globally affect the scheduling decision, you can do so by {@link QueueDecisionHandler} + * and alter the list of actions that you get. Alternatively, you can implement your own {@link LoadBalancer} + * and bypass the whole label/assignment mechanism to control the decision into your own hands. + * * @author Kohsuke Kawaguchi * @since 1.416 */
expanding the contract to improve the usability of LabelAssignmentAction
jenkinsci_jenkins
train
12b51ff859ffaee3dfb46c29a72445894ab4a20f
diff --git a/command/agent/cache/lease_cache.go b/command/agent/cache/lease_cache.go index <HASH>..<HASH> 100644 --- a/command/agent/cache/lease_cache.go +++ b/command/agent/cache/lease_cache.go @@ -12,6 +12,7 @@ import ( "io/ioutil" "net/http" "strings" + "sync" "github.com/hashicorp/errwrap" hclog "github.com/hashicorp/go-hclog" @@ -69,6 +70,7 @@ type LeaseCache struct { logger hclog.Logger db *cachememdb.CacheMemDB baseCtxInfo *cachememdb.ContextInfo + l *sync.RWMutex } // LeaseCacheConfig is the configuration for initializing a new @@ -108,6 +110,7 @@ func NewLeaseCache(conf *LeaseCacheConfig) (*LeaseCache, error) { logger: conf.Logger, db: db, baseCtxInfo: baseCtxInfo, + l: &sync.RWMutex{}, }, nil } @@ -305,7 +308,9 @@ func (c *LeaseCache) Send(ctx context.Context, req *SendRequest) (*SendResponse, func (c *LeaseCache) createCtxInfo(ctx context.Context) *cachememdb.ContextInfo { if ctx == nil { + c.l.RLock() ctx = c.baseCtxInfo.Ctx + c.l.RUnlock() } return cachememdb.NewContextInfo(ctx) } @@ -500,14 +505,15 @@ func (c *LeaseCache) handleCacheClear(ctx context.Context, clearType string, cle // Cancel the base context which triggers all the goroutines to // stop and evict entries from cache. c.logger.Debug("canceling base context") + c.l.Lock() c.baseCtxInfo.CancelFunc() - // Reset the base context baseCtx, baseCancel := context.WithCancel(ctx) c.baseCtxInfo = &cachememdb.ContextInfo{ Ctx: baseCtx, CancelFunc: baseCancel, } + c.l.Unlock() // Reset the memdb instance if err := c.db.Flush(); err != nil {
Add locking around base context (#<I>) Got offline 👍 from Calvin.
hashicorp_vault
train
033813421d0f644077887cb908f87ba747a7561e
diff --git a/lib/Base.js b/lib/Base.js index <HASH>..<HASH> 100644 --- a/lib/Base.js +++ b/lib/Base.js @@ -32,6 +32,12 @@ Base.prototype.init = function(iface,callback) { } if(callback) callback(err,self.properties); + + // emit current properties after init callback, + // so added listeners can pick it up + for(var type in self.properties) { + self.emit(type,self.properties[type]); + } }); // Monitor manager and technogy API self.connman.on('ServicesChanged',onServicesChanged.bind(self)); @@ -139,10 +145,10 @@ Base.prototype._setService = function(serviceName,callback) { } self.service = service; self.serviceProperties = Parser.parseService(serviceProperties); - self.service.on('PropertyChanged', onServicePropertyChanged.bind(self)); for(var type in self.serviceProperties) { self.emit(type,self.serviceProperties[type]); } + self.service.on('PropertyChanged', onServicePropertyChanged.bind(self)); self.emit('serviceChanged',self.service,self.serviceProperties); }); };
emit current properties after init callback
Doodle3D_connman-simplified
train
27649b81ee35dac0e51885ad4faac13a80153be7
diff --git a/spec/dummy/config/environments/test.rb b/spec/dummy/config/environments/test.rb index <HASH>..<HASH> 100644 --- a/spec/dummy/config/environments/test.rb +++ b/spec/dummy/config/environments/test.rb @@ -12,10 +12,6 @@ Rails.application.configure do # preloads Rails for running tests, you may have to set it to true. config.eager_load = false - # Configure static asset server for tests with Cache-Control for performance. - config.serve_static_assets = true - config.static_cache_control = 'public, max-age=3600' - # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false
Removes deprecated settings from dummy app's test environment
csm123_starburst
train
5fd23e49a0155c04b53dcaf4d5a18e31511c76ab
diff --git a/src/Illuminate/Cache/RedisTaggedCache.php b/src/Illuminate/Cache/RedisTaggedCache.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Cache/RedisTaggedCache.php +++ b/src/Illuminate/Cache/RedisTaggedCache.php @@ -9,13 +9,13 @@ class RedisTaggedCache extends TaggedCache * * @var string */ - const REFERENCE_KEY_FOREVER = 'forever'; + const REFERENCE_KEY_FOREVER = 'forever_ref'; /** * Standard reference key. * * @var string */ - const REFERENCE_KEY_STANDARD = 'standard'; + const REFERENCE_KEY_STANDARD = 'standard_ref'; /** * Store an item in the cache.
Change redis ref keys to avoid breaking upgrades (#<I>)
laravel_framework
train
7431735ebbc83b8fdf647bc044864f8663b6e1b4
diff --git a/soco/data_structures.py b/soco/data_structures.py index <HASH>..<HASH> 100755 --- a/soco/data_structures.py +++ b/soco/data_structures.py @@ -501,10 +501,13 @@ class DidlObject(with_metaclass(DidlMetaClass, object)): if parent_id is None: raise DIDLMetadataError("Missing parentID attribute") parent_id = really_unicode(parent_id) + + # CAUTION: This implementation deviates from the spec. + # Elements are normally required to have a `restricted` tag, but + # Spotify direct violates this. To make it work, a missing restricted + # tag is interpreted as `restricted = True`. restricted = element.get('restricted', None) - if restricted is None: - raise DIDLMetadataError("Missing restricted attribute") - restricted = True if restricted in [1, 'true', 'True'] else False + restricted = False if restricted in [0, 'false', 'False'] else True # There must be a title. According to spec, it should be the first # child, but Sonos does not abide by this
removed check for missing restricted attribute and set True as default
SoCo_SoCo
train
5bf7699dd432904cf52a012c72d8653771cef97f
diff --git a/src/java/com/samskivert/util/HashIntMap.java b/src/java/com/samskivert/util/HashIntMap.java index <HASH>..<HASH> 100644 --- a/src/java/com/samskivert/util/HashIntMap.java +++ b/src/java/com/samskivert/util/HashIntMap.java @@ -463,8 +463,7 @@ public class HashIntMap<V> extends AbstractMap<Integer,V> Record<V>[] buckets = result._buckets = result._buckets.clone(); for (int ii = buckets.length - 1; ii >= 0; ii--) { if (buckets[ii] != null) { - @SuppressWarnings("unchecked") - Record<V> entry = (Record<V>) buckets[ii].clone(); + Record<V> entry = buckets[ii].clone(); buckets[ii] = entry; } } @@ -585,15 +584,14 @@ public class HashIntMap<V> extends AbstractMap<Integer,V> return key + "=" + StringUtil.toString(value); } - @Override public Object clone () + @Override public Record<V> clone () { try { @SuppressWarnings("unchecked") Record<V> result = (Record<V>) super.clone(); // value is not cloned if (result.next != null) { - @SuppressWarnings("unchecked") - Record<V> next = (Record<V>) result.next.clone(); + Record<V> next = result.next.clone(); result.next = next; } return result;
Missed a spot. Oh baby, look at the @SuppressWarnings and cast removal. It's all itchy, flakey, and pale under the cast! git-svn-id: <URL>
samskivert_samskivert
train
f07ca5db72be5770ba8587abcbe3886f47b2430e
diff --git a/diff_cover/report_generator.py b/diff_cover/report_generator.py index <HASH>..<HASH> 100644 --- a/diff_cover/report_generator.py +++ b/diff_cover/report_generator.py @@ -202,21 +202,16 @@ class TemplateReportGenerator(BaseReportGenerator): def generate_report(self, output_file): """ See base class. + output_file must be a file handler that takes in bytes! """ if self.TEMPLATE_NAME is not None: - - # Find the template template = TEMPLATE_ENV.get_template(self.TEMPLATE_NAME) - - # Render the template report = template.render(self._context()) - # Encode the output as a bytestring (Python < 3) - if not isinstance(report, six.binary_type): + if isinstance(report, six.string_types): report = report.encode('utf-8') - # Write the output file output_file.write(report) def _context(self): diff --git a/diff_cover/tests/test_integration.py b/diff_cover/tests/test_integration.py index <HASH>..<HASH> 100644 --- a/diff_cover/tests/test_integration.py +++ b/diff_cover/tests/test_integration.py @@ -7,6 +7,7 @@ import os import os.path from subprocess import Popen from io import BytesIO +import six import tempfile import shutil from diff_cover.tool import main @@ -128,7 +129,10 @@ class ToolsIntegrationBase(unittest.TestCase): Redirect output sent to `sys.stdout` to the BytesIO buffer `string_buffer`. """ - self._mock_sys.stdout = string_buffer + if six.PY3: + self._mock_sys.stdout.buffer = string_buffer + else: + self._mock_sys.stdout = string_buffer def _set_git_diff_output(self, stdout, stderr): """ diff --git a/diff_cover/tool.py b/diff_cover/tool.py index <HASH>..<HASH> 100644 --- a/diff_cover/tool.py +++ b/diff_cover/tool.py @@ -18,6 +18,7 @@ from diff_cover.report_generator import ( HtmlQualityReportGenerator, StringQualityReportGenerator ) from lxml import etree +import six COVERAGE_XML_HELP = "XML coverage report" HTML_REPORT_HELP = "Diff coverage HTML output" @@ -149,7 +150,7 @@ def generate_coverage_report(coverage_xml, compare_branch, html_report=None): reporter.generate_report(output_file) reporter = StringReportGenerator(coverage, diff) - output_file = sys.stdout + output_file = sys.stdout if six.PY2 else sys.stdout.buffer # Generate the report reporter.generate_report(output_file) @@ -166,7 +167,7 @@ def generate_quality_report(tool, compare_branch, html_report=None): output_file = open(html_report, "wb") else: reporter = StringQualityReportGenerator(tool, diff) - output_file = sys.stdout + output_file = sys.stdout if six.PY2 else sys.stdout.buffer reporter.generate_report(output_file)
Make sure we pass in bytes only handlers. This means that in python2 we can use sys.stdout, but in python3 we need to pass in sys.stdout.buffer
Bachmann1234_diff-cover
train
5d415ab5e642a02a4a67c51319977ee1c2983aa6
diff --git a/skpy/user.py b/skpy/user.py index <HASH>..<HASH> 100644 --- a/skpy/user.py +++ b/skpy/user.py @@ -147,6 +147,27 @@ class SkypeUser(SkypeObj): auth=SkypeConnection.Auth.SkypeToken, json={"mri": "8:{0}".format(self.id), "greeting": greeting}) + def block(self, report=False): + """ + Block the user from all communication. + + Args: + report (bool): whether to report this user to Skype + """ + self.skype.conn("PUT", "{0}/users/{1}/contacts/blocklist/8:{2}" + .format(SkypeConnection.API_CONTACTS, self.skype.userId, self.id), + auth=SkypeConnection.Auth.SkypeToken, json={"report_abuse": report, "ui_version": "skype.com"}) + self.blocked = True + + def unblock(self): + """ + Unblock a previously blocked user. + """ + self.skype.conn("DELETE", "{0}/users/{1}/contacts/blocklist/8:{2}" + .format(SkypeConnection.API_CONTACTS, self.skype.userId, self.id), + auth=SkypeConnection.Auth.SkypeToken) + self.blocked = False + @SkypeUtils.initAttrs class SkypeContact(SkypeUser): @@ -302,6 +323,12 @@ class SkypeContacts(SkypeObjs): When using key lookups, it checks the contact list first, with a user fallback for non-contacts. Contacts can also be iterated over, where only authorised users are returned in the collection. + + Attributes: + groups (dict): + Set of :class:`SkypeContactGroup` instances, keyed by group name. + blocked (SkypeContactGroup): + Group of users blocked from all communication. """ def __init__(self, skype=None): @@ -343,6 +370,8 @@ class SkypeContacts(SkypeObjs): self.contactIds.append(contact.id) for json in resp.get("groups", []): self.groups[json.get("name", json.get("id"))] = SkypeContactGroup.fromRaw(self.skype, json) + blocked = resp.get("blocklist", []) + self.blocked = SkypeContactGroup(self.skype, blocked, userIds=[block.get("mri") for block in blocked]) super(SkypeContacts, self).sync() def contact(self, id):
Add support for user (un)block and listing blocks
Terrance_SkPy
train
bb3cc738c5cd09d36ce590cc820fbe3b7ad1d442
diff --git a/api/secret.go b/api/secret.go index <HASH>..<HASH> 100644 --- a/api/secret.go +++ b/api/secret.go @@ -293,6 +293,7 @@ type SecretAuth struct { IdentityPolicies []string `json:"identity_policies"` Metadata map[string]string `json:"metadata"` Orphan bool `json:"orphan"` + EntityID string `json:"entity_id"` LeaseDuration int `json:"lease_duration"` Renewable bool `json:"renewable"`
Added missing entity_id to SecretAuth struct (#<I>)
hashicorp_vault
train
9ab128e2121453e1801fe8d5ce3fd565944efd27
diff --git a/core/src/main/java/org/cache2k/impl/BaseCache.java b/core/src/main/java/org/cache2k/impl/BaseCache.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/cache2k/impl/BaseCache.java +++ b/core/src/main/java/org/cache2k/impl/BaseCache.java @@ -2103,15 +2103,12 @@ public abstract class BaseCache<E extends Entry, K, T> getEvictionExecutor().execute(r); } - protected void expireEntry(E e) { + protected void expireEntry(E e) { synchronized (e) { if (e.isRemovedState() || e.isExpiredState()) { return; } e.setExpiredState(); - if (storage != null && !hasKeepAfterExpired()) { - storage.expire(e); - } synchronized (lock) { checkClosed(); if (hasKeepAfterExpired()) { diff --git a/core/src/main/java/org/cache2k/impl/Entry.java b/core/src/main/java/org/cache2k/impl/Entry.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/cache2k/impl/Entry.java +++ b/core/src/main/java/org/cache2k/impl/Entry.java @@ -32,6 +32,7 @@ import org.cache2k.storage.StorageEntry; * * @author Jens Wilke */ +@SuppressWarnings("unchecked") public class Entry<E extends Entry, K, T> implements MutableCacheEntry<K,T>, StorageEntry { @@ -89,7 +90,7 @@ public class Entry<E extends Entry, K, T> * Hash implementation: the calculated, modified hash code, retrieved from the key when the entry is * inserted in the cache * - * @see #modifiedHash(int) + * @see BaseCache#modifiedHash(int) */ public int hashCode; @@ -107,6 +108,9 @@ public class Entry<E extends Entry, K, T> fetchedTime = t << 1; } + /** + * Memory entry needs to be send to the storage. + */ public boolean isDirty() { return (fetchedTime & 1) == 0; } @@ -145,11 +149,10 @@ public class Entry<E extends Entry, K, T> /** * The entry value was fetched and is valid, which means it can be - * returned by the cache. If a valid an entry with {@link #isDataValidState()} - * true gets removed from the cache the data is still valid. This is - * because a concurrent get needs to return the data. There is also - * the chance that an entry is removed by eviction, or is never inserted - * to the cache, before the get returns it. + * returned by the cache. If a valid entry gets removed from the + * cache the data is still valid. This is because a concurrent get needs to + * return the data. There is also the chance that an entry is removed by eviction, + * or is never inserted to the cache, before the get returns it. * * <p/>Even if this is true, the data may be expired. Use hasFreshData() to * make sure to get not expired data. @@ -235,8 +238,7 @@ public class Entry<E extends Entry, K, T> } if (needsTimeCheck()) { long now = System.currentTimeMillis(); - boolean f = now < -nextRefreshTime; - return f; + return now < -nextRefreshTime; } return false; } @@ -264,17 +266,6 @@ public class Entry<E extends Entry, K, T> return false; } - public void setFetchedState() { - nextRefreshTime = FETCHED_STATE; - } - - public void setLoadedNonValid() { - synchronized (this) { - nextRefreshTime = LOADED_NON_VALID; - notifyAll(); - } - } - public boolean isLoadedNonValid() { return nextRefreshTime == LOADED_NON_VALID; } @@ -308,10 +299,6 @@ public class Entry<E extends Entry, K, T> return nextRefreshTime == REMOVED_STATE; } - public void setFetchNextTimeState() { - nextRefreshTime = FETCH_NEXT_TIME_STATE; - } - public void setGettingRefresh() { nextRefreshTime = REFRESH_STATE; } @@ -324,10 +311,6 @@ public class Entry<E extends Entry, K, T> return nextRefreshTime == REPUT_STATE; } - public void setReputState() { - nextRefreshTime = REPUT_STATE; - } - public boolean needsTimeCheck() { return nextRefreshTime < 0; } @@ -441,4 +424,14 @@ public class Entry<E extends Entry, K, T> return this == obj; } + /* check entry states */ + static { + Entry e = new Entry(); + e.nextRefreshTime = FETCHED_STATE; + e.setGettingRefresh(); + e = new Entry(); + e.setLoadedNonValidAndFetch(); + e.setExpiredState(); + } + } diff --git a/core/src/main/java/org/cache2k/storage/ImageFileStorage.java b/core/src/main/java/org/cache2k/storage/ImageFileStorage.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/cache2k/storage/ImageFileStorage.java +++ b/core/src/main/java/org/cache2k/storage/ImageFileStorage.java @@ -956,6 +956,8 @@ public class ImageFileStorage return getTotalValueSpace() - getFreeSpace(); } + public long getPutCnt() { return putCount; } + /** * Prints out current state. The output is not necessarily consistent, because * no lock is used. diff --git a/src/site/markdown/todo.md b/src/site/markdown/todo.md index <HASH>..<HASH> 100644 --- a/src/site/markdown/todo.md +++ b/src/site/markdown/todo.md @@ -1,5 +1,7 @@ ## Todo + * rename from fetch to entry operation? + A poor mans issue tracker. ### 0.20 @@ -62,6 +64,10 @@ Planned API breaking changes in this release: * developer description for storage * Storage aggregation * async storage + +#### minor storage improvements + + * purge expired heap entries from storage directly ### robustness
working on storage passivation / cache evition and the dirty flag
cache2k_cache2k
train
78029487fe241b4098cb9c3b0dbe6decdfff3c80
diff --git a/src/livestreamer_curses/main.py b/src/livestreamer_curses/main.py index <HASH>..<HASH> 100755 --- a/src/livestreamer_curses/main.py +++ b/src/livestreamer_curses/main.py @@ -38,6 +38,7 @@ import termios import imp from livestreamer import Livestreamer from multiprocessing.pool import ThreadPool as Pool +import json PY3 = sys.version_info.major >= 3 @@ -164,7 +165,7 @@ class StreamPlayer(object): class StreamList(object): - def __init__(self, filename, rc_module): + def __init__(self, filename, rc_module, list_streams=False, init_stream_list=None): """ Init and try to load a stream list, nothing about curses yet """ self.db_was_read = False @@ -177,7 +178,17 @@ class StreamList(object): 'Database could not be opened, another livestreamer-curses instance might be already running. ' 'Please note that a database created with Python 2.x cannot be used with Python 3.x and vice versa.' ) + self.max_id = 0 + if init_stream_list: + f['streams'] = init_stream_list + for i, s in enumerate(f['streams']): + s['id'] = s.get('id') or i + s['seen'] = s.get('seen') or 0 + s['last_seen'] = s.get('last_seen') or 0 + self.max_id = i + f.sync() + # Sort streams by view count try: @@ -186,6 +197,10 @@ class StreamList(object): # Max id, needed when adding a new stream self.max_id = max(self.max_id, s['id']) s['online'] = 2 + if list_streams: + print(json.dumps(self.streams)) + f.close() + sys.exit(0) except: self.streams = [] self.db_was_read = True @@ -925,6 +940,8 @@ def main(): default=os.path.join(os.environ['HOME'], u'.livestreamer-curses.db')) parser.add_argument('-f', type=arg_type, metavar='configfile', help='default: ~/.livestreamer-cursesrc', default=os.path.join(os.environ['HOME'], u'.livestreamer-cursesrc')) + parser.add_argument('-p', action='store', type=arg_type, metavar='JSON file', help='load (overwrite) database with data from this file. Use - for stdin') + parser.add_argument('-l', action='store_true', help='print the list of streams and exit') args = parser.parse_args() rc_filename = args.f @@ -936,8 +953,33 @@ def main(): sys.exit(1) else: rc_module = imp.new_module('rc') - l = StreamList(args.d, rc_module) - curses.wrapper(l) + + init_stream_list = [] + if args.p: + if args.p == '-': + buf = sys.stdin + elif os.path.exists(args.p): + buf = open(args.p) + else: + IOError("No such file or directory: '{0}'".format(args.p)) + init_stream_list = json.load(buf) + if not isinstance(init_stream_list, list): + raise ValueError('The stream list must be provided as a valid JSON array') + + keys = {'name':arg_type, 'url':arg_type, 'res':arg_type} + def check_stream(s): + for k, t in keys.items(): + try: + if not isinstance(s[k], t): + return False + except: + return False + return True + init_stream_list = list(filter(check_stream, init_stream_list)) + + l = StreamList(args.d, rc_module, list_streams=args.l, init_stream_list=init_stream_list) + if not args.l: + curses.wrapper(l) if __name__ == '__main__': main()
options to dump/load stream list from file
gapato_livestreamer-curses
train
18aa1cd8022919d8e7d6ab70532f55c8a5d71da2
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -12,6 +12,7 @@ module.exports = function(afterAllCb) { ' Make sure all the calls to "next" are on the same tick'; var calls = 0; var done = false; + var finalError = null; process.nextTick(function() { if (calls === 0) { @@ -26,12 +27,12 @@ module.exports = function(afterAllCb) { return function thecallback(err) { var args = arguments; - if (isError(err)) afterAllCb(err); + if (isError(err) && !finalError) finalError = err; process.nextTick(function() { if (cb) cb.apply(null, args); if (--calls === 0) { done = true; - afterAllCb(); + afterAllCb(finalError); } }); }; diff --git a/test/index.js b/test/index.js index <HASH>..<HASH> 100644 --- a/test/index.js +++ b/test/index.js @@ -105,8 +105,9 @@ test('should catch errors and pass it to the final callback', function(t) { test('should only call the final callback once in the case of an error', function(t) { var count = 0; - var next = afterAll(function() { - t.ok(++count === 1); + var next = afterAll(function(err) { + t.equal(err.message, 'Oops!'); + t.equal(++count, 1); t.end(); }); @@ -116,18 +117,19 @@ test('should only call the final callback once in the case of an error', functio n1(); n2(new Error('Oops!')); - n3(new Error('Oops!')); + n3(new Error('Oops! 2')); }); test('should call all the callbacks even in case of error', function(t) { var count = 0; var next = afterAll(function() { - t.equal(count, 0); + t.equal(count, 3); + t.end(); }); - + var countup = function() { - if (++count === 3) t.end(); + count++; }; var n1 = next(countup);
Call the after-all callback in the end (even in the case of an error).
sorribas_after-all
train
70b334c1b383e914c4d7414f9a0cf90423eb9197
diff --git a/src/Factory/Api.php b/src/Factory/Api.php index <HASH>..<HASH> 100644 --- a/src/Factory/Api.php +++ b/src/Factory/Api.php @@ -28,10 +28,9 @@ class Api Client $client = null, SerializerInterface $serializer = null ) { - AnnotationRegistry::registerLoader('class_exists'); - $afterpayClient = $client ? : new Client([ 'base_url' => $authorization->getEndpoint() ]); + $afterpayClient = $client ? : new Client([ 'base_uri' => $authorization->getEndpoint() ]); $afterpaySerializer = $serializer ? : SerializerFactory::getSerializer(); return new ConfigurationService($afterpayClient, $authorization, $afterpaySerializer); @@ -51,7 +50,7 @@ class Api AnnotationRegistry::registerLoader('class_exists'); - $afterpayClient = $client ? : new Client([ 'base_url' => $authorization->getEndpoint() ]); + $afterpayClient = $client ? : new Client([ 'base_uri' => $authorization->getEndpoint() ]); $afterpaySerializer = $serializer ? : SerializerFactory::getSerializer(); return new PaymentsService($afterpayClient, $authorization, $afterpaySerializer); @@ -70,7 +69,7 @@ class Api ) { AnnotationRegistry::registerLoader('class_exists'); - $afterpayClient = $client ? : new Client([ 'base_url' => $authorization->getEndpoint() ]); + $afterpayClient = $client ? : new Client([ 'base_uri' => $authorization->getEndpoint() ]); $afterpaySerializer = $serializer ? : SerializerFactory::getSerializer(); return new OrdersService($afterpayClient, $authorization, $afterpaySerializer);
Guzzle6 changed base_url to base_uri
culturekings_afterpay
train
5a84dd8990131f906dab21768b5b0487aac49fd5
diff --git a/src/org/zoodb/internal/util/DBLogger.java b/src/org/zoodb/internal/util/DBLogger.java index <HASH>..<HASH> 100644 --- a/src/org/zoodb/internal/util/DBLogger.java +++ b/src/org/zoodb/internal/util/DBLogger.java @@ -101,7 +101,7 @@ public class DBLogger { private static RuntimeException newEx(Class<? extends RuntimeException> exCls, String msg, Throwable cause, Object failed) { - severe(msg); + //severe(msg); Constructor<? extends RuntimeException> con; con = ReflTools.getConstructor(exCls, String.class, Throwable.class, Object.class); return ReflTools.newInstance(con, msg, cause, failed);
Removed double logging of exceptions as SEVERE error
tzaeschke_zoodb
train
fca8af88d20ffae6e8f0367f45c88af39cdfd0e0
diff --git a/release/.buildkite/build_pipeline.py b/release/.buildkite/build_pipeline.py index <HASH>..<HASH> 100644 --- a/release/.buildkite/build_pipeline.py +++ b/release/.buildkite/build_pipeline.py @@ -361,6 +361,7 @@ def build_pipeline(steps): RAY_BRANCH = os.environ.get("RAY_BRANCH", "master") RAY_REPO = os.environ.get("RAY_REPO", "https://github.com/ray-project/ray.git") + RAY_VERSION = os.environ.get("RAY_VERSION", "") RAY_TEST_BRANCH = os.environ.get("RAY_TEST_BRANCH", RAY_BRANCH) RAY_TEST_REPO = os.environ.get("RAY_TEST_REPO", RAY_REPO) @@ -373,6 +374,7 @@ def build_pipeline(steps): f"Ray repo/branch to test:\n" f" RAY_REPO = {RAY_REPO}\n" f" RAY_BRANCH = {RAY_BRANCH}\n\n" + f" RAY_VERSION = {RAY_VERSION}\n\n" f"Ray repo/branch containing the test configurations and scripts:" f" RAY_TEST_REPO = {RAY_TEST_REPO}\n" f" RAY_TEST_BRANCH = {RAY_TEST_BRANCH}\n\n" @@ -394,8 +396,10 @@ def build_pipeline(steps): logging.info(f"Adding test: {test_base}/{test_name}") - cmd = str(f"python release/e2e.py " - f"--ray-branch {RAY_BRANCH} " + cmd = str(f"RAY_REPO=\"{RAY_REPO}\" " + f"RAY_BRANCH=\"{RAY_BRANCH}\" " + f"RAY_VERSION=\"{RAY_VERSION}\" " + f"python release/e2e.py " f"--category {RAY_BRANCH} " f"--test-config {test_file} " f"--test-name {test_name}") diff --git a/release/e2e.py b/release/e2e.py index <HASH>..<HASH> 100644 --- a/release/e2e.py +++ b/release/e2e.py @@ -215,32 +215,39 @@ formatter = logging.Formatter(fmt="[%(levelname)s %(asctime)s] " handler.setFormatter(formatter) logger.addHandler(handler) + +def getenv_default(key: str, default: Optional[str] = None): + """Return environment variable with default value""" + # If the environment variable is set but "", still return default + return os.environ.get(key, None) or default + + GLOBAL_CONFIG = { - "ANYSCALE_USER": os.environ.get("ANYSCALE_USER", + "ANYSCALE_USER": getenv_default("ANYSCALE_USER", "release-automation@anyscale.com"), - "ANYSCALE_HOST": os.environ.get("ANYSCALE_HOST", + "ANYSCALE_HOST": getenv_default("ANYSCALE_HOST", "https://beta.anyscale.com"), - "ANYSCALE_CLI_TOKEN": os.environ.get("ANYSCALE_CLI_TOKEN"), - "ANYSCALE_CLOUD_ID": os.environ.get( + "ANYSCALE_CLI_TOKEN": getenv_default("ANYSCALE_CLI_TOKEN"), + "ANYSCALE_CLOUD_ID": getenv_default( "ANYSCALE_CLOUD_ID", "cld_4F7k8814aZzGG8TNUGPKnc"), # cld_4F7k8814aZzGG8TNUGPKnc - "ANYSCALE_PROJECT": os.environ.get("ANYSCALE_PROJECT", ""), - "RAY_VERSION": os.environ.get("RAY_VERSION", "2.0.0.dev0"), - "RAY_REPO": os.environ.get("RAY_REPO", + "ANYSCALE_PROJECT": getenv_default("ANYSCALE_PROJECT", ""), + "RAY_VERSION": getenv_default("RAY_VERSION", "2.0.0.dev0"), + "RAY_REPO": getenv_default("RAY_REPO", "https://github.com/ray-project/ray.git"), - "RAY_BRANCH": os.environ.get("RAY_BRANCH", "master"), - "RELEASE_AWS_BUCKET": os.environ.get("RELEASE_AWS_BUCKET", + "RAY_BRANCH": getenv_default("RAY_BRANCH", "master"), + "RELEASE_AWS_BUCKET": getenv_default("RELEASE_AWS_BUCKET", "ray-release-automation-results"), - "RELEASE_AWS_LOCATION": os.environ.get("RELEASE_AWS_LOCATION", "dev"), - "RELEASE_AWS_DB_NAME": os.environ.get("RELEASE_AWS_DB_NAME", "ray_ci"), - "RELEASE_AWS_DB_TABLE": os.environ.get("RELEASE_AWS_DB_TABLE", + "RELEASE_AWS_LOCATION": getenv_default("RELEASE_AWS_LOCATION", "dev"), + "RELEASE_AWS_DB_NAME": getenv_default("RELEASE_AWS_DB_NAME", "ray_ci"), + "RELEASE_AWS_DB_TABLE": getenv_default("RELEASE_AWS_DB_TABLE", "release_test_result"), - "RELEASE_AWS_DB_SECRET_ARN": os.environ.get( + "RELEASE_AWS_DB_SECRET_ARN": getenv_default( "RELEASE_AWS_DB_SECRET_ARN", "arn:aws:secretsmanager:us-west-2:029272617770:secret:" "rds-db-credentials/cluster-7RB7EYTTBK2EUC3MMTONYRBJLE/ray_ci-MQN2hh", ), - "RELEASE_AWS_DB_RESOURCE_ARN": os.environ.get( + "RELEASE_AWS_DB_RESOURCE_ARN": getenv_default( "RELEASE_AWS_DB_RESOURCE_ARN", "arn:aws:rds:us-west-2:029272617770:cluster:ci-reporting", ),
[release] Fix e2e environment variable passing from pipeline (#<I>)
ray-project_ray
train
96ba0f5184bf28b61fc3afde8791bc81fa9627da
diff --git a/tests/test_creation_and_reading_functional.py b/tests/test_creation_and_reading_functional.py index <HASH>..<HASH> 100644 --- a/tests/test_creation_and_reading_functional.py +++ b/tests/test_creation_and_reading_functional.py @@ -8,6 +8,8 @@ import pytest from dtoolcore.filehasher import sha256sum_hexdigest +from dtool_irods.storagebroker import _path_exists + from . import tmp_uuid_and_uri # NOQA from . import TEST_SAMPLE_DATA @@ -90,10 +92,14 @@ def test_proto_dataset_freeze_functional(tmp_uuid_and_uri): # NOQA with pytest.raises(DtoolCoreTypeError): DataSet.from_uri(dest_uri) + # At this point the temporary fragments directory should exist. + assert _path_exists( + proto_dataset._storage_broker._metadata_fragments_abspath) + proto_dataset.freeze() # Freezing removes the temporary metadata fragments directory. - assert not os.path.isdir( + assert not _path_exists( proto_dataset._storage_broker._metadata_fragments_abspath) # Now we shouln't be able to load as a ProtoDataSet
Fix defect in test; now works in iRODS space rather than on local file system disk
jic-dtool_dtool-irods
train
b58faffeacebf6d4e0735c5a5edfe0b78be628cb
diff --git a/consul/server_test.go b/consul/server_test.go index <HASH>..<HASH> 100644 --- a/consul/server_test.go +++ b/consul/server_test.go @@ -321,14 +321,14 @@ func TestServer_JoinSeparateLanAndWanAddresses(t *testing.T) { // Check the WAN members on s1 testutil.WaitForResult(func() (bool, error) { - return len(s1.WANMembers()) == 2, nil + return len(s1.WANMembers()) == 3, nil }, func(err error) { t.Fatalf("bad len") }) // Check the WAN members on s2 testutil.WaitForResult(func() (bool, error) { - return len(s2.WANMembers()) == 2, nil + return len(s2.WANMembers()) == 3, nil }, func(err error) { t.Fatalf("bad len") })
Fixes a unit test that needed to account for WAN flooding.
hashicorp_consul
train
cffb425d8baf071fbdf89e9d16289caeb3487f6c
diff --git a/src/Message/Request/Ftp/FtpRequest.php b/src/Message/Request/Ftp/FtpRequest.php index <HASH>..<HASH> 100644 --- a/src/Message/Request/Ftp/FtpRequest.php +++ b/src/Message/Request/Ftp/FtpRequest.php @@ -87,7 +87,10 @@ class FtpRequest extends AbstractRequest */ protected function prepare() { - $this->addOption(CURLOPT_FTP_USE_EPSV, true); + //Force passice mode if not specified + if( !$this->hasOption(CURLOPT_FTP_USE_EPSV) ) { + $this->addOption(CURLOPT_FTP_USE_EPSV, true); + } //To make call on different files, we must retrieve the root and apply commands to the path $tmp = clone $this->getUrl();
FTP: Use given passive mode value if there is one
bee4_transport
train
a73425840e12bb5da9d7b133a35b80cdb2615a70
diff --git a/extras.py b/extras.py index <HASH>..<HASH> 100644 --- a/extras.py +++ b/extras.py @@ -1,14 +1,20 @@ # Here are a few functions that aren't critical to properly scrobbling a song # However, I they were fun to put together and might be of use to others. import requests +import datetime import os api_root = 'http://ws.audioscrobbler.com/2.0/' def user_tracks(user_name): resp = requests.get(api_root + '?method=user.getrecenttracks&user=' + user_name + '&api_key=' + os.environ['LAST_FM_API'] + '&format=json') - print resp.text + return resp.text def user_weekly_tracks(user_name): resp = requests.get(api_root + '?method=user.getweeklytrackchart&user=' + user_name + '&api_key=' + os.environ['LAST_FM_API'] + '&format=json') - print resp.text + return resp.text + +def user_daily_tracks(user_name): + dayStart = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0).strftime("%s") + resp = requests.get(api_root + '?method=user.getrecenttracks&user=' + user_name + '&api_key=' + os.environ['LAST_FM_API'] + '&from=' + str(dayStart) + '&limit=200' +'&format=json') + return resp.text
Add function for extracting tracks played by user that day
huberf_lastfm-scrobbler
train
fa90f1cd0d2c25f7bcb305645e61d2124f56326f
diff --git a/consul/catalog_endpoint_test.go b/consul/catalog_endpoint_test.go index <HASH>..<HASH> 100644 --- a/consul/catalog_endpoint_test.go +++ b/consul/catalog_endpoint_test.go @@ -232,6 +232,57 @@ func TestCatalogListNodes(t *testing.T) { } } +func TestCatalogListNodes_StaleRaad(t *testing.T) { + dir1, s1 := testServer(t) + defer os.RemoveAll(dir1) + defer s1.Shutdown() + client1 := rpcClient(t, s1) + defer client1.Close() + + dir2, s2 := testServer(t) + defer os.RemoveAll(dir2) + defer s2.Shutdown() + client2 := rpcClient(t, s2) + defer client2.Close() + + // Try to join + addr := fmt.Sprintf("127.0.0.1:%d", + s1.config.SerfLANConfig.MemberlistConfig.BindPort) + if _, err := s2.JoinLAN([]string{addr}); err != nil { + t.Fatalf("err: %v", err) + } + + // Wait for a leader + time.Sleep(100 * time.Millisecond) + + // Use the follower as the client + var client *rpc.Client + if !s1.IsLeader() { + client = client1 + + // Inject fake data on the follower! + s1.fsm.State().EnsureNode(1, structs.Node{"foo", "127.0.0.1"}) + } else { + client = client2 + + // Inject fake data on the follower! + s2.fsm.State().EnsureNode(1, structs.Node{"foo", "127.0.0.1"}) + } + + args := structs.DCSpecificRequest{ + Datacenter: "dc1", + QueryOptions: structs.QueryOptions{AllowStale: true}, + } + var out structs.IndexedNodes + if err := client.Call("Catalog.ListNodes", &args, &out); err != nil { + t.Fatalf("err: %v", err) + } + + if len(out.Nodes) != 3 { + t.Fatalf("bad: %v", out) + } +} + func BenchmarkCatalogListNodes(t *testing.B) { dir1, s1 := testServer(nil) defer os.RemoveAll(dir1) diff --git a/consul/rpc.go b/consul/rpc.go index <HASH>..<HASH> 100644 --- a/consul/rpc.go +++ b/consul/rpc.go @@ -142,6 +142,11 @@ func (s *Server) forward(method string, info structs.RPCInfo, args interface{}, return true, err } + // Check if we can allow a stale read + if info.IsRead() && info.AllowStaleRead() { + return false, nil + } + // Handle leader forwarding if !s.IsLeader() { err := s.forwardLeader(method, args, reply)
consul: Support a stale read query
hashicorp_consul
train
00ce7488726e2663115839bf0a9c2db52e469177
diff --git a/test/main.js b/test/main.js index <HASH>..<HASH> 100644 --- a/test/main.js +++ b/test/main.js @@ -12,11 +12,12 @@ test.beforeEach(t => { const parseArguments = sinon.stub().returns({logLevel: 'info'}) const travis = sinon.stub() const run = sinon.stub() - const stubs = {} - stubs[require.resolve('../src/arguments')] = {parseArguments} - stubs[require.resolve('../src/logging')] = {logger} - stubs[require.resolve('../src/run/all')] = run - stubs[require.resolve('../src/travis')] = travis + const stubs = { + [require.resolve('../src/arguments')]: {parseArguments}, + [require.resolve('../src/logging')]: {logger}, + [require.resolve('../src/run/all')]: run, + [require.resolve('../src/travis')]: travis + } const main = requireInject('../src/main', stubs).default t.context = {logger, main, run, travis} diff --git a/test/run/all.js b/test/run/all.js index <HASH>..<HASH> 100644 --- a/test/run/all.js +++ b/test/run/all.js @@ -19,10 +19,11 @@ test.beforeEach(t => { exists: sinon.stub(), mkdir: sinon.stub() } - const stubs = {} - stubs[require.resolve('../../src/logging')] = {logger} - stubs[require.resolve('../../src/run/one')] = one - stubs[require.resolve('../../src/util')] = util + const stubs = { + [require.resolve('../../src/logging')]: {logger}, + [require.resolve('../../src/run/one')]: one, + [require.resolve('../../src/util')]: util + } const runAllTests = requireInject('../../src/run/all', stubs).default t.context = {logger, one, runAllTests, util} }) diff --git a/test/run/one.js b/test/run/one.js index <HASH>..<HASH> 100644 --- a/test/run/one.js +++ b/test/run/one.js @@ -21,9 +21,10 @@ test.beforeEach(t => { exec: sinon.stub(), mkdir: sinon.stub() } - const stubs = {} - stubs[require.resolve('../../src/logging')] = {logger} - stubs[require.resolve('../../src/util')] = util + const stubs = { + [require.resolve('../../src/logging')]: {logger}, + [require.resolve('../../src/util')]: util + } const runTests = requireInject('../../src/run/one', stubs).default t.context = {logger, runTests, util} diff --git a/test/travis.js b/test/travis.js index <HASH>..<HASH> 100644 --- a/test/travis.js +++ b/test/travis.js @@ -6,21 +6,20 @@ import 'sinon-as-promised' import test from 'ava' test.beforeEach(t => { + const logger = { + info: sinon.spy(), + error: sinon.spy() + } + const util = {} const stubs = { path: { basename: path.basename, extname: path.extname, join: sinon.stub().returns('<travis-file>') - } + }, + [require.resolve('../src/logging')]: {logger}, + [require.resolve('../src/util')]: util } - const logger = { - info: sinon.spy(), - error: sinon.spy() - } - stubs[require.resolve('../src/logging')] = {logger} - - const util = {} - stubs[require.resolve('../src/util')] = util const parse = requireInject('../src/travis', stubs).default t.context = {logger, parse, util}
Refactor test cases to use computed property names
jcollado_multitest
train
b15babf682088ea7ae7b5c5630807a0864475c9f
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -12,11 +12,11 @@ def readme(): return f.read() setup(name='pycabara', - version='0.3', + version='0.4', description='Python implementation of Capybara, an acceptance test framework for web applications', long_description=readme(), classifiers=[ - 'Development Status :: 3 - Alpha', + 'Development Status :: 4 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Testing',
Version set to <I> (alpha 4)
excellalabs_pycabara
train
85c4d581db3d9652116bf30dbd2efe7388d6369c
diff --git a/eventsourcing/persistence.py b/eventsourcing/persistence.py index <HASH>..<HASH> 100644 --- a/eventsourcing/persistence.py +++ b/eventsourcing/persistence.py @@ -413,3 +413,8 @@ class InfrastructureFactory(ABC): or default ) ) + + +class Tracking(ImmutableObject): + application_name: str + notification_id: int diff --git a/eventsourcing/popo.py b/eventsourcing/popo.py index <HASH>..<HASH> 100644 --- a/eventsourcing/popo.py +++ b/eventsourcing/popo.py @@ -9,11 +9,10 @@ from typing import ( ) from uuid import UUID -from eventsourcing.system import Tracking from eventsourcing.persistence import ( AggregateRecorder, ApplicationRecorder, InfrastructureFactory, Notification, ProcessRecorder, - RecordConflictError, StoredEvent, + RecordConflictError, StoredEvent, Tracking, ) diff --git a/eventsourcing/postgres.py b/eventsourcing/postgres.py index <HASH>..<HASH> 100644 --- a/eventsourcing/postgres.py +++ b/eventsourcing/postgres.py @@ -11,9 +11,8 @@ from psycopg2.extensions import cursor, connection from eventsourcing.persistence import ( AggregateRecorder, ApplicationRecorder, InfrastructureFactory, Notification, ProcessRecorder, - RecordConflictError, StoredEvent, + RecordConflictError, StoredEvent, Tracking, ) -from eventsourcing.system import Tracking psycopg2.extras.register_uuid() diff --git a/eventsourcing/sqlite.py b/eventsourcing/sqlite.py index <HASH>..<HASH> 100644 --- a/eventsourcing/sqlite.py +++ b/eventsourcing/sqlite.py @@ -8,9 +8,8 @@ from uuid import UUID from eventsourcing.persistence import ( AggregateRecorder, ApplicationRecorder, InfrastructureFactory, Notification, ProcessRecorder, - RecordConflictError, StoredEvent, + RecordConflictError, StoredEvent, Tracking, ) -from eventsourcing.system import Tracking class SQLiteDatabase: diff --git a/eventsourcing/system.py b/eventsourcing/system.py index <HASH>..<HASH> 100644 --- a/eventsourcing/system.py +++ b/eventsourcing/system.py @@ -2,7 +2,6 @@ from abc import ABC, abstractmethod from collections import defaultdict from threading import Event, Thread from typing import ( - Any, Dict, Iterable, List, @@ -11,19 +10,14 @@ from typing import ( Type, TypeVar, ) -from eventsourcing.domain import Aggregate, ImmutableObject +from eventsourcing.domain import Aggregate from eventsourcing.persistence import ApplicationRecorder, Mapper, Notification, \ - ProcessRecorder + ProcessRecorder, Tracking from eventsourcing.utils import get_topic, resolve_topic from eventsourcing.application import AbstractNotificationLog, Application, Section -class Tracking(ImmutableObject): - application_name: str - notification_id: int - - class ProcessEvent: def __init__(self, tracking: Tracking): self.tracking = tracking diff --git a/eventsourcing/tests/processrecorder_testcase.py b/eventsourcing/tests/processrecorder_testcase.py index <HASH>..<HASH> 100644 --- a/eventsourcing/tests/processrecorder_testcase.py +++ b/eventsourcing/tests/processrecorder_testcase.py @@ -3,8 +3,7 @@ from timeit import timeit from unittest.case import TestCase from uuid import uuid4 -from eventsourcing.system import Tracking -from eventsourcing.persistence import RecordConflictError, StoredEvent +from eventsourcing.persistence import RecordConflictError, StoredEvent, Tracking class ProcessRecordsTestCase(TestCase, ABC): diff --git a/eventsourcing/tests/test_processingpolicy.py b/eventsourcing/tests/test_processingpolicy.py index <HASH>..<HASH> 100644 --- a/eventsourcing/tests/test_processingpolicy.py +++ b/eventsourcing/tests/test_processingpolicy.py @@ -3,7 +3,8 @@ from unittest.case import TestCase from uuid import uuid4 from eventsourcing.domain import Aggregate -from eventsourcing.system import ProcessEvent, Tracking +from eventsourcing.system import ProcessEvent +from eventsourcing.persistence import Tracking from eventsourcing.tests.test_aggregate import BankAccount
Moved Tracking class to persistence.py.
johnbywater_eventsourcing
train
d13337401c5da901699e53edfb29b4c6b5e3134d
diff --git a/core/src/main/java/io/neba/core/util/JsonUtil.java b/core/src/main/java/io/neba/core/util/JsonUtil.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/neba/core/util/JsonUtil.java +++ b/core/src/main/java/io/neba/core/util/JsonUtil.java @@ -21,7 +21,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; - import static org.apache.commons.lang3.ClassUtils.wrapperToPrimitive; /** @@ -74,7 +73,7 @@ public class JsonUtil { return '"' + ((String) value).replaceAll("\"", "\\\\\"") + '"'; } if (value instanceof Collection) { - return toJson((Collection) value); + return toJson((Collection<?>) value); } if (value instanceof Map) { return toJson((Map<?, ?>) value);
Review: Wildcard instead of raw type
unic_neba
train
5e133165c6f2f6e6fff83e893d4e1d804327be10
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,9 @@ const options = { /** * whether or not to include null values as empty strings in FormData instance - * defaults to false + * defaults to true */ - noNulls: false + nulls: true }; const formData = objectToFormData( diff --git a/__tests__/index.js b/__tests__/index.js index <HASH>..<HASH> 100644 --- a/__tests__/index.js +++ b/__tests__/index.js @@ -24,13 +24,13 @@ test('null', () => { expect(formData.get('foo')).toBe(''); }); -test('null with noNulls option', () => { +test('null with nulls option', () => { const formData = objectToFormData( { foo: null }, { - noNulls: true + nulls: false } ); diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -51,13 +51,13 @@ function objectToFormData(obj, cfg, fd, pre) { cfg = cfg || {}; cfg.indices = cfg.indices || false; - cfg.noNulls = cfg.noNulls || false; + cfg.nulls = isUndefined(cfg.nulls) ? true : cfg.nulls; fd = fd || new FormData(); if (isUndefined(obj)) { return fd; } else if (isNull(obj)) { - if (!cfg.noNulls) { + if (cfg.nulls) { fd.append(pre, ''); } } else if (isArray(obj)) {
Clarifying noNulls option by replacing it with nulls option
therealparmesh_object-to-formdata
train
e02ec9184b88ba5a0df2e83352b976743ac4b5cf
diff --git a/ModelBundle/DataFixtures/MongoDB/LoadDemoSiteData.php b/ModelBundle/DataFixtures/MongoDB/LoadDemoSiteData.php index <HASH>..<HASH> 100644 --- a/ModelBundle/DataFixtures/MongoDB/LoadDemoSiteData.php +++ b/ModelBundle/DataFixtures/MongoDB/LoadDemoSiteData.php @@ -33,7 +33,7 @@ class LoadDemoSiteData extends AbstractLoadSiteData implements OrchestraProducti $site2->setSiteId('2'); $site2->setName('Demo site'); $this->addSitesAliases( - array('demo.open-orchestra.com', 'demo.openorchestra.inte', 'demo.openorchestra.dev'), + array('demo.open-orchestra.com', 'demo.openorchestra.inte', 'demo.openorchestra.1-2.dev'), array('fr', 'en', 'de'), $site2); $site2->setSitemapPriority(0.5);
update host <I> site fixture
open-orchestra_open-orchestra-model-bundle
train