hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
3c2509b4d85551bd751e74d26673fadf9a278443
diff --git a/holocube/element/geo.py b/holocube/element/geo.py index <HASH>..<HASH> 100644 --- a/holocube/element/geo.py +++ b/holocube/element/geo.py @@ -26,14 +26,13 @@ class GeoElement(Element2D): def __init__(self, data, **kwargs): crs = None - if isinstance(data, GeoElement): - crs = data.crs - elif isinstance(data, iris.cube.Cube): - coord_sys = data.coord_system() + crs_data = data.data if isinstance(data, HoloCube) else data + if isinstance(crs_data, iris.cube.Cube): + coord_sys = crs_data.coord_system() if hasattr(coord_sys, 'as_cartopy_projection'): crs = coord_sys.as_cartopy_projection() - elif isinstance(data, (Feature, GoogleTiles)): - crs = data.crs + elif isinstance(crs_data, (Feature, GoogleTiles)): + crs = crs_data.crs supplied_crs = kwargs.get('crs', None) if supplied_crs and crs and crs != supplied_crs:
Further fix for casting HoloCubes
pyviz_geoviews
train
156561a529b2380a6e73e1393e1661e749685c31
diff --git a/inspire_matcher/core.py b/inspire_matcher/core.py index <HASH>..<HASH> 100644 --- a/inspire_matcher/core.py +++ b/inspire_matcher/core.py @@ -102,7 +102,9 @@ def _compile_fuzzy(query, record): } for clause in clauses: - boost, path = clause['boost'], clause['path'] + path = clause['path'] + + boost = clause.get('boost', 1) values = get_value(record, path) if not values: diff --git a/tests/test_core.py b/tests/test_core.py index <HASH>..<HASH> 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -310,6 +310,56 @@ def test_compile_fuzzy_supports_slicing_in_paths(): assert expected == result +def test_compile_fuzzy_falls_back_to_boost_1(): + query = { + 'clauses': [ + {'path': 'abstracts'}, + ], + } + record = { + 'abstracts': [ + { + 'source': 'arXiv', + 'value': 'Probably not.', + }, + ], + } + + expected = { + 'min_score': 1, + 'query': { + 'dis_max': { + 'queries': [ + { + 'more_like_this': { + 'boost': 1, + 'docs': [ + { + 'doc': { + 'abstracts': [ + { + 'source': 'arXiv', + 'value': 'Probably not.', + }, + ], + }, + }, + ], + 'max_query_terms': 25, + 'min_doc_freq': 1, + 'min_term_freq': 1, + }, + }, + ], + 'tie_breaker': 0.3, + }, + }, + } + result = _compile_fuzzy(query, record) + + assert expected == result + + def test_compile_fuzzy_raises_if_path_contains_a_dot(): query = { 'clauses': [
core: fall back to boost 1 in fuzzy queries
inspirehep_inspire-matcher
train
3ee0c22e5d9e06c2db6421daf9e4132d4f6725c8
diff --git a/web/concrete/src/Multilingual/Service/Detector.php b/web/concrete/src/Multilingual/Service/Detector.php index <HASH>..<HASH> 100755 --- a/web/concrete/src/Multilingual/Service/Detector.php +++ b/web/concrete/src/Multilingual/Service/Detector.php @@ -106,6 +106,9 @@ class Detector public function isEnabled() { if (!isset($this->enabled)) { + if (!\Database::getDefaultConnection()) { + return false; + } $db = \Database::connection(); $count = $db->GetOne('select count(cID) from MultilingualSections'); $this->enabled = $count > 0;
Don't try to access database if it isn't still configured Former-commit-id: <I>b2f<I>add<I>c0aad<I>e<I>a<I>a<I>b1a<I> Former-commit-id: e<I>ab<I>d9fbbee<I>c<I>e<I>fe0f<I>bc6c<I>ff
concrete5_concrete5
train
e9f36fd50114418c8dcf8a70cd3d0c713cb7fc08
diff --git a/src/main/java/com/mebigfatguy/fbcontrib/detect/SQLInLoop.java b/src/main/java/com/mebigfatguy/fbcontrib/detect/SQLInLoop.java index <HASH>..<HASH> 100755 --- a/src/main/java/com/mebigfatguy/fbcontrib/detect/SQLInLoop.java +++ b/src/main/java/com/mebigfatguy/fbcontrib/detect/SQLInLoop.java @@ -25,6 +25,7 @@ import java.util.Set; import org.apache.bcel.classfile.Code; import com.mebigfatguy.fbcontrib.utils.BugType; +import com.mebigfatguy.fbcontrib.utils.OpcodeUtils; import com.mebigfatguy.fbcontrib.utils.ToString; import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet; @@ -119,7 +120,7 @@ public class SQLInLoop extends BytecodeScanningDetector { if (queryClasses.contains(clsName) && queryMethods.contains(methodName)) queryLocations.add(Integer.valueOf(getPC())); - } else if ((seen == GOTO) || (seen == GOTO_W)) { + } else if (OpcodeUtils.isBranch(seen)) { int branchTarget = getBranchTarget(); int pc = getPC(); if (branchTarget < pc) {
fix SIL detector finding the bottom of loops for #<I>
mebigfatguy_fb-contrib
train
b24c1101b6ea1c94bb11e6a2e719289927959b9f
diff --git a/pyModeS/decoder/common.py b/pyModeS/decoder/common.py index <HASH>..<HASH> 100644 --- a/pyModeS/decoder/common.py +++ b/pyModeS/decoder/common.py @@ -205,8 +205,8 @@ def altcode(msg): int: altitude in ft """ - if df(msg) not in [4, 20]: - raise RuntimeError("Message must be Downlink Format 4 or 20.") + if df(msg) not in [0, 4, 16, 20]: + raise RuntimeError("Message must be Downlink Format 0, 4, 16, or 20.") # Altitude code, bit 20-32 mbin = hex2bin(msg)
add DF 0 and <I> to altcode
junzis_pyModeS
train
7eb935895a34de5f5a13d8a6d2d9026a34b579f3
diff --git a/app/builders/ndr_ui/bootstrap/readonly.rb b/app/builders/ndr_ui/bootstrap/readonly.rb index <HASH>..<HASH> 100644 --- a/app/builders/ndr_ui/bootstrap/readonly.rb +++ b/app/builders/ndr_ui/bootstrap/readonly.rb @@ -9,8 +9,8 @@ module NdrUi module Readonly def self.included(base) # These have different signatures, or aren't affected by `readonly`: - not_affected = [:fields_for] - needs_custom = [:label, :radio_button, :file_field, :hidden_field] + + not_affected = [:label, :fields_for] + needs_custom = [:radio_button, :file_field, :hidden_field] + base.field_helpers_from_form_options_helper (base.field_helpers - needs_custom - not_affected).each do |selector| @@ -51,12 +51,6 @@ module NdrUi @template.content_tag(:p, readonly_value, class: 'form-control-static') end - # For labels, the for attribute should be removed: - def label(method, text = nil, **options, &block) - return super unless readonly? - super(object_name, method, options.merge(for: nil), &block) - end - # radio_button takes another intermediate argument: def radio_button(method, tag_value, options = {}) return super unless readonly? diff --git a/test/builders/ndr_ui/bootstrap_builder/readonly_test.rb b/test/builders/ndr_ui/bootstrap_builder/readonly_test.rb index <HASH>..<HASH> 100644 --- a/test/builders/ndr_ui/bootstrap_builder/readonly_test.rb +++ b/test/builders/ndr_ui/bootstrap_builder/readonly_test.rb @@ -102,19 +102,4 @@ class ReadonlyTest < ActionView::TestCase assert_select 'input[type=hidden]#post_created_at', 0 assert_select 'p.form-control-static', 0 end - - test 'readonly label should not display for attribute' do - time = Time.current - post = Post.new(created_at: time) - - bootstrap_form_for post do |form| - assert_dom_equal '<label for="post_created_at">Created at</label>', - form.label(:created_at, 'Created at') - end - - bootstrap_form_for post, readonly: true do |form| - assert_dom_equal '<label>Created at</label>', - form.label(:created_at, 'Created at') - end - end end
Reverting <I>f (#<I>) ...because it has an undesirable effect on readonly label text
PublicHealthEngland_ndr_ui
train
aa8c1e97619d4948ec24782a484eb59717acad1c
diff --git a/Adapter/ShopwareAdapter/ServiceBus/CommandHandler/Product/HandleProductCommandHandler.php b/Adapter/ShopwareAdapter/ServiceBus/CommandHandler/Product/HandleProductCommandHandler.php index <HASH>..<HASH> 100644 --- a/Adapter/ShopwareAdapter/ServiceBus/CommandHandler/Product/HandleProductCommandHandler.php +++ b/Adapter/ShopwareAdapter/ServiceBus/CommandHandler/Product/HandleProductCommandHandler.php @@ -309,7 +309,7 @@ class HandleProductCommandHandler implements CommandHandlerInterface * @var LoggerInterface $logger */ $logger = Shopware()->Container()->get('plenty_connector.logger'); - $logger->notice('langauge not mapped - ' . $languageIdentifier, ['command' => $command]); + $logger->notice('language not mapped - ' . $languageIdentifier, ['command' => $command]); continue; }
Typo (#<I>)
plentymarkets_plentymarkets-shopware-connector
train
8f70af575478036e40fd5b2170bba5141c0f2bc1
diff --git a/pass.go b/pass.go index <HASH>..<HASH> 100644 --- a/pass.go +++ b/pass.go @@ -85,7 +85,12 @@ func (k *passKeyring) Set(i Item) error { func (k *passKeyring) Remove(key string) error { name := filepath.Join(k.prefix, key) - _, err := k.pass("rm", name) + cmd, err := k.pass("rm", "-f", name) + if err != nil { + return err + } + + err = cmd.Run() if err != nil { return err } diff --git a/pass_test.go b/pass_test.go index <HASH>..<HASH> 100644 --- a/pass_test.go +++ b/pass_test.go @@ -130,3 +130,27 @@ func TestPassKeyringKeysWhenNotEmpty(t *testing.T) { t.Fatalf("Expected llamas") } } + +func TestPassKeyringRemove(t *testing.T) { + k, teardown := setup(t) + defer teardown(t) + + item := Item{Key: "llamas", Data: []byte("llamas are great")} + + if err := k.Set(item); err != nil { + t.Fatal(err) + } + + if err := k.Remove(item.Key); err != nil { + t.Fatalf(err.Error()) + } + + keys, err := k.Keys() + if err != nil { + t.Fatal(err) + } + + if len(keys) != 0 { + t.Fatalf("Expected 0 keys, got %d", len(keys)) + } +}
Fix removal of keys with the pass backend and add corresponding test Prior to this commit, `aws-vault remove somekey` appeared to succeed but does not actually remove anything from the pass password store. This is due to the cmd returned from the call to the pass function never actually being run. Additionally, to avoid pass prompting the user whether they want to remove the key, run with the `-f|--force` option. This implies that the caller will take the appropriate steps and prompt/warn the user prior to key removal.
99designs_keyring
train
c4cfa367613733ae7ee0db5136daaf9005bb8eb6
diff --git a/lib/hub/commands.rb b/lib/hub/commands.rb index <HASH>..<HASH> 100644 --- a/lib/hub/commands.rb +++ b/lib/hub/commands.rb @@ -998,7 +998,7 @@ help # included after the __END__ of the file so we can grab it using # DATA. def hub_raw_manpage - if File.exists? file = File.dirname(__FILE__) + '/../../man/hub.1' + if File.exist? file = File.dirname(__FILE__) + '/../../man/hub.1' File.read(file) else DATA.read @@ -1085,7 +1085,7 @@ help # the pullrequest_editmsg_file, which newer hub would pick up and # misinterpret as a message which should be reused after a failed PR. def valid_editmsg_file?(message_file) - File.exists?(message_file) && + File.exist?(message_file) && File.mtime(message_file) > File.mtime(__FILE__) end diff --git a/test/standalone_test.rb b/test/standalone_test.rb index <HASH>..<HASH> 100644 --- a/test/standalone_test.rb +++ b/test/standalone_test.rb @@ -7,15 +7,15 @@ class StandaloneTest < Minitest::Test include FileUtils def setup - rm "hub" if File.exists? 'hub' - rm_rf "/tmp/_hub_private" if File.exists? '/tmp/_hub_private' + rm "hub" if File.exist? 'hub' + rm_rf "/tmp/_hub_private" if File.exist? '/tmp/_hub_private' mkdir "/tmp/_hub_private" chmod 0400, "/tmp/_hub_private" end def teardown - rm "hub" if File.exists? 'hub' - rm_rf "/tmp/_hub_private" if File.exists? "/tmp/_hub_private" + rm "hub" if File.exist? 'hub' + rm_rf "/tmp/_hub_private" if File.exist? "/tmp/_hub_private" end def test_standalone
Remove deprecated calls to `File.exists?` They emit Ruby warnings on Ruby <I>
github_hub
train
f59e69e11c237293ce1cfd020d0e43d5696d4218
diff --git a/packages/openapi-resolver/index.js b/packages/openapi-resolver/index.js index <HASH>..<HASH> 100644 --- a/packages/openapi-resolver/index.js +++ b/packages/openapi-resolver/index.js @@ -220,7 +220,7 @@ function scanExternalRefs(options) { let $ref = obj[key].$ref; if (!$ref.startsWith('#')) { if (!refs[$ref]) { - refs[$ref] = { resolved: false, paths: [], sources: [], description: obj.description }; + refs[$ref] = { resolved: false, paths: [], sources: [], description: obj[key].description }; } if (refs[$ref].resolved) { if (options.rewriteRefs) {
resolver; fix preservation of $ref + description
Mermade_oas-kit
train
46a313bde75ddbc2796c570019a5ea8d47e8b50e
diff --git a/dynash/dynash.py b/dynash/dynash.py index <HASH>..<HASH> 100755 --- a/dynash/dynash.py +++ b/dynash/dynash.py @@ -601,7 +601,7 @@ class DynamoDBShell(Cmd): count = True elif arg[0] == '-' and arg[1:].isdigit(): - max = arg[1:] + max = int(arg[1:]) elif arg == '--': break
the max count in scan should be a number, not a string :(
raff_dynash
train
d5302eea8309a97baa5f9af78a7a840333c4b514
diff --git a/backend/scrapers/classes/parsers/ellucianClassParser.js b/backend/scrapers/classes/parsers/ellucianClassParser.js index <HASH>..<HASH> 100644 --- a/backend/scrapers/classes/parsers/ellucianClassParser.js +++ b/backend/scrapers/classes/parsers/ellucianClassParser.js @@ -318,8 +318,12 @@ class EllucianClassParser extends EllucianBaseParser.EllucianBaseParser { // If is a single day class (exams, and some classes that happen like 2x a month specify specific dates). const splitTimeString = tableData.daterange[i].split('-'); if (splitTimeString.length > 1) { - const startDate = moment(splitTimeString[0].trim(), 'MMM D,YYYY'); - const endDate = moment(splitTimeString[1].trim(), 'MMM D,YYYY'); + // The Z's and the +0000 ensure that this date is parsed in +0000 time zone. + // Without this, it will parse this date (Apr 30, 2015) in local time (Apr 30, 2015 00:00 +0800) and the 0s below will be in local time too (1970 08:00 +0800) + // So, if you are running this code in Asia, it will say that there is one day of a difference less than there would be if you are running it in North America + // The Z's and moment(0, 'x')'s below ensure that everything is parsed at UTC+0 + const startDate = moment(splitTimeString[0].trim() + ' +0000', 'MMM D,YYYY Z'); + const endDate = moment(splitTimeString[1].trim() + ' +0000', 'MMM D,YYYY Z'); if (!startDate.isValid() || !endDate.isValid()) { macros.log('ERROR: one of parsed dates is not valid', splitTimeString, url); @@ -328,11 +332,11 @@ class EllucianClassParser extends EllucianBaseParser.EllucianBaseParser { // Add the dates if they are valid. // Store as days since epoch 1970. if (startDate.isValid()) { - sectionStartingData.meetings[index].startDate = startDate.diff(0, 'day'); + sectionStartingData.meetings[index].startDate = startDate.diff(moment(0, 'x'), 'day'); } if (endDate.isValid()) { - sectionStartingData.meetings[index].endDate = endDate.diff(0, 'day'); + sectionStartingData.meetings[index].endDate = endDate.diff(moment(0, 'x'), 'day'); } } else { macros.log('ERROR, invalid split time string or blank or something', splitTimeString, tableData.daterange[i]);
Fixed tests that were failing because I am in asia
ryanhugh_searchneu
train
8cb3ac1728f9a8b6f9df6ec0b4fcf197cf6764fd
diff --git a/networking_arista/ml2/arista_ml2.py b/networking_arista/ml2/arista_ml2.py index <HASH>..<HASH> 100644 --- a/networking_arista/ml2/arista_ml2.py +++ b/networking_arista/ml2/arista_ml2.py @@ -184,7 +184,10 @@ class AristaRPCWrapperBase(object): :param network_id: globally unique neutron network identifier :param network_segments: segments associated with the network """ - self.delete_network_segments(tenant_id, network_segments) + segments_info = [] + segments_info.extend({'id': segment['id'], 'network_id': network_id} + for segment in network_segments) + self.delete_network_segments(tenant_id, segments_info) self.delete_network_bulk(tenant_id, [network_id]) def delete_vm(self, tenant_id, vm_id): diff --git a/networking_arista/tests/unit/ml2/test_arista_mechanism_driver.py b/networking_arista/tests/unit/ml2/test_arista_mechanism_driver.py index <HASH>..<HASH> 100644 --- a/networking_arista/tests/unit/ml2/test_arista_mechanism_driver.py +++ b/networking_arista/tests/unit/ml2/test_arista_mechanism_driver.py @@ -1060,7 +1060,6 @@ class PositiveRPCWrapperValidConfigTestCase(testlib_api.SqlTestCase): segments = [{'segmentation_id': 101, 'physical_network': 'default', 'id': 'segment_id_1', - 'network_id': network_id, 'network_type': 'vlan'}] self.drv.delete_network(tenant_id, network_id, segments) cmd1 = ['show openstack agent uuid']
Fix for segments info in delete_network_segments The delete_network_segments API expects 'id' and 'network_id' in the segments argument for deleting a network segment. This patch fixes the issue by adding 'network_id' to the argument. Change-Id: I3c<I>e<I>f<I>a<I>c1be<I>dfbc0e9ab5b3b
openstack_networking-arista
train
fb8fc4c6372743a800ebeb2cf04848a73e0c8aea
diff --git a/lib/aruba/processes/spawn_process.rb b/lib/aruba/processes/spawn_process.rb index <HASH>..<HASH> 100644 --- a/lib/aruba/processes/spawn_process.rb +++ b/lib/aruba/processes/spawn_process.rb @@ -83,7 +83,7 @@ module Aruba sleep startup_wait_time end rescue ChildProcess::LaunchError => e - raise LaunchError, "It tried to start #{cmd}. " + e.message + raise LaunchError, "It tried to start #{commandline}. " + e.message end after_run diff --git a/spec/aruba/spawn_process_spec.rb b/spec/aruba/spawn_process_spec.rb index <HASH>..<HASH> 100644 --- a/spec/aruba/spawn_process_spec.rb +++ b/spec/aruba/spawn_process_spec.rb @@ -56,5 +56,39 @@ RSpec.describe Aruba::Processes::SpawnProcess do it { expect {process.start}.to raise_error Aruba::LaunchError } end + + context "with a childprocess launch error" do + let(:child) { instance_double(ChildProcess::AbstractProcess) } + let(:command) { 'foo' } + + before do + allow(ChildProcess).to receive(:build).and_return(child) + + # STEP 1: Simlulate the program exists (but will fail to run, e.g. EACCESS?) + allow(Aruba.platform).to receive(:which).with(command, anything).and_return("/foo") + + # STEP 2: Simulate the failure on Windows + allow(child).to receive(:start).and_raise(ChildProcess::LaunchError, "Foobar!") + + # TODO: wrap the result of ChildProcess.build with a special Aruba + # class , so the remaining mocks below won't be needed + allow(child).to receive(:leader=) + + io = instance_double(ChildProcess::AbstractIO) + allow(io).to receive(:stdout=) + allow(io).to receive(:stderr=) + + allow(child).to receive(:io).and_return(io) + + allow(child).to receive(:duplex=) + allow(child).to receive(:cwd=) + + allow(child).to receive(:environment).and_return({}) + end + + it "reraises LaunchError as Aruba's LaunchError" do + expect { process.start }.to raise_error(Aruba::LaunchError, "It tried to start foo. Foobar!") + end + end end end
Fix missing variable in exception handler Previously, "cmd" was passed to a different method. The reason this never came up earlier is because on Unix, if a file is not in the PATH, a Aruba::LaunchError is raised much earlier. One way this could've been triggered is: if the program file existed, but wasn't accessible (e.g. EACCES error). That way it wouldn't fail the `which` test, but would fail once it was attempted to be executed.
cucumber_aruba
train
1ed73ac3d1c218b9a3b56640543fd13d0913d27e
diff --git a/packages/ember-metal/lib/main.js b/packages/ember-metal/lib/main.js index <HASH>..<HASH> 100644 --- a/packages/ember-metal/lib/main.js +++ b/packages/ember-metal/lib/main.js @@ -223,7 +223,6 @@ Ember._Cache = Cache; Ember.generateGuid = generateGuid; Ember.GUID_KEY = GUID_KEY; -Ember.keys = Object.keys; Ember.platform = { defineProperty: true, hasPropertyAccessors: true @@ -408,5 +407,6 @@ if (Ember.__loader.registry['ember-debug']) { } Ember.create = Ember.deprecateFunc('Ember.create is deprecated in-favour of Object.create', Object.create); +Ember.keys = Ember.deprecateFunc('Ember.keys is deprecated in-favour of Object.keys', Object.keys); export default Ember; diff --git a/packages/ember-metal/tests/main_test.js b/packages/ember-metal/tests/main_test.js index <HASH>..<HASH> 100644 --- a/packages/ember-metal/tests/main_test.js +++ b/packages/ember-metal/tests/main_test.js @@ -32,8 +32,13 @@ QUnit.test('SEMVER_REGEX properly validates and invalidates version numbers', fu validateVersionString('1.11', false); }); +QUnit.test('Ember.keys is deprecated', function() { + expectDeprecation(function() { + Ember.keys({}); + }, 'Ember.keys is deprecated in-favour of Object.keys'); +}); -QUnit.test('Ember.create is deprecated', function() { +QUnit.test('Ember.keys is deprecated', function() { expectDeprecation(function() { Ember.create(null); }, 'Ember.create is deprecated in-favour of Object.create'); diff --git a/packages/ember-routing/lib/system/router_state.js b/packages/ember-routing/lib/system/router_state.js index <HASH>..<HASH> 100644 --- a/packages/ember-routing/lib/system/router_state.js +++ b/packages/ember-routing/lib/system/router_state.js @@ -1,4 +1,5 @@ -import Ember from 'ember-metal/core'; +import isEmpty from 'ember-metal/is_empty'; +import keys from 'ember-metal/keys'; import EmberObject from 'ember-runtime/system/object'; import merge from 'ember-metal/merge'; @@ -11,7 +12,7 @@ var RouterState = EmberObject.extend({ var state = this.routerJsState; if (!this.routerJs.isActiveIntent(routeName, models, null, state)) { return false; } - var emptyQueryParams = Ember.isEmpty(Ember.keys(queryParams)); + var emptyQueryParams = isEmpty(keys(queryParams)); if (queryParamsMustMatch && !emptyQueryParams) { var visibleQueryParams = {}; @@ -37,4 +38,3 @@ function shallowEqual(a, b) { } export default RouterState; - diff --git a/packages/ember/tests/component_registration_test.js b/packages/ember/tests/component_registration_test.js index <HASH>..<HASH> 100644 --- a/packages/ember/tests/component_registration_test.js +++ b/packages/ember/tests/component_registration_test.js @@ -1,5 +1,6 @@ import 'ember'; import Ember from 'ember-metal/core'; +import keys from 'ember-metal/keys'; import compile from 'ember-template-compiler/system/compile'; import helpers from 'ember-htmlbars/helpers'; @@ -12,7 +13,7 @@ function prepare() { Ember.TEMPLATES['components/expand-it'] = compile('<p>hello {{yield}}</p>'); Ember.TEMPLATES.application = compile('Hello world {{#expand-it}}world{{/expand-it}}'); - originalHelpers = Ember.A(Ember.keys(helpers)); + originalHelpers = Ember.A(keys(helpers)); } function cleanup() { @@ -28,7 +29,7 @@ function cleanup() { } function cleanupHandlebarsHelpers() { - var currentHelpers = Ember.A(Ember.keys(helpers)); + var currentHelpers = Ember.A(keys(helpers)); currentHelpers.forEach(function(name) { if (!originalHelpers.contains(name)) {
[BUGFIX release] Deprecate Ember.keys.
emberjs_ember.js
train
f8c88af369213ec92bd084eeee40622e4fda43db
diff --git a/tamil/utf8.py b/tamil/utf8.py index <HASH>..<HASH> 100644 --- a/tamil/utf8.py +++ b/tamil/utf8.py @@ -242,3 +242,38 @@ def get_letters( word ): #print ta_letters #print u"".join(ta_letters) return ta_letters + +# same as get_letters but use as iterable +def get_letters_iterable( word ): + """ splits the word into a character-list of tamil/english + characters present in the stream """ + prev = u''#word = unicode(word) #.encode('utf-8') + #word=word.decode('utf-8') + ta_letters = [] + for c in word: + if c in uyir_letters or c == ayudha_letter: + yield (prev+c) + prev = u'' + elif c in agaram_letters or c in sanskrit_letters: + if prev != u'': + yield (prev) + prev = c + elif c in accent_symbols: + yield (prev+c) + prev = u'' + else: + if prev != u'': + yield (prev+c) + prev = u'' + elif ord(c) < 256: + # plain-old ascii + yield ( c.decode('utf-8') ) + else: + # assertion is somewhat heavy handed here + print(u"Warning: #unknown/expected state - continuing tamil letter tokenizing. Copy unknown character to string output") + yield c + if prev != u'': #if prev is not null it is $c + yield prev +#print ta_letters +#print u"".join(ta_letters) + raise StopIteration diff --git a/test/letter_tests.py b/test/letter_tests.py index <HASH>..<HASH> 100644 --- a/test/letter_tests.py +++ b/test/letter_tests.py @@ -21,6 +21,17 @@ class Letters(unittest.TestCase): for pos,letter in enumerate(letters): print(u"%d %s"%(pos,letter)) assert( letter == (u"ர்") ) + + def test_letter_extract_yield(self): + letters = [] + for l in utf8.get_letters_iterable(u"கூவிளம் என்பது என்ன சீர்"): + letters.append( l ) + #print "len ==== > " , len(letters) + assert( len(letters) == 15 ) + for pos,letter in enumerate(letters): + print(u"%d %s"%(pos,letter)) + assert( letter == (u"ர்") ) + def test_tamil_letter_sizes( self ): assert( len(utf8.uyir_letters) == 12 )
iterable version of get_letters to work on a situation with large data
Ezhil-Language-Foundation_open-tamil
train
c45c69ab052202b83707807d450a73cf5fe7f5d4
diff --git a/tock.js b/tock.js index <HASH>..<HASH> 100644 --- a/tock.js +++ b/tock.js @@ -40,7 +40,7 @@ if ( typeof Function.prototype.bind != 'function' ) { this.final_time = 0; this.go = false; this.callback(this); - window.clearTimeout(this.timeout); + clearTimeout(this.timeout); this.complete(this); return; } @@ -60,7 +60,7 @@ if ( typeof Function.prototype.bind != 'function' ) { } } else if ( this.go ) { - this.timeout = window.setTimeout(_tick.bind(this), next_interval_in); + this.timeout = setTimeout(_tick.bind(this), next_interval_in); } } @@ -161,7 +161,7 @@ if ( typeof Function.prototype.bind != 'function' ) { this.pause_time = this.lap(); this.go = false; - window.clearTimeout(this.timeout); + clearTimeout(this.timeout); if ( this.countdown ) { this.final_time = this.duration_ms - this.time;
remove ref to window for use in node tock currently throws a ReferenceError when used in Node. Removing the reference to `window` will fix this error without breaking browser functionality. another option would be to add a line like `window = window || global;` around line <I>.
mrchimp_tock
train
79aae2aec101ccd38dbeb7427c0f0fc6b7c78a2c
diff --git a/app/config/mako.php b/app/config/mako.php index <HASH>..<HASH> 100644 --- a/app/config/mako.php +++ b/app/config/mako.php @@ -38,6 +38,15 @@ return array */ 'timezone' => 'UTC', + + /** + * Bundles to initialize by default. + */ + + 'bundles' => array + ( + + ), /** * Error handler settings. diff --git a/libraries/mako/Mako.php b/libraries/mako/Mako.php index <HASH>..<HASH> 100644 --- a/libraries/mako/Mako.php +++ b/libraries/mako/Mako.php @@ -228,6 +228,13 @@ namespace mako // Set locale static::locale(static::$config['mako']['locale']['locales'], static::$config['mako']['locale']['lc_numeric']); + + // Initialize bundles + + foreach(static::$config['mako']['bundles'] as $bundle) + { + static::bundle($bundle); + } } /** @@ -353,6 +360,22 @@ namespace mako return static::$config[$file]; } + + /** + * + */ + + public static function bundle($bundle) + { + $file = MAKO_BUNDLES . '/' . $bundle . '/init.php'; + + if(file_exists($file)) + { + return include $file; + } + + throw new RuntimeException(vsprintf("%s(): Unable to initialize the '%s' bundle. Make sure that it has been installed.", array(__METHOD__, $bundle))); + } /** * Set locale information.
Added "bundle loader"
mako-framework_framework
train
d75112ce8d8fd39ade107513144d074de6d694ef
diff --git a/pool/worker.go b/pool/worker.go index <HASH>..<HASH> 100644 --- a/pool/worker.go +++ b/pool/worker.go @@ -13,7 +13,7 @@ var ErrWorkerPoolExiting = errors.New("worker pool exiting") // DefaultWorkerTimeout is the default duration after which a worker goroutine // will exit to free up resources after having received no newly submitted // tasks. -const DefaultWorkerTimeout = 5 * time.Second +const DefaultWorkerTimeout = 90 * time.Second type ( // WorkerState is an interface used by the Worker to abstract the
pool/worker: increase worker timeout to <I>s This commit increases the default worker timeout currently backing the read and write pools. This allows the read and write pools to sustain regular bursty traffic such as ping/pong without releasing their buffers back to the underlying gc queue. In the future, jitter can be added to our ping and/or gossip messages to reduce the concurrent usage of read and write pools, which will make this change even more effective.
lightningnetwork_lnd
train
e48d759db266703cddc67633f76bf389e3a76d92
diff --git a/vault/policy_store.go b/vault/policy_store.go index <HASH>..<HASH> 100644 --- a/vault/policy_store.go +++ b/vault/policy_store.go @@ -84,6 +84,15 @@ path "sys/capabilities-self" { capabilities = ["update"] } +# Allow a token to look up its own entity by id or name +path "identity/entity/id/{{identity.entity.id}}" { + capabilities = ["read"] +} +path "identity/entity/name/{{identity.entity.name}}" { + capabilities = ["read"] +} + + # Allow a token to look up its resultant ACL from all policies. This is useful # for UIs. It is an internal path because the format may change at any time # based on how the internal ACL features and capabilities change.
add entity lookup to the default policy (#<I>) * add entity lookup to the default policy * only use id for lookup * back in with name
hashicorp_vault
train
19811e00829958f06d9bfbfeb0d0e6b7aaff3767
diff --git a/EmailValidator/Validation/MultipleValidationWithAnd.php b/EmailValidator/Validation/MultipleValidationWithAnd.php index <HASH>..<HASH> 100644 --- a/EmailValidator/Validation/MultipleValidationWithAnd.php +++ b/EmailValidator/Validation/MultipleValidationWithAnd.php @@ -3,23 +3,60 @@ namespace Egulias\EmailValidator\Validation; use Egulias\EmailValidator\EmailLexer; +use Egulias\EmailValidator\Exception\InvalidEmail; use Egulias\EmailValidator\Validation\Exception\EmptyValidationList; class MultipleValidationWithAnd implements EmailValidation { + /** + * If one of validations gets failure skips all succeeding validation. + * This means MultipleErrors will only contain a single error which first found. + */ + const STOP_ON_ERROR = 0; + + /** + * All of validations will be invoked even if one of them got failure. + * So MultipleErrors will contain all causes. + */ + const ALLOW_ALL_ERRORS = 1; + + /** + * @var EmailValidation[] + */ private $validations = []; + + /** + * @var array + */ private $warnings = []; + + /** + * @var MultipleErrors + */ private $error; - - public function __construct(array $validations) + + /** + * @var bool + */ + private $mode; + + /** + * @param EmailValidation[] $validations The validations. + * @param int $mode The validation mode (one of the constants). + */ + public function __construct(array $validations, $mode = self::ALLOW_ALL_ERRORS) { if (count($validations) == 0) { throw new EmptyValidationList(); } $this->validations = $validations; + $this->mode = $mode; } + /** + * {@inheritdoc} + */ public function isValid($email, EmailLexer $emailLexer) { $result = true; @@ -29,17 +66,32 @@ class MultipleValidationWithAnd implements EmailValidation $result = $result && $validation->isValid($email, $emailLexer); $this->warnings = array_merge($this->warnings, $validation->getWarnings()); $errors[] = $validation->getError(); + + if ($this->shouldStop($result)) { + break; + } } $this->error = new MultipleErrors($errors); return $result; } + private function shouldStop($result) + { + return !$result && $this->mode === self::STOP_ON_ERROR; + } + + /** + * {@inheritdoc} + */ public function getError() { return $this->error; } + /** + * {@inheritdoc} + */ public function getWarnings() { return $this->warnings; diff --git a/Tests/EmailValidator/Validation/MultipleValidationWitAndTest.php b/Tests/EmailValidator/Validation/MultipleValidationWitAndTest.php index <HASH>..<HASH> 100644 --- a/Tests/EmailValidator/Validation/MultipleValidationWitAndTest.php +++ b/Tests/EmailValidator/Validation/MultipleValidationWitAndTest.php @@ -25,7 +25,7 @@ class MultipleValidationWitAndTest extends \PHPUnit_Framework_TestCase } /** - * @expectedException Egulias\EmailValidator\Validation\Exception\EmptyValidationList + * @expectedException \Egulias\EmailValidator\Validation\Exception\EmptyValidationList */ public function testEmptyListIsNotAllowed() { @@ -79,4 +79,27 @@ class MultipleValidationWitAndTest extends \PHPUnit_Framework_TestCase $multipleValidation->isValid("[email protected]", $lexer); $this->assertEquals($expectedResult, $multipleValidation->getError()); } + + public function testBreakOutOfLoopWhenError() + { + $error = new CommaInDomain(); + + $expectedResult = new MultipleErrors([$error]); + + $lexer = $this->getMock("Egulias\\EmailValidator\\EmailLexer"); + + $validation1 = $this->getMock("Egulias\\EmailValidator\\Validation\\EmailValidation"); + $validation1->expects($this->any())->method("isValid")->willReturn(false); + $validation1->expects($this->once())->method("getWarnings")->willReturn([]); + $validation1->expects($this->once())->method("getError")->willReturn($error); + + $validation2 = $this->getMock("Egulias\\EmailValidator\\Validation\\EmailValidation"); + $validation2->expects($this->never())->method("isValid"); + $validation2->expects($this->never())->method("getWarnings"); + $validation2->expects($this->never())->method("getError"); + + $multipleValidation = new MultipleValidationWithAnd([$validation1, $validation2], MultipleValidationWithAnd::STOP_ON_ERROR); + $multipleValidation->isValid("[email protected]", $lexer); + $this->assertEquals($expectedResult, $multipleValidation->getError()); + } }
MultipleValidatorWithAnd now can break out of loop when error occurs (#<I>) * MultipleValidatorWithAnd now can break out of loop when error occurs * improved logic * updated doc * bugfix
egulias_EmailValidator
train
fc206ad15109db0b627c7e67fb5bbef6d2d6be12
diff --git a/beets/mediafile.py b/beets/mediafile.py index <HASH>..<HASH> 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -33,7 +33,7 @@ Internally ``MediaFile`` uses ``MediaField`` descriptors to access the data from the tags. In turn ``MediaField`` uses a number of ``StorageStyle`` strategies to handle format specific logic. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import mutagen import mutagen.mp3
Standardize __future__ imports without parentheses Since the list is short enough now, we don't need parentheses for the line wrap. This is a little less ugly. Original: beetbox/beets@e<I>c7ee
beetbox_mediafile
train
53adb6168022428c9816479fe757fc97194c060b
diff --git a/lib/bibliothecary/parsers/go.rb b/lib/bibliothecary/parsers/go.rb index <HASH>..<HASH> 100644 --- a/lib/bibliothecary/parsers/go.rb +++ b/lib/bibliothecary/parsers/go.rb @@ -150,7 +150,7 @@ module Bibliothecary def self.parse_go_resolved(file_contents, options: {}) JSON.parse(file_contents) .select { |dep| dep["Main"] != "true" } - .map { |dep| { name: dep["Path"], requirement: dep["Version"], type: 'runtime' } } + .map { |dep| { name: dep["Path"], requirement: dep["Version"], type: dep.fetch("Scope") { "runtime" } } } end def self.map_dependencies(manifest, attr_name, dep_attr_name, version_attr_name, type) diff --git a/spec/fixtures/go-resolved-dependencies.json b/spec/fixtures/go-resolved-dependencies.json index <HASH>..<HASH> 100644 --- a/spec/fixtures/go-resolved-dependencies.json +++ b/spec/fixtures/go-resolved-dependencies.json @@ -2,84 +2,105 @@ "Path": "main", "Main": "true", "Version": "", - "Indirect": "false" + "Indirect": "false", + "Scope": "runtime" }, { "Path": "cloud.google.com/go", "Main": "false", "Version": "v0.36.0", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "dmitri.shuralyov.com/app/changes", "Main": "false", "Version": "v0.0.0-20180602232624-0a106ad413e3", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "dmitri.shuralyov.com/html/belt", "Main": "false", "Version": "v0.0.0-20180602232347-f7d459c86be0", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "dmitri.shuralyov.com/service/change", "Main": "false", "Version": "v0.0.0-20181023043359-a85b471d5412", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "dmitri.shuralyov.com/state", "Main": "false", "Version": "v0.0.0-20180228185332-28bcc343414c", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "git.apache.org/thrift.git", "Main": "false", "Version": "v0.0.0-20180902110319-2566ecd5d999", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "github.com/BurntSushi/toml", "Main": "false", "Version": "v0.3.1", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "github.com/Masterminds/semver", "Main": "false", "Version": "v1.5.0", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "github.com/Masterminds/semver/v3", "Main": "false", "Version": "v3.0.3", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "github.com/OneOfOne/xxhash", "Main": "false", "Version": "v1.2.2", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "github.com/ajg/form", "Main": "false", "Version": "v1.5.1", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "github.com/alecthomas/template", "Main": "false", "Version": "v0.0.0-20160405071501-a0175ee3bccc", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" }, { "Path": "github.com/alecthomas/units", "Main": "false", "Version": "v0.0.0-20151022065526-2efee857e7cf", - "Indirect": "true" + "Indirect": "true", + "Scope": "runtime" + }, + { + "Path": "github.com/stretchr/testify", + "Main": "false", + "Version": "v1.7.0", + "Indirect": "false", + "Scope": "test" } - ] \ No newline at end of file + ] diff --git a/spec/parsers/go_spec.rb b/spec/parsers/go_spec.rb index <HASH>..<HASH> 100644 --- a/spec/parsers/go_spec.rb +++ b/spec/parsers/go_spec.rb @@ -282,6 +282,7 @@ describe Bibliothecary::Parsers::Go do {:name=>"github.com/ajg/form", :requirement=>"v1.5.1", :type=>"runtime"}, {:name=>"github.com/alecthomas/template", :requirement=>"v0.0.0-20160405071501-a0175ee3bccc", :type=>"runtime"}, {:name=>"github.com/alecthomas/units", :requirement=>"v0.0.0-20151022065526-2efee857e7cf", :type=>"runtime"}, + {:name=>"github.com/stretchr/testify", :requirement=>"v1.7.0", :type=>"test"}, ], kind: 'lockfile', success: true
Look for custom "Scope" value in go-resolved-dependencies.json (#<I>)
librariesio_bibliothecary
train
ebccc8dc686223003771022a00fa932e03378fc4
diff --git a/src/wrappers/wrapper.js b/src/wrappers/wrapper.js index <HASH>..<HASH> 100644 --- a/src/wrappers/wrapper.js +++ b/src/wrappers/wrapper.js @@ -413,6 +413,8 @@ export default class Wrapper implements BaseWrapper { } // $FlowIgnore : Problem with possibly null this.vm this.vm._computedWatchers[key].value = computed[key] + this.vm._computedWatchers[key].getter = () => computed[key] + } else { // $FlowIgnore : Problem with possibly null this.vm if (!this.vm._watchers.some(w => w.getter.name === key)) { @@ -422,6 +424,7 @@ export default class Wrapper implements BaseWrapper { this.vm._watchers.forEach((watcher) => { if (watcher.getter.name === key) { watcher.value = computed[key] + watcher.getter = () => computed[key] } }) } diff --git a/test/unit/specs/mount/Wrapper/setComputed.spec.js b/test/unit/specs/mount/Wrapper/setComputed.spec.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/mount/Wrapper/setComputed.spec.js +++ b/test/unit/specs/mount/Wrapper/setComputed.spec.js @@ -32,6 +32,26 @@ describe('setComputed', () => { const computed1 = 'new computed' wrapper.setComputed({ computed1 }) expect(info.args[0][0]).to.equal(computed1) + expect(wrapper.vm.computed1).to.equal(computed1) + }) + + it('updates vm computed value', () => { + const TestComponent = { + data () { + return { + a: 1 + } + }, + computed: { + b () { + return this.a * 2 + } + } + } + + const wrapper = mount(TestComponent) + wrapper.setComputed({b: 3}) + expect(wrapper.vm.b).to.equal(3) }) it('throws an error if node is not a Vue instance', () => {
fix(setComputed): permanently update computed watcher when called fixes #<I>
vuejs_vue-test-utils
train
fe782260c6acf820126c2d41e506db12abb1da35
diff --git a/host/pybar/scans/test_tdc.py b/host/pybar/scans/test_tdc.py index <HASH>..<HASH> 100644 --- a/host/pybar/scans/test_tdc.py +++ b/host/pybar/scans/test_tdc.py @@ -65,8 +65,8 @@ class TdcTest(Fei4RunBase): def scan(self): self.dut['tdc_rx2']['ENABLE'] = True - self.dut['tdc_rx2']['EN_ARMING'] = False - self.dut['tdc_rx2']['EN_TRIGGER_COUNT'] = True + self.dut['tdc_rx2']['EN_TRIGGER_DIST'] = True + self.dut['tdc_rx2']['EN_NO_WRITE_TRIG_ERR'] = False with PdfPages(self.output_filename + '.pdf') as output_pdf: if self.test_tdc_values: @@ -80,11 +80,11 @@ class TdcTest(Fei4RunBase): time.sleep(self.n_pulses * pulse_width * 1e-9 + 0.1) data = self.fifo_readout.read_data() if data[is_tdc_word(data)].shape[0] != 0: - if len(is_tdc_word(data)) != self.n_pulses: - logging.warning('%d TDC words instead of %d ' % (len(is_tdc_word(data)), self.n_pulses)) tdc_values = np.bitwise_and(data[is_tdc_word(data)], 0x00000FFF) tdc_counter = np.bitwise_and(data[is_tdc_word(data)], 0x000FF000) tdc_counter = np.right_shift(tdc_counter, 12) + if len(is_tdc_word(data)) != self.n_pulses: + logging.warning('%d TDC words instead of %d ' % (len(is_tdc_word(data)), self.n_pulses)) try: if np.any(np.logical_and(tdc_counter[np.gradient(tdc_counter) != 1] != 0, tdc_counter[np.gradient(tdc_counter) != 1] != 255)): logging.warning('The counter did not count correctly') @@ -103,12 +103,13 @@ class TdcTest(Fei4RunBase): plotting.plot_scatter(x, y, y_err, title='FPGA TDC linearity, ' + str(self.n_pulses) + ' each', x_label='Pulse width [ns]', y_label='TDC value', filename=output_pdf) plotting.plot_scatter(x, y_err, title='FPGA TDC RMS, ' + str(self.n_pulses) + ' each', x_label='Pulse width [ns]', y_label='TDC RMS', filename=output_pdf) - plotting.plot_tdc_counter(tdc_hist, title='All TDC values', filename=output_pdf) + if tdc_hist is not None: + plotting.plot_tdc_counter(tdc_hist, title='All TDC values', filename=output_pdf) if self.test_trigger_delay: x, y, y_err = [], [], [] self.fifo_readout.reset_sram_fifo() # clear fifo data - for pulse_delay in [i for j in (range(0, 100, 5), range(100, 500, 20)) for i in j]: + for pulse_delay in [i for j in (range(0, 100, 5), range(100, 500, 500)) for i in j]: logging.info('Test TDC for a pulse delay of %d' % pulse_delay) for _ in range(10): self.start_pulser(pulse_width=100, n_pulses=1, pulse_delay=pulse_delay)
ENH: no crash if no TDC words ENH: increased delay range check ENH: new TDC configuration
SiLab-Bonn_pyBAR
train
dff044e36f7ecd480944f0a290463fb6fc905a77
diff --git a/baton/json.py b/baton/json.py index <HASH>..<HASH> 100644 --- a/baton/json.py +++ b/baton/json.py @@ -54,10 +54,12 @@ def _set_last_modified_timestamp(timestamped: Timestamped, datetime_as_string: s _timestamped_json_mappings = [ JsonPropertyMapping("created", object_property_getter=lambda timestamped: timestamped.created.isoformat(), - object_property_setter=lambda timestamped, datetime_as_string: _set_created_timestamp(timestamped, datetime_as_string)), - JsonPropertyMapping("last_modified", + object_property_setter=lambda timestamped, datetime_as_string: _set_created_timestamp( + timestamped, datetime_as_string)), + JsonPropertyMapping("modified", optional=True, object_property_getter=lambda timestamped: timestamped.last_modified.isoformat(), - object_property_setter=lambda timestamped, datetime_as_string: _set_last_modified_timestamp(timestamped, datetime_as_string)) + object_property_setter=lambda timestamped, datetime_as_string: _set_last_modified_timestamp( + timestamped, datetime_as_string)) ] _TimestampedJSONEncoder = MappingJSONEncoderClassBuilder(Timestamped, _timestamped_json_mappings).build() _TimestampedJSONDecoder = MappingJSONDecoderClassBuilder(Timestamped, _timestamped_json_mappings).build() @@ -169,9 +171,9 @@ _collection_json_mappings = [ JsonPropertyMapping(BATON_COLLECTION_PROPERTY, "path", "path") ] CollectionJSONEncoder = MappingJSONEncoderClassBuilder( - Collection, _collection_json_mappings, (_IrodsEntityJSONEncoder, _TimestampedJSONEncoder)).build() + Collection, _collection_json_mappings, (_IrodsEntityJSONEncoder,)).build() CollectionJSONDecoder = MappingJSONDecoderClassBuilder( - Collection, _collection_json_mappings, (_IrodsEntityJSONDecoder, _TimestampedJSONDecoder)).build() + Collection, _collection_json_mappings, (_IrodsEntityJSONDecoder, )).build() # JSON encoder/decoder for `SearchCriterion` diff --git a/baton/models.py b/baton/models.py index <HASH>..<HASH> 100644 --- a/baton/models.py +++ b/baton/models.py @@ -63,8 +63,9 @@ class DataObject(IrodsEntity): """ from baton.collections import IrodsMetadata - def __init__(self, replicas: Iterable[DataObjectReplica]=(), *args, **kwargs): - super().__init__(*args, **kwargs) + def __init__(self, path: str, access_control_list: Iterable[AccessControl]=None, metadata: IrodsMetadata=None, + replicas: Iterable[DataObjectReplica]=()): + super().__init__(path, access_control_list, metadata) from baton.collections import DataObjectReplicaCollection self.replicas = DataObjectReplicaCollection(replicas) diff --git a/baton/tests/test_models.py b/baton/tests/test_models.py index <HASH>..<HASH> 100644 --- a/baton/tests/test_models.py +++ b/baton/tests/test_models.py @@ -13,7 +13,7 @@ class TestDataObject(unittest.TestCase): Tests for `DataObject`. """ def setUp(self): - self.data_object = DataObject("%s/%s" % (_COLLECTION, _FILE_NAME), _CHECKSUMS[0], [], []) + self.data_object = DataObject(path="%s/%s" % (_COLLECTION, _FILE_NAME), checksum=_CHECKSUMS[0]) def test_get_collection_path(self): self.assertEquals(self.data_object.get_collection_path(), _COLLECTION) diff --git a/requirements.txt b/requirements.txt index <HASH>..<HASH> 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ git+https://github.com/wtsi-hgi/python-common.git@b2ea5807efc9ec640a4cd024ea78442120801767#egg=hgicommon -git+https://github.com/wtsi-hgi/python-json.git@5ec1f95bb6c456689cead38f956de9a181f0fb27#egg=hgijson \ No newline at end of file +git+https://github.com/wtsi-hgi/python-json.git@1011307dff82a8438059cf2f51130a7b05a4cf6d#egg=hgijson \ No newline at end of file
Collections do not have timestamps in iRODS.
wtsi-hgi_python-baton-wrapper
train
0c57f6bedb6be516186bbd8971a4cce2078641ee
diff --git a/core/src/main/java/com/graphhopper/Trip.java b/core/src/main/java/com/graphhopper/Trip.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/graphhopper/Trip.java +++ b/core/src/main/java/com/graphhopper/Trip.java @@ -38,14 +38,23 @@ public class Trip { public final Point geometry; public final Date arrivalTime; + public final Date plannedArrivalTime; + public final Date predictedArrivalTime; + public final Date departureTime; + public final Date plannedDepartureTime; + public final Date predictedDepartureTime; - public Stop(String stop_id, String name, Point geometry, Date arrivalTime, Date departureTime) { + public Stop(String stop_id, String name, Point geometry, Date arrivalTime, Date plannedArrivalTime, Date predictedArrivalTime, Date departureTime, Date plannedDepartureTime, Date predictedDepartureTime) { this.stop_id = stop_id; this.stop_name = name; this.geometry = geometry; this.arrivalTime = arrivalTime; + this.plannedArrivalTime = plannedArrivalTime; + this.predictedArrivalTime = predictedArrivalTime; this.departureTime = departureTime; + this.plannedDepartureTime = plannedDepartureTime; + this.predictedDepartureTime = predictedDepartureTime; } @Override diff --git a/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/TripFromLabel.java b/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/TripFromLabel.java index <HASH>..<HASH> 100644 --- a/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/TripFromLabel.java +++ b/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/TripFromLabel.java @@ -213,7 +213,7 @@ class TripFromLabel { Instant plannedDeparture = Instant.ofEpochMilli(t.label.currentTime); Instant updatedDeparture = plannedDeparture.plus(getDepartureDelay(stopSequence), SECONDS); Stop stop = gtfsFeed.stops.get(stopTime.stop_id); - stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), null, Date.from(updatedDeparture))); + stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), null, null, null, Date.from(updatedDeparture), Date.from(plannedDeparture), Date.from(updatedDeparture))); break; } case HOP: { @@ -227,7 +227,7 @@ class TripFromLabel { Instant plannedDeparture = Instant.ofEpochMilli(t.label.currentTime); Instant updatedDeparture = plannedDeparture.plus(getDepartureDelay(stopTime.stop_sequence), SECONDS); Stop stop = gtfsFeed.stops.get(stopTime.stop_id); - stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), Date.from(updatedArrival), Date.from(updatedDeparture))); + stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), Date.from(updatedArrival), Date.from(arrivalTimeFromHopEdge), Date.from(updatedArrival), Date.from(updatedDeparture), Date.from(plannedDeparture), Date.from(updatedDeparture))); break; } default: { @@ -258,7 +258,7 @@ class TripFromLabel { void finish() { Stop stop = gtfsFeed.stops.get(stopTime.stop_id); - stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), Date.from(updatedArrival), null)); + stops.add(new Trip.Stop(stop.stop_id, stop.stop_name, geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)), Date.from(updatedArrival), Date.from(arrivalTimeFromHopEdge), Date.from(updatedArrival), null, null, null)); for (Trip.Stop tripStop : stops) { logger.trace("{}", tripStop); } diff --git a/reader-gtfs/src/test/java/com/graphhopper/RealtimeIT.java b/reader-gtfs/src/test/java/com/graphhopper/RealtimeIT.java index <HASH>..<HASH> 100644 --- a/reader-gtfs/src/test/java/com/graphhopper/RealtimeIT.java +++ b/reader-gtfs/src/test/java/com/graphhopper/RealtimeIT.java @@ -341,7 +341,9 @@ public class RealtimeIT { GHResponse response = graphHopperFactory.createWith(feedMessageBuilder.build()).route(ghRequest); assertEquals(1, response.getAll().size()); - assertEquals("My line run is 3 minutes late.", LocalDateTime.parse("2007-01-01T06:52:00").atZone(zoneId).toInstant(), response.getBest().getLegs().get(response.getBest().getLegs().size() - 1).getArrivalTime().toInstant()); + Trip.PtLeg ptLeg = ((Trip.PtLeg) response.getBest().getLegs().get(response.getBest().getLegs().size() - 2)); + assertEquals("My line run is 3 minutes late.", LocalDateTime.parse("2007-01-01T06:52:00").atZone(zoneId).toInstant(), ptLeg.getArrivalTime().toInstant()); + assertEquals("It is still reporting its original, scheduled time.", LocalDateTime.parse("2007-01-01T06:49:00").atZone(zoneId).toInstant(), ptLeg.stops.get(ptLeg.stops.size()-1).plannedArrivalTime.toInstant()); } @Test
Insert separate fields for planned/predicted departure/arrival time
graphhopper_graphhopper
train
09e70d104badb5adbe62aea897ab2e2c6d9645f1
diff --git a/src/python/dxpy/bindings/dxfile.py b/src/python/dxpy/bindings/dxfile.py index <HASH>..<HASH> 100644 --- a/src/python/dxpy/bindings/dxfile.py +++ b/src/python/dxpy/bindings/dxfile.py @@ -168,20 +168,11 @@ class DXFile(DXDataObject): _close = staticmethod(dxpy.api.file_close) _list_projects = staticmethod(dxpy.api.file_list_projects) - _http_threadpool = None _http_threadpool_size = DXFILE_HTTP_THREADS + _http_threadpool = dxpy.utils.get_futures_threadpool(max_workers=_http_threadpool_size) NO_PROJECT_HINT = 'NO_PROJECT_HINT' - @classmethod - def set_http_threadpool_size(cls, num_threads): - cls._http_threadpool_size = num_threads - - @classmethod - def _ensure_http_threadpool(cls): - if cls._http_threadpool is None: - cls._http_threadpool = dxpy.utils.get_futures_threadpool(max_workers=cls._http_threadpool_size) - def __init__(self, dxid=None, project=None, mode=None, read_buffer_size=DEFAULT_BUFFER_SIZE, write_buffer_size=DEFAULT_BUFFER_SIZE, expected_file_size=None, file_is_mmapd=False): """ @@ -436,8 +427,6 @@ class DXFile(DXDataObject): self._http_threadpool_futures = set() def _async_upload_part_request(self, *args, **kwargs): - self._ensure_http_threadpool() - while len(self._http_threadpool_futures) >= self._http_threadpool_size: future = dxpy.utils.wait_for_a_future(self._http_threadpool_futures) if future.exception() != None: @@ -753,8 +742,6 @@ class DXFile(DXDataObject): FILE_REQUEST_TIMEOUT], {} def _next_response_content(self): - self._ensure_http_threadpool() - if self._response_iterator is None: self._response_iterator = dxpy.utils.response_iterator( self._request_iterator, diff --git a/src/python/dxpy/bindings/dxfile_functions.py b/src/python/dxpy/bindings/dxfile_functions.py index <HASH>..<HASH> 100644 --- a/src/python/dxpy/bindings/dxfile_functions.py +++ b/src/python/dxpy/bindings/dxfile_functions.py @@ -256,7 +256,6 @@ def _download_dxfile(dxid, filename, part_retry_counter, try: # Main loop. In parallel: download chunks, verify them, and write them to disk. cur_part, got_bytes, hasher = None, None, None - dxfile._ensure_http_threadpool() for chunk_part, chunk_data in response_iterator(chunk_requests(), dxfile._http_threadpool): if chunk_part != cur_part: verify_part(cur_part, got_bytes, hasher)
PTFM-<I> Simplify dxfile class initialization Summary: We want to streamline the initialization for dxfile, notably by removing set_http_threadpool_size and _ensure_http_threadpool. The former is not called in any other method, and the latter needs only to be called at initialization of the class. Test Plan: dxpy integration tests Reviewers: orodeh Reviewed By: orodeh Differential Revision: <URL>
dnanexus_dx-toolkit
train
db2b219c54c7b5270a01a1becd6d533c6a42d0a7
diff --git a/docs-source/functions/objectToLiteralString.js b/docs-source/functions/objectToLiteralString.js index <HASH>..<HASH> 100644 --- a/docs-source/functions/objectToLiteralString.js +++ b/docs-source/functions/objectToLiteralString.js @@ -3,6 +3,8 @@ function objectToLiteralString(object) { return "[Function]" } else if (object === null) { return "null" + } else if (object === undefined) { + return "undefined" } else if (Array.isArray(object)) { return "["+object.map(objectToLiteralString).join(", ")+"]" } else if (typeof object == 'object') {
add support for undefined in objectToLiteralString
L1lith_Sandhands
train
52b159b1db8f99119ced93923592a229b64b8918
diff --git a/cmd/object-handlers.go b/cmd/object-handlers.go index <HASH>..<HASH> 100644 --- a/cmd/object-handlers.go +++ b/cmd/object-handlers.go @@ -1454,6 +1454,22 @@ func (api objectAPIHandlers) CopyObjectPartHandler(w http.ResponseWriter, r *htt cpSrcPath = r.Header.Get("X-Amz-Copy-Source") } + // Check https://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectVersioning.html + // Regardless of whether you have enabled versioning, each object in your bucket + // has a version ID. If you have not enabled versioning, Amazon S3 sets the value + // of the version ID to null. If you have enabled versioning, Amazon S3 assigns a + // unique version ID value for the object. + if u, err := url.Parse(cpSrcPath); err == nil { + // Check if versionId query param was added, if yes then check if + // its non "null" value, we should error out since we do not support + // any versions other than "null". + if vid := u.Query().Get("versionId"); vid != "" && vid != "null" { + writeErrorResponse(w, ErrNoSuchVersion, r.URL, guessIsBrowserReq(r)) + return + } + cpSrcPath = u.Path + } + srcBucket, srcObject := path2BucketAndObject(cpSrcPath) // If source object is empty or bucket is empty, reply back invalid copy source. if srcObject == "" || srcBucket == "" { @@ -2242,6 +2258,11 @@ func (api objectAPIHandlers) DeleteObjectHandler(w http.ResponseWriter, r *http. return } + if vid := r.URL.Query().Get("versionId"); vid != "" && vid != "null" { + writeErrorResponse(w, ErrNoSuchVersion, r.URL, guessIsBrowserReq(r)) + return + } + // Deny if WORM is enabled if globalWORMEnabled { // Not required to check whether given object exists or not, because
Allow versionId to be null for Delete,CopyObjectPart (#<I>)
minio_minio
train
b63899095d53e7f9782a21cf0a29d875d7a734e1
diff --git a/domain_compat.go b/domain_compat.go index <HASH>..<HASH> 100644 --- a/domain_compat.go +++ b/domain_compat.go @@ -40,7 +40,7 @@ int virDomainCoreDumpWithFormatCompat(virDomainPtr domain, #if LIBVIR_VERSION_NUMBER < 1002003 assert(0); // Caller should have checked version #else - return virDomainCoreDumpWithFormatCompat(domain, to, dumpformat, flags); + return virDomainCoreDumpWithFormat(domain, to, dumpformat, flags); #endif } @@ -232,7 +232,7 @@ int virDomainGetPerfEventsCompat(virDomainPtr dom, #if LIBVIR_VERSION_NUMBER < 1003003 assert(0); // Caller should have checked version #else - return virDomainGetPerfEventsCompat(dom, params, nparams, flags); + return virDomainGetPerfEvents(dom, params, nparams, flags); #endif } @@ -245,7 +245,7 @@ int virDomainSetPerfEventsCompat(virDomainPtr dom, #if LIBVIR_VERSION_NUMBER < 1003003 assert(0); // Caller should have checked version #else - return virDomainSetPerfEventsCompat(dom, params, nparams, flags); + return virDomainSetPerfEvents(dom, params, nparams, flags); #endif }
Fix mistakes in compat functions calling themselves
libvirt_libvirt-go
train
ed8c784ea787f83ddb1adf4640c72424569bb227
diff --git a/vacation/lexer.py b/vacation/lexer.py index <HASH>..<HASH> 100644 --- a/vacation/lexer.py +++ b/vacation/lexer.py @@ -6,6 +6,23 @@ SETRATE = 'setrate' SETDAYS = 'setdays' MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] +def lex(args): """ Lex input. """ + if len(args) == 0: + return [(SHOW)] + elif isMonth(args[0]): + if not args[2:]: + return [(TAKE, lexDate(args[0:2]))] - print('inputs were {}'.format(inputs)) + +def lexDate(args): + #print('\n@@@ {}'.format(args)) + month = args[0][:3].lower() + day = int(args[1]) + if not isMonth(args[0]): + raise ValueError('Not valid month') + return '{} {}'.format(month, day) + +def isMonth(arg): + month = arg[:3].lower() + return month in MONTHS
Extract a single date from args
pulseenergy_vacation
train
8816a9a7716a7345296a177fdc27acd0a3be458d
diff --git a/src/js/EventHandler.js b/src/js/EventHandler.js index <HASH>..<HASH> 100644 --- a/src/js/EventHandler.js +++ b/src/js/EventHandler.js @@ -468,12 +468,30 @@ define([ }; /** + * Drag and Drop Events + * + * @param {Object} oLayoutInfo - layout Informations + * @param {Boolean} disableDragAndDrop + */ + var handleDragAndDropEvent = function (oLayoutInfo, disableDragAndDrop) { + if (disableDragAndDrop) { + // prevent default drop event + $document.on('drop', function (e) { + e.preventDefault(); + }); + } else { + attachDragAndDropEvent(oLayoutInfo); + } + }; + + /** * attach Drag and Drop Events * * @param {Object} oLayoutInfo - layout Informations */ var attachDragAndDropEvent = function (oLayoutInfo) { - var collection = $(), $dropzone = oLayoutInfo.dropzone, + var collection = $(), + $dropzone = oLayoutInfo.dropzone, $dropzoneMessage = oLayoutInfo.dropzone.find('.note-dropzone-message'); // show dropzone on dragenter when dragging a object to document. @@ -581,9 +599,7 @@ define([ // handlers for frame mode (toolbar, statusbar) if (!options.airMode) { // handler for drag and drop - if (!options.disableDragAndDrop) { - attachDragAndDropEvent(oLayoutInfo); - } + handleDragAndDropEvent(oLayoutInfo, options.disableDragAndDrop); // handler for toolbar oLayoutInfo.toolbar.on('click', hToolbarAndPopoverClick);
Prevent default drop event when disableDragAndDrop is true. #<I>.
summernote_summernote
train
2260ceb51332fb789f1ceaff2c7672c3edd63393
diff --git a/src/main/java/com/bugsnag/Bugsnag.java b/src/main/java/com/bugsnag/Bugsnag.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/bugsnag/Bugsnag.java +++ b/src/main/java/com/bugsnag/Bugsnag.java @@ -82,7 +82,7 @@ public class Bugsnag { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { - sessionTracker.setShuttingDown(true); + sessionTracker.shutdown(); sessionExecutorService.shutdown(); try { if (!sessionExecutorService diff --git a/src/main/java/com/bugsnag/SessionTracker.java b/src/main/java/com/bugsnag/SessionTracker.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/bugsnag/SessionTracker.java +++ b/src/main/java/com/bugsnag/SessionTracker.java @@ -8,6 +8,7 @@ import java.util.Date; import java.util.UUID; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; class SessionTracker { @@ -19,7 +20,7 @@ class SessionTracker { enqueuedSessionCounts = new ConcurrentLinkedQueue<SessionCount>(); private final Semaphore flushingRequest = new Semaphore(1); - private volatile boolean shuttingDown; + private final AtomicBoolean shuttingDown = new AtomicBoolean(); SessionTracker(Configuration configuration) { this.config = configuration; @@ -27,7 +28,8 @@ class SessionTracker { void startSession(Date date, boolean autoCaptured) { if ((!config.shouldAutoCaptureSessions() && autoCaptured) - || !config.shouldNotifyForReleaseStage()) { + || !config.shouldNotifyForReleaseStage() + || shuttingDown.get()) { return; } @@ -68,9 +70,13 @@ class SessionTracker { } void flushSessions(Date now) { - if (shuttingDown) { + if (shuttingDown.get()) { return; } + sendSessions(now); + } + + private void sendSessions(Date now) { updateBatchCountIfNeeded(DateUtils.roundTimeToLatestMinute(now)); if (!enqueuedSessionCounts.isEmpty() && flushingRequest.tryAcquire(1)) { @@ -87,7 +93,9 @@ class SessionTracker { } } - void setShuttingDown(boolean shuttingDown) { - this.shuttingDown = shuttingDown; + void shutdown() { + if (shuttingDown.compareAndSet(false, true)) { + sendSessions(new Date(Long.MAX_VALUE)); // flush all remaining sessions + } } } diff --git a/src/test/java/com/bugsnag/SessionTrackerTest.java b/src/test/java/com/bugsnag/SessionTrackerTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/bugsnag/SessionTrackerTest.java +++ b/src/test/java/com/bugsnag/SessionTrackerTest.java @@ -14,7 +14,6 @@ import com.bugsnag.serialization.Serializer; import org.junit.Before; import org.junit.Test; -import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; @@ -290,30 +289,52 @@ public class SessionTrackerTest { } @Test - public void sessionDeliveryShutdown() throws Throwable { + public void zeroSessionCount() throws Throwable { CustomDelivery sessionDelivery = new CustomDelivery() {}; configuration.sessionDelivery = sessionDelivery; - sessionTracker.startSession(new Date(10000000L), false); - sessionTracker.setShuttingDown(true); sessionTracker.flushSessions(new Date(10120000L)); + sessionTracker.flushSessions(new Date(14000000L)); assertFalse(sessionDelivery.delivered); } @Test - public void zeroSessionCount() throws Throwable { - CustomDelivery sessionDelivery = new CustomDelivery() {}; - configuration.sessionDelivery = sessionDelivery; - sessionTracker.flushSessions(new Date(10120000L)); - sessionTracker.flushSessions(new Date(14000000L)); - assertFalse(sessionDelivery.delivered); + public void testSessionShutdownStartSession() { + sessionTracker.shutdown(); + sessionTracker.startSession(new Date(), true); + assertNull(sessionTracker.getSession()); + } + + @Test + public void testSessionShutdownDelivers() { + CustomDelivery delivery = new CustomDelivery() {}; + configuration.sessionDelivery = delivery; + + sessionTracker.startSession(new Date(), true); + sessionTracker.shutdown(); + assertTrue(delivery.recentRequest instanceof SessionPayload); + assertEquals(1, delivery.count.get()); + } + + @Test + public void testMultiShutdown() { + CustomDelivery delivery = new CustomDelivery() {}; + configuration.sessionDelivery = delivery; + + sessionTracker.startSession(new Date(), true); + sessionTracker.shutdown(); + sessionTracker.shutdown(); // second should have no effect + assertTrue(delivery.recentRequest instanceof SessionPayload); + assertEquals(1, delivery.count.get()); } abstract static class CustomDelivery implements Delivery { boolean delivered; AtomicInteger count = new AtomicInteger(0); + Object recentRequest; @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { + this.recentRequest = object; delivered = true; count.getAndIncrement(); }
refactor: shutdown will now flush any remaining sessions and drop any newly added sessions When shutting down, any extant sessions will be immediately sent in a request. Newly added sessions will be ignored at this point.
bugsnag_bugsnag-java
train
b7a4f6df96ef83e82c7ed6238e4d0346c0f666f7
diff --git a/spec/LdapTools/Security/SecurityDescriptorSpec.php b/spec/LdapTools/Security/SecurityDescriptorSpec.php index <HASH>..<HASH> 100644 --- a/spec/LdapTools/Security/SecurityDescriptorSpec.php +++ b/spec/LdapTools/Security/SecurityDescriptorSpec.php @@ -147,4 +147,44 @@ class SecurityDescriptorSpec extends ObjectBehavior $this->setGroup(new SID('PS'))->getGroup()->toString()->shouldBeEqualTo(SID::SHORT_NAME['PS']); $this->setGroup(SID::SHORT_NAME['BA'])->getGroup()->toString()->shouldBeEqualTo(SID::SHORT_NAME['BA']); } + + function it_should_not_require_the_owner_when_going_to_binary() + { + $this->beConstructedWith(); + $this->setGroup(SID::SHORT_NAME['PS']); + $this->setDacl((new Dacl())->addAce((new Ace(AceType::TYPE['ACCESS_ALLOWED']))->setTrustee(SID::SHORT_NAME['PS']))); + $this->setSacl((new Sacl())->addAce((new Ace(AceType::TYPE['SYSTEM_AUDIT']))->setTrustee(SID::SHORT_NAME['PS']))); + + $this->toBinary()->shouldBeEqualTo(hex2bin('010014800000000014000000200000003c00000001010000000000050a00000004001c0001000000020014000000000001010000000000050a00000004001c0001000000000014000000000001010000000000050a000000')); + } + + function it_should_not_require_the_group_when_going_to_binary() + { + $this->beConstructedWith(); + $this->setOwner(SID::SHORT_NAME['PS']); + $this->setDacl((new Dacl())->addAce((new Ace(AceType::TYPE['ACCESS_ALLOWED']))->setTrustee(SID::SHORT_NAME['PS']))); + $this->setSacl((new Sacl())->addAce((new Ace(AceType::TYPE['SYSTEM_AUDIT']))->setTrustee(SID::SHORT_NAME['PS']))); + + $this->toBinary()->shouldBeEqualTo(hex2bin('010014801400000000000000200000003c00000001010000000000050a00000004001c0001000000020014000000000001010000000000050a00000004001c0001000000000014000000000001010000000000050a000000')); + } + + function it_should_not_require_the_dacl_when_going_to_binary() + { + $this->beConstructedWith(); + $this->setOwner(SID::SHORT_NAME['PS']); + $this->setGroup(SID::SHORT_NAME['PS']); + $this->setSacl((new Sacl())->addAce((new Ace(AceType::TYPE['SYSTEM_AUDIT']))->setTrustee(SID::SHORT_NAME['PS']))); + + $this->toBinary()->shouldBeEqualTo(hex2bin('0100108014000000200000002c0000000000000001010000000000050a00000001010000000000050a00000004001c0001000000020014000000000001010000000000050a000000')); + } + + function it_should_not_require_the_sacl_when_going_to_binary() + { + $this->beConstructedWith(); + $this->setOwner(SID::SHORT_NAME['PS']); + $this->setGroup(SID::SHORT_NAME['PS']); + $this->setDacl((new Dacl())->addAce((new Ace(AceType::TYPE['ACCESS_ALLOWED']))->setTrustee(SID::SHORT_NAME['PS']))); + + $this->toBinary()->shouldBeEqualTo(hex2bin('010004801400000020000000000000002c00000001010000000000050a00000001010000000000050a00000004001c0001000000000014000000000001010000000000050a000000')); + } } diff --git a/src/LdapTools/Security/SecurityDescriptor.php b/src/LdapTools/Security/SecurityDescriptor.php index <HASH>..<HASH> 100644 --- a/src/LdapTools/Security/SecurityDescriptor.php +++ b/src/LdapTools/Security/SecurityDescriptor.php @@ -233,13 +233,6 @@ class SecurityDescriptor $dacl = $this->dacl ? $this->dacl->toBinary($canonicalize) : null; $sacl = $this->sacl ? $this->sacl->toBinary() : null; - if ($owner === null || $group === null) { - throw new LogicException('The owner and the group must be set in the Security Descriptor.'); - } - if ($sacl === null && $dacl === null) { - throw new LogicException('Either the SACL or DACL must be set on the Security Descriptor.'); - } - /** * According the the MS docs, the order of the elements is not important. And indeed, I have found no rhyme or * reason as to how the owner/group/sacl/dacl elements are ordered in the security descriptor. As long as they
Allow elements of the security descriptor to be optional going to binary.
ldaptools_ldaptools
train
5525524f4e0e50b475c2d7045f0528d896a58f1b
diff --git a/spec/ast/arithmetic_spec.rb b/spec/ast/arithmetic_spec.rb index <HASH>..<HASH> 100644 --- a/spec/ast/arithmetic_spec.rb +++ b/spec/ast/arithmetic_spec.rb @@ -15,6 +15,7 @@ describe Dentaku::AST::Arithmetic do expect(sub(one, two)).to eq(-1) expect(mul(one, two)).to eq(2) expect(div(one, two)).to eq(0.5) + expect(neg(one)).to eq(-1) end it 'performs an arithmetic operation with one numeric operand and one string operand' do @@ -34,6 +35,7 @@ describe Dentaku::AST::Arithmetic do expect(sub(x, y)).to eq(-1) expect(mul(x, y)).to eq(2) expect(div(x, y)).to eq(0.5) + expect(neg(x)).to eq(-1) end private @@ -53,4 +55,8 @@ describe Dentaku::AST::Arithmetic do def div(left, right) Dentaku::AST::Division.new(left, right).value(ctx) end + + def neg(node) + Dentaku::AST::Negation.new(node).value(ctx) + end end
Add negation tests to arithmetic spec
rubysolo_dentaku
train
a0267e74b90d19981359535c2b4cc66fdd181b1f
diff --git a/hca/upload/__init__.py b/hca/upload/__init__.py index <HASH>..<HASH> 100644 --- a/hca/upload/__init__.py +++ b/hca/upload/__init__.py @@ -25,14 +25,9 @@ def forget_area(uuid_or_alias): """ Remove an area from our cache of upload areas. """ - matching_areas = UploadArea.areas_matching_alias(alias=uuid_or_alias) - if len(matching_areas) == 0: - raise UploadException("Sorry I don't recognize area \"%s\"" % (uuid_or_alias,)) - elif len(matching_areas) == 1: - matching_areas[0].forget() - return matching_areas[0] - else: - raise UploadException("\"%s\" matches more than one area, please provide more characters." % (uuid_or_alias,)) + area = UploadArea.from_alias(uuid_or_alias) + area.forget() + return area def list_current_area(detail=False): diff --git a/hca/upload/cli/select_command.py b/hca/upload/cli/select_command.py index <HASH>..<HASH> 100644 --- a/hca/upload/cli/select_command.py +++ b/hca/upload/cli/select_command.py @@ -1,4 +1,4 @@ -from ..upload_area import UploadArea +from ..upload_area import UploadArea, UploadException from .common import UploadCLICommand @@ -30,11 +30,8 @@ class SelectCommand(UploadCLICommand): print("In future you may refer to this upload area using the alias \"%s\"" % area.unique_prefix) def _select_area_by_alias(self, alias): - matching_areas = UploadArea.areas_matching_alias(alias) - if len(matching_areas) == 0: - print("Sorry I don't recognize area \"%s\"" % (alias,)) - elif len(matching_areas) == 1: - matching_areas[0].select() - print("Upload area %s selected." % matching_areas[0].uuid) - else: - print("\"%s\" matches more than one area, please provide more characters." % (alias,)) + try: + area = UploadArea.from_alias(alias) + area.select() + except UploadException as e: + print(str(e)) diff --git a/hca/upload/upload_area.py b/hca/upload/upload_area.py index <HASH>..<HASH> 100644 --- a/hca/upload/upload_area.py +++ b/hca/upload/upload_area.py @@ -41,6 +41,17 @@ class UploadArea: return [cls(uuid=uuid) for uuid in UploadConfig().areas.keys()] @classmethod + def from_alias(cls, uuid_or_alias): + matching_areas = UploadArea.areas_matching_alias(alias=uuid_or_alias) + if len(matching_areas) == 0: + raise UploadException("Sorry I don't recognize area \"%s\"" % (uuid_or_alias,)) + elif len(matching_areas) == 1: + return matching_areas[0] + else: + raise UploadException( + "\"%s\" matches more than one area, please provide more characters." % (uuid_or_alias,)) + + @classmethod def areas_matching_alias(cls, alias): return [cls(uuid=uuid) for uuid in UploadConfig().areas if re.match(alias, uuid)]
upload: consolidate "area matching alias" logic into UploadArea.from_alias()
HumanCellAtlas_dcp-cli
train
8409c5c102f4eac9bd2d7ba0353cc1087f5cdad6
diff --git a/state/watcher.go b/state/watcher.go index <HASH>..<HASH> 100644 --- a/state/watcher.go +++ b/state/watcher.go @@ -624,6 +624,127 @@ func (w *ServiceRelationsWatcher) loop() (err error) { return nil } +// ServiceRelationsWatcher2 notifies about the lifecycle changes of the +// relations the service is in. The first event returned by the watcher is +// the set of ids of all relations that the service is part of, irrespective +// of their life state. Subsequent events return batches of newly added +// relations and relations which have changed their lifecycle. After a +// relation is found to be Dead, no further event will include it. +type ServiceRelationsWatcher2 struct { + commonWatcher + service *Service + out chan []int + known map[string]relationDoc +} + +// WatchRelations2 returns a new ServiceRelationsWatcher2 for s. +func (s *Service) WatchRelations2() *ServiceRelationsWatcher2 { + return newServiceRelationsWatcher2(s) +} + +func newServiceRelationsWatcher2(s *Service) *ServiceRelationsWatcher2 { + w := &ServiceRelationsWatcher2{ + commonWatcher: commonWatcher{st: s.st}, + out: make(chan []int), + known: make(map[string]relationDoc), + service: &Service{s.st, s.doc}, // Copy so it may be freely refreshed + } + go func() { + defer w.tomb.Done() + defer close(w.out) + w.tomb.Kill(w.loop()) + }() + return w +} + +func (w *ServiceRelationsWatcher2) Stop() error { + w.tomb.Kill(nil) + return w.tomb.Wait() +} + +// Changes returns the event channel for w. +func (w *ServiceRelationsWatcher2) Changes() <-chan []int { + return w.out +} + +func (w *ServiceRelationsWatcher2) initial() (new []int, err error) { + docs := []relationDoc{} + err = w.st.relations.Find(D{{"endpoints.servicename", w.service.doc.Name}}).Select(D{{"_id", 1}, {"id", 1}, {"life", 1}}).All(&docs) + if err == mgo.ErrNotFound { + return nil, nil + } + if err != nil { + return nil, err + } + for _, doc := range docs { + w.known[doc.Key] = doc + new = append(new, doc.Id) + } + return new, nil +} + +func (w *ServiceRelationsWatcher2) merge(pending []int, key string) (new []int, err error) { + doc := relationDoc{} + err = w.st.relations.FindId(key).One(&doc) + if err != nil && err != mgo.ErrNotFound { + return nil, err + } + old, known := w.known[key] + if err == mgo.ErrNotFound { + if known && old.Life != Dead { + delete(w.known, key) + return append(pending, old.Id), nil + } + return pending, nil + } + if !known { + return append(pending, doc.Id), nil + } + if old.Life != doc.Life { + w.known[key] = doc + for _, v := range pending { + if v == doc.Id { + return pending, nil + } + } + pending = append(pending, doc.Id) + } + return pending, nil +} + +func (w *ServiceRelationsWatcher2) loop() (err error) { + ch := make(chan watcher.Change) + w.st.watcher.WatchCollection(w.st.relations.Name, ch) + defer w.st.watcher.UnwatchCollection(w.st.relations.Name, ch) + changes, err := w.initial() + if err != nil { + return err + } + prefix1 := w.service.doc.Name + ":" + prefix2 := " " + w.service.doc.Name + ":" + out := w.out + for { + select { + case <-w.st.watcher.Dead(): + return watcher.MustErr(w.st.watcher) + case <-w.tomb.Dying(): + return tomb.ErrDying + case c := <-ch: + key := c.Id.(string) + if !strings.HasPrefix(key, prefix1) && !strings.Contains(key, prefix2) { + continue + } + if len(changes) > 0 { + out = w.out + } + case out <- changes: + out = nil + changes = nil + } + } + return nil +} + // WatchPrincipalUnits returns a watcher for observing units being // added to or removed from the machine. func (m *Machine) WatchPrincipalUnits() *MachinePrincipalUnitsWatcher {
state: add new lifecycle aware service relations watcher
juju_juju
train
4f6bea5f9fa163fd5a0fae0555ee6a1be16b12e1
diff --git a/tests/Doctrine/Migrations/Tests/Tools/Console/Command/StatusCommandTest.php b/tests/Doctrine/Migrations/Tests/Tools/Console/Command/StatusCommandTest.php index <HASH>..<HASH> 100644 --- a/tests/Doctrine/Migrations/Tests/Tools/Console/Command/StatusCommandTest.php +++ b/tests/Doctrine/Migrations/Tests/Tools/Console/Command/StatusCommandTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Doctrine\Migrations\Tests\Tools\Console\Command; use DateTimeImmutable; +use Doctrine\DBAL\Version as DBALVersion; use Doctrine\Migrations\Configuration\Configuration; use Doctrine\Migrations\Configuration\Connection\ExistingConnection; use Doctrine\Migrations\Configuration\Migration\ExistingConfiguration; @@ -73,6 +74,12 @@ class StatusCommandTest extends MigrationTestCase $lines = array_map('trim', explode("\n", trim($this->commandTester->getDisplay(true)))); + if (DBALVersion::compare('2.11.0') > 0) { + $databaseDriver = 'Doctrine\DBAL\Driver\PDOSqlite\Driver '; // Trailing space bufferes outout assertion + } else { + $databaseDriver = 'Doctrine\DBAL\Driver\PDO\SQLite\Driver'; + } + self::assertSame( [ '+----------------------+----------------------+------------------------------------------------------------------------+', @@ -82,7 +89,7 @@ class StatusCommandTest extends MigrationTestCase '| | Table Name | doctrine_migration_versions |', '| | Column Name | version |', '|----------------------------------------------------------------------------------------------------------------------|', - '| Database | Driver | Doctrine\DBAL\Driver\PDOSqlite\Driver |', + '| Database | Driver | ' . $databaseDriver . ' |', '| | Name | |', '|----------------------------------------------------------------------------------------------------------------------|', '| Versions | Previous | 1230 |',
Allow for PDO namespaces pre and post dbal <I>
doctrine_migrations
train
9e82edcb732b2c488c119356b289e5004ecf51be
diff --git a/tests/test_validators.py b/tests/test_validators.py index <HASH>..<HASH> 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -2,6 +2,7 @@ import unittest from troposphere import Parameter, Ref from troposphere.validators import boolean, integer, integer_range from troposphere.validators import positive_integer, network_port +from troposphere.validators import s3_bucket_name class TestValidators(unittest.TestCase): @@ -57,5 +58,9 @@ class TestValidators(unittest.TestCase): p = Parameter('myport') network_port(Ref(p)) + def test_s3_bucket_name(self): + s3_bucket_name('wicked.sweet.bucket') + s3_bucket_name('!invalid_bucket') + if __name__ == '__main__': unittest.main() diff --git a/troposphere/s3.py b/troposphere/s3.py index <HASH>..<HASH> 100644 --- a/troposphere/s3.py +++ b/troposphere/s3.py @@ -134,7 +134,7 @@ class Bucket(AWSObject): props = { 'AccessControl': (basestring, False), - 'BucketName': (basestring, False), + 'BucketName': (s3_bucket_name, False), 'CorsConfiguration': (CorsConfiguration, False), 'LifecycleConfiguration': (LifecycleConfiguration, False), 'LoggingConfiguration': (LoggingConfiguration, False), diff --git a/troposphere/validators.py b/troposphere/validators.py index <HASH>..<HASH> 100644 --- a/troposphere/validators.py +++ b/troposphere/validators.py @@ -52,6 +52,15 @@ def network_port(x): return x +def s3_bucket_name(b): + from re import compile + s3_bucket_name_re = compile(r'^[a-zA-Z0-9][a-zA-Z0-9\._-]{1,253}[a-zA-Z0-9]$') + if s3_bucket_name_re.match(b): + return b + else: + raise ValueError("%s is not a valid s3 bucket name" % b) + + def encoding(encoding): valid_encodings = ['plain', 'base64'] if encoding not in valid_encodings:
Adding validator for s3 bucket names and unit test
cloudtools_troposphere
train
d512fb1faceae5455045d91fc56f27939ec8d7ae
diff --git a/lib/GameRoom.js b/lib/GameRoom.js index <HASH>..<HASH> 100644 --- a/lib/GameRoom.js +++ b/lib/GameRoom.js @@ -162,8 +162,12 @@ function GameRoom(config) { * instance of the room. Will override settings from the required file. * @param {boolean} startGame Whether to send 'start' request to clients. * Default: False. + * @param {string} treatmentName The name of the treatment with which to start + * the game. + * @param {object} settings Options corresponding to the chosen treatment. + * TODO: Remove parameter and get the options from ServerNode. */ -GameRoom.prototype.startGame = function(mixinConf, startClients) { +GameRoom.prototype.startGame = function(mixinConf, startClients, treatmentName, settings) { var game, channel, node, room; if (mixinConf && 'object' !== typeof mixinConf) { @@ -179,7 +183,7 @@ GameRoom.prototype.startGame = function(mixinConf, startClients) { // game = channel.require(this.logicPath, { node: node }); // Alternative 2 - game = require(this.logicPath)(node, channel, this); + game = require(this.logicPath)(node, channel, this, treatmentName, settings); // Alternative 3 // game = require(this.logicPath); @@ -207,4 +211,4 @@ GameRoom.prototype.startGame = function(mixinConf, startClients) { node.connect(null, startCb, { startingRoom: this.name }); -}; \ No newline at end of file +}; diff --git a/lib/ServerNode.js b/lib/ServerNode.js index <HASH>..<HASH> 100644 --- a/lib/ServerNode.js +++ b/lib/ServerNode.js @@ -83,8 +83,17 @@ function ServerNode(options) { */ this.info = { channels: {}, - games: {} + games: {} // TODO: To be replaced by ServerNode.games, maybe }; + + /** + * ## ServerNode.games + * + * Object containing global information about games and their treatments + * + * @see ServerNode.loadGames + */ + this.games = {}; /** * ## ServerNode.defaults @@ -448,6 +457,13 @@ ServerNode.prototype.addGame = function(game, gameDir) { this.logger.info('ServerNode: new game added. ' + game.name + ': ' + gamePath); + + // TODO + //this.games[game.name] = { + // name: game.name, + // descr: game.description, + // treatments: {} + //}; }; /** @@ -688,6 +704,8 @@ ServerNode.prototype.loadConfFile = function(file, cb) { * @return {object} The games info structure. See above for details. */ ServerNode.prototype.getGames = function() { + //return this.games; + // TODO: Dummy data for now return { gameA: {
Extra parameters for GameRoom.startGame to make treatments work for now Added ServerNode.games, not used yet.
nodeGame_nodegame-server
train
fd48363a878bc3786b5e0de372997f4f69142d85
diff --git a/src/main/java/com/github/jleyba/dossier/Linker.java b/src/main/java/com/github/jleyba/dossier/Linker.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/jleyba/dossier/Linker.java +++ b/src/main/java/com/github/jleyba/dossier/Linker.java @@ -184,7 +184,7 @@ public class Linker { instanceProperty = true; } - NominalType type = typeRegistry.getNominalType(typeName); + NominalType type = getType(typeName); // Link might be a qualified path to a property. if (type == null && propertyName.isEmpty()) { @@ -193,7 +193,7 @@ public class Linker { instanceProperty = false; propertyName = typeName.substring(index + 1); typeName = typeName.substring(0, index); - type = typeRegistry.getNominalType(typeName); + type = getType(typeName); } } @@ -205,8 +205,10 @@ public class Linker { String filePath = getFilePath(type).getFileName().toString(); if (!propertyName.isEmpty()) { - if (instanceProperty) { - if (type.getJsdoc().isConstructor() || type.getJsdoc().isInterface()) { + if (instanceProperty || type.isModuleExports()) { + if (type.isModuleExports() + || type.getJsdoc().isConstructor() + || type.getJsdoc().isInterface()) { filePath += "#" + propertyName; } } else { @@ -216,6 +218,15 @@ public class Linker { return filePath; } + @Nullable + private NominalType getType(String name) { + NominalType type = typeRegistry.getNominalType(name); + if (type == null) { + type = typeRegistry.getModule(name); + } + return type; + } + private static final String MDN_PREFIX = "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/"; diff --git a/src/main/java/com/github/jleyba/dossier/TypeRegistry.java b/src/main/java/com/github/jleyba/dossier/TypeRegistry.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/jleyba/dossier/TypeRegistry.java +++ b/src/main/java/com/github/jleyba/dossier/TypeRegistry.java @@ -154,6 +154,11 @@ public class TypeRegistry { return nominalTypes.get(name); } + @Nullable + public NominalType getModule(String name) { + return moduleExports.get(name); + } + public Collection<NominalType> getModules() { return Collections.unmodifiableCollection(moduleExports.values()); } diff --git a/src/test/java/com/github/jleyba/dossier/LinkerTest.java b/src/test/java/com/github/jleyba/dossier/LinkerTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/github/jleyba/dossier/LinkerTest.java +++ b/src/test/java/com/github/jleyba/dossier/LinkerTest.java @@ -204,6 +204,22 @@ public class LinkerTest { } @Test + public void testGetLink_module() { + Path module = fileSystem.getPath("/src/module/foo.js"); + + when(mockConfig.getModulePrefix()).thenReturn(fileSystem.getPath("/src/module")); + DossierCompiler compiler = new DossierCompiler(System.err, ImmutableList.of(module)); + CompilerOptions options = Main.createOptions(fileSystem, typeRegistry, compiler); + util = new CompilerUtil(compiler, options); + + util.compile(module, "exports = {foo: function() {}};"); + assertThat(typeRegistry.getModules()).isNotEmpty(); + + assertEquals("module_foo.html", linker.getLink("dossier$$module__$src$module$foo")); + assertEquals("module_foo.html#bar", linker.getLink("dossier$$module__$src$module$foo.bar")); + } + + @Test public void testGetSourcePath_nullNode() { assertEquals( Dossier.SourceLink.newBuilder()
Update linker to handle commonjs module references.
jleyba_js-dossier
train
8401673d76b68ce08c7af96acf27648f1aff6556
diff --git a/server/irc/connection.js b/server/irc/connection.js index <HASH>..<HASH> 100644 --- a/server/irc/connection.js +++ b/server/irc/connection.js @@ -40,6 +40,9 @@ var IrcConnection = function (hostname, port, ssl, nick, user, options, state, c // If the connection closes and this is false, we reconnect this.requested_disconnect = false; + // Number of times we have tried to reconnect + this.reconnect_attempts = 0; + // IRCd write buffers (flood controll) this.write_buffer = []; @@ -308,12 +311,24 @@ IrcConnection.prototype.connect = function () { delete global.clients.port_pairs[that.identd_port_pair]; } - should_reconnect = (!that.requested_disconnect && was_connected && had_registered); + // If trying to reconnect, continue with it + if (that.reconnect_attempts && that.reconnect_attempts < 3) { + should_reconnect = true; + + // If this was an unplanned disconnect and we were originally connected OK, reconnect + } else if (!that.requested_disconnect && was_connected && had_registered) { + should_reconnect = true; + + } else { + should_reconnect = false; + } if (should_reconnect) { + that.reconnect_attempts++; that.emit('reconnecting'); } else { that.emit('close', had_error); + that.reconnect_attempts = 0; } // Close the whole socket down @@ -324,7 +339,7 @@ IrcConnection.prototype.connect = function () { if (should_reconnect) { setTimeout(function() { that.connect(); - }, 3000); + }, 4000); } }); });
Better IRC server reconnection logic
prawnsalad_KiwiIRC
train
2f7eb0dfce78138da6fb4dcfe385324ca022d010
diff --git a/Arr.php b/Arr.php index <HASH>..<HASH> 100755 --- a/Arr.php +++ b/Arr.php @@ -172,25 +172,15 @@ class Arr */ public static function flatten($array, $depth = INF) { - $result = []; - - foreach ($array as $item) { + return array_reduce($array, function ($result, $item) use ($depth) { $item = $item instanceof Collection ? $item->all() : $item; - if (is_array($item)) { - if ($depth === 1) { - $result = array_merge($result, $item); - continue; - } - - $result = array_merge($result, static::flatten($item, $depth - 1)); - continue; + if ($depth === 1 || ! is_array($item)) { + return array_merge($result, array_values((array) $item)); } - $result[] = $item; - } - - return $result; + return array_merge($result, static::flatten($item, $depth - 1)); + }, []); } /**
[<I>] Fix: flatten should always ignore keys (#<I>) * Failing test for flatten(1) which works for flatten() * Refactor flatten method * Never save keys in Arr::flatten * Cleanup test
illuminate_support
train
177327fe33d5de6d0397f76b646b39443ec8b472
diff --git a/parsl/executors/high_throughput/interchange.py b/parsl/executors/high_throughput/interchange.py index <HASH>..<HASH> 100644 --- a/parsl/executors/high_throughput/interchange.py +++ b/parsl/executors/high_throughput/interchange.py @@ -390,7 +390,6 @@ class Interchange(object): self._command_thread.start() poller = zmq.Poller() - # poller.register(self.task_incoming, zmq.POLLIN) poller.register(self.task_outgoing, zmq.POLLIN) poller.register(self.results_incoming, zmq.POLLIN)
Remove a commented out line of dead code in htex (#<I>) Poller registration for task_incoming happens in migrate_tasks_to_internal
Parsl_parsl
train
dbb86fdce17afffcf3681c57ec38335ca1ddbf91
diff --git a/docroot/modules/custom/openy_digital_signage/openy_digital_signage_classes_schedule/src/Entity/OpenYClassesSession.php b/docroot/modules/custom/openy_digital_signage/openy_digital_signage_classes_schedule/src/Entity/OpenYClassesSession.php index <HASH>..<HASH> 100644 --- a/docroot/modules/custom/openy_digital_signage/openy_digital_signage_classes_schedule/src/Entity/OpenYClassesSession.php +++ b/docroot/modules/custom/openy_digital_signage/openy_digital_signage_classes_schedule/src/Entity/OpenYClassesSession.php @@ -5,6 +5,7 @@ namespace Drupal\openy_digital_signage_classes_schedule\Entity; use Drupal\Core\Field\BaseFieldDefinition; use Drupal\Core\Entity\ContentEntityBase; use Drupal\Core\Entity\EntityTypeInterface; +use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem; /** * Defines Digital Signage Classes Session entity. @@ -167,9 +168,10 @@ class OpenYClassesSession extends ContentEntityBase implements OpenYClassesSessi 'weight' => 1, ]) ->setDisplayOptions('form', [ - 'type' => 'datetime_default', + 'type' => 'datetime', 'weight' => 1, ]) + ->setSetting('datetime_type', DateTimeItem::DATETIME_TYPE_DATE) ->setDisplayConfigurable('view', TRUE) ->setDisplayConfigurable('form', TRUE);
[YGB-<I>] Change type of the field
ymcatwincities_openy
train
4f46c040de0cf3f110129e9ecca2fd0284a30119
diff --git a/flubber/timeout.py b/flubber/timeout.py index <HASH>..<HASH> 100644 --- a/flubber/timeout.py +++ b/flubber/timeout.py @@ -32,7 +32,7 @@ class Timeout(BaseException): assert not self._timer, '%r is already started; to restart it, cancel it first' % self loop = flubber.current.loop current = flubber.current.task - if self.seconds is None: + if self.seconds is None or self.seconds < 0: # "fake" timeout (never expires) self._timer = None elif self.exception is None or isinstance(self.exception, bool): diff --git a/tests/test_timeout.py b/tests/test_timeout.py index <HASH>..<HASH> 100644 --- a/tests/test_timeout.py +++ b/tests/test_timeout.py @@ -29,6 +29,15 @@ class TimeoutTests(FlubberTestCase): flubber.spawn(func) self.loop.run() + def test_with_negative_timeout(self): + def sleep(): + with Timeout(-1): + flubber.sleep(0.01) + def func(): + sleep() + flubber.spawn(func) + self.loop.run() + def test_timeout_custom_exception(self): def sleep(): with Timeout(0.01, FooTimeout):
If seconds is negative, make Timeout objects infinite
saghul_evergreen
train
f40fb67cfac8c04905738e365f2e7b64a8ed1d18
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/uiUtils.js b/bundles/org.eclipse.orion.client.ui/web/orion/uiUtils.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.ui/web/orion/uiUtils.js +++ b/bundles/org.eclipse.orion.client.ui/web/orion/uiUtils.js @@ -181,7 +181,7 @@ define([ } if (isKeyEvent && event.keyCode === lib.KEY.ESCAPE) { if (hideRefNode) { - refNode.style.display = "inline"; //$NON-NLS-0$ + refNode.style.display = ""; } done = true; editBox.parentNode.removeChild(editBox); @@ -194,13 +194,13 @@ define([ return; } else if (newValue.length === 0 || (!isInitialValid && newValue === initialText)) { if (hideRefNode) { - refNode.style.display = "inline"; //$NON-NLS-0$ + refNode.style.display = ""; } done = true; } else { onComplete(newValue); if (hideRefNode && refNode.parentNode) { - refNode.style.display = "inline"; //$NON-NLS-0$ + refNode.style.display = ""; } done = true; }
Bug <I> - cancelling file rename leaves the file name mis-positioned in the navigator
eclipse_orion.client
train
0dc5878d4e6e5165c5d1c4be34e1ada060105604
diff --git a/examples/route-any/index.php b/examples/route-any/index.php index <HASH>..<HASH> 100644 --- a/examples/route-any/index.php +++ b/examples/route-any/index.php @@ -1,9 +1,11 @@ -<?php declare (strict_types = 1); +<?php -require_once __DIR__ . '/../../vendor/autoload.php'; +declare(strict_types=1); + +require_once __DIR__.'/../../vendor/autoload.php'; -use Siler\Route; use Siler\Http\Request; +use Siler\Route; Route\any('/any-route', function () { if (Request\method_is('get')) { diff --git a/src/Route/Route.php b/src/Route/Route.php index <HASH>..<HASH> 100644 --- a/src/Route/Route.php +++ b/src/Route/Route.php @@ -1,6 +1,6 @@ <?php -declare (strict_types = 1); +declare(strict_types=1); /** * Siler routing facilities. @@ -157,21 +157,21 @@ function regexify(string $path) : string */ function resource(string $basePath, string $resourcesPath, string $identityParam = null, $request = null) { - $basePath = '/' . trim($basePath, '/'); + $basePath = '/'.trim($basePath, '/'); $resourcesPath = rtrim($resourcesPath, '/'); if (is_null($identityParam)) { $identityParam = 'id'; } - get($basePath, $resourcesPath . '/index.php', $request); - get($basePath . '/create', $resourcesPath . '/create.php', $request); - get($basePath . '/{' . $identityParam . '}/edit', $resourcesPath . '/edit.php', $request); - get($basePath . '/{' . $identityParam . '}', $resourcesPath . '/show.php', $request); + get($basePath, $resourcesPath.'/index.php', $request); + get($basePath.'/create', $resourcesPath.'/create.php', $request); + get($basePath.'/{'.$identityParam.'}/edit', $resourcesPath.'/edit.php', $request); + get($basePath.'/{'.$identityParam.'}', $resourcesPath.'/show.php', $request); - post($basePath, $resourcesPath . '/store.php', $request); - put($basePath . '/{' . $identityParam . '}', $resourcesPath . '/update.php', $request); - delete($basePath . '/{' . $identityParam . '}', $resourcesPath . '/destroy.php', $request); + post($basePath, $resourcesPath.'/store.php', $request); + put($basePath.'/{'.$identityParam.'}', $resourcesPath.'/update.php', $request); + delete($basePath.'/{'.$identityParam.'}', $resourcesPath.'/destroy.php', $request); } /** @@ -190,11 +190,11 @@ function routify(string $filename) : array $tokens = array_slice(explode('.', $filename), 0, -1); $tokens = array_map(function ($token) { if ($token[0] == '$') { - $token = '{' . substr($token, 1) . '}'; + $token = '{'.substr($token, 1).'}'; } if ($token[0] == '@') { - $token = '?{' . substr($token, 1) . '}?'; + $token = '?{'.substr($token, 1).'}?'; } return $token; @@ -202,7 +202,7 @@ function routify(string $filename) : array $method = array_pop($tokens); $path = implode('/', $tokens); - $path = '/' . trim(str_replace('index', '', $path), '/'); + $path = '/'.trim(str_replace('index', '', $path), '/'); return [$method, $path]; } @@ -239,7 +239,7 @@ function files(string $basePath, string $routePrefix = '', $request = null) $path = $routePrefix; } } else { - $path = $routePrefix . $path; + $path = $routePrefix.$path; } route($method, $path, $filename, $request); diff --git a/tests/Unit/Route/RouteFacadeTest.php b/tests/Unit/Route/RouteFacadeTest.php index <HASH>..<HASH> 100644 --- a/tests/Unit/Route/RouteFacadeTest.php +++ b/tests/Unit/Route/RouteFacadeTest.php @@ -1,6 +1,6 @@ <?php -declare (strict_types = 1); +declare(strict_types=1); namespace Siler\Test\Unit;
Apply fixes from StyleCI (#<I>)
leocavalcante_siler
train
caf034cb48bef5c17cc91c564d715bc935d97e19
diff --git a/src/bbn/appui/imessages.php b/src/bbn/appui/imessages.php index <HASH>..<HASH> 100644 --- a/src/bbn/appui/imessages.php +++ b/src/bbn/appui/imessages.php @@ -172,8 +172,7 @@ class imessages extends \bbn\models\cls\db SELECT {$cfg['table']}.* FROM {$cfg['tables']['users']} RIGHT JOIN {$cfg['table']} - ON {$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_user']} - AND {$cfg['table']}.{$cfg['arch']['imessages']['id']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_imessage']} + ON {$cfg['table']}.{$cfg['arch']['imessages']['id']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_imessage']} WHERE ( {$cfg['table']}.{$cfg['arch']['imessages']['start']} IS NULL OR {$cfg['table']}.{$cfg['arch']['imessages']['start']} <= ?
Fix in DB query for iMessages
nabab_bbn
train
101c529581873fc137384af67876b7c13bb9ad66
diff --git a/src/main/java/no/digipost/signature/client/core/internal/ClientHelper.java b/src/main/java/no/digipost/signature/client/core/internal/ClientHelper.java index <HASH>..<HASH> 100644 --- a/src/main/java/no/digipost/signature/client/core/internal/ClientHelper.java +++ b/src/main/java/no/digipost/signature/client/core/internal/ClientHelper.java @@ -283,9 +283,13 @@ public class ClientHelper { Optional<String> responseContentType = optional(response.getHeaderString(HttpHeaders.CONTENT_TYPE)); if (responseContentType.isSome() && MediaType.valueOf(responseContentType.get()).equals(APPLICATION_XML_TYPE)) { try { + response.bufferEntity(); error = response.readEntity(XMLError.class); } catch (Exception e) { - throw new UnexpectedResponseException(null, e, Status.fromStatusCode(response.getStatus()), OK); + throw new UnexpectedResponseException( + HttpHeaders.CONTENT_TYPE + " " + responseContentType.orElse("unknown") + ": " + + optional(nonblank, response.readEntity(String.class)).orElse("<no content in response>"), + e, Status.fromStatusCode(response.getStatus()), OK); } } else { throw new UnexpectedResponseException(
Even more enhancement in error handling Prints out the unexpected response when failing to unmarshall XMLError.
digipost_signature-api-client-java
train
bc98de3a0fc225a8f24cf55d1f603d45310b9db0
diff --git a/src/chart/pie/labelLayout.js b/src/chart/pie/labelLayout.js index <HASH>..<HASH> 100644 --- a/src/chart/pie/labelLayout.js +++ b/src/chart/pie/labelLayout.js @@ -221,8 +221,16 @@ export default function (seriesModel, r, viewWidth, viewHeight, sum) { } var font = labelModel.getFont(); - var labelRotate = labelModel.get('rotate') - ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0; + var labelRotate; + var rotate = labelModel.get('rotate'); + if (typeof rotate === 'number') { + labelRotate = rotate * (Math.PI / 180); + } + else { + labelRotate = rotate + ? (dx < 0 ? -midAngle + Math.PI : -midAngle) + : 0; + } var text = seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx); var textRect = textContain.getBoundingRect(
feat(pie): support label rotate to pie chart (#<I>)
apache_incubator-echarts
train
6e11e0ea71ee02add45c945e215b8fe7a001b47c
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,7 @@ Any old unfinished experiment key will be deleted from the user's data storage i By default Split will avoid users participating in multiple experiments at once. This means you are less likely to skew results by adding in more variation to your tests. -To stop this behaviour and allow users to participate in multiple experiments at once enable the `allow_multiple_experiments` config option like so: +To stop this behaviour and allow users to participate in multiple experiments at once set the `allow_multiple_experiments` config option to true like so: ```ruby Split.configure do |config| @@ -179,6 +179,17 @@ Split.configure do |config| end ``` +This will allow the user to participate in any number of experiments and belong to any alternative in each experiment. This has the possible downside of a variation in one experiment influencing the outcome of another. + +To address this, setting the `allow_multiple_experiments` config option to 'control' like so: +```ruby +Split.configure do |config| + config.allow_multiple_experiments = 'control' +end +``` + +For this to work, each and every experiment you define must have an alternative named 'control'. This will allow the user to participate in multiple experiments as long as the user belongs to the alternative 'control' in each experiment. As soon as the user belongs to an alternative named something other than 'control' the user may not participate in any more experiments. Calling ab_test(<other experiments>) will always return the first alternative without adding the user to that experiment. + ### Experiment Persistence Split comes with three built-in persistence adapters for storing users and the alternatives they've been given for each experiment. diff --git a/lib/split/user.rb b/lib/split/user.rb index <HASH>..<HASH> 100644 --- a/lib/split/user.rb +++ b/lib/split/user.rb @@ -19,8 +19,14 @@ module Split end def max_experiments_reached?(experiment_key) - !Split.configuration.allow_multiple_experiments && - keys_without_experiment(user.keys, experiment_key).length > 0 + if Split.configuration.allow_multiple_experiments == 'control' + experiments = active_experiments + count_control = experiments.values.count {|v| v == 'control'} + experiments.size > count_control + else + !Split.configuration.allow_multiple_experiments && + keys_without_experiment(user.keys, experiment_key).length > 0 + end end def cleanup_old_versions!(experiment) diff --git a/spec/helper_spec.rb b/spec/helper_spec.rb index <HASH>..<HASH> 100755 --- a/spec/helper_spec.rb +++ b/spec/helper_spec.rb @@ -191,6 +191,26 @@ describe Split::Helper do expect(button_size_alt.participant_count).to eq(1) end + it "should let a user participate in many experiment with one non-'control' alternative with allow_multiple_experiments = 'control'" do + Split.configure do |config| + config.allow_multiple_experiments = 'control' + end + groups = [] + (0..100).each do |n| + alt = ab_test("test#{n}".to_sym, {'control' => (100 - n)}, {'test#{n}-alt' => n}) + groups << alt + end + + experiments = ab_user.active_experiments + expect(experiments.size).to be > 1 + + count_control = experiments.values.count { |g| g == 'control' } + expect(count_control).to eq(experiments.size - 1) + + count_alts = groups.count { |g| g != 'control' } + expect(count_alts).to eq(1) + end + it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => 'blue', experiment.finished_key => true }
Issue #<I> Running concurrent experiments on same endpoint/view (#<I>) * Issue #<I> use config.allow_multiple_experiments = 'control' for multiple experiments per user with at most 1-non-control * Update README.md
splitrb_split
train
c81f7b18cc3bf54be811243f07e43ac09ef7c68c
diff --git a/lib/heroku/helpers/pg_diagnose.rb b/lib/heroku/helpers/pg_diagnose.rb index <HASH>..<HASH> 100644 --- a/lib/heroku/helpers/pg_diagnose.rb +++ b/lib/heroku/helpers/pg_diagnose.rb @@ -63,7 +63,7 @@ module Heroku::Helpers::PgDiagnose def warn_old_databases(attachment) @uri = URI.parse(attachment.url) # for #nine_two? if !nine_two? - warn "WARNING: pg:diagnose is only fully suppoted on Postgres version >= 9.2. Some checks will be skipped.\n\n" + warn "WARNING: pg:diagnose is only fully supported on Postgres version >= 9.2. Some checks will be skipped.\n\n" end end
Correct typo Changed "WARNING: pg:diagnose is only fully **suppoted** on Postgres version >= <I>." to "WARNING: pg:diagnose is only fully **supported** on Postgres version >= <I>. "
heroku_legacy-cli
train
69d4de3b9849c8f6f50d90535d3cd4faccc53ff0
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -24,7 +24,7 @@ wheel = ["wheel"] if needs_wheel else [] with open("README.rst", "r") as f: long_description = f.read() -test_requires = ["pytest>=2.8", "ufoNormalizer>=0.3.2"] +test_requires = ["pytest>=2.8", "ufoNormalizer>=0.3.2", "xmldiff>=2.2"] if sys.version_info < (3, 3): test_requires.append("mock>=2.0.0") diff --git a/tests/builder/designspace_gen_test.py b/tests/builder/designspace_gen_test.py index <HASH>..<HASH> 100644 --- a/tests/builder/designspace_gen_test.py +++ b/tests/builder/designspace_gen_test.py @@ -16,6 +16,7 @@ from __future__ import print_function, division, absolute_import, unicode_literals import os +from xmldiff import main, formatting import pytest import defcon @@ -54,16 +55,15 @@ def test_designspace_generation_regular_same_family_name(tmpdir): path = os.path.join(str(tmpdir), "actual.designspace") designspace.write(path) - with open(path) as fp: - actual = fp.read() expected_path = os.path.join( os.path.dirname(__file__), "..", "data", "DesignspaceGenTestRegular.designspace" ) - with open(expected_path) as fp: - expected = fp.read() - assert expected == actual + assert ( + len(main.diff_files(path, expected_path, formatter=formatting.DiffFormatter())) + == 0 + ) def test_designspace_generation_italic_same_family_name(tmpdir): @@ -102,16 +102,15 @@ def test_designspace_generation_italic_same_family_name(tmpdir): path = os.path.join(str(tmpdir), "actual.designspace") designspace.write(path) - with open(path) as fp: - actual = fp.read() expected_path = os.path.join( os.path.dirname(__file__), "..", "data", "DesignspaceGenTestItalic.designspace" ) - with open(expected_path) as fp: - expected = fp.read() - assert expected == actual + assert ( + len(main.diff_files(path, expected_path, formatter=formatting.DiffFormatter())) + == 0 + ) def test_designspace_generation_regular_different_family_names(tmpdir): diff --git a/tests/builder/interpolation_test.py b/tests/builder/interpolation_test.py index <HASH>..<HASH> 100644 --- a/tests/builder/interpolation_test.py +++ b/tests/builder/interpolation_test.py @@ -15,16 +15,15 @@ # limitations under the License. from __future__ import print_function, division, absolute_import, unicode_literals -import difflib import os.path import shutil import sys import tempfile import unittest import xml.etree.ElementTree as etree +from xmldiff import main, formatting import defcon -from fontTools.misc.py23 import open from glyphsLib.builder.constants import GLYPHS_PREFIX from glyphsLib.builder.instances import set_weight_class, set_width_class from glyphsLib.classes import GSFont, GSFontMaster, GSInstance @@ -157,16 +156,14 @@ class DesignspaceTest(unittest.TestCase): def _expect_designspace(self, doc, expected_path): actual_path = self.write_to_tmp_path(doc, "generated.designspace") - with open(actual_path, mode="r", encoding="utf-8") as f: - actual = f.readlines() - with open(expected_path, mode="r", encoding="utf-8") as f: - expected = f.readlines() - if actual != expected: + actual_diff = main.diff_files( + actual_path, expected_path, formatter=formatting.DiffFormatter() + ) + if len(actual_diff) != 0: expected_name = os.path.basename(expected_path) - for line in difflib.unified_diff( - expected, actual, fromfile=expected_name, tofile="<generated>" - ): - sys.stderr.write(line) + sys.stderr.write("%s discrepancies (per xmldiff):\n" % (expected_name)) + for line in actual_diff.split("\n"): + sys.stderr.write(" %s" % (line)) self.fail("*.designspace file is different from expected") def expect_designspace_roundtrip(self, doc): diff --git a/tox.ini b/tox.ini index <HASH>..<HASH> 100644 --- a/tox.ini +++ b/tox.ini @@ -6,6 +6,7 @@ deps = pytest coverage ufonormalizer + xmldiff py27: mock>=2.0.0 -rrequirements.txt commands =
Switch XML tests from flat comparison to xmldiff
googlefonts_glyphsLib
train
ac98f564a38ad61fe93a18dd802332af7383c2da
diff --git a/rtv/content.py b/rtv/content.py index <HASH>..<HASH> 100644 --- a/rtv/content.py +++ b/rtv/content.py @@ -72,16 +72,12 @@ class BaseContent(object): data['body'] = comment.body data['created'] = humanize_timestamp(comment.created_utc) data['score'] = '{} pts'.format(comment.score) - data['author'] = ( - comment.author.name if getattr( - comment, - 'author') else '[deleted]') - data['is_author'] = ( - data['author'] == getattr( - comment.submission, - 'author')) - data['flair'] = ( - comment.author_flair_text if comment.author_flair_text else '') + author = getattr(comment, 'author') + data['author'] = (author.name if author else '[deleted]') + sub_author = getattr(comment.submission, 'author') + data['is_author'] = (data['author'] == sub_author) + flair = comment.author_flair_text + data['flair'] = (flair if flair else '') data['likes'] = comment.likes return data @@ -103,10 +99,8 @@ class BaseContent(object): data['created'] = humanize_timestamp(sub.created_utc) data['comments'] = '{} comments'.format(sub.num_comments) data['score'] = '{} pts'.format(sub.score) - data['author'] = ( - sub.author.name if getattr( - sub, - 'author') else '[deleted]') + author = getattr(sub, 'author') + data['author'] = (author.name if author else '[deleted]') data['permalink'] = sub.permalink data['subreddit'] = strip_subreddit_url(sub.permalink) data['flair'] = (sub.link_flair_text if sub.link_flair_text else '') @@ -169,13 +163,10 @@ class SubmissionContent(BaseContent): elif index == -1: data = self._submission_data - data['split_title'] = textwrap.wrap( - data['title'], - width=n_cols - - 2) + data['split_title'] = textwrap.wrap(data['title'], + width=n_cols -2) data['split_text'] = wrap_text(data['text'], width=n_cols - 2) - data['n_rows'] = len( - data['split_title']) + len(data['split_text']) + 5 + data['n_rows'] = len(data['split_title']) + len(data['split_text']) + 5 data['offset'] = 0 else: diff --git a/rtv/exceptions.py b/rtv/exceptions.py index <HASH>..<HASH> 100644 --- a/rtv/exceptions.py +++ b/rtv/exceptions.py @@ -1,27 +1,23 @@ class SubmissionError(Exception): - - "Submission could not be loaded" + """Submission could not be loaded""" def __init__(self, url): self.url = url class SubredditError(Exception): - - "Subreddit could not be reached" + """Subreddit could not be reached""" def __init__(self, name): self.name = name class ProgramError(Exception): - - "Problem executing an external program" + """Problem executing an external program""" def __init__(self, name): self.name = name class EscapeInterrupt(Exception): - - "Signal that the ESC key has been pressed" + """Signal that the ESC key has been pressed""" diff --git a/rtv/subreddit.py b/rtv/subreddit.py index <HASH>..<HASH> 100644 --- a/rtv/subreddit.py +++ b/rtv/subreddit.py @@ -59,13 +59,8 @@ class SubredditPage(BasePage): n_rows, n_cols = self.stdscr.getmaxyx() self.stdscr.addstr(n_rows - 1, 0, prompt, attr) self.stdscr.refresh() - window = self.stdscr.derwin( - 1, - n_cols - - len(prompt), - n_rows - - 1, - len(prompt)) + window = self.stdscr.derwin(1, n_cols - len(prompt), + n_rows - 1, len(prompt)) window.attrset(attr) out = text_input(window)
fixed some janky things that autopep8 did
michael-lazar_rtv
train
9e533f9cec0d3e7f49d8ff92d62ad5efe53a1a72
diff --git a/ui/js/jquery.pods.upgrade.js b/ui/js/jquery.pods.upgrade.js index <HASH>..<HASH> 100644 --- a/ui/js/jquery.pods.upgrade.js +++ b/ui/js/jquery.pods.upgrade.js @@ -19,9 +19,13 @@ 'method' : $( '#pods-wizard-box' ).data( 'method' ), '_wpnonce' : $( '#pods-wizard-box' ).data( '_wpnonce' ), 'step' : 'prepare', - 'type' : $row.data( 'upgrade' ) + 'type' : $row.data( 'upgrade' ), + 'pod' : '' }; + if ( 'undefined' != typeof $row.data( 'pod' ) ) + postdata[ 'pod' ] = $row.data( 'pod' ); + $.ajax( { type : 'POST', url : pods_ajaxurl, @@ -32,6 +36,11 @@ $row.find( 'td.pods-wizard-count' ).text( d ); $row.removeClass( 'pods-wizard-table-active' ).addClass( 'pods-wizard-table-complete' ); + if ( 'undefined' == typeof $row.data( 'pod' ) ) + $( '#pods-wizard-panel-3 table tbody tr[data-upgrade="' + $row.data( 'upgrade' ) + '"] td.pods-wizard-count' ).text( d ); + else + $( '#pods-wizard-panel-3 table tbody tr[data-pod="' + $row.data( 'pod' ) + '"] td.pods-wizard-count' ).text( d ); + // Run next return methods[ 'prepare' ](); } @@ -74,9 +83,13 @@ 'method' : $( '#pods-wizard-box' ).data( 'method' ), '_wpnonce' : $( '#pods-wizard-box' ).data( '_wpnonce' ), 'step' : 'migrate', - 'type' : $row.data( 'upgrade' ) + 'type' : $row.data( 'upgrade' ), + 'pod' : '' }; + if ( 'undefined' != typeof $row.data( 'pod' ) ) + postdata[ 'pod' ] = $row.data( 'pod' ); + $.ajax( { type : 'POST', url : pods_ajaxurl, @@ -84,11 +97,10 @@ data : postdata, success : function ( d ) { if ( -1 == d.indexOf( '<e>' ) && -1 != d ) { - $row.find( 'td.pods-wizard-count' ).text( d ); $row.removeClass( 'pods-wizard-table-active' ).addClass( 'pods-wizard-table-complete' ); // Run next - return methods[ 'prepare' ](); + return methods[ 'migrate' ](); } else { $row.removeClass( 'pods-wizard-table-active' ).addClass( 'pods-wizard-table-error' ); @@ -96,7 +108,7 @@ console.log( d.replace( '<e>', '' ).replace( '</e>', '' ) ); // Run next - return methods[ 'prepare' ](); + return methods[ 'migrate' ](); } }, error : function () { @@ -107,7 +119,7 @@ } ); } else { - jQuery( '#pods-wizard-next' ).show(); + jQuery( '#pods-wizard-next' ).click(); } } };
Updated handling to sync counts to migrate screen
pods-framework_pods
train
05f14519497292477f5f274e0df103bb14ca304f
diff --git a/lib/zeus/client.rb b/lib/zeus/client.rb index <HASH>..<HASH> 100644 --- a/lib/zeus/client.rb +++ b/lib/zeus/client.rb @@ -49,6 +49,9 @@ module Zeus slave.close pid = socket.readline.chomp.to_i + rescue Errno::ENOENT, Errno::ECONNREFUSED + Zeus.ui.error "Zeus doesn't seem to be running, try 'zeus start`" + abort end def make_winch_channel
catch if zeus is not already running, but we expect it to be, and present a helpful message.
burke_zeus
train
4011cdeb9029586a0e91d3d1966a930a5087930f
diff --git a/src/Spatie/Activitylog/ActivitylogSupervisor.php b/src/Spatie/Activitylog/ActivitylogSupervisor.php index <HASH>..<HASH> 100644 --- a/src/Spatie/Activitylog/ActivitylogSupervisor.php +++ b/src/Spatie/Activitylog/ActivitylogSupervisor.php @@ -3,7 +3,7 @@ namespace Spatie\Activitylog; use Illuminate\Config\Repository; -use Illuminate\Auth\Guard; +use Illuminate\Contracts\Auth\Guard; use Spatie\Activitylog\Handlers\BeforeHandler; use Spatie\Activitylog\Handlers\DefaultLaravelHandler; use Request;
Guard not exist problem fixed for Laravel <I>
spatie_activitylog
train
6fa11a89cb297383756499f0e44bc1a678b87902
diff --git a/holoviews/core/element.py b/holoviews/core/element.py index <HASH>..<HASH> 100644 --- a/holoviews/core/element.py +++ b/holoviews/core/element.py @@ -11,7 +11,7 @@ from .overlay import Overlayable, NdOverlay, CompositeOverlay from .spaces import HoloMap, GridSpace from .tree import AttrTree from .util import (dimension_sort, get_param_values, dimension_sanitizer, - unique_array) + unique_array, wrap_tuple) class Element(ViewableElement, Composable, Overlayable): @@ -166,10 +166,7 @@ class Element(ViewableElement, Composable, Overlayable): for dim in vdims]) else: values = [()]*length - - data = zip(keys, values) - overrides = dict(kdims=kdims, vdims=vdims, **kwargs) - return NdElement(data, **dict(get_param_values(self), **overrides)) + return OrderedDict(zip(keys, values)) def array(self, dimensions=[]): @@ -530,7 +527,6 @@ class Collator(NdMapping): group = param.String(default='Collator') - progress_bar = param.Parameter(default=None, doc=""" The progress bar instance used to report progress. Set to None to disable progress bars.""") @@ -556,6 +552,27 @@ class Collator(NdMapping): NdLayout: (GridSpace, HoloMap, ViewableElement), NdOverlay: Element} + def __init__(self, data=None, **params): + if isinstance(data, list) and all(np.isscalar(el) for el in data): + data = (((k,), (v,)) for k, v in enumerate(data)) + + if isinstance(data, Element): + params = dict(get_param_values(data), **params) + mapping = data if isinstance(data, Collator) else data.mapping() + data = mapping.data + if 'kdims' not in params: + params['kdims'] = mapping.kdims + if 'vdims' not in params: + params['vdims'] = mapping.vdims + + kdims = params.get('kdims', self.kdims) + if (data is not None and not isinstance(data, NdMapping) and 'Index' not in kdims): + params['kdims'] = ['Index'] + list(kdims) + data_items = data.items() if isinstance(data, dict) else data + data = [((i,)+wrap_tuple(k), v) for i, (k, v) in enumerate(data_items)] + super(Collator, self).__init__(data, **params) + + def __call__(self): """ Filter each Layout in the Collator with the supplied
Made Collator constructor independent of NdElement
pyviz_holoviews
train
b271a2adb8a9c9e07f8e8d5c6b4240a093cff67b
diff --git a/lib/chef/provider/git.rb b/lib/chef/provider/git.rb index <HASH>..<HASH> 100644 --- a/lib/chef/provider/git.rb +++ b/lib/chef/provider/git.rb @@ -246,25 +246,34 @@ class Chef refs = ref_lines.map { |line| line.split("\t") } # first try for ^{} indicating the commit pointed to by an # annotated tag - tagged_commit = refs.find { |m| m[1].end_with?("#{@new_resource.revision}^{}") } + tagged_commit = refs.find_all { |m| m[1].end_with?("#{@new_resource.revision}^{}") } # It is possible for a user to create a tag named 'HEAD'. # Using such a degenerate annotated tag would be very # confusing. We avoid the issue by disallowing the use of # annotated tags named 'HEAD'. - if tagged_commit && rev_pattern != 'HEAD' - tagged_commit[0] + if !tagged_commit.empty? && rev_pattern != 'HEAD' + found = tagged_commit else - found = refs.find { |m| m[1].end_with?(@new_resource.revision) } - if found - found[0] - else - nil - end + found = refs.find_all { |m| m[1].end_with?(@new_resource.revision) } end + pick_shortest_ref(found) end private + def pick_shortest_ref(refs=[]) + if refs.empty? + nil + else + # refs is an Array of two-element Arrays: [SHA, TAG_NAME]: e.g,, + # [['faceb423432...', 'refs/tags/2014.9.3'], ...] + # Return the SHA of the shortest tag, since :find_all :end_with? + # was used to build the list of refs. + ref = refs.sort { |a, b| a[1].length <=> b[1].length }.first + ref[0] + end + end + def run_options(run_opts={}) env = {} if @new_resource.user
Find all refs with desired suffix; choose shortest one
chef_chef
train
a3b4332999ce7e750191a1c8b38b290a9fe2ae32
diff --git a/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php b/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php index <HASH>..<HASH> 100644 --- a/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php +++ b/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php @@ -97,10 +97,6 @@ class EventBridgeEndpointMiddlewareTest extends TestCase if (!$isCrtAvailable && !empty($endpointId)) { $this->markTestSkipped(); } - $isMvpRegion = getenv('AIRGAPPED_REGION') == 'LCK'; - if ($isMvpRegion) { - $this->markTestSkipped(); - } $clientConfig = [ 'region' => $clientRegion, diff --git a/tests/S3/BucketEndpointArnMiddlewareTest.php b/tests/S3/BucketEndpointArnMiddlewareTest.php index <HASH>..<HASH> 100644 --- a/tests/S3/BucketEndpointArnMiddlewareTest.php +++ b/tests/S3/BucketEndpointArnMiddlewareTest.php @@ -40,10 +40,6 @@ class BucketEndpointArnMiddlewareTest extends TestCase $signingRegion, $signingService ) { - $isMvpRegion = getenv('AIRGAPPED_REGION') == 'LCK'; - if ($isMvpRegion) { - $this->markTestSkipped(); - } $s3 = $this->getTestClient('s3', $options); $this->addMockResults($s3, [[]]); $command = $s3->getCommand( diff --git a/tests/S3/S3EndpointMiddlewareTest.php b/tests/S3/S3EndpointMiddlewareTest.php index <HASH>..<HASH> 100644 --- a/tests/S3/S3EndpointMiddlewareTest.php +++ b/tests/S3/S3EndpointMiddlewareTest.php @@ -549,10 +549,6 @@ class S3EndpointMiddlewareTest extends TestCase $endpointUrl, $expectedEndpoint) { - $isMvpRegion = getenv('AIRGAPPED_REGION') == 'LCK'; - if ($isMvpRegion) { - $this->markTestSkipped(); - } //additional flags is not used yet, will be in the future if dualstack support is added $clientConfig = [ 'region' => $clientRegion,
unskip LCK tests (#<I>)
aws_aws-sdk-php
train
2b8f35303d2855c79f9f3f9b3584338a1ff7edbd
diff --git a/net.go b/net.go index <HASH>..<HASH> 100644 --- a/net.go +++ b/net.go @@ -4,7 +4,7 @@ import ( "fmt" "net" - utp "github.com/jbenet/go-multiaddr-net/Godeps/_workspace/src/github.com/h2so5/utp" + // utp "github.com/jbenet/go-multiaddr-net/Godeps/_workspace/src/github.com/h2so5/utp" ma "github.com/jbenet/go-multiaddr-net/Godeps/_workspace/src/github.com/jbenet/go-multiaddr" ) @@ -112,16 +112,18 @@ func (d *Dialer) Dial(remote ma.Multiaddr) (Conn, error) { return nil, err } case "utp": - // construct utp dialer, with options on our net.Dialer - utpd := utp.Dialer{ - Timeout: d.Dialer.Timeout, - LocalAddr: d.Dialer.LocalAddr, - } - - nconn, err = utpd.Dial(rnet, rnaddr) - if err != nil { - return nil, err - } + return nil, fmt.Errorf("utp is currently broken") + + // // construct utp dialer, with options on our net.Dialer + // utpd := utp.Dialer{ + // Timeout: d.Dialer.Timeout, + // LocalAddr: d.Dialer.LocalAddr, + // } + // + // nconn, err = utpd.Dial(rnet, rnaddr) + // if err != nil { + // return nil, err + // } } // get local address (pre-specified or assigned within net.Conn) @@ -225,7 +227,8 @@ func Listen(laddr ma.Multiaddr) (Listener, error) { var nl net.Listener switch lnet { case "utp": - nl, err = utp.Listen(lnet, lnaddr) + // nl, err = utp.Listen(lnet, lnaddr) + return nil, fmt.Errorf("utp is currently broken") default: nl, err = net.Listen(lnet, lnaddr) } diff --git a/net_test.go b/net_test.go index <HASH>..<HASH> 100644 --- a/net_test.go +++ b/net_test.go @@ -165,7 +165,7 @@ func TestListenAddrs(t *testing.T) { test("/ip4/127.0.0.1/tcp/4324", true) test("/ip4/127.0.0.1/udp/4325", false) test("/ip4/127.0.0.1/udp/4326/udt", false) - test("/ip4/127.0.0.1/udp/4326/utp", true) + // test("/ip4/127.0.0.1/udp/4326/utp", true) } func TestListenAndDial(t *testing.T) { @@ -230,6 +230,7 @@ func TestListenAndDial(t *testing.T) { } func TestListenAndDialUTP(t *testing.T) { + t.Skip("utp is broken") maddr := newMultiaddr(t, "/ip4/127.0.0.1/udp/4323/utp") listener, err := Listen(maddr)
disable utp for now (broken)
multiformats_go-multiaddr
train
60377aa24dd62cc8c9fedae6b55ba68592aa21e2
diff --git a/lib/mail/utilities.rb b/lib/mail/utilities.rb index <HASH>..<HASH> 100644 --- a/lib/mail/utilities.rb +++ b/lib/mail/utilities.rb @@ -233,11 +233,11 @@ module Mail # Using String#encode is better performing than Regexp def self.to_lf(input) - input.kind_of?(String) ? input.to_str.encode(:universal_newline => true) : '' + input.kind_of?(String) ? input.to_str.encode(input.encoding, :universal_newline => true) : '' end def self.to_crlf(input) - input.kind_of?(String) ? input.to_str.encode(:universal_newline => true).encode!(:crlf_newline => true) : '' + input.kind_of?(String) ? input.to_str.encode(input.encoding, :universal_newline => true).encode!(input.encoding, :crlf_newline => true) : '' end else diff --git a/spec/mail/utilities_spec.rb b/spec/mail/utilities_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mail/utilities_spec.rb +++ b/spec/mail/utilities_spec.rb @@ -452,6 +452,16 @@ describe "Utilities Module" do expect(Mail::Utilities.to_lf("\r \n\r\n")).to eq "\n \n\n" end + if defined?(Encoding) + it "should not change the encoding of the string" do + saved_default_internal = Encoding.default_internal + Encoding.default_internal = "UTF-8" + ascii_string = "abcd".force_encoding("ASCII-8BIT") + expect(Mail::Utilities.to_lf(ascii_string).encoding).to eq(Encoding::ASCII_8BIT) + Encoding.default_internal = saved_default_internal + end + end + describe "to_lf method on String" do it "should leave lf as lf" do expect(Mail::Utilities.to_lf("\n")).to eq "\n" @@ -507,6 +517,16 @@ describe "Utilities Module" do expect(Mail::Utilities.to_crlf(string)).to eq "\343\201\202\343\201\210\343\201\206\343\201\210\343\201\212\r\n\r\n\343\201\213\343\201\215\343\201\217\343\201\221\343\201\223\r\n\r\n\343\201\225\343\201\227\343\201\244\343\201\233\343\201\235\r\n\r\n" end + if defined?(Encoding) + it "should not change the encoding of the string" do + saved_default_internal = Encoding.default_internal + Encoding.default_internal = "UTF-8" + ascii_string = "abcd".force_encoding("ASCII-8BIT") + expect(Mail::Utilities.to_crlf(ascii_string).encoding).to eq(Encoding::ASCII_8BIT) + Encoding.default_internal = saved_default_internal + end + end + end describe "methods on NilClass" do
Fix issue introduced by #<I>
mikel_mail
train
6506e0ed575d28e6f045eafb4ecb1c8fa88bc2e3
diff --git a/src/RingaEvent.js b/src/RingaEvent.js index <HASH>..<HASH> 100644 --- a/src/RingaEvent.js +++ b/src/RingaEvent.js @@ -218,22 +218,33 @@ class RingaEvent extends RingaObject { } if (__DEV__ || this.detail.debug) { - this.dispatchStack = ErrorStackParser.parse(new Error()); + + try { this.dispatchStack = ErrorStackParser.parse(new Error()); } + catch(err) { this.dispatchStack = []; } + this.dispatchStack.shift(); // Remove a reference to RingaEvent.dispatch() if (this.dispatchStack.length && this.dispatchStack[0].toString().search('Object.dispatch') !== -1) { this.dispatchStack.shift(); // Remove a reference to Object.dispatch() } + } else { this.dispatchStack = 'To turn on stack traces, build Ringa in development mode. See documentation.'; } if (isDOMNode(bus)) { - this.customEvent = new CustomEvent(this.type, { - detail: this.detail, - bubbles: this.bubbles, - cancelable: this.cancelable - }); + try { + this.customEvent = new CustomEvent(this.type, { + detail: this.detail, + bubbles: this.bubbles, + cancelable: this.cancelable + }); + } + catch(err) { + + this.customEvent = document.createEvent('CustomEvent'); + this.customEvent.initCustomEvent(this.type, this.bubbles, this.cancelable, this.detail); + } } this.dispatched = true;
Fixed 2 issues on IE<I>: one being that error-stack-parser fails to parse errors (might have been solved in newer releases?), the other being that CustomEvent() cannot be used as a constructor.
ringa-js_ringa
train
23970466144f696c14e9737b8b3d42da65116717
diff --git a/tool.py b/tool.py index <HASH>..<HASH> 100755 --- a/tool.py +++ b/tool.py @@ -766,6 +766,7 @@ class IANA(object): 'bloomberg': 'whois.nic.bloomberg', 'bm': 'whois.afilias-srs.net', 'book': 'whois.nic.book', + 'booking': 'whois.nic.booking', 'bz': 'whois.afilias-grs.net', 'buzz': 'whois.nic.buzz', 'cd': 'chois.nic.cd', @@ -1183,7 +1184,7 @@ if __name__ == '__main__': '-v', '--version', action='version', - version='%(prog)s 0.9.12-beta' + version='%(prog)s 0.9.13-beta' ) ARGS = PARSER.parse_args()
Introduction of `booking` whois server cf: Whois lookup to whois.nic.booking
funilrys_PyFunceble
train
cc5c839cde9116ba85209d17abc8567b568648a0
diff --git a/src/js/server.js b/src/js/server.js index <HASH>..<HASH> 100644 --- a/src/js/server.js +++ b/src/js/server.js @@ -161,11 +161,19 @@ Server.prototype.request = function (request) // Advance message ID this._id++; - if (this._remote.trace) { - utils.logObject("server: request: %s", request.message); + if (this._state === "online" || + (request.message.command === "subscribe" && this._ws.readyState === 1)) { + if (this._remote.trace) { + utils.logObject("server: request: %s", request.message); + } + + this._ws.send(JSON.stringify(request.message)); + } else { + // XXX There are many ways to make this smarter. + this.once('connect', function () { + this._ws.send(JSON.stringify(request.message)); + }); } - - this._ws.send(JSON.stringify(request.message)); } else { if (this._remote.trace) { utils.logObject("server: request: DROPPING: %s", request.message);
JS: Hold requests until connection is established. This will have to change when we add multiple server support, but it does the trick for now.
ChainSQL_chainsql-lib
train
6f50225b1e3aaf3498b8bcbbc4fd77874025163f
diff --git a/bundle/EzPublishCoreBundle.php b/bundle/EzPublishCoreBundle.php index <HASH>..<HASH> 100644 --- a/bundle/EzPublishCoreBundle.php +++ b/bundle/EzPublishCoreBundle.php @@ -20,6 +20,7 @@ use eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Compiler\AddFieldTypePass, eZ\Bundle\EzPublishCoreBundle\DependencyInjection\EzPublishCoreExtension, eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Configuration\Parser as ConfigParser, eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Security\Factory as EzPublishSecurityFactory, + eZ\Bundle\EzPublishCoreBundle\DependencyInjection\Security\HttpBasicFactory, Symfony\Component\HttpKernel\Bundle\Bundle, Symfony\Component\DependencyInjection\ContainerBuilder; @@ -39,6 +40,7 @@ class EzPublishCoreBundle extends Bundle $securityExtension = $container->getExtension( 'security' ); $securityExtension->addSecurityListenerFactory( new EzPublishSecurityFactory ); + $securityExtension->addSecurityListenerFactory( new HttpBasicFactory ); } public function getContainerExtension()
Implemented EZP-<I>: Implement basic auth for REST
ezsystems_ezplatform-xmltext-fieldtype
train
2beb7b1a3e9b4e9f7a64625433023fee4dd0e98a
diff --git a/gui/controls/notebook.py b/gui/controls/notebook.py index <HASH>..<HASH> 100644 --- a/gui/controls/notebook.py +++ b/gui/controls/notebook.py @@ -83,7 +83,15 @@ class TabPanel(Component): selected = Spec(_get_selection, _set_selection, type='boolean') - + def destroy(self): + # remove the page to the notebook + self._parent.wx_obj.RemovePage(self.index) + # reindex (maybe this should be moved to Notebook) + for page in self._parent.pages[self.index+1:]: + print "reindexing", page.name + page.index = page.index - 1 + Component.destroy(self) + # update metadata for the add context menu at the designer:
Notebook: added support to remove page (destroy)
reingart_gui2py
train
cdc6728fc23a2ada075171dd75e3688646853b9a
diff --git a/xgraphics/image.go b/xgraphics/image.go index <HASH>..<HASH> 100644 --- a/xgraphics/image.go +++ b/xgraphics/image.go @@ -106,6 +106,7 @@ func New(X *xgbutil.XUtil, r image.Rectangle) *Image { func (im *Image) Destroy() { if im.Pixmap != 0 { xproto.FreePixmap(im.X.Conn(), im.Pixmap) + im.Pixmap = 0 } }
Make sure to reset Pixmap to 0 when it's destroyed so that we know when to create it again.
BurntSushi_xgbutil
train
73aa12585721ca504229fafa4a8d8add0d5d2647
diff --git a/src/Support/Helpers.php b/src/Support/Helpers.php index <HASH>..<HASH> 100644 --- a/src/Support/Helpers.php +++ b/src/Support/Helpers.php @@ -698,7 +698,7 @@ if ( ! function_exists("dot")) */ function dot( $key ) { - return Strings::splite($key , '.'); + return explode('.' , $key); } }
edit dot helper to not use strings surface
vinala_kernel
train
bf30e07b1e7fd7cc43b132a7ca0595e005592261
diff --git a/isochrones/config.py b/isochrones/config.py index <HASH>..<HASH> 100644 --- a/isochrones/config.py +++ b/isochrones/config.py @@ -3,3 +3,6 @@ import os ISOCHRONES = os.getenv('ISOCHRONES', os.path.expanduser(os.path.join('~','.isochrones'))) +if not os.path.exists(ISOCHRONES): + os.makedirs(ISOCHRONES) + \ No newline at end of file
making ISOCHRONES if does not exist
timothydmorton_isochrones
train
f0f2fed167bda47136252edd05f73735be0ac1b7
diff --git a/pysd/py_backend/functions.py b/pysd/py_backend/functions.py index <HASH>..<HASH> 100644 --- a/pysd/py_backend/functions.py +++ b/pysd/py_backend/functions.py @@ -18,7 +18,11 @@ import imp import warnings import random import xarray as xr -from inspect import signature + +try: + from inspect import signature +except ImportError: + from sklearn.externals.funcsigs import signature try: import scipy.stats as stats
Fix issue with import the `signature`.
JamesPHoughton_pysd
train
3dc2a81d7242e1ae40c2c25beaf93e87a1ea70dd
diff --git a/pyrogram/client/types/user_and_chats/chat.py b/pyrogram/client/types/user_and_chats/chat.py index <HASH>..<HASH> 100644 --- a/pyrogram/client/types/user_and_chats/chat.py +++ b/pyrogram/client/types/user_and_chats/chat.py @@ -231,6 +231,7 @@ class Chat(Object): if isinstance(full_chat, types.ChatFull): parsed_chat = Chat._parse_chat_chat(client, chat) + parsed_chat.description = full_chat.about or None if isinstance(full_chat.participants, types.ChatParticipants): parsed_chat.members_count = len(full_chat.participants.participants)
Add Chat.description for basic chats
pyrogram_pyrogram
train
eb9325792c07770adced2c79e8aa18c2910d7fbe
diff --git a/system/HTTP/Message.php b/system/HTTP/Message.php index <HASH>..<HASH> 100644 --- a/system/HTTP/Message.php +++ b/system/HTTP/Message.php @@ -377,4 +377,15 @@ class Message return $this; } + + /** + * Determines if this is a json message based on the Content-Type header + * + * @return boolean + */ + public function isJson() + { + return $this->hasHeader('Content-Type') + && $this->getHeader('Content-Type')->getValue() === 'application/json'; + } } diff --git a/system/Validation/Validation.php b/system/Validation/Validation.php index <HASH>..<HASH> 100644 --- a/system/Validation/Validation.php +++ b/system/Validation/Validation.php @@ -364,7 +364,7 @@ class Validation implements ValidationInterface */ public function withRequest(RequestInterface $request): ValidationInterface { - if ($request->hasHeader('Content-Type') && $request->getHeader('Content-Type')->getValue() === 'application/json') + if ($request->isJson()) { $this->data = $request->getJSON(true); return $this; diff --git a/tests/system/HTTP/MessageTest.php b/tests/system/HTTP/MessageTest.php index <HASH>..<HASH> 100644 --- a/tests/system/HTTP/MessageTest.php +++ b/tests/system/HTTP/MessageTest.php @@ -332,4 +332,21 @@ class MessageTest extends \CodeIgniter\Test\CIUnitTestCase $_SERVER = $original; // restore so code coverage doesn't break } + public function testIsJsonReturnsFalseWithNoHeader() + { + $this->assertFalse($this->message->isJson()); + } + + public function testIsJsonReturnsFalseWithWrongContentType() + { + $this->message->setHeader('Content-Type', 'application/xml'); + $this->assertFalse($this->message->isJson()); + } + + public function testIsJsonReturnsTrue() + { + $this->message->setHeader('Content-Type', 'application/json'); + $this->assertTrue($this->message->isJson()); + } + }
Created the Message::isJson method to be able to determine if an HTTP Message is a JSON message.
codeigniter4_CodeIgniter4
train
23f2bf5cd83e0884bbffbab62dbc453c4c3c398f
diff --git a/src/Refinery29.php b/src/Refinery29.php index <HASH>..<HASH> 100644 --- a/src/Refinery29.php +++ b/src/Refinery29.php @@ -47,9 +47,13 @@ class Refinery29 extends Config { $rules = [ '@PSR2' => true, - 'align_double_arrow' => false, - 'align_equals' => false, - 'binary_operator_spaces' => true, + 'array_syntax' => [ + 'syntax' => 'short', + ], + 'binary_operator_spaces' => [ + 'align_double_arrow' => false, + 'align_equals' => false, + ], 'blank_line_after_opening_tag' => true, 'blank_line_before_return' => true, 'cast_spaces' => true, @@ -87,7 +91,7 @@ class Refinery29 extends Config 'no_short_bool_cast' => true, 'no_short_echo_tag' => true, 'no_singleline_whitespace_before_semicolons' => true, - 'no_spaces_inside_offset' => true, + 'no_spaces_around_offset' => true, 'no_trailing_comma_in_list_call' => true, 'no_trailing_comma_in_singleline_array' => true, 'no_unneeded_control_parentheses' => true, @@ -96,7 +100,7 @@ class Refinery29 extends Config 'no_useless_else' => false, 'no_useless_return' => true, 'no_whitespace_before_comma_in_array' => true, - 'no_whitespace_in_blank_lines' => true, + 'no_whitespace_in_blank_line' => true, 'not_operator_with_space' => false, 'not_operator_with_successor_space' => false, 'object_operator_without_whitespace' => true, @@ -128,7 +132,6 @@ class Refinery29 extends Config 'psr0' => false, 'random_api_migration' => false, 'self_accessor' => false, - 'short_array_syntax' => true, 'short_scalar_cast' => true, 'simplified_null_return' => true, 'single_blank_line_before_namespace' => true, @@ -140,8 +143,6 @@ class Refinery29 extends Config 'ternary_operator_spaces' => true, 'trailing_comma_in_multiline_array' => true, 'trim_array_spaces' => true, - 'unalign_double_arrow' => true, - 'unalign_equals' => true, 'unary_operator_spaces' => true, 'whitespace_after_comma_in_array' => true, ]; diff --git a/test/Refinery29Test.php b/test/Refinery29Test.php index <HASH>..<HASH> 100644 --- a/test/Refinery29Test.php +++ b/test/Refinery29Test.php @@ -92,9 +92,13 @@ class Refinery29Test extends \PHPUnit_Framework_TestCase { return [ '@PSR2' => true, - 'align_double_arrow' => false, // conflicts with unalign_double_arrow (which is enabled) - 'align_equals' => false, // conflicts with unalign_double (yet to be enabled) - 'binary_operator_spaces' => true, + 'array_syntax' => [ + 'syntax' => 'short', + ], + 'binary_operator_spaces' => [ + 'align_double_arrow' => false, + 'align_equals' => false, + ], 'blank_line_after_opening_tag' => true, 'blank_line_before_return' => true, 'cast_spaces' => true, @@ -132,7 +136,7 @@ class Refinery29Test extends \PHPUnit_Framework_TestCase 'no_short_bool_cast' => true, 'no_short_echo_tag' => true, 'no_singleline_whitespace_before_semicolons' => true, - 'no_spaces_inside_offset' => true, + 'no_spaces_around_offset' => true, 'no_trailing_comma_in_list_call' => true, 'no_trailing_comma_in_singleline_array' => true, 'no_unneeded_control_parentheses' => true, @@ -141,7 +145,7 @@ class Refinery29Test extends \PHPUnit_Framework_TestCase 'no_useless_else' => false, // has issues with edge cases, see https://github.com/FriendsOfPHP/PHP-CS-Fixer/issues/1923 'no_useless_return' => true, 'no_whitespace_before_comma_in_array' => true, - 'no_whitespace_in_blank_lines' => true, + 'no_whitespace_in_blank_line' => true, 'not_operator_with_space' => false, // have decided not to use it 'not_operator_with_successor_space' => false, // have decided not to use it 'object_operator_without_whitespace' => true, @@ -173,7 +177,6 @@ class Refinery29Test extends \PHPUnit_Framework_TestCase 'psr0' => false, // using PSR-4 'random_api_migration' => false, // risky 'self_accessor' => false, // it causes an edge case error - 'short_array_syntax' => true, 'short_scalar_cast' => true, 'simplified_null_return' => true, 'single_blank_line_before_namespace' => true, @@ -185,8 +188,6 @@ class Refinery29Test extends \PHPUnit_Framework_TestCase 'ternary_operator_spaces' => true, 'trailing_comma_in_multiline_array' => true, 'trim_array_spaces' => true, - 'unalign_double_arrow' => true, - 'unalign_equals' => true, 'unary_operator_spaces' => true, 'whitespace_after_comma_in_array' => true, ];
Fix: Adjust for renamed fixers and configuration
refinery29_php-cs-fixer-config
train
042353c4c905c48defef5a46fe4b8c99cd8934d5
diff --git a/src/main/java/yahoofinance/histquotes2/CrumbManager.java b/src/main/java/yahoofinance/histquotes2/CrumbManager.java index <HASH>..<HASH> 100644 --- a/src/main/java/yahoofinance/histquotes2/CrumbManager.java +++ b/src/main/java/yahoofinance/histquotes2/CrumbManager.java @@ -34,18 +34,20 @@ public class CrumbManager { redirectableRequest.setReadTimeout(YahooFinance.CONNECTION_TIMEOUT); URLConnection connection = redirectableRequest.openConnection(); - List<String> cookies = connection.getHeaderFields().get("Set-Cookie"); - if(cookies != null && cookies.size() > 0) { - for(String cookieValue : cookies) { - if(cookieValue.matches("B=.*")) { - cookie = cookieValue.split(";")[0]; - YahooFinance.logger.log(Level.FINE, "Set cookie from http request: " + cookie); - return; + for(String headerKey : connection.getHeaderFields().keySet()) { + if("Set-Cookie".equalsIgnoreCase(headerKey)) { + for(String cookieField : connection.getHeaderFields().get(headerKey)) { + for(String cookieValue : cookieField.split(";")) { + if(cookieValue.matches("B=.*")) { + cookie = cookieValue; + YahooFinance.logger.log(Level.FINE, "Set cookie from http request: " + cookie); + return; + } + } } } - } else { - YahooFinance.logger.log(Level.WARNING, "Failed to set cookie from http request. Set-Cookie header not available. Historical quote requests will most likely fail."); } + YahooFinance.logger.log(Level.WARNING, "Failed to set cookie from http request. Historical quote requests will most likely fail."); } private static void setCrumb() throws IOException {
Set-Cookie header might have different capitalization than expected
sstrickx_yahoofinance-api
train
6934eeae4a801001406497bbe64bf3a6475562c4
diff --git a/modules/core/Mediamanager/bootstrap.php b/modules/core/Mediamanager/bootstrap.php index <HASH>..<HASH> 100644 --- a/modules/core/Mediamanager/bootstrap.php +++ b/modules/core/Mediamanager/bootstrap.php @@ -111,6 +111,34 @@ if(COCKPIT_ADMIN) { "title" => "Mediamanager", "active" => (strpos($app["route"], '/mediamanager') === 0) ], 0); + + + // handle global search request + $app->on("cockpit.globalsearch", function($search, $list) use($app){ + + $user = $app("session")->read("app.auth"); + + $bookmarks = $app->memory->get("mediamanager.bookmarks.".$user["_id"], ["folders"=>[], "files"=>[]]); + + foreach ($bookmarks["folders"] as $f) { + if(stripos($f["name"], $search)!==false){ + $list[] = [ + "title" => '<i class="uk-icon-folder-o"></i> '.$f["name"], + "url" => $app->routeUrl('/mediamanager#'.$f["path"]) + ]; + } + } + + foreach ($bookmarks["files"] as $f) { + if(stripos($f["name"], $search)!==false){ + $list[] = [ + "title" => '<i class="uk-icon-file-o"></i> '.$f["name"], + "url" => $app->routeUrl('/mediamanager#'.dirname($f["path"])) + ]; + } + } + }); + }); // acl
in-app search for media manager bookmarks
agentejo_cockpit
train
0dc133036bf0f08e90a2c199f52b3f9babe1daab
diff --git a/src/main/java/org/gaul/s3proxy/S3ProxyHandler.java b/src/main/java/org/gaul/s3proxy/S3ProxyHandler.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/gaul/s3proxy/S3ProxyHandler.java +++ b/src/main/java/org/gaul/s3proxy/S3ProxyHandler.java @@ -143,6 +143,7 @@ public class S3ProxyHandler { "location", "marker", "max-keys", + "part-number-marker", "partNumber", "prefix", "response-cache-control", @@ -1888,7 +1889,13 @@ public class S3ProxyHandler { private void handleListParts(HttpServletRequest request, HttpServletResponse response, BlobStore blobStore, String containerName, String blobName, String uploadId) - throws IOException { + throws IOException, S3Exception { + // support only the no-op zero case + String partNumberMarker = request.getParameter("part-number-marker"); + if (partNumberMarker != null && !partNumberMarker.equals("0")) { + throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED); + } + // TODO: how to reconstruct original mpu? MultipartUpload mpu = MultipartUpload.create(containerName, blobName, uploadId, createFakeBlobMetadata(blobStore), diff --git a/src/test/java/org/gaul/s3proxy/S3AwsSdkTest.java b/src/test/java/org/gaul/s3proxy/S3AwsSdkTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/gaul/s3proxy/S3AwsSdkTest.java +++ b/src/test/java/org/gaul/s3proxy/S3AwsSdkTest.java @@ -56,6 +56,7 @@ import com.amazonaws.services.s3.model.GroupGrantee; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.ListObjectsRequest; +import com.amazonaws.services.s3.model.ListPartsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.Permission; @@ -500,6 +501,24 @@ public final class S3AwsSdkTest { .isEqualTo(expiresTime); } + @Test + public void testPartNumberMarker() throws Exception { + String blobName = "foo"; + InitiateMultipartUploadResult result = client.initiateMultipartUpload( + new InitiateMultipartUploadRequest(containerName, blobName)); + ListPartsRequest request = new ListPartsRequest(containerName, + blobName, result.getUploadId()); + + client.listParts(request.withPartNumberMarker(0)); + + try { + client.listParts(request.withPartNumberMarker(1)); + Fail.failBecauseExceptionWasNotThrown(AmazonS3Exception.class); + } catch (AmazonS3Exception e) { + assertThat(e.getErrorCode()).isEqualTo("NotImplemented"); + } + } + private static final class NullX509TrustManager implements X509TrustManager { @Override
Ignore part-number-marker when zero S3Proxy does not support pagination but it can support this initial no-op value. Fixes #<I>.
gaul_s3proxy
train
55df7f6fc242af816a69b5b063a193cdc8185058
diff --git a/okhttp/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java b/okhttp/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java index <HASH>..<HASH> 100644 --- a/okhttp/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java +++ b/okhttp/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java @@ -550,6 +550,8 @@ public final class HostnameVerifierTest { assertThat(verifier.verify("2a03:2880:f003:c07:face:b00c:0:3", session)).isFalse(); assertThat(verifier.verify("127.0.0.1", session)).isFalse(); assertThat(verifier.verify("192.168.1.1", session)).isTrue(); + assertThat(verifier.verify("::ffff:192.168.1.1", session)).isTrue(); + assertThat(verifier.verify("0:0:0:0:0:FFFF:C0A8:0101", session)).isTrue(); } @Test public void verifyAsIpAddress() {
More extreme canonical forms in Hostname Verifier (#<I>)
square_okhttp
train
d877a66365304f1927cc05aec4bef4e516656b6e
diff --git a/src/components/ProjectSearch/index.js b/src/components/ProjectSearch/index.js index <HASH>..<HASH> 100644 --- a/src/components/ProjectSearch/index.js +++ b/src/components/ProjectSearch/index.js @@ -110,19 +110,6 @@ class ProjectSearch extends Component<Props> { return <div className="search-container">{this.renderTextSearch()}</div>; } } - -ProjectSearch.propTypes = { - sources: PropTypes.object.isRequired, - results: PropTypes.object, - textSearchQuery: PropTypes.string, - setActiveSearch: PropTypes.func.isRequired, - closeActiveSearch: PropTypes.func.isRequired, - closeProjectSearch: PropTypes.func.isRequired, - searchSources: PropTypes.func, - activeSearch: PropTypes.string, - selectLocation: PropTypes.func.isRequired -}; - ProjectSearch.contextTypes = { shortcuts: PropTypes.object };
Switch ProjectSearch PropTypes to Props (#<I>)
firefox-devtools_debugger
train
65b322bdebc4ffe30292aea1395670a2dafac275
diff --git a/sqliteschema/_extractor.py b/sqliteschema/_extractor.py index <HASH>..<HASH> 100644 --- a/sqliteschema/_extractor.py +++ b/sqliteschema/_extractor.py @@ -104,6 +104,22 @@ class SQLiteSchemaExtractor: return [table for table in table_names if table not in SQLITE_SYSTEM_TABLES] + @stash_row_factory + def fetch_view_names(self) -> List[str]: + """ + :return: List of view names in the database. + :rtype: list + """ + + self._con.row_factory = None + cur = self._con.cursor() + + result = cur.execute("SELECT name FROM sqlite_master WHERE TYPE='view'") + if result is None: + return [] + + return [record[0] for record in result.fetchall()] + def fetch_table_schema(self, table_name: str) -> SQLiteTableSchema: return SQLiteTableSchema( table_name, diff --git a/test/test_schema_extractor.py b/test/test_schema_extractor.py index <HASH>..<HASH> 100644 --- a/test/test_schema_extractor.py +++ b/test/test_schema_extractor.py @@ -39,6 +39,13 @@ class Test_SQLiteSchemaExtractor_fetch_table_names: assert extractor.fetch_table_names() == ["testdb0", "testdb1", "constraints"] +class Test_SQLiteSchemaExtractor_fetch_view_names: + def test_normal(self, database_path): + extractor = SQLiteSchemaExtractor(database_path) + + assert extractor.fetch_view_names() == ["view1"] + + class Test_SQLiteSchemaExtractor_fetch_sqlite_master: def test_normal(self, database_path): extractor = SQLiteSchemaExtractor(database_path)
Add fetch_view_names method to SQLiteSchemaExtractor class
thombashi_sqliteschema
train
ee460111370905b51f39c5c6566e647bb6d1d0bd
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -63,16 +63,15 @@ module ActiveRecord class TableDefinition # An array of ColumnDefinition objects, representing the column changes # that have been defined. - attr_accessor :indexes + attr_accessor :columns, :indexes def initialize(base) + @columns = [] @columns_hash = {} @indexes = {} @base = base end - def columns; @columns_hash.values; end - def xml(*args) raise NotImplementedError unless %w{ sqlite mysql mysql2 @@ -302,6 +301,7 @@ module ActiveRecord def new_column_definition(base, name, type) definition = create_column_definition base, name, type + @columns << definition @columns_hash[name] = definition definition end
Apparently people were mutating this array. :'( This reverts commit abba<I>e2bbe<I>ba<I>ebdf<I>a1d2af<I>b.
rails_rails
train
ac95d255145007667979ea24e020469efde1e07e
diff --git a/lib/cf/version.rb b/lib/cf/version.rb index <HASH>..<HASH> 100644 --- a/lib/cf/version.rb +++ b/lib/cf/version.rb @@ -1,3 +1,3 @@ module CF - VERSION = "4.0.0rc2".freeze + VERSION = "4.0.1.rc1".freeze end
Bump to <I>.rc1
cloudfoundry-attic_cf
train
5cec1aad152115502f8ba0d7fcc1c3e40b915d7a
diff --git a/core/chain_manager.go b/core/chain_manager.go index <HASH>..<HASH> 100644 --- a/core/chain_manager.go +++ b/core/chain_manager.go @@ -577,10 +577,10 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) { // Compare the TD of the last known block in the canonical chain to make sure it's greater. // At this point it's possible that a different chain (fork) becomes the new canonical chain. if block.Td.Cmp(self.td) > 0 { - // Check for chain forks. If H(block.num - 1) != block.parent, we're on a fork and need to do some merging - if previous := self.getBlockByNumber(block.NumberU64() - 1); previous.Hash() != block.ParentHash() { + // chain fork + if block.ParentHash() != cblock.Hash() { // during split we merge two different chains and create the new canonical chain - self.merge(previous, block) + self.merge(cblock, block) queue[i] = ChainSplitEvent{block, logs} queueEvent.splitCount++ @@ -641,9 +641,17 @@ func (self *ChainManager) diff(oldBlock, newBlock *types.Block) types.Blocks { oldStart = oldBlock newStart = newBlock ) - // first find common number - for newBlock = newBlock; newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = self.GetBlock(newBlock.ParentHash()) { - newChain = append(newChain, newBlock) + + // first reduce whoever is higher bound + if oldBlock.NumberU64() > newBlock.NumberU64() { + // reduce old chain + for oldBlock = oldBlock; oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = self.GetBlock(oldBlock.ParentHash()) { + } + } else { + // reduce new chain and append new chain blocks for inserting later on + for newBlock = newBlock; newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = self.GetBlock(newBlock.ParentHash()) { + newChain = append(newChain, newBlock) + } } numSplit := newBlock.Number() @@ -669,7 +677,7 @@ func (self *ChainManager) diff(oldBlock, newBlock *types.Block) types.Blocks { func (self *ChainManager) merge(oldBlock, newBlock *types.Block) { newChain := self.diff(oldBlock, newBlock) - // insert blocks + // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly for _, block := range newChain { self.insert(block) } diff --git a/miner/miner.go b/miner/miner.go index <HASH>..<HASH> 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -47,6 +47,7 @@ func (self *Miner) update() { atomic.StoreInt32(&self.canStart, 0) if self.Mining() { self.Stop() + atomic.StoreInt32(&self.shouldStart, 1) glog.V(logger.Info).Infoln("Mining operation aborted due to sync operation") } case downloader.DoneEvent, downloader.FailedEvent:
core, miner: fork resolving and restart miner after sync op Fork resolving fixes #<I>
ethereum_go-ethereum
train
c0f54aefe38bc16406a187b3d20b6ffddc70eb04
diff --git a/commands/hugo.go b/commands/hugo.go index <HASH>..<HASH> 100644 --- a/commands/hugo.go +++ b/commands/hugo.go @@ -136,7 +136,7 @@ func InitializeConfig() { viper.SetDefault("FootnoteAnchorPrefix", "") viper.SetDefault("FootnoteReturnLinkContents", "") viper.SetDefault("NewContentEditor", "") - viper.SetDefault("Blackfriday", map[string]bool{"angledQuotes": false, "documentIDAnchor": true}) + viper.SetDefault("Blackfriday", map[string]bool{"angledQuotes": false, "plainIdAnchors": false}) if hugoCmdV.PersistentFlags().Lookup("buildDrafts").Changed { viper.Set("BuildDrafts", Draft) diff --git a/docs/content/overview/configuration.md b/docs/content/overview/configuration.md index <HASH>..<HASH> 100644 --- a/docs/content/overview/configuration.md +++ b/docs/content/overview/configuration.md @@ -77,14 +77,14 @@ But Hugo does expose some options -- in the table below matched with the corresp Flag | Default | Blackfriday flag | Purpose --- | --- | --- | --- angledQuotes | false | HTML_SMARTYPANTS_ANGLED_QUOTES | Enable angled double quotes (`« »`) -documentIDAnchor | true | FootnoteAnchorPrefix and HeaderIDSuffix | Enable the prepending / appending of the unique document ID to the footnote and header anchor IDs +plainIdAnchors | false | FootnoteAnchorPrefix and HeaderIDSuffix | If true, then header and footnote IDs are generated without the document ID (so, `#my-header` instead of `#my-header:bec3ed8ba720b9073ab75abcf3ba5d97`) **Note** that these flags must be grouped under the `blackfriday` key and can be set on **both site and page level**. If set on page, it will override the site setting. ``` blackfriday: angledQuotes = true - documentIDAnchor = false + plainIdAnchors = true ``` ## Notes diff --git a/helpers/content.go b/helpers/content.go index <HASH>..<HASH> 100644 --- a/helpers/content.go +++ b/helpers/content.go @@ -85,7 +85,9 @@ func GetHtmlRenderer(defaultFlags int, ctx RenderingContext) blackfriday.Rendere FootnoteReturnLinkContents: viper.GetString("FootnoteReturnLinkContents"), } - if m, ok := ctx.ConfigFlags["documentIDAnchor"]; ok && m && len(ctx.DocumentId) != 0 { + b := len(ctx.DocumentId) != 0 + + if m, ok := ctx.ConfigFlags["plainIdAnchors"]; b && ((ok && !m) || !ok) { renderParameters.FootnoteAnchorPrefix = ctx.DocumentId + ":" + renderParameters.FootnoteAnchorPrefix renderParameters.HeaderIDSuffix = ":" + ctx.DocumentId }
Rename to plainIdAnchors
gohugoio_hugo
train
b6f40a9d157a787ba376dab30ddd74cda4888fc1
diff --git a/lib/adapters/cucumber_adapter.rb b/lib/adapters/cucumber_adapter.rb index <HASH>..<HASH> 100644 --- a/lib/adapters/cucumber_adapter.rb +++ b/lib/adapters/cucumber_adapter.rb @@ -3,11 +3,15 @@ class CucumberAdapter def self.command(ruby_interpreter, files) "export AUTOTEST=1; #{ruby_interpreter} script/cucumber -f progress --backtrace -r features/support -r features/step_definitions #{files} -t ~@disabled_in_cruise" end - - def self.file_pattern - '**/**/*.feature' + + def self.test_files(dir) + Dir["#{dir}/#{file_pattern}"] end + def self.find_sizes(files) + files.map { |file| File.stat(file).size } + end + def self.requester_port 2230 end @@ -27,5 +31,10 @@ class CucumberAdapter def self.type pluralized end - + +private + + def self.file_pattern + '**/**/*.feature' + end end diff --git a/lib/adapters/rspec_adapter.rb b/lib/adapters/rspec_adapter.rb index <HASH>..<HASH> 100644 --- a/lib/adapters/rspec_adapter.rb +++ b/lib/adapters/rspec_adapter.rb @@ -4,8 +4,12 @@ class RSpecAdapter "export RSPEC_COLOR=true; #{ruby_interpreter} script/spec -O spec/spec.opts #{files}" end - def self.file_pattern - '**/**/*_spec.rb' + def self.test_files(dir) + Dir["#{dir}/#{file_pattern}"] + end + + def self.find_sizes(files) + files.map { |file| File.stat(file).size } end def self.requester_port @@ -27,5 +31,11 @@ class RSpecAdapter def self.type 'spec' end - + +private + + def self.file_pattern + '**/**/*_spec.rb' + end + end diff --git a/lib/adapters/test_unit_adapter.rb b/lib/adapters/test_unit_adapter.rb index <HASH>..<HASH> 100644 --- a/lib/adapters/test_unit_adapter.rb +++ b/lib/adapters/test_unit_adapter.rb @@ -4,8 +4,12 @@ class TestUnitAdapter "#{ruby_interpreter} -Itest -e '%w(#{files}).each { |file| require(file) }'" end - def self.file_pattern - '**/**/*_test.rb' + def self.test_files(dir) + Dir["#{dir}/#{file_pattern}"] + end + + def self.find_sizes(files) + files.map { |file| File.stat(file).size } end def self.requester_port @@ -28,4 +32,10 @@ class TestUnitAdapter 'test' end +private + + def self.file_pattern + '**/**/*_test.rb' + end + end diff --git a/lib/requester.rb b/lib/requester.rb index <HASH>..<HASH> 100644 --- a/lib/requester.rb +++ b/lib/requester.rb @@ -42,7 +42,7 @@ class Requester system "rsync -az --delete -e ssh #{rsync_ignores} . #{rsync_uri}" files = find_tests(adapter, dir) - sizes = find_sizes(files) + sizes = find_sizes(adapter, files) build_id = HTTParty.post("#{server_uri}/builds", :body => { :root => root, :type => adapter.type.to_s, @@ -133,11 +133,11 @@ class Requester end def find_tests(adapter, dir) - Dir["#{dir}/#{adapter.file_pattern}"] + adapter.test_files(dir) end - def find_sizes(files) - files.map { |file| File.stat(file).size } + def find_sizes(adapter, files) + adapter.find_sizes(files) end def jruby?
Refactoring to allow more customization in the adapters.
joakimk_testbot
train
374a2689bf4bbf78cf99b9d6c2f9e1c1c469084c
diff --git a/core/typechecker/src/main/java/org/overture/typechecker/utilities/pattern/PossibleTypeFinder.java b/core/typechecker/src/main/java/org/overture/typechecker/utilities/pattern/PossibleTypeFinder.java index <HASH>..<HASH> 100644 --- a/core/typechecker/src/main/java/org/overture/typechecker/utilities/pattern/PossibleTypeFinder.java +++ b/core/typechecker/src/main/java/org/overture/typechecker/utilities/pattern/PossibleTypeFinder.java @@ -35,6 +35,7 @@ import org.overture.ast.patterns.AIdentifierPattern; import org.overture.ast.patterns.AIgnorePattern; import org.overture.ast.patterns.AIntegerPattern; import org.overture.ast.patterns.AMapPattern; +import org.overture.ast.patterns.AMapUnionPattern; import org.overture.ast.patterns.ANilPattern; import org.overture.ast.patterns.AObjectPattern; import org.overture.ast.patterns.AQuotePattern; @@ -205,6 +206,12 @@ public class PossibleTypeFinder extends AnswerAdaptor<PType> } @Override + public PType caseAMapUnionPattern(AMapUnionPattern pattern) throws AnalysisException + { + return AstFactory.newAMapMapType(pattern.getLocation(), AstFactory.newAUnknownType(pattern.getLocation()), AstFactory.newAUnknownType(pattern.getLocation())); + } + + @Override public PType caseAObjectPattern(AObjectPattern pattern) throws AnalysisException {
Map union pattern matching fails during type check, fixes #<I>
overturetool_overture
train
467867adaa91f8580490e4205100cd5ee9a088ad
diff --git a/lib/maltese/sitemap.rb b/lib/maltese/sitemap.rb index <HASH>..<HASH> 100644 --- a/lib/maltese/sitemap.rb +++ b/lib/maltese/sitemap.rb @@ -42,7 +42,7 @@ module Maltese @sitemap ||= SitemapGenerator::LinkSet.new( default_host: sitemap_url, sitemaps_host: sitemap_url, - #adapter: s3_adapter, + adapter: s3_adapter, sitemaps_path: sitemaps_path, finalize: false) end @@ -138,7 +138,7 @@ module Maltese def push_data(options={}) # sync time with AWS S3 before uploading - #fog_storage.sync_clock + fog_storage.sync_clock sitemap.finalize! options[:start_time] ||= Time.now
Undo accidental removal of s3 adapter
datacite_maltese
train
f349c2396439388bd34e4266ee6977fc73c91cb8
diff --git a/cmd/influxd/server_integration_test.go b/cmd/influxd/server_integration_test.go index <HASH>..<HASH> 100644 --- a/cmd/influxd/server_integration_test.go +++ b/cmd/influxd/server_integration_test.go @@ -1358,7 +1358,7 @@ func runTestsData(t *testing.T, testName string, nodes Cluster, database, retent urlDb = tt.queryDb } qry := rewriteDbRp(tt.query, database, retention) - got, ok := queryAndWait(t, qNodes, rewriteDbRp(urlDb, database, retention), qry, rewriteDbRp(tt.expected, database, retention), rewriteDbRp(tt.expectPattern, database, retention), 60*time.Second) + got, ok := queryAndWait(t, qNodes, rewriteDbRp(urlDb, database, retention), qry, rewriteDbRp(tt.expected, database, retention), rewriteDbRp(tt.expectPattern, database, retention), 10*time.Second) if !ok { if tt.expected != "" { t.Errorf("Test #%d: \"%s\" failed\n query: %s\n exp: %s\n got: %s\n", i, name, qry, rewriteDbRp(tt.expected, database, retention), got)
Should be no need to wait <I> seconds Each of these tests relies on a write of only a few points. It simply should not take <I> seconds.
influxdata_influxdb
train
86fa458013a143f74af143c9ba0bacebd65879c4
diff --git a/simulator/src/main/java/com/hazelcast/simulator/common/CountdownWatch.java b/simulator/src/main/java/com/hazelcast/simulator/common/CountdownWatch.java index <HASH>..<HASH> 100644 --- a/simulator/src/main/java/com/hazelcast/simulator/common/CountdownWatch.java +++ b/simulator/src/main/java/com/hazelcast/simulator/common/CountdownWatch.java @@ -5,13 +5,13 @@ public class CountdownWatch { private final long limit; - private CountdownWatch(long delay) { - if (delay < 0) { - throw new IllegalArgumentException("Delay cannot be negative, passed " + delay + "."); + private CountdownWatch(long delayMillis) { + if (delayMillis < 0) { + throw new IllegalArgumentException("Delay cannot be negative, passed " + delayMillis + "."); } long now = System.currentTimeMillis(); - long candidate = now + delay; + long candidate = now + delayMillis; // overflow protection limit = (candidate >= now ? candidate : Long.MAX_VALUE); } @@ -24,8 +24,8 @@ public class CountdownWatch { return System.currentTimeMillis() >= limit; } - public static CountdownWatch started(long delay) { - return new CountdownWatch(delay); + public static CountdownWatch started(long delayMillis) { + return new CountdownWatch(delayMillis); } public static CountdownWatch unboundedStarted() { diff --git a/simulator/src/test/java/com/hazelcast/simulator/common/CountdownWatchTest.java b/simulator/src/test/java/com/hazelcast/simulator/common/CountdownWatchTest.java index <HASH>..<HASH> 100644 --- a/simulator/src/test/java/com/hazelcast/simulator/common/CountdownWatchTest.java +++ b/simulator/src/test/java/com/hazelcast/simulator/common/CountdownWatchTest.java @@ -54,5 +54,4 @@ public class CountdownWatchTest { Thread.sleep(10); assertThat(watch.getRemainingMs(), is(0l)); } - }
Minor cleanup of CountdownWatch to make clear which time unit is used.
hazelcast_hazelcast-simulator
train
9be374b3dcd0af4657ccf66ffbde6daf145e8fcf
diff --git a/doc/ex/Adispatch.rb b/doc/ex/Adispatch.rb index <HASH>..<HASH> 100755 --- a/doc/ex/Adispatch.rb +++ b/doc/ex/Adispatch.rb @@ -5,8 +5,14 @@ f = Magick::Image.read("images/Flower_Hat.jpg").first pixels = f.dispatch(0,0,f.columns,f.rows,"RGB") -# Write the pixels to a file, to be included -# in the constitute.rb example. +# Write the pixels to a file, to be loaded in the Zconstitute.rb +# example. Ruby 1.6.8 # loads the Pixels array much faster if we break +# the array into many small pieces and concatenate them together, so this +# program generates such a sequence. + +first = true +total = pixels.length + File.open('pixels-array', 'w') { |txt| txt.puts("Width = #{f.columns}") txt.puts("Height = #{f.rows}") @@ -16,7 +22,22 @@ File.open('pixels-array', 'w') { |txt| txt.printf("%3d,", p) x = x.succ txt.printf("\n") if x % 25 == 0 + if x % 1000 == 0 + if first + txt.puts(']') + first = false + else + txt.puts('])') + end + txt.print('Pixels.concat([') + end + end + + if first + txt.puts(']') + first = false + else + txt.puts('])') end - txt.puts(']') } exit
Generate 'pixels-array' file such that the Pixels array is built by concatenating many small arrays. This makes the Zconstitute.rb script run _much_ faster in Ruby <I>.
rmagick_rmagick
train
3e5e1f16ccd91f6df3b1fadbbc1759812120eabc
diff --git a/src/DataSource/DoctrineDataSource.php b/src/DataSource/DoctrineDataSource.php index <HASH>..<HASH> 100644 --- a/src/DataSource/DoctrineDataSource.php +++ b/src/DataSource/DoctrineDataSource.php @@ -360,5 +360,14 @@ class DoctrineDataSource extends FilterableDataSource implements IDataSource { return 'param'.($this->placeholder++); } + + /** + * @param callable $aggregationCallback + * @return void + */ + public function processAggregation(callable $aggregationCallback) + { + call_user_func($aggregationCallback, $this->data_source); + } }
aggregation support for doctrine source
contributte_datagrid
train
ab19123120e5bdea2c2dff5697da7e150c5d8039
diff --git a/lib/pith/version.rb b/lib/pith/version.rb index <HASH>..<HASH> 100644 --- a/lib/pith/version.rb +++ b/lib/pith/version.rb @@ -1,3 +1,3 @@ module Pith - VERSION = "0.0.2".freeze + VERSION = "0.0.3".freeze end
We'll call that "<I>".
mdub_pith
train
db4fba6f305a8baf8258fc13d88d1ac198c21782
diff --git a/assets/__pm.js b/assets/__pm.js index <HASH>..<HASH> 100644 --- a/assets/__pm.js +++ b/assets/__pm.js @@ -53,8 +53,9 @@ }); DOM.addEventListener('change', function (event) { + var debounceRoot = root; setTimeout(function() { - sendForm(event.target.form, event); + if (root === debounceRoot) sendForm(event.target.form, event); }, event.target.tagName === "TEXTAREA" ? 250 : 0); });
Attempting to debounce textarea change event delay.
jadencarver_superconductor
train
74379a9730a7a9b730843cacfface4b2c3183c89
diff --git a/lib/Models/WebMapServiceCatalogGroup.js b/lib/Models/WebMapServiceCatalogGroup.js index <HASH>..<HASH> 100644 --- a/lib/Models/WebMapServiceCatalogGroup.js +++ b/lib/Models/WebMapServiceCatalogGroup.js @@ -282,7 +282,8 @@ function createWmsDataSource(wmsGroup, capabilities, layer) { result.layers = layer.Name; result.url = wmsGroup.url; - result.updateFromCapabilities(capabilities, true, layer); + var availableStyles = WebMapServiceCatalogItem.getAllAvailableStylesFromCapabilities(capabilities); + result.updateFromCapabilities(capabilities, true, layer, availableStyles); if (typeof(wmsGroup.itemProperties) === 'object') { result.updateFromJson(wmsGroup.itemProperties);
Avoid repeated work for WMS groups.
TerriaJS_terriajs
train
373945f3aa5d8a990e5a63282f16366633d23c97
diff --git a/event/class.go b/event/class.go index <HASH>..<HASH> 100644 --- a/event/class.go +++ b/event/class.go @@ -46,13 +46,13 @@ type Class struct { } // A Example is a real query and its database, timestamp, and Query_time. -// If the query is larger than MaxExampleBytes, it is truncated and "..." +// If the query is larger than MaxExampleBytes, it is truncated and TruncatedExampleSuffix // is appended. type Example struct { QueryTime float64 // Query_time Db string // Schema: <db> or USE <db> Query string // truncated to MaxExampleBytes - Truncated bool `json:",omitempty"` // true if Query is truncated to MaxExampleBytes + Size int `json:",omitempty"` // Original size of query. Ts string `json:",omitempty"` // in MySQL time zone } @@ -89,6 +89,7 @@ func (c *Class) AddEvent(e *log.Event, outlier bool) { if n, ok := e.TimeMetrics["Query_time"]; ok { if float64(n) > c.Example.QueryTime { c.Example.QueryTime = float64(n) + c.Example.Size = len(e.Query) if e.Db != "" { c.Example.Db = e.Db } else { @@ -96,7 +97,6 @@ func (c *Class) AddEvent(e *log.Event, outlier bool) { } if len(e.Query) > MaxExampleBytes { c.Example.Query = e.Query[0:MaxExampleBytes-len(TruncatedExampleSuffix)] + TruncatedExampleSuffix - c.Example.Truncated = true } else { c.Example.Query = e.Query }
Instead of marking as truncated just save original size.
percona_go-mysql
train
42c65eca200a26b0fe34d9fb8c5e227dd1186fcb
diff --git a/cltk/prosody/greek/scanner.py b/cltk/prosody/greek/scanner.py index <HASH>..<HASH> 100644 --- a/cltk/prosody/greek/scanner.py +++ b/cltk/prosody/greek/scanner.py @@ -193,8 +193,9 @@ class Scansion: scanned_sent.append('¯') else: scanned_sent.append('˘') - del scanned_sent[-1] - scanned_sent.append('x') + if len(scanned_sent) > 1: + del scanned_sent[-1] + scanned_sent.append('x') scanned_text.append(''.join(scanned_sent)) return scanned_text
Fixed index error in Greek scanner class (#<I>) * Fixed index error * Started wrapper class * Delete morpheus.py
cltk_cltk
train
01001a235ed542234c29a13b98e01d2f4e96f360
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,9 @@ LR(0) parser Change Log 1.1.0 ----- -No changes yet. +* Add: methods `getChildren()` and `getChildrenCount()` to interface + `VovanVE\parser\common\TreeNodeInterface` with its implementations in classes + `VovanVE\parser\common\Token` and `VovanVE\parser\tree\NonTerminal`. 1.0.3 diff --git a/src/common/Token.php b/src/common/Token.php index <HASH>..<HASH> 100644 --- a/src/common/Token.php +++ b/src/common/Token.php @@ -62,6 +62,24 @@ class Token extends BaseObject implements TreeNodeInterface /** * @inheritdoc + * @since 1.1.0 + */ + public function getChildrenCount() + { + return 0; + } + + /** + * @inheritdoc + * @since 1.1.0 + */ + public function getChildren() + { + return []; + } + + /** + * @inheritdoc */ public function dumpAsString($indent = '', $last = true) { diff --git a/src/common/TreeNodeInterface.php b/src/common/TreeNodeInterface.php index <HASH>..<HASH> 100644 --- a/src/common/TreeNodeInterface.php +++ b/src/common/TreeNodeInterface.php @@ -11,6 +11,18 @@ interface TreeNodeInterface public function getNodeName(); /** + * @return integer + * @since 1.1.0 + */ + public function getChildrenCount(); + + /** + * @return TreeNodeInterface[] + * @since 1.1.0 + */ + public function getChildren(); + + /** * @param string $indent * @param bool $last * @return string diff --git a/src/tree/NonTerminal.php b/src/tree/NonTerminal.php index <HASH>..<HASH> 100644 --- a/src/tree/NonTerminal.php +++ b/src/tree/NonTerminal.php @@ -21,6 +21,24 @@ class NonTerminal extends BaseObject implements TreeNodeInterface /** * @inheritdoc + * @since 1.1.0 + */ + public function getChildrenCount() + { + return count($this->children); + } + + /** + * @inheritdoc + * @since 1.1.0 + */ + public function getChildren() + { + return $this->children; + } + + /** + * @inheritdoc */ public function dumpAsString($indent = '', $last = true) { diff --git a/tests/unit/common/TokenTest.php b/tests/unit/common/TokenTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/common/TokenTest.php +++ b/tests/unit/common/TokenTest.php @@ -13,6 +13,9 @@ class TokenTest extends BaseTestCase $token = new Token($type, $content); + $this->assertEquals(0, $token->getChildrenCount()); + $this->assertCount(0, $token->getChildren()); + $dump_end = " `- $type <$content>" . PHP_EOL; foreach (['', ' ', "\t"] as $indent) { diff --git a/tests/unit/tree/NonTerminalTest.php b/tests/unit/tree/NonTerminalTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/tree/NonTerminalTest.php +++ b/tests/unit/tree/NonTerminalTest.php @@ -18,6 +18,9 @@ class NonTerminalTest extends BaseTestCase $node->name = 'V'; $node->children = [$token]; + $this->assertEquals(1, $node->getChildrenCount()); + $this->assertCount(1, $node->getChildren()); + $this->assertEquals(<<<'DUMP' `- V `- int <42> @@ -87,6 +90,9 @@ DUMP $node->name = 'E'; $node->children = [$p, $mul, $v]; + $this->assertEquals(3, $node->getChildrenCount()); + $this->assertCount(3, $node->getChildren()); + $this->assertEquals( <<<'DUMP' .... `- E
Add methods to `TreeNodeInterface` to deal with tree children
Vovan-VE_parser
train
7d430c6698ad903cfe7567233ea77a798cad779a
diff --git a/structr-rest/src/test/java/org/structr/test/rest/entity/TestOne.java b/structr-rest/src/test/java/org/structr/test/rest/entity/TestOne.java index <HASH>..<HASH> 100644 --- a/structr-rest/src/test/java/org/structr/test/rest/entity/TestOne.java +++ b/structr-rest/src/test/java/org/structr/test/rest/entity/TestOne.java @@ -21,6 +21,7 @@ package org.structr.test.rest.entity; import java.util.Date; import java.util.Map; import org.structr.common.PropertyView; +import org.structr.common.SecurityContext; import org.structr.common.View; import org.structr.core.Export; import org.structr.core.entity.AbstractNode; @@ -46,20 +47,20 @@ public class TestOne extends AbstractNode { ); @Export - public RestMethodResult test01(final Map<String, Object> params) { + public RestMethodResult test01(final SecurityContext securityContext, final Map<String, Object> params) { return null; } @Export - public void test02(final Map<String, Object> params) { + public void test02(final SecurityContext securityContext, final Map<String, Object> params) { } @Export - public RestMethodResult test03() { + public RestMethodResult test03(final SecurityContext securityContext) { return null; } @Export - public void test04() { + public void test04(final SecurityContext securityContext) { } }
Fixes Test: Adds securityContext to hard-coded test methods
structr_structr
train