hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
5791a1d11a22ad6874b9c9a713507fe544dcd4ae
diff --git a/addon/mixins/hammer-events.js b/addon/mixins/hammer-events.js index <HASH>..<HASH> 100644 --- a/addon/mixins/hammer-events.js +++ b/addon/mixins/hammer-events.js @@ -76,6 +76,7 @@ export default Ember.Mixin.create({ document.body.addEventListener('click', function (e) { e = e || window.event; var cancelOn = Ember.$(e.target).filter('a[href], button, input[type="submit"], input[type="button"]'); + Ember.Logger.debug('Click Canceller:', e.target, cancelOn, !!cancelOn.length); if (cancelOn.length) { e.preventDefault(); e.stopPropagation(); @@ -136,36 +137,39 @@ export default Ember.Mixin.create({ __executeGestureWithFilters : function (eventName, event, view, context) { var shouldFilter = isGesture(eventName) ? (view.get('gestureAllow') || view.get('gestureExclude')) : false, - element, + element, result, isInput = isInputEvent(eventName); if (context) { element = shouldFilter ? view._filterTouchableElements.call(view, event.target) : false; - if (isInput) { debugger; } + if (shouldFilter && !element) { + return false; + } - if (shouldFilter && !element) { return false; } + result = Ember.run(context, context[eventName], event, view); + return result; - Ember.run(context, context[eventName], event, view); - return false; - } - - if (view.has(eventName)) { + } else { element = shouldFilter ? view._filterTouchableElements.call(view, event.target) : false; - if (isInput) { debugger; } + if (isInput) { + Ember.Logger.debug('View ' + view.elementId + (view.has(eventName) ? ' has ' : ' does not have ') + 'a handler for ' + eventName); + } - if (shouldFilter && !element) { return false; } + if (shouldFilter && !element) { + Ember.Logger.debug('filtering event'); + return false; + } - Ember.run.join(view, view.handleEvent, eventName, event); - return false; + result = Ember.run.join(view, view.handleEvent, eventName, event); + Ember.Logger.debug('Event Run Result: ', result); + return result; } - return true; //keep bubbling - }, @@ -177,8 +181,7 @@ export default Ember.Mixin.create({ result = this.__executeGestureWithFilters(eventName, event, view, object); // Do not preventDefault in eventManagers. event.stopPropagation(); - } - else { + } else if (view) { result = this._bubbleEvent(view, event, eventName); }
bring return back into line with ember's expectations
runspired_ember-mobiletouch
train
6050a1b9124e095f7c0af7f7d48939d829e0b244
diff --git a/lib/adhearsion/call_controller/output.rb b/lib/adhearsion/call_controller/output.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/call_controller/output.rb +++ b/lib/adhearsion/call_controller/output.rb @@ -1,10 +1,14 @@ module Adhearsion class CallController module Output - def speak(text, options = {}) + def say(text, options = {}) play_ssml(text, options) || output(:text, text.to_s, options) end + def speak(text, options = {}) + say text, options + end + # # Plays the specified sound file names. This method will handle Time/DateTime objects (e.g. Time.now), # Fixnums (e.g. 1000), Strings which are valid Fixnums (e.g "123"), and direct sound files. To specify how the Date/Time objects are said diff --git a/spec/adhearsion/call_controller/output_spec.rb b/spec/adhearsion/call_controller/output_spec.rb index <HASH>..<HASH> 100644 --- a/spec/adhearsion/call_controller/output_spec.rb +++ b/spec/adhearsion/call_controller/output_spec.rb @@ -272,12 +272,19 @@ module Adhearsion end describe "#speak" do + it "should be an alias for #say" do + subject.should_receive(:say).once.with(:foo, {}).and_return true + subject.speak :foo + end + end + + describe "#say" do describe "with a RubySpeech document" do it 'plays the correct SSML' do doc = RubySpeech::SSML.draw { string "Hello world" } subject.should_receive(:play_ssml).once.with(doc, {}).and_return true subject.should_receive(:output).never - subject.speak(doc).should be true + subject.say(doc).should be true end end @@ -286,7 +293,7 @@ module Adhearsion string = "Hello world" subject.should_receive(:play_ssml).once.with(string, {}) subject.should_receive(:output).once.with(:text, string, {}).and_return true - subject.speak(string).should be true + subject.say(string).should be true end end @@ -296,7 +303,7 @@ module Adhearsion argument = 123 subject.should_receive(:play_ssml).once.with(argument, {}) subject.should_receive(:output).once.with(:text, expected_string, {}).and_return true - subject.speak(argument) + subject.say(argument) end end end
[FEATURE] Rename CallController#speak to #say, with an alias
adhearsion_adhearsion
train
d3079246438a97666de46cf4fb148f035bb0a359
diff --git a/abydos/distance/_guttman_lambda_a.py b/abydos/distance/_guttman_lambda_a.py index <HASH>..<HASH> 100644 --- a/abydos/distance/_guttman_lambda_a.py +++ b/abydos/distance/_guttman_lambda_a.py @@ -138,21 +138,20 @@ class GuttmanLambdaA(_TokenDistance): """ if src == tar: return 1.0 + if not src or not tar: + return 0.0 self._tokenize(src, tar) - if not self._src_card() or not self._tar_card(): - return 0.0 - a = self._intersection_card() b = self._src_only_card() c = self._tar_only_card() d = self._total_complement_card() n = self._population_unique_card() - num = float(max(a, c) + max(b, d) - max(a + b, c + d)) + num = round(float(max(a, c) + max(b, d) - max(a + b, c + d)), 15) if num: - return num / n - max(a + b, c + d) + return num / float(n - max(a + b, c + d)) return 0.0 diff --git a/abydos/distance/_guttman_lambda_b.py b/abydos/distance/_guttman_lambda_b.py index <HASH>..<HASH> 100644 --- a/abydos/distance/_guttman_lambda_b.py +++ b/abydos/distance/_guttman_lambda_b.py @@ -138,21 +138,20 @@ class GuttmanLambdaB(_TokenDistance): """ if src == tar: return 1.0 + if not src or not tar: + return 0.0 self._tokenize(src, tar) - if not self._src_card() or not self._tar_card(): - return 0.0 - a = self._intersection_card() b = self._src_only_card() c = self._tar_only_card() d = self._total_complement_card() n = self._population_unique_card() - num = float(max(a, b) + max(c, d) - max(a + c, b + d)) + num = round(float(max(a, b) + max(c, d) - max(a + c, b + d)), 15) if num: - return num / (n - max(a + c, b + d)) + return num / float(n - max(a + c, b + d)) return 0.0
fixed formula for A & simplified both, added rounding
chrislit_abydos
train
2447a5e84a56642f4d2ad6d7856d35f68cc12c44
diff --git a/src/trumbowyg.js b/src/trumbowyg.js index <HASH>..<HASH> 100644 --- a/src/trumbowyg.js +++ b/src/trumbowyg.js @@ -415,7 +415,9 @@ jQuery.trumbowyg = { t.buildOverlay(); - t.$c.trigger('tbwinit'); + setTimeout(function () { + t.$c.trigger('tbwinit'); + }); }, addBtnDef: function (btnName, btnDef) {
fix: fix tbwinit event
Alex-D_Trumbowyg
train
3b2ed78a97132115fe4caaeddd5a45d93ea88cce
diff --git a/lib/rack/app/constants.rb b/lib/rack/app/constants.rb index <HASH>..<HASH> 100644 --- a/lib/rack/app/constants.rb +++ b/lib/rack/app/constants.rb @@ -43,14 +43,15 @@ module Rack::App::Constants CONTENT_TYPE = 'CONTENT_TYPE'.freeze REQUEST_HANDLER = 'rack-app.handler'.freeze - PARSED_PARAMS = 'rack-app.parsed_params'.freeze - VALIDATED_PARAMS = 'rack-app.validated_params'.freeze + PARAMS_GETTER = 'rack-app.params.getter' + PARSED_PARAMS = 'rack-app.params.parsed'.freeze + VALIDATED_PARAMS = 'rack-app.params.validated'.freeze PAYLOAD = 'rack-app.payload'.freeze - PAYLOAD_PARSER = 'rack-app.payload_parser'.freeze - PAYLOAD_GETTER = 'rack-app.payload_getter'.freeze - PARSED_PAYLOAD = 'rack-app.parsed_payload'.freeze - VALIDATED_PAYLOAD = 'rack-app.validated_payload'.freeze + PAYLOAD_PARSER = 'rack-app.payload.parser'.freeze + PAYLOAD_GETTER = 'rack-app.payload.getter'.freeze + PARSED_PAYLOAD = 'rack-app.payload.parsed'.freeze + VALIDATED_PAYLOAD = 'rack-app.payload.validated'.freeze ORIGINAL_PATH_INFO = 'rack-app.original_path_info'.freeze PATH_PARAMS_MATCHER = 'rack-app.path_params_matcher'.freeze
refactor: update Constants
rack-app_rack-app
train
f3fbff62079f1ba338f0e59a2bd017d2f5304ff4
diff --git a/classes/fields/pick.php b/classes/fields/pick.php index <HASH>..<HASH> 100644 --- a/classes/fields/pick.php +++ b/classes/fields/pick.php @@ -2223,6 +2223,7 @@ class PodsField_Pick extends PodsField { }//end if } elseif ( $pick_object + && $this->setup_related_objects() && isset( self::$related_objects[ $pick_object ] ) && ! empty( self::$related_objects[$pick_object ]['data'] ) ) { @@ -2231,6 +2232,7 @@ class PodsField_Pick extends PodsField { $simple = true; } elseif ( $pick_object + && $this->setup_related_objects() && isset( self::$related_objects[ $pick_object ] ) && isset( self::$related_objects[ $pick_object ]['data_callback'] ) && is_callable( self::$related_objects[ $pick_object ]['data_callback'] )
Ensure related objects are set up when getting data
pods-framework_pods
train
2f902806221ca9393e8819c57c4ed69c52d5eeaa
diff --git a/lib/passport/context/http/actions.js b/lib/passport/context/http/actions.js index <HASH>..<HASH> 100644 --- a/lib/passport/context/http/actions.js +++ b/lib/passport/context/http/actions.js @@ -17,7 +17,7 @@ var actions = module.exports = {}; * @param {Object} info * @api public */ -actions.success = function(user, info) { +actions.success = function(user, profile) { this.delegate.success.apply(this, arguments); } diff --git a/lib/passport/middleware/authenticate.js b/lib/passport/middleware/authenticate.js index <HASH>..<HASH> 100644 --- a/lib/passport/middleware/authenticate.js +++ b/lib/passport/middleware/authenticate.js @@ -24,9 +24,11 @@ var util = require('util') * the default manner in which authentication attempts are handled. The * callback has the following signature, where `user` will be set to the * authenticated user on a successful authentication attempt, or `false` - * otherwise. + * otherwise. An optional `profile` will be provided, containing + * service-specific profile information, when using third-party authentication + * strategies. * - * passport.authenticate('local', function(err, user) { + * passport.authenticate('local', function(err, user, profile) { * if (err) { return next(err) } * if (!user) { return res.redirect('/signin') } * res.redirect('/account'); @@ -62,9 +64,9 @@ module.exports = function authenticate(name, options, callback) { return function authenticate(req, res, next) { var passport = this; var delegate = {}; - delegate.success = function(user, extra) { + delegate.success = function(user, profile) { if (callback) { - return callback(null, user, extra); + return callback(null, user, profile); } req.logIn(user, options, function(err) { diff --git a/test/middleware/authenticate-test.js b/test/middleware/authenticate-test.js index <HASH>..<HASH> 100644 --- a/test/middleware/authenticate-test.js +++ b/test/middleware/authenticate-test.js @@ -9,7 +9,7 @@ function MockSuccessStrategy() { } MockSuccessStrategy.prototype.authenticate = function(req) { - this.success({ id: '1', username: 'jaredhanson' }); + this.success({ id: '1', username: 'jaredhanson' }, { location: 'Oakland, CA' }); } function MockFailureStrategy() { @@ -147,8 +147,8 @@ vows.describe('authenticate').addBatch({ var self = this; var passport = new Passport(); passport.use('success', new MockSuccessStrategy); - var callback = function(err, user) { - this.done(err, user); + var callback = function(err, user, profile) { + this.done(err, user, profile); } var context = {}; @@ -163,8 +163,8 @@ vows.describe('authenticate').addBatch({ var self = this; var req = new MockRequest(); var res = new MockResponse(); - context.done = function(err, user) { - self.callback(err, req, res, user); + context.done = function(err, user, profile) { + self.callback(err, req, res, user, profile); } function next(err) { @@ -175,17 +175,21 @@ vows.describe('authenticate').addBatch({ }); }, - 'should not generate an error' : function(err, req, res, user) { + 'should not generate an error' : function(err, req, res, user, profile) { assert.isNull(err); }, - 'should not set user on request' : function(err, req, res, user) { + 'should not set user on request' : function(err, req, res, user, profile) { assert.isUndefined(req.user); }, - 'should pass user to callback' : function(err, req, res, user) { + 'should pass user to callback' : function(err, req, res, user, profile) { assert.isObject(user); assert.equal(user.id, '1'); assert.equal(user.username, 'jaredhanson'); }, + 'should pass profile to callback' : function(err, req, res, user, profile) { + assert.isObject(profile); + assert.equal(profile.location, 'Oakland, CA'); + }, }, },
Document and test that profile parameter is passed to authenticate callback.
jaredhanson_passport
train
1f6956a1d38e37e35a50c18883be0d30e9ee0996
diff --git a/lib/puppet/ssl/host.rb b/lib/puppet/ssl/host.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/ssl/host.rb +++ b/lib/puppet/ssl/host.rb @@ -218,7 +218,7 @@ On the master: puppet cert clean #{Puppet[:certname]} On the agent: 1a. On most platforms: find #{Puppet[:ssldir]} -name #{Puppet[:certname]}.pem -delete - 1b. On Windows: del "#{Puppet[:ssldir]}/#{Puppet[:certname]}.pem" /f + 1b. On Windows: del "#{Puppet[:certdir].gsub('/', '\\')}\\#{Puppet[:certname]}.pem" /f 2. puppet agent -t ERROR_STRING end
(PUP-<I>) Fix Windows cert clean instructions - Previously the instructions would say something like: del "C:/ProgramData/PuppetLabs/puppet/etc/ssl/agent.pem" /f This fails in a cmd.exe prompt, and is the incorrect directory anyhow Updated so that it shows like: del "C:\ProgramData\PuppetLabs\puppet\etc\ssl\certs\agent.pem" /f
puppetlabs_puppet
train
7905f8547399502246c1b520efa74c49b4a19fd7
diff --git a/cumulusci/tasks/salesforce/sourcetracking.py b/cumulusci/tasks/salesforce/sourcetracking.py index <HASH>..<HASH> 100644 --- a/cumulusci/tasks/salesforce/sourcetracking.py +++ b/cumulusci/tasks/salesforce/sourcetracking.py @@ -23,7 +23,16 @@ class ListChanges(BaseSalesforceApiTask): api_version = "47.0" task_options = { - "include": {"description": "Include changed components matching this string."}, + "include": { + "description": "A comma-separated list of strings. " + "Components will be included if one of these strings " + "is part of either the metadata type or name. " + "Example: ``-o include CustomField,Admin`` matches both " + "``CustomField: Favorite_Color__c`` and ``Profile: Admin``" + }, + "types": { + "description": "A comma-separated list of metadata types to include." + }, "exclude": {"description": "Exclude changed components matching this string."}, "snapshot": { "description": "If True, all matching items will be set to be ignored at their current revision number. This will exclude them from the results unless a new edit is made." @@ -32,7 +41,9 @@ class ListChanges(BaseSalesforceApiTask): def _init_options(self, kwargs): super(ListChanges, self)._init_options(kwargs) - self.options["include"] = process_list_arg(self.options.get("include", [])) + self.options["include"] = process_list_arg(self.options.get("include", [])) + [ + f"{mdtype}:" for mdtype in process_list_arg(self.options.get("types", [])) + ] self.options["exclude"] = process_list_arg(self.options.get("exclude", [])) self.options["snapshot"] = process_bool_arg(self.options.get("snapshot", False)) self._include = self.options["include"]
update based on @jstvz feedback
SFDO-Tooling_CumulusCI
train
0bf42bb525c688b0f873094cd6666cf26c57a864
diff --git a/Neos.Fusion.Afx/Classes/Service/AfxService.php b/Neos.Fusion.Afx/Classes/Service/AfxService.php index <HASH>..<HASH> 100644 --- a/Neos.Fusion.Afx/Classes/Service/AfxService.php +++ b/Neos.Fusion.Afx/Classes/Service/AfxService.php @@ -178,7 +178,7 @@ class AfxService $childrenPropertyName = 'content'; } $childFusion = self::astNodeListToFusion($payload['children'], $indentation . self::INDENTATION); - if ($childFusion !== null) { + if ($childFusion) { $fusion .= $indentation . self::INDENTATION . $childrenPropertyName . ' = ' . $childFusion . PHP_EOL; } } @@ -215,7 +215,7 @@ class AfxService }); if (count($payload) == 0) { - return ''; + return '\'\''; } elseif (count($payload) == 1) { return self::astToFusion(array_shift($payload), $indentation); } else { diff --git a/Neos.Fusion.Afx/Tests/Functional/AfxServiceTest.php b/Neos.Fusion.Afx/Tests/Functional/AfxServiceTest.php index <HASH>..<HASH> 100644 --- a/Neos.Fusion.Afx/Tests/Functional/AfxServiceTest.php +++ b/Neos.Fusion.Afx/Tests/Functional/AfxServiceTest.php @@ -14,6 +14,7 @@ class AfxServiceTest extends FunctionalTestCase { $afxCode = ''; $expectedFusion = <<<'EOF' +'' EOF; $this->assertEquals($expectedFusion, AfxService::convertAfxToFusion($afxCode)); } @@ -25,6 +26,7 @@ EOF; { $afxCode = ' '; $expectedFusion = <<<'EOF' +'' EOF; $this->assertEquals($expectedFusion, AfxService::convertAfxToFusion($afxCode)); } @@ -46,6 +48,38 @@ EOF; /** * @test */ + public function htmlTagsWithSpaceContentAreConvertedToFusionTags() + { + $afxCode = '<h1> </h1>'; + $expectedFusion = <<<'EOF' +Neos.Fusion:Tag { + tagName = 'h1' + content = ' ' +} +EOF; + $this->assertEquals($expectedFusion, AfxService::convertAfxToFusion($afxCode)); + } + + /** + * @test + */ + public function htmlTagsWithIgnoredContentAreConvertedToFusionTags() + { + $afxCode = '<h1> + +</h1>'; + $expectedFusion = <<<'EOF' +Neos.Fusion:Tag { + tagName = 'h1' + content = '' +} +EOF; + $this->assertEquals($expectedFusion, AfxService::convertAfxToFusion($afxCode)); + } + + /** + * @test + */ public function multipleHtmlTagsAreConvertedToFusionArray() { $afxCode = '<h1></h1><p></p><p></p>';
TASK: Handle empty nodeLists properly If a node only contained children that were ignored the returned fusion code was invalid. This case is fixed by creating an empty string for NodeLists that do not contain meaningful items.
neos_neos-development-collection
train
a3537d132a68a102bf0eb9e06c959566a1ef5a55
diff --git a/test/test_guard.py b/test/test_guard.py index <HASH>..<HASH> 100644 --- a/test/test_guard.py +++ b/test/test_guard.py @@ -15,14 +15,14 @@ class TestGuard(TestCase): def test_one_time_code(self): timestamp = 1469184207 code = guard.generate_one_time_code(self.shared_secret, timestamp) - self.assertEquals(code, 'P2QJN') + self.assertEqual(code, 'P2QJN') def test_confirmation_key(self): timestamp = 1470838334 confirmation_key = guard.generate_confirmation_key(self.identity_secret, Tag.CONF.value, timestamp) - self.assertEquals(confirmation_key, b'pWqjnkcwqni+t/n+5xXaEa0SGeA=') + self.assertEqual(confirmation_key, b'pWqjnkcwqni+t/n+5xXaEa0SGeA=') def test_generate_device_id(self): steam_id = "12341234123412345" device_id = guard.generate_device_id(steam_id) - self.assertEquals(device_id, "android:677cf5aa-3300-7807-d1e2-c408142742e2") + self.assertEqual(device_id, "android:677cf5aa-3300-7807-d1e2-c408142742e2") diff --git a/test/test_utils.py b/test/test_utils.py index <HASH>..<HASH> 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -9,14 +9,14 @@ class TestUtils(TestCase): def test_text_between(self): text = 'var a = "dupadupa";' text_between = utils.text_between(text, 'var a = "', '";') - self.assertEquals(text_between, 'dupadupa') + self.assertEqual(text_between, 'dupadupa') def test_texts_between(self): text = "<li>element 1</li>\n<li>some random element</li>" items = [] for el in utils.texts_between(text, "<li>", "</li>"): items.append(el) - self.assertEquals(items, ["element 1", "some random element"]) + self.assertEqual(items, ["element 1", "some random element"]) def test_account_id_to_steam_id(self): account_id = '358617487' @@ -26,17 +26,17 @@ class TestUtils(TestCase): def test_steam_id_to_account_id(self): steam_id = '76561198318883215' account_id = utils.steam_id_to_account_id(steam_id) - self.assertEquals(account_id, '358617487') + self.assertEqual(account_id, '358617487') def test_parse_price_with_currency_symbol(self): price = '$11.33 USD' decimal_price = utils.parse_price(price) - self.assertEquals(decimal_price, decimal.Decimal('11.33')) + self.assertEqual(decimal_price, decimal.Decimal('11.33')) def test_parse_price_without_currency_symbol(self): price = '11,33 USD' decimal_price = utils.parse_price(price) - self.assertEquals(decimal_price, decimal.Decimal('11.33')) + self.assertEqual(decimal_price, decimal.Decimal('11.33')) def test_parse_price_without_space(self): price = '21,37zł' @@ -46,7 +46,7 @@ class TestUtils(TestCase): def test_parse_price_without_decimal_separator(self): price = '2137 CZK' decimal_price = utils.parse_price(price) - self.assertEquals(decimal_price, decimal.Decimal('2137')) + self.assertEqual(decimal_price, decimal.Decimal('2137')) def test_get_key_value_from_url(self): url = 'https://steamcommunity.com/tradeoffer/new/?partner=aaa&token=bbb'
Use assertEqual instead of assertEquals for Python <I> compatibility.
bukson_steampy
train
215abfda39c34aa125f9405d9bb848eb45ee7ac6
diff --git a/git/diff.py b/git/diff.py index <HASH>..<HASH> 100644 --- a/git/diff.py +++ b/git/diff.py @@ -16,7 +16,7 @@ from .objects.util import mode_str_to_int # typing ------------------------------------------------------------------ from typing import Any, Iterator, List, Match, Optional, Tuple, Type, Union, TYPE_CHECKING, cast -from git.types import PathLike, TBD, Literal +from git.types import PathLike, TBD, Literal, TypeGuard if TYPE_CHECKING: from .objects.tree import Tree @@ -26,8 +26,13 @@ if TYPE_CHECKING: Lit_change_type = Literal['A', 'D', 'C', 'M', 'R', 'T'] + +def is_change_type(inp: str) -> TypeGuard[Lit_change_type]: + return inp in ['A', 'D', 'C', 'M', 'R', 'T'] + # ------------------------------------------------------------------------ + __all__ = ('Diffable', 'DiffIndex', 'Diff', 'NULL_TREE') # Special object to compare against the empty tree in diffs @@ -202,6 +207,7 @@ class DiffIndex(list): for diff in self: diff = cast('Diff', diff) + if diff.change_type == change_type: yield diff elif change_type == "A" and diff.new_file: @@ -505,7 +511,8 @@ class Diff(object): # Change type can be R100 # R: status letter # 100: score (in case of copy and rename) - change_type: Lit_change_type = _change_type[0] # type: ignore + assert is_change_type(_change_type[0]) + change_type: Lit_change_type = _change_type[0] score_str = ''.join(_change_type[1:]) score = int(score_str) if score_str.isdigit() else None path = path.strip()
Readd typeguard to Diff.py
gitpython-developers_GitPython
train
258cfb02da59f73572bbf5fbf3a3f74b0c79569a
diff --git a/cv/internal/prjmanager/impl/state/components.go b/cv/internal/prjmanager/impl/state/components.go index <HASH>..<HASH> 100644 --- a/cv/internal/prjmanager/impl/state/components.go +++ b/cv/internal/prjmanager/impl/state/components.go @@ -27,6 +27,7 @@ import ( "go.chromium.org/luci/common/clock" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/common/logging" + "go.chromium.org/luci/common/retry/transient" "go.chromium.org/luci/common/runtime/paniccatcher" "go.chromium.org/luci/common/sync/parallel" @@ -103,7 +104,11 @@ func (s *State) triageComponents(ctx context.Context) ([]*cAction, error) { case err != nil: // Log error here since only total errs count will be propagated up // the stack. - logging.Errorf(ctx, "%s while processing component: %s", err, protojson.Format(oldC)) + level := logging.Error + if transient.Tag.In(err) { + level = logging.Warning + } + logging.Logf(ctx, level, "%s while processing component: %s", err, protojson.Format(oldC)) return err default: mutex.Lock()
[cv] log transient errors of triage at warning level. R=qyearsley, yiwzhang Change-Id: I<I>b<I>eda<I>ab1a<I>cc0ba<I>f<I>b<I>d Reviewed-on: <URL>
luci_luci-go
train
21b26f30a35c956662bcf148a88f45fb052a4997
diff --git a/rip/schema/list_field.py b/rip/schema/list_field.py index <HASH>..<HASH> 100644 --- a/rip/schema/list_field.py +++ b/rip/schema/list_field.py @@ -30,6 +30,10 @@ class ListField(BaseField): if self.nullable and value is None: return ValidationResult(is_success=True) + if type(value) != list: + return ValidationResult(is_success=False, + reason="This field should be an array.") + for item in value: validation_result = self.field.validate(request, item) if not validation_result.is_success: diff --git a/tests/unit_tests/schema/test_list_field.py b/tests/unit_tests/schema/test_list_field.py index <HASH>..<HASH> 100644 --- a/tests/unit_tests/schema/test_list_field.py +++ b/tests/unit_tests/schema/test_list_field.py @@ -18,6 +18,13 @@ class TestValidateListField(unittest.TestCase): assert not result.is_success + def test_return_failure_if_value_is_not_a_list(self): + field = ListField(field=StringField(), nullable=False) + + result = field.validate(request=None, value='blah') + + assert not result.is_success + def test_return_success_if_validation_passes(self): field = ListField(field=StringField(), nullable=True)
Validates whether the data passed to a list field is actually a list.
Aplopio_django_rip
train
176f7f6dff3988936540cac64e3ea32a901d2af4
diff --git a/lib/Algo/Tools/Pairwise.php b/lib/Algo/Tools/Pairwise.php index <HASH>..<HASH> 100644 --- a/lib/Algo/Tools/Pairwise.php +++ b/lib/Algo/Tools/Pairwise.php @@ -16,27 +16,29 @@ use Condorcet\Timer\Chrono as Timer_Chrono; class Pairwise implements \Iterator { // Implement Iterator - - private $position = 1; + private $valid = true; public function rewind() { - $this->position = 1; + reset($this->_Pairwise); + $this->valid = true; } public function current() { - return $this->position; + return $this->_Pairwise[$this->key()]; } public function key() { - return $this->position; + return key($this->_Pairwise); } public function next() { - ++$this->position; + if (next($this->_Pairwise) === false) : + $this->valid = false; + endif; } public function valid() { - return true; + return $this->valid; }
Pairwise is now an object ! (step 2)
julien-boudry_Condorcet
train
45292a949dfe0f3f9ee9f5de6a60017b1ac82e9b
diff --git a/dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java b/dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java index <HASH>..<HASH> 100644 --- a/dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java +++ b/dropwizard-db/src/main/java/io/dropwizard/db/DataSourceFactory.java @@ -128,7 +128,7 @@ import java.util.concurrent.TimeUnit; * </tr> * <tr> * <td>{@code maxSize}</td> - * <td>10</td> + * <td>100</td> * <td> * The maximum size of the connection pool. * </td>
Update DataSourceFactory.maxSize api docs * maxSize is initialized to <I>, not <I>
dropwizard_dropwizard
train
9d72ae249c58fd4e431a8a92d9c950a6c6cc0341
diff --git a/lib/accesslib.php b/lib/accesslib.php index <HASH>..<HASH> 100644 --- a/lib/accesslib.php +++ b/lib/accesslib.php @@ -4232,7 +4232,7 @@ function count_role_users($roleid, context $context, $parent = false) { array_unshift($params, $context->id); - $sql = "SELECT COUNT(u.id) + $sql = "SELECT COUNT(DISTINCT u.id) FROM {role_assignments} r JOIN {user} u ON u.id = r.userid WHERE (r.contextid = ? $parentcontexts)
MDL-<I> access: count_role_users gives unexpected results The count_role_users function in lib/accesslib.php gives the wrong results if a user has the same role at multiple levels in a context path. For example a user is a coursecreator on a course and the category that the course is in, in this case they would be counted twice, rather than being recognised as the same user. This change will make the function only count unique users.
moodle_moodle
train
fdc12c9d7c4f80144ef1274a9b14609d706bcf24
diff --git a/lib/dawn/core.rb b/lib/dawn/core.rb index <HASH>..<HASH> 100644 --- a/lib/dawn/core.rb +++ b/lib/dawn/core.rb @@ -14,10 +14,11 @@ module Dawn puts "\t$ dawn -C --json a_sinatra_webapp_directory" puts "\t$ dawn --ascii-tabular-report my_rails_blog_ecommerce" puts "\t$ dawn --html -F my_report.html my_rails_blog_ecommerce" - printf "\n -r, --rails\t\t\t\t\tforce dawn to consider the target a rails application" - printf "\n -s, --sinatra\t\t\t\tforce dawn to consider the target a sinatra application" - printf "\n -p, --padrino\t\t\t\tforce dawn to consider the target a padrino application" - printf "\n -G, --gem-lock\t\t\t\tforce dawn to scan only for vulnerabilities affecting dependencies in Gemfile.lock" + printf "\n -r, --rails\t\t\t\t\tforce dawn to consider the target a rails application (DEPRECATED)" + printf "\n -s, --sinatra\t\t\t\tforce dawn to consider the target a sinatra application (DEPRECATED)" + printf "\n -p, --padrino\t\t\t\tforce dawn to consider the target a padrino application (DEPRECATED)" + printf "\n -G, --gem-lock\t\t\t\tforce dawn to scan only for vulnerabilities affecting dependencies in Gemfile.lock (DEPRECATED)" + printf "\n -d, --dependencies\t\t\t\tforce dawn to scan only for vulnerabilities affecting dependencies in Gemfile.lock" printf "\n -a, --ascii-tabular-report\t\t\tcause dawn to format findings using table in ascii art" printf "\n -j, --json\t\t\t\t\tcause dawn to format findings using json" printf "\n -C, --count-only\t\t\t\tdawn will only count vulnerabilities (useful for scripts)"
Marked DEPRECATED flags in help message
thesp0nge_dawnscanner
train
3733edc314702ed970b667a0ddb30e105519249a
diff --git a/backtrader/feeds/csvgeneric.py b/backtrader/feeds/csvgeneric.py index <HASH>..<HASH> 100644 --- a/backtrader/feeds/csvgeneric.py +++ b/backtrader/feeds/csvgeneric.py @@ -24,7 +24,7 @@ from __future__ import (absolute_import, division, print_function, from datetime import datetime import itertools -from .. import feed +from .. import feed, TimeFrame from ..utils import date2num @@ -82,7 +82,7 @@ class GenericCSVData(feed.CSVDataBase): dt = datetime.strptime(dtfield, dtformat) - if self.p.timeframe >= bt.TimeFrame.Days: + if self.p.timeframe >= TimeFrame.Days: # check if the expected end of session is larger than parsed expeos = datetime.combine(dt.date(), self.p.sessionend) if expeos > dt:
Fix #<I> by directly importing TimeFrame
backtrader_backtrader
train
5bebb702a06ac93bb020efc1bbb96058c0213323
diff --git a/app/src/main/java/com/mikepenz/crossfadedrawerlayout/app/SimpleActivity.java b/app/src/main/java/com/mikepenz/crossfadedrawerlayout/app/SimpleActivity.java index <HASH>..<HASH> 100755 --- a/app/src/main/java/com/mikepenz/crossfadedrawerlayout/app/SimpleActivity.java +++ b/app/src/main/java/com/mikepenz/crossfadedrawerlayout/app/SimpleActivity.java @@ -47,7 +47,6 @@ public class SimpleActivity extends AppCompatActivity { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); - // Create a few sample profile // NOTE you have to define the loader logic too. See the CustomApplication for more details final IProfile profile = new ProfileDrawerItem().withName("Mike Penz").withEmail("mikepenz@gmail.com").withIcon("https://avatars3.githubusercontent.com/u/1476232?v=3&s=460"); @@ -60,16 +59,6 @@ public class SimpleActivity extends AppCompatActivity { .addProfiles( profile, profile2 ) - .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { - @Override - public boolean onProfileChanged(View view, IProfile profile, boolean current) { - //IMPORTANT! notify the MiniDrawer about the profile click - miniResult.onProfileClick(); - - //false if you have not consumed the event and it should close the drawer - return false; - } - }) .withSavedInstance(savedInstanceState) .build(); @@ -82,6 +71,7 @@ public class SimpleActivity extends AppCompatActivity { .withDrawerLayout(crossfadeDrawerLayout) .withHasStableIds(true) .withDrawerWidthDp(72) + .withGenerateMiniDrawer(true) .withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header .addDrawerItems( new PrimaryDrawerItem().withName(R.string.drawer_item_first).withIcon(GoogleMaterial.Icon.gmd_3d_rotation).withIdentifier(1), @@ -100,8 +90,7 @@ public class SimpleActivity extends AppCompatActivity { Toast.makeText(SimpleActivity.this, ((Nameable) drawerItem).getName().getText(SimpleActivity.this), Toast.LENGTH_SHORT).show(); } - //IMPORTANT notify the MiniDrawer about the onItemClick - return miniResult.onItemClick(drawerItem); + return false; } }) .withSavedInstance(savedInstanceState) @@ -111,8 +100,10 @@ public class SimpleActivity extends AppCompatActivity { //define maxDrawerWidth crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this)); //add second view (which is the miniDrawer) - miniResult = new MiniDrawer().withDrawer(result).withAccountHeader(headerResult); + MiniDrawer miniResult = result.getMiniDrawer(); + //build the view for the MiniDrawer View view = miniResult.build(this); + //set the background of the MiniDrawer as this would be transparent view.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(this, com.mikepenz.materialdrawer.R.attr.material_drawer_background, com.mikepenz.materialdrawer.R.color.material_drawer_background)); //we do not have the MiniDrawer view during CrossfadeDrawerLayout creation so we will add it here crossfadeDrawerLayout.getSmallView().addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); @@ -135,6 +126,14 @@ public class SimpleActivity extends AppCompatActivity { return crossfadeDrawerLayout.isCrossfaded(); } }); + + //hook to the crossfade event + crossfadeDrawerLayout.withCrossfadeListener(new CrossfadeDrawerLayout.CrossfadeListener() { + @Override + public void onCrossfade(View containerView, float currentSlidePercentage, int slideOffset) { + //Log.e("CrossfadeDrawerLayout", "crossfade: " + currentSlidePercentage + " - " + slideOffset); + } + }); } @Override
* modify sample app to follow the updated drawer
mikepenz_CrossfadeDrawerLayout
train
4e5859e8300e7c56f28ca07c47131d14f6cf8632
diff --git a/api.go b/api.go index <HASH>..<HASH> 100644 --- a/api.go +++ b/api.go @@ -1094,7 +1094,7 @@ func ServeFd(addr string, handle http.Handler) error { // Since ListenFD will return one or more sockets we have // to create a go func to spawn off multiple serves - for i, _ := range ls { + for i := range ls { listener := ls[i] go func() { httpSrv := http.Server{Handler: handle}
fix(api): , _ removed to simplify code in range Docker-DCO-<I>-
containers_storage
train
2bb0f2d6e5f3aac609bb85d6c62290c30f5c6346
diff --git a/app/src/grunt/sass.js b/app/src/grunt/sass.js index <HASH>..<HASH> 100644 --- a/app/src/grunt/sass.js +++ b/app/src/grunt/sass.js @@ -7,7 +7,6 @@ module.exports = { */ boltCss: { options: { - outputStyle: 'compressed', includePaths: [ '<%= path.src.bower %>/bootstrap-sass/assets/stylesheets/', '<%= path.src.bower %>/font-awesome/scss/'
Write sass output uncompressed, csswring wil do that later
bolt_bolt
train
4cf29bd75f84c82f0a2dec2fc3732b2afe4a13ef
diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java index <HASH>..<HASH> 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java @@ -69,7 +69,7 @@ public class DefaultBotSession implements BotSession { lastReceivedUpdate = 0; - readerThread = new ReaderThread(updatesSupplier); + readerThread = new ReaderThread(updatesSupplier, this); readerThread.setName(callback.getBotUsername() + " Telegram Connection"); readerThread.start(); @@ -135,12 +135,14 @@ public class DefaultBotSession implements BotSession { private class ReaderThread extends Thread implements UpdatesReader { private final UpdatesSupplier updatesSupplier; + private final Object lock; private CloseableHttpClient httpclient; private ExponentialBackOff exponentialBackOff; private RequestConfig requestConfig; - public ReaderThread(UpdatesSupplier updatesSupplier) { + public ReaderThread(UpdatesSupplier updatesSupplier, Object lock) { this.updatesSupplier = Optional.ofNullable(updatesSupplier).orElse(this::getUpdatesFromServer); + this.lock = lock; } @Override @@ -183,41 +185,45 @@ public class DefaultBotSession implements BotSession { public void run() { setPriority(Thread.MIN_PRIORITY); while (running) { - try { - List<Update> updates = updatesSupplier.getUpdates(); - if (updates.isEmpty()) { - synchronized (this) { - this.wait(500); - } - } else { - updates.removeIf(x -> x.getUpdateId() < lastReceivedUpdate); - lastReceivedUpdate = updates.parallelStream() - .map( - Update::getUpdateId) - .max(Integer::compareTo) - .orElse(0); - receivedUpdates.addAll(updates); - - synchronized (receivedUpdates) { - receivedUpdates.notifyAll(); - } - } - } catch (InterruptedException e) { - if (!running) { - receivedUpdates.clear(); - } - BotLogger.debug(LOGTAG, e); - } catch (Exception global) { - BotLogger.severe(LOGTAG, global); - try { - synchronized (this) { - this.wait(exponentialBackOff.nextBackOffMillis()); - } - } catch (InterruptedException e) { - if (!running) { - receivedUpdates.clear(); + synchronized (lock) { + if (running) { + try { + List<Update> updates = updatesSupplier.getUpdates(); + if (updates.isEmpty()) { + if (running) { + lock.wait(500); + } + } else { + updates.removeIf(x -> x.getUpdateId() < lastReceivedUpdate); + lastReceivedUpdate = updates.parallelStream() + .map( + Update::getUpdateId) + .max(Integer::compareTo) + .orElse(0); + receivedUpdates.addAll(updates); + + synchronized (receivedUpdates) { + receivedUpdates.notifyAll(); + } + } + } catch (InterruptedException e) { + if (!running) { + receivedUpdates.clear(); + } + BotLogger.debug(LOGTAG, e); + } catch (Exception global) { + BotLogger.severe(LOGTAG, global); + try { + synchronized (lock) { + lock.wait(exponentialBackOff.nextBackOffMillis()); + } + } catch (InterruptedException e) { + if (!running) { + receivedUpdates.clear(); + } + BotLogger.debug(LOGTAG, e); + } } - BotLogger.debug(LOGTAG, e); } } } @@ -248,8 +254,8 @@ public class DefaultBotSession implements BotSession { if (response.getStatusLine().getStatusCode() >= 500) { BotLogger.warn(LOGTAG, responseContent); - synchronized (this) { - this.wait(500); + synchronized (lock) { + lock.wait(500); } } else { try { @@ -261,9 +267,7 @@ public class DefaultBotSession implements BotSession { } } } catch (SocketException e) { - if (!e.getMessage().equals("Socket Closed")) { - BotLogger.severe(LOGTAG, e); - } + BotLogger.severe(LOGTAG, e); } catch (SocketTimeoutException e) { BotLogger.fine(LOGTAG, e); } catch (InvalidObjectException | TelegramApiRequestException e) {
Clean up some thread usage, seems to close #<I>.
rubenlagus_TelegramBots
train
48f0ac034b25564145f4ae89f3646f68ac5252a9
diff --git a/coveralls/api.py b/coveralls/api.py index <HASH>..<HASH> 100644 --- a/coveralls/api.py +++ b/coveralls/api.py @@ -97,10 +97,10 @@ class Coveralls: @staticmethod def load_config_from_circle(): - number = os.environ.get( - 'CIRCLE_WORKFLOW_ID') or os.environ.get('CIRCLE_BUILD_NUM') - pr = (os.environ.get('CI_PULL_REQUEST') or "").split("/")[-1] or None - job = os.environ.get('CIRCLE_NODE_INDEX') or None + number = (os.environ.get('CIRCLE_WORKFLOW_ID') + or os.environ.get('CIRCLE_BUILD_NUM')) + pr = (os.environ.get('CI_PULL_REQUEST') or '').split('/')[-1] or None + job = os.environ.get('CIRCLE_NODE_INDEX') return 'circleci', job, number, pr def load_config_from_github(self): diff --git a/tests/api/configuration_test.py b/tests/api/configuration_test.py index <HASH>..<HASH> 100644 --- a/tests/api/configuration_test.py +++ b/tests/api/configuration_test.py @@ -128,7 +128,8 @@ class NoConfiguration(unittest.TestCase): def test_circleci_parallel_no_config(self): cover = Coveralls(repo_token='xxx') assert cover.config['service_name'] == 'circleci' - assert cover.config['service_number'] == '0ea2c0f7-4e56-4a94-bf77-bfae6bdbf80a' + assert cover.config['service_number'] == ( + '0ea2c0f7-4e56-4a94-bf77-bfae6bdbf80a') assert cover.config['service_job_id'] == '15' @mock.patch.dict(
chore: fix lint issues
coveralls-clients_coveralls-python
train
e761072012289887078073d295c52cac7bf47529
diff --git a/providence-thrift/src/main/java/net/morimekta/providence/thrift/io/FramedBufferInputSteram.java b/providence-thrift/src/main/java/net/morimekta/providence/thrift/io/FramedBufferInputSteram.java index <HASH>..<HASH> 100644 --- a/providence-thrift/src/main/java/net/morimekta/providence/thrift/io/FramedBufferInputSteram.java +++ b/providence-thrift/src/main/java/net/morimekta/providence/thrift/io/FramedBufferInputSteram.java @@ -38,7 +38,12 @@ public class FramedBufferInputSteram extends InputStream { return -1; } } - return buffer.get(); + return intValue(buffer.get()); + } + + private static int intValue(byte b) { + if (b < 0) return b + 0x100; + return b; } @Override
Fix nit about negative int from byte in FramedBufferInputStream.
morimekta_providence
train
0be1c9a81f9e88d35304b24d7c3d0a62f90b7759
diff --git a/consumer_config.go b/consumer_config.go index <HASH>..<HASH> 100644 --- a/consumer_config.go +++ b/consumer_config.go @@ -176,6 +176,7 @@ func DefaultConsumerConfig() *ConsumerConfig { config.NumWorkers = 10 config.MaxWorkerRetries = 3 config.WorkerRetryThreshold = 100 + config.WorkerThresholdTimeWindow = 1 * time.Minute config.WorkerBackoff = 500 * time.Millisecond config.WorkerTaskTimeout = 1 * time.Minute config.WorkerManagersStopTimeout = 1 * time.Minute @@ -298,6 +299,10 @@ func (c *ConsumerConfig) Validate() error { return errors.New("Please provide a WorkerFailedAttemptCallback") } + if c.WorkerThresholdTimeWindow < time.Millisecond { + return errors.New("WorkerThresholdTimeWindow must be at least 1ms") + } + if c.Strategy == nil { return errors.New("Please provide a Strategy") }
Added default WorkerThresholdTimeWindow config that caused high CPU usage while being idle. re #1
elodina_go_kafka_client
train
62e8993f734cbc3acfdfa0bbf3e19406dcfa57f1
diff --git a/src/BoomCMS/Policies/PagePolicy.php b/src/BoomCMS/Policies/PagePolicy.php index <HASH>..<HASH> 100644 --- a/src/BoomCMS/Policies/PagePolicy.php +++ b/src/BoomCMS/Policies/PagePolicy.php @@ -28,6 +28,18 @@ class PagePolicy extends BoomCMSPolicy return true; } - return parent::check($role, $person, $page); + do { + $result = parent::check($role, $person, $page); + + if ($page->getParentId() === null) { + break; + } + + if ($result === null) { + $page = $page->getParent(); + } + } while ($result === null && $page !== null); + + return (bool) $result; } }
Fixed page permissions not cascading down tree
boomcms_boom-core
train
88ad193bbafa9661edf8110287b4ea79187af71e
diff --git a/collection.go b/collection.go index <HASH>..<HASH> 100644 --- a/collection.go +++ b/collection.go @@ -39,10 +39,12 @@ type ValidationError struct { } type TimeCreatedTracker interface { + GetCreated() time.Time SetCreated(time.Time) } type TimeModifiedTracker interface { + GetModified() time.Time SetModified(time.Time) } diff --git a/collection_test.go b/collection_test.go index <HASH>..<HASH> 100644 --- a/collection_test.go +++ b/collection_test.go @@ -122,11 +122,11 @@ func TestCollection(t *testing.T) { err := conn.Collection("tests").Save(doc) So(err, ShouldEqual, nil) - So(doc.Created.UnixNano(), ShouldEqual, doc.Modified.UnixNano()) + So(doc.Created.UnixNano(), ShouldEqual, doc.GetModified().UnixNano()) err = conn.Collection("tests").Save(doc) So(err, ShouldEqual, nil) - So(doc.Modified.UnixNano(), ShouldBeGreaterThan, doc.Created.UnixNano()) + So(doc.Modified.UnixNano(), ShouldBeGreaterThan, doc.GetCreated().UnixNano()) }) Reset(func() { diff --git a/documentBase.go b/documentBase.go index <HASH>..<HASH> 100644 --- a/documentBase.go +++ b/documentBase.go @@ -36,6 +36,14 @@ func (d *DocumentBase) SetCreated(t time.Time) { d.Created = t } +func (d *DocumentBase) GetCreated() time.Time { + return d.Created +} + func (d *DocumentBase) SetModified(t time.Time) { d.Modified = t } + +func (d *DocumentBase) GetModified() time.Time { + return d.Modified +}
Added `GetCreated` to `TimeCreatedTracker` and `GetModified` to `TimeModifiedTracker`
go-bongo_bongo
train
b45a12e3544b4c246d160a1e17f47ec25d0f03bb
diff --git a/components/user-agreement/service.js b/components/user-agreement/service.js index <HASH>..<HASH> 100644 --- a/components/user-agreement/service.js +++ b/components/user-agreement/service.js @@ -145,12 +145,13 @@ export default class UserAgreementService { } this._alertPromise = new Promise((resolve, reject) => { const {userAgreement, reviewNow, remindLater} = (this.config.translations || {}); - const onReview = () => this.showDialog(true).then(resolve); const onRemind = () => { this.hideDialogAndAlert(withoutNotifications); reject('Postponed'); }; + const onReview = () => this.showDialog(true, false, {onRemindLater: onRemind}).then(resolve); + const message = ( <Group> <span>{userAgreement || 'User Agreement'}</span> @@ -184,7 +185,7 @@ export default class UserAgreementService { } } - showDialog = (withoutNotifications, preview = false) => { + showDialog = (withoutNotifications, preview = false, restOptions) => { const {translations, onDialogShow} = this.config; const {text} = this.userAgreement; const show = true; @@ -203,7 +204,15 @@ export default class UserAgreementService { const onClose = this.hideDialogAndAlert; - const props = {text, show, onAccept, onDecline, onClose, translations, preview}; + const props = { + text, + show, + onAccept, + onDecline, + onClose, + translations, + preview, ...restOptions + }; render( <UserAgreement {...props}/>, diff --git a/components/user-agreement/user-agreement.css b/components/user-agreement/user-agreement.css index <HASH>..<HASH> 100644 --- a/components/user-agreement/user-agreement.css +++ b/components/user-agreement/user-agreement.css @@ -15,7 +15,13 @@ } .suggestion { + padding-bottom: unit; + white-space: nowrap; font-size: 12px; } + +.remindLaterButton { + float: right; +} diff --git a/components/user-agreement/user-agreement.js b/components/user-agreement/user-agreement.js index <HASH>..<HASH> 100644 --- a/components/user-agreement/user-agreement.js +++ b/components/user-agreement/user-agreement.js @@ -27,6 +27,7 @@ export default class UserAgreement extends PureComponent { onAccept: PropTypes.func.isRequired, onDecline: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, + onRemindLater: PropTypes.func, translations: PropTypes.object }; @@ -35,7 +36,8 @@ export default class UserAgreement extends PureComponent { accept: 'Accept', decline: 'Decline', close: 'Close', - scrollToAccept: 'View the entire agreement to continue' + scrollToAccept: 'View the entire agreement to continue', + remindLater: 'Remind me later' }, show: false }; @@ -48,7 +50,8 @@ export default class UserAgreement extends PureComponent { render() { const {scrolledDown} = this.state; - const {translations, onAccept, onDecline, onClose, text, show, preview} = this.props; + // eslint-disable-next-line max-len + const {translations, onAccept, onDecline, onClose, onRemindLater, text, show, preview} = this.props; return ( <Dialog @@ -67,13 +70,22 @@ export default class UserAgreement extends PureComponent { </Content> {!preview && ( <Panel> + {onRemindLater && !scrolledDown && ( + <div className={style.suggestion}>{translations.scrollToAccept}</div> + )} <Button primary disabled={!scrolledDown} onClick={onAccept}> {translations.accept} </Button> <Button onClick={onDecline} autoFocus>{translations.decline}</Button> - {!scrolledDown && ( + + {!onRemindLater && !scrolledDown && ( <span className={style.suggestion}>{translations.scrollToAccept}</span> )} + {onRemindLater && ( + <Button className={style.remindLaterButton} onClick={onRemindLater}> + {translations.remindLater} + </Button> + )} </Panel> )} {preview && (
RG-<I> support postponing EUA for guest right on the modal dialog
JetBrains_ring-ui
train
012345328cb3f73e915e7efcb4bcdb64fbc35655
diff --git a/pycanlib/CAN.py b/pycanlib/CAN.py index <HASH>..<HASH> 100644 --- a/pycanlib/CAN.py +++ b/pycanlib/CAN.py @@ -43,7 +43,7 @@ TRANS_SN_ARRAY = ctypes.c_ubyte * MAX_TRANS_SN_LENGTH class Message(object): - def __init__(self, timestamp=0.0, is_remote_frame=False, id_type=ID_TYPE_11_BIT, is_wakeup=(not WAKEUP_MSG), is_error_frame=(not ERROR_FRAME), arbitration_id=0, data=[], dlc=0, info_string=""): + def __init__(self, timestamp=0.0, is_remote_frame=False, id_type=ID_TYPE_11_BIT, is_wakeup=(not WAKEUP_MSG), is_error_frame=(not ERROR_FRAME), arbitration_id=0, data=[], dlc=0, info_strings=[]): self.timestamp = timestamp self.is_remote_frame = is_remote_frame self.id_type = id_type @@ -52,7 +52,7 @@ class Message(object): self.arbitration_id = arbitration_id self.data = data self.dlc = dlc - self.info_string = info_string + self.info_strings = info_strings @property def timestamp(self): @@ -176,13 +176,15 @@ class Message(object): self.__flags = value @property - def info_string(self): - return self.__info_string + def info_strings(self): + return self.__info_strings - @info_string.setter - def info_string(self, value): - InputValidation.verify_parameter_type("@info_string.setter", "info_string", value, types.StringType) - self.__info_string = value + @info_strings.setter + def info_strings(self, value): + InputValidation.verify_parameter_type("@info_strings.setter", "info_strings", value, types.ListType) + for (_index, _string) in enumerate(value): + InputValidation.verify_parameter_type("@info_strings.setter", "info_strings[%d]" % _index, _string, types.StringType) + self.__info_strings = value def check_equality(self, other, fields): InputValidation.verify_parameter_type("check_equality", "other", other, Message) @@ -214,9 +216,9 @@ class Message(object): _data_strings.append("%.2x" % byte) if len(_data_strings) > 0: _field_strings.append(" ".join(_data_strings)) - if len(self.info_string) > 0: - _field_strings.append(self.info_string) - return "\t".join(_field_strings) + _current_length = len(" ".join(_field_strings)) + _field_strings.append(("\n" + (" " * (_current_length + 4))).join(self.info_strings)) + return " ".join(_field_strings) class MessageList(object):
Single CAN messages can now have multiple information message strings attached to them
hardbyte_python-can
train
5a324c63f71d4c3ae71bc534221a740648a3bbc9
diff --git a/frontdoor.js b/frontdoor.js index <HASH>..<HASH> 100644 --- a/frontdoor.js +++ b/frontdoor.js @@ -2,6 +2,7 @@ var Route = require("./lib/route"); var Section = require("./lib/section"); +var Types = require("./lib/types"); var middleware = require("./lib/middleware"); var Api = require("./lib/api"); @@ -11,6 +12,7 @@ module.exports = function(description) { module.exports.Section = Section; module.exports.Route = Route; +module.exports.Types = Types; module.exports.middleware = middleware; diff --git a/lib/middleware.js b/lib/middleware.js index <HASH>..<HASH> 100644 --- a/lib/middleware.js +++ b/lib/middleware.js @@ -4,7 +4,7 @@ var error = require("http-error"); exports.jsonWriter = function() { return function(req, res, next) { - res.json = function(json, headers) { + res.json = function(json, headers, code) { var data; try { data = JSON.stringify(json); @@ -18,7 +18,7 @@ exports.jsonWriter = function() { headers = headers || {}; headers["Content-Type"] = "application/json"; - res.writeHead(200, headers); + res.writeHead(code || 200, headers); res.end(data); }; diff --git a/lib/route.js b/lib/route.js index <HASH>..<HASH> 100644 --- a/lib/route.js +++ b/lib/route.js @@ -62,7 +62,7 @@ module.exports = function Route(route, options, handler, types) { } path = path - .replace(/\/:(\w+)/g, function(match, key) { + .replace(/\/:([\w\.\-\_]+)(\*?)/g, function(match, key, wildcard) { keys.push(key); if (!params[key]) { params[key] = {}; @@ -75,9 +75,13 @@ module.exports = function Route(route, options, handler, types) { param.source = "url"; else throw new Error("Url parameters must have 'url' as source but found '" + param.source + "'"); - return "\/([^\\/]+)"; + if (wildcard) + return "(/*)"; + else + return "/([^\\/]+)"; }) - .replace(/([\/.])/g, '\\$1'); + .replace(/([\/.])/g, '\\$1') + .replace(/\*/g, '(.*)'); return new RegExp('^' + path + '$'); } @@ -224,6 +228,9 @@ module.exports = function Route(route, options, handler, types) { else { if (value !== EMPTY) req.params[key] = value; + else if ("default" in param) + req.params[key] = param.default + } } } diff --git a/lib/route_test.js b/lib/route_test.js index <HASH>..<HASH> 100644 --- a/lib/route_test.js +++ b/lib/route_test.js @@ -40,6 +40,30 @@ module.exports = { assert.equal(route.lastMatch.id, 123); }, + "test router: complex route with wildcard arguments": function() { + var route = new Route("/user/:name/:rest*", { + params: { + id: { + type: "int" + }, + rest: { + type: "string" + } + } + }, sinon.stub()); + + assert.equal(route.match("/user/fabian"), false); + assert.equal(route.match("/user/fabian/"), true); + assert.equal(route.lastMatch.name, "fabian"); + assert.equal(route.lastMatch.rest, "/"); + assert.equal(route.match("/user/fabian/abc"), true); + assert.equal(route.lastMatch.name, "fabian"); + assert.equal(route.lastMatch.rest, "/abc"); + assert.equal(route.match("/user/fabian/abc/123"), true); + assert.equal(route.lastMatch.name, "fabian"); + assert.equal(route.lastMatch.rest, "/abc/123"); + }, + "test router: complex route with multiple arguments": function() { var route = new Route("/user/:name/:id", { params: { diff --git a/lib/section.js b/lib/section.js index <HASH>..<HASH> 100644 --- a/lib/section.js +++ b/lib/section.js @@ -32,6 +32,15 @@ module.exports = function Section(name, description, types) { this.registerType = types.register.bind(types); + this.all = function(method, route, options, handler) { + var self = this; + var args = arguments; + + methods.forEach(function(method) { + self[method].apply(self, args); + }); + }; + this.use = function(middleware) { this.middlewares.push(middleware); }; diff --git a/lib/types.js b/lib/types.js index <HASH>..<HASH> 100644 --- a/lib/types.js +++ b/lib/types.js @@ -110,7 +110,10 @@ exports.Number.prototype.check = function(value) { return typeof value == "number"; }; -exports.Integer = function() {}; +exports.Integer = function(min, max) { + this.min = min === undefined ? Number.MIN_VALUE : min; + this.max - max === undefined ? Number.MAX_VALUE : max; +}; inherits(exports.Integer, exports.Type); exports.Integer.prototype.parse = function(string) { return parseInt(string, 10);
Add support for wildcard url params and for "all" routes
cloud9ide_frontdoor
train
d0a518d0216a0e22561d5ba8fe68889863caae08
diff --git a/AppiumLibrary/keywords/_screenshot.py b/AppiumLibrary/keywords/_screenshot.py index <HASH>..<HASH> 100644 --- a/AppiumLibrary/keywords/_screenshot.py +++ b/AppiumLibrary/keywords/_screenshot.py @@ -4,6 +4,7 @@ import os import robot from .keywordgroup import KeywordGroup +EMBED = "EMBED" class _ScreenshotKeywords(KeywordGroup): @@ -22,21 +23,30 @@ class _ScreenshotKeywords(KeywordGroup): also considered relative to the same directory, if it is not given in absolute format. + If `filename` equals to EMBED (case insensitive), then screenshot is + embedded as Base64 image to the log.html. + In this case no file is created in the filesystem. + `css` can be used to modify how the screenshot is taken. By default the background color is changed to avoid possible problems with background leaking when the page layout is somehow broken. """ - path, link = self._get_screenshot_paths(filename) - - if hasattr(self._current_application(), 'get_screenshot_as_file'): - self._current_application().get_screenshot_as_file(path) + if filename and filename.casefold() == EMBED.casefold(): + base64_screenshot = self._current_application().get_screenshot_as_base64() + self._html('</td></tr><tr><td colspan="3">' + '<img src="data:image/png;base64, %s" width="800px">' % base64_screenshot) else: - self._current_application().save_screenshot(path) + path, link = self._get_screenshot_paths(filename) + + if hasattr(self._current_application(), 'get_screenshot_as_file'): + self._current_application().get_screenshot_as_file(path) + else: + self._current_application().save_screenshot(path) - # Image is shown on its own row and thus prev row is closed on purpose - self._html('</td></tr><tr><td colspan="3"><a href="%s">' - '<img src="%s" width="800px"></a>' % (link, link)) - return path + # Image is shown on its own row and thus prev row is closed on purpose + self._html('</td></tr><tr><td colspan="3"><a href="%s">' + '<img src="%s" width="800px"></a>' % (link, link)) + return path # Private diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -37,7 +37,7 @@ setup(name='robotframework-appiumlibrary', 'robotframework >= 2.6.0', 'docutils >= 0.8.1', 'Appium-Python-Client >= 1.1.0', - 'selenium >= 2.47.1, < 4', + 'selenium >= 2.47.1', 'kitchen >= 1.2.4', 'six >= 1.10.0' ],
Add a parameter to embed screenshot in log.html as base<I> contents. (a first step regarding issue #<I>)
serhatbolsu_robotframework-appiumlibrary
train
a53ab747fab3b8514bb461ce56f49a7fdc3a462f
diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -1257,9 +1257,9 @@ abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializab * @param mixed $value * @return \Illuminate\Database\Eloquent\Model|null */ - public function resolveRouteBinding($routeKey) + public function resolveRouteBinding($value) { - return $this->where($this->getRouteKeyName(), $routeKey)->first(); + return $this->where($this->getRouteKeyName(), $value)->first(); } /**
routeKey -> value (#<I>)
laravel_framework
train
50987d04ea0ef603b722ff200f66c4c39ca99849
diff --git a/course/lib.php b/course/lib.php index <HASH>..<HASH> 100644 --- a/course/lib.php +++ b/course/lib.php @@ -2558,7 +2558,7 @@ function update_course($data, $editoroptions = NULL) { // The summary might be very long, we don't wan't to fill up the log record with the full text. $updatedfields[$field] = '(updated)'; } - } else if ($field == 'tags') { + } else if ($field == 'tags' && !empty($CFG->usetags)) { // Tags might not have the same array keys, just check the values. if (array_values($data->$field) !== array_values($value)) { $updatedfields[$field] = $data->$field;
MDL-<I> course: Make sure tags are on when logging updated settings
moodle_moodle
train
9974568598f419733038b45fc977990d3337e836
diff --git a/cumulusci/tasks/salesforce.py b/cumulusci/tasks/salesforce.py index <HASH>..<HASH> 100644 --- a/cumulusci/tasks/salesforce.py +++ b/cumulusci/tasks/salesforce.py @@ -1311,30 +1311,30 @@ class RunApexTests(BaseSalesforceToolingApiTask): ) def _wait_for_tests(self): - poll_interval = int(self.options.get('poll_interval', 1)) - while True: - self._retry() - counts = { - 'Aborted': 0, - 'Completed': 0, - 'Failed': 0, - 'Holding': 0, - 'Preparing': 0, - 'Processing': 0, - 'Queued': 0, - } - for test_queue_item in self.result['records']: - counts[test_queue_item['Status']] += 1 - self.logger.info('Completed: {} Processing: {} Queued: {}' - .format( - counts['Completed'], - counts['Processing'], - counts['Queued'], - )) - if counts['Queued'] == 0 and counts['Processing'] == 0: - self.logger.info('Apex tests completed') - break - time.sleep(poll_interval) + self._poll_interval_s = int(self.options.get('poll_interval', 1)) + self._poll() + + def _poll_action(self): + self._retry() + counts = { + 'Aborted': 0, + 'Completed': 0, + 'Failed': 0, + 'Holding': 0, + 'Preparing': 0, + 'Processing': 0, + 'Queued': 0, + } + for test_queue_item in self.result['records']: + counts[test_queue_item['Status']] += 1 + self.logger.info('Completed: {} Processing: {} Queued: {}'.format( + counts['Completed'], + counts['Processing'], + counts['Queued'], + )) + if counts['Queued'] == 0 and counts['Processing'] == 0: + self.logger.info('Apex tests completed') + self.poll_complete = True def _try(self): self.result = self.tooling.query_all(
use _poll() for checking test results
SFDO-Tooling_CumulusCI
train
0e5273221da416a09939c9a80392acd98c6cd5bf
diff --git a/cookiecutter/main.py b/cookiecutter/main.py index <HASH>..<HASH> 100755 --- a/cookiecutter/main.py +++ b/cookiecutter/main.py @@ -37,11 +37,9 @@ def cookiecutter(input_dir, checkout=None, no_input=False): # If it's a git repo, clone if input_dir.endswith('.git'): - got_repo_arg = True repo_dir = git_clone(input_dir, checkout) else: # If it's a local repo, set flag so it doesn't get deleted later - got_repo_arg = False repo_dir = input_dir context_file = os.path.join(repo_dir, 'cookiecutter.json') @@ -63,13 +61,6 @@ def cookiecutter(input_dir, checkout=None, no_input=False): context=context ) - # Remove repo if Cookiecutter cloned it in the first place. - # Here the user just wants a project, not a project template. - if got_repo_arg: - generated_project = context['cookiecutter']['repo_name'] - remove_repo(repo_dir, generated_project) - - def parse_cookiecutter_args(args): """ Parse the command-line arguments to Cookiecutter. """ diff --git a/tests/test_main.py b/tests/test_main.py index <HASH>..<HASH> 100755 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -99,7 +99,7 @@ class TestCookiecutterRepoArg(unittest.TestCase): sys.stdin = StringIO('\n\n\n\n\n\n\n\n\n') main.cookiecutter('https://github.com/audreyr/cookiecutter-pypackage.git') logging.debug('Current dir is {0}'.format(os.getcwd())) - self.assertFalse(os.path.exists('cookiecutter-pypackage')) + self.assertTrue(os.path.exists('cookiecutter-pypackage')) self.assertTrue(os.path.isdir('boilerplate')) self.assertTrue(os.path.isfile('boilerplate/README.rst')) self.assertTrue(os.path.exists('boilerplate/setup.py'))
Don't delete the repo anymore, as per my comments today in #<I>.
audreyr_cookiecutter
train
28acfcf69ef51da6c0d1094ec292815ba63d81d5
diff --git a/api/unit/unit.go b/api/unit/unit.go index <HASH>..<HASH> 100644 --- a/api/unit/unit.go +++ b/api/unit/unit.go @@ -33,3 +33,9 @@ func (u *Unit) RemoveRelation(su *Unit) error { log.Printf("unrelating %s with service %s", u.Name, su.Name) return cmd.Start() } + +func (u *Unit) Command(command string) ([]byte, error) { + cmd := exec.Command("juju", "scp", "-o", "'StrictHostKeyChecking'", "no", u.Name+"/0", command) + log.Printf("executing %s on %s", command, u.Name) + return cmd.Output() +} diff --git a/api/unit/unit_test.go b/api/unit/unit_test.go index <HASH>..<HASH> 100644 --- a/api/unit/unit_test.go +++ b/api/unit/unit_test.go @@ -31,6 +31,20 @@ func (s *S) TestCreateAndDestroy(c *C) { c.Assert(err, IsNil) } +func (s *S) TestCommand(c *C) { + u := unit.Unit{Type: "django", Name: "myUnit"} + + err := u.Create() + c.Assert(err, IsNil) + + output, err := u.Command("uname") + c.Assert(err, IsNil) + c.Assert(string(output), Equals, "Linux") + + err = u.Destroy() + c.Assert(err, IsNil) +} + func (s *S) TestAddRelation(c *C) { appUnit := unit.Unit{Type: "django", Name: "myUnit"} serviceUnit := unit.Unit{Type: "mysql", Name: "MyService"}
added unit.Command to run a command in an unit
tsuru_tsuru
train
e712214c6a161b741d6a9d52055aaadde7c7f867
diff --git a/gql/transport/requests.py b/gql/transport/requests.py index <HASH>..<HASH> 100644 --- a/gql/transport/requests.py +++ b/gql/transport/requests.py @@ -29,6 +29,7 @@ class RequestsHTTPTransport(Transport): timeout=None, # type: int verify=True, # type: bool retries=0, # type: int + method="POST", # type: str **kwargs # type: Any ): """Initialize the transport with the given request parameters. @@ -43,6 +44,7 @@ class RequestsHTTPTransport(Transport): the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. (Default: True). :param retries: Pre-setup of the requests' Session for performing retries + :param method: HTTP method used for requests. (Default: POST). :param kwargs: Optional arguments that ``request`` takes. These can be seen at the :requests_: source code or the official :docs_: @@ -56,6 +58,7 @@ class RequestsHTTPTransport(Transport): self.use_json = use_json self.default_timeout = timeout self.verify = verify + self.method = method self.kwargs = kwargs # Creating a session that can later be re-use to configure custom mechanisms @@ -101,7 +104,7 @@ class RequestsHTTPTransport(Transport): post_args.update(self.kwargs) # Using the created session to perform requests - response = self.session.post(self.url, **post_args) # type: ignore + response = self.session.request(self.method, self.url, **post_args) # type: ignore try: result = response.json() if not isinstance(result, dict): diff --git a/tests/test_client.py b/tests/test_client.py index <HASH>..<HASH> 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -167,6 +167,37 @@ def test_http_transport_verify_error(http_transport_query): assert "Unverified HTTPS request is being made to host" in str(record[0].message) +def test_http_transport_specify_method_valid(http_transport_query): + client = Client( + transport=RequestsHTTPTransport( + url="https://countries.trevorblades.com/", + use_json=True, + headers={"Content-type": "application/json"}, + method="POST", + ) + ) + + result = client.execute(http_transport_query) + client.close() + assert result is not None + + +def test_http_transport_specify_method_invalid(http_transport_query): + client = Client( + transport=RequestsHTTPTransport( + url="https://countries.trevorblades.com/", + use_json=True, + headers={"Content-type": "application/json"}, + method="GET", + ) + ) + + with pytest.raises(Exception) as exc_info: + client.execute(http_transport_query) + client.close() + assert "400 Client Error: Bad Request for url" in str(exc_info.value) + + def test_gql(): sample_path = os.path.join( os.path.dirname(os.path.abspath(__file__)),
Allows for custom/any HTTP method (other than POST) (#<I>)
graphql-python_gql
train
5ba82a5eb2774c212c6678052559fe1486fe0b70
diff --git a/tests/src/main/java/org/hibernate/beanvalidation/tck/tests/metadata/PropertyDescriptorTest.java b/tests/src/main/java/org/hibernate/beanvalidation/tck/tests/metadata/PropertyDescriptorTest.java index <HASH>..<HASH> 100644 --- a/tests/src/main/java/org/hibernate/beanvalidation/tck/tests/metadata/PropertyDescriptorTest.java +++ b/tests/src/main/java/org/hibernate/beanvalidation/tck/tests/metadata/PropertyDescriptorTest.java @@ -157,7 +157,9 @@ public class PropertyDescriptorTest extends AbstractTCKTest { } @Test - // FIXME: update spec assertions + @SpecAssertion(section = Sections.CONSTRAINTMETADATA_CONTAINERDESCRIPTOR, id = "a") + @SpecAssertion(section = Sections.CONSTRAINTMETADATA_CONTAINERDESCRIPTOR, id = "b") + @SpecAssertion(section = Sections.CONSTRAINTMETADATA_CONTAINERDESCRIPTOR, id = "c") public void testGetContainerElementTypes() { PropertyDescriptor descriptor = getPropertyDescriptor( ComplexOrder.class, "orderLines" );
BVTCK-<I> Update assertion references
beanvalidation_beanvalidation-tck
train
65449c1e589bab58b97dba1ea394ba80d50900b8
diff --git a/packages/core/resolve-redux/src/create_view_models_reducer.js b/packages/core/resolve-redux/src/create_view_models_reducer.js index <HASH>..<HASH> 100644 --- a/packages/core/resolve-redux/src/create_view_models_reducer.js +++ b/packages/core/resolve-redux/src/create_view_models_reducer.js @@ -165,8 +165,9 @@ export default function createViewModelsReducer(viewModels) { const aggregateKeys = Array.from( new Set(aggregateHash.get(action.aggregateId)) ) - if (aggregateKeys) { - for (const aggregateKey of aggregateKeys) { + + for (const aggregateKey of aggregateKeys) { + if (state[viewModel.name] && state[viewModel.name][aggregateKey]) { for (const aggregateArgs of Object.keys( state[viewModel.name][aggregateKey] )) {
Fix no wildcard viewmodel event apply (#<I>)
reimagined_resolve
train
65459afb48600f85d0a4ed9978d03076d8387024
diff --git a/core/src/main/java/com/capitalone/dashboard/model/Dashboard.java b/core/src/main/java/com/capitalone/dashboard/model/Dashboard.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/capitalone/dashboard/model/Dashboard.java +++ b/core/src/main/java/com/capitalone/dashboard/model/Dashboard.java @@ -17,7 +17,6 @@ public class Dashboard extends BaseModel { private List<Widget> widgets = new ArrayList<>(); private String owner; private DashboardType type; - private List<TeamDashboard> teamDashboards = new ArrayList<>(); //Only used for team dashboards private Application application; @@ -73,13 +72,4 @@ public class Dashboard extends BaseModel { public void setType(DashboardType type) { this.type = type; } - public List<TeamDashboard> getTeamDashboards() { return this.teamDashboards; } - - public void setTeamDashboards(List<TeamDashboard> teamDashboards) { this.teamDashboards = teamDashboards; } - - public void addTeamDashboard(TeamDashboard teamDashboard){ - this.teamDashboards.add(teamDashboard); - } - - }
Missed removing this reference to TeamDashboard type on the Dashboard model object.
Hygieia_Hygieia
train
0fbe6e103c4f86903368e5edf864c040f18ed800
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -1,15 +1,17 @@ var Promise = require('bluebird'); var phantom = require('phantom'); +var util = require('util'); +var EventEmitter = require('events').EventEmitter; module.exports = Phantasma = function () { - + EventEmitter.call(this); this.ph = null; this.page = null; - }; +util.inherits(Phantasma, EventEmitter); + Phantasma.prototype.go = function (url) { - console.log('go', url); var self = this; if(this.ph && this.page){ return this.open(url); @@ -29,6 +31,9 @@ Phantasma.prototype.init = function () { self.ph = ph; ph.createPage(function (page) { self.page = page; + page.set('onLoadFinished', function (status) { + self.emit('onLoadFinished', status); + }); resolve(); }); }); @@ -49,13 +54,44 @@ Phantasma.prototype.open = function (url) { }; Phantasma.prototype.exit = function () { - console.log('exit'); this.ph.exit(); }; +Phantasma.prototype.wait = function () { + var self = this; + + return new Promise(function (resolve, reject) { + self.once('onLoadFinished', function (status) { + resolve(status); + }); + }); +}; + Phantasma.prototype.evaluate = function (fn) { var self = this; + + var args = [].slice.call(arguments); return new Promise(function (resolve, reject) { - self.page.evaluate(fn, resolve); + args = [fn, resolve].concat(args.slice(1)); + self.page.evaluate.apply(null, args); }); +}; + +Phantasma.prototype.type = function (element, value) { + var self = this; + + return this.evaluate(function (element, value) { + document.querySelector(element).value = value; + }, element, value); +}; + +Phantasma.prototype.click = function (element) { + var self = this; + + return this.evaluate(function (element) { + var evt = document.createEvent('MouseEvent'); + evt.initEvent('click', true, true); + var ele = document.querySelector(element); + ele.dispatchEvent(evt); + }, element); }; \ No newline at end of file
added wait, type, click. added args to evaluate
petecoop_phantasma
train
5c3ebf28559e8ce7e07fc5c8e965916808d7fc20
diff --git a/src/bosh/infrastructure/device_path_resolver/vsphere_device_path_resolver.go b/src/bosh/infrastructure/device_path_resolver/vsphere_device_path_resolver.go index <HASH>..<HASH> 100644 --- a/src/bosh/infrastructure/device_path_resolver/vsphere_device_path_resolver.go +++ b/src/bosh/infrastructure/device_path_resolver/vsphere_device_path_resolver.go @@ -59,6 +59,8 @@ func (devicePathResolver vsphereDevicePathResolver) GetRealDevicePath(devicePath if err != nil || len(devicePaths) == 0 { time.Sleep(devicePathResolver.diskWaitTimeout) continue + } else { + break } } diff --git a/src/bosh/infrastructure/device_path_resolver/vsphere_device_path_resolver_test.go b/src/bosh/infrastructure/device_path_resolver/vsphere_device_path_resolver_test.go index <HASH>..<HASH> 100644 --- a/src/bosh/infrastructure/device_path_resolver/vsphere_device_path_resolver_test.go +++ b/src/bosh/infrastructure/device_path_resolver/vsphere_device_path_resolver_test.go @@ -63,6 +63,23 @@ var _ = Describe("VSphere Path Resolver", func() { }) }) + Context("when device is found", func() { + It("does not retry detection of device", func() { + fs.SetGlob("/sys/bus/scsi/devices/fake-host-id:0:fake-disk-id:0/block/*", + []string{"/sys/bus/scsi/devices/fake-host-id:0:fake-disk-id:0/block/sdf"}, + []string{}, + []string{}, + []string{}, + []string{}, + []string{"/sys/bus/scsi/devices/fake-host-id:0:fake-disk-id:0/block/bla"}, + ) + + devicePath, err := resolver.GetRealDevicePath("fake-disk-id") + Expect(err).NotTo(HaveOccurred()) + Expect(devicePath).To(Equal("/dev/sdf")) + }) + }) + Context("when device never appears", func() { It("returns not err", func() { fs.SetGlob("/sys/bus/scsi/devices/fake-host-id:0:fake-disk-id:0/block/*", []string{})
Do not retry to find device path once it is found
cloudfoundry_bosh-agent
train
78a6e0612a5aaba4f7cb0c9c78240ed38018a136
diff --git a/src/Search/Mapper.php b/src/Search/Mapper.php index <HASH>..<HASH> 100644 --- a/src/Search/Mapper.php +++ b/src/Search/Mapper.php @@ -126,6 +126,8 @@ class Mapper public function toGoogle(Document $obj_source, GoogleDocument $obj_target) { $obj_target->setId($obj_source->getId()); + + // Field data foreach($obj_source->getSchema()->getFields() as $str_name => $int_type) { $obj_value = $obj_target->addField()->setName($str_name)->mutableValue(); if(Schema::FIELD_GEOPOINT === $int_type) { @@ -155,6 +157,17 @@ class Mapper } } } + + // Facets + foreach($obj_source->getFacets() as $arr_facet) { + $obj_facet = $obj_target->addFacet()->setName($arr_facet['name']); + if(isset($arr_facet['atom'])) { + $obj_facet->mutableValue()->setType(\storage_onestore_v3\FacetValue\ContentType::ATOM)->setStringValue($arr_facet['atom']); + } elseif (isset($arr_facet['number'])) { + $obj_facet->mutableValue()->setType(\storage_onestore_v3\FacetValue\ContentType::NUMBER)->setStringValue($arr_facet['number']); + } + } + return $obj_target; }
Mapping facets to Google search index
tomwalder_php-appengine-search
train
a67ec79e4e6c1ca3d0e05837dbf8cefeef3bdcb3
diff --git a/baron/baron.py b/baron/baron.py index <HASH>..<HASH> 100644 --- a/baron/baron.py +++ b/baron/baron.py @@ -43,7 +43,12 @@ def parse(source_code, print_function=None): if source_code and source_code[-1] != "\n": source_code += "\n" - return _parse(tokenize(source_code, print_function), print_function)[:-1] + to_return = _parse(tokenize(source_code, print_function), print_function) + + if to_return[-1]["type"] == "endl": + return to_return[:-1] + else: + return to_return return _parse(tokenize(source_code, print_function), print_function)
[fix] in special case, the last token is not an endl token
PyCQA_baron
train
28c60ebbeb4750eda02409b6b7d465bfa61809a8
diff --git a/src/index.test.js b/src/index.test.js index <HASH>..<HASH> 100644 --- a/src/index.test.js +++ b/src/index.test.js @@ -123,7 +123,7 @@ test('\'merge\' reducer only merge the existent field of state', () => { name: 'merge', job: 'student', information: { - height: 180, + height: 150, address: 'test address' } } @@ -135,7 +135,7 @@ test('\'merge\' reducer only merge the existent field of state', () => { expect(state.test.job).toBeUndefined() // ignore 'information.address' expect(state.test.information).toEqual({ - height: 180, + height: 150, weight: 200 }) })
[test] differ the action payload and origin state
Fullstop000_redux-sirius
train
7019f7b310d28113f52cc58c3a681fc986ea6f9e
diff --git a/pebble/pebble.py b/pebble/pebble.py index <HASH>..<HASH> 100644 --- a/pebble/pebble.py +++ b/pebble/pebble.py @@ -14,6 +14,19 @@ # along with Pebble. If not, see <http://www.gnu.org/licenses/>. +from functools import wraps + + +def coroutine(func): + @wraps(func) + def start(*args, **kwargs): + cr = func(*args, **kwargs) + cr.next() + return cr + + return start + + class PebbleError(Exception): """Pebble base exception.""" pass diff --git a/pebble/process.py b/pebble/process.py index <HASH>..<HASH> 100644 --- a/pebble/process.py +++ b/pebble/process.py @@ -36,7 +36,7 @@ try: # Python 2 except: # Python 3 from pickle import PicklingError -from .pebble import TimeoutError, TaskCancelled +from .pebble import TimeoutError, TaskCancelled, coroutine STOPPED = 0 @@ -153,9 +153,6 @@ class Task(object): self._worker = worker self._timeout = timeout self._callback = callback - self._worker_listener = Thread(target=self._set) - self._worker_listener.daemon = True - self._worker_listener.start() def __str__(self): return self.__repr__() @@ -251,7 +248,9 @@ class ProcessPool(object): self._workers = workers self._limit = task_limit self._pool = [] + self._tasks = {} self._state = RUNNING + self._task_scheduler = self._dispatch_tasks() self.initializer = initializer self.initargs = initargs @@ -271,26 +270,30 @@ class ProcessPool(object): def _maintain_pool(self): while self._state != STOPPED: - workers = [] expired = [w for w in self._pool if not w.is_alive()] self._pool = [w for w in self._pool if w not in expired] + # join expired processes for w in expired: w.join() + # re-spawn missing processes for _ in range(self._workers - len(self._pool)): - w = Worker(self._queue, self._limit, + w = Worker(self._limit, None, self.initializer, self.initargs) w.start() - workers.append(w) - self._pool.extend(workers) - self._dispatch_tasks.send(workers) + w.taskin.close() + w.resout.close() + self._pool.append(w) + self._task_scheduler.send(w) + sleep(0.6) def _manage_results(self): while self._state != STOPPED: - ready, _, _ = select([w.resout for w in self._pool], [], []) + ready, _, _ = select([w.resin for w in self._pool], [], []) workers = [w for w in self._pool if w.resout in ready] - self._dispatch_tasks.send(workers) + print ready, workers for w in workers: + self._task_scheduler.send(w) try: results = w.resout.recv() task = self._tasks[w] @@ -300,13 +303,16 @@ class ProcessPool(object): finally: del self._tasks[w] + @coroutine def _dispatch_tasks(self): - workers = (yield) - for w in workers: + while self._state != STOPPED: + worker = (yield) t = self._queue.get() try: - w.taskin.send(tuple(t[1:])) - self._tasks[w] = t[0] + worker.taskout.send(tuple(t[1:])) + task = t[0] + task._worker = worker + self._tasks[worker] = task except (IOError, OSError, EOFError): # closed pipe self._queue.put(t) @@ -368,7 +374,7 @@ class ProcessPool(object): self._pool_maintainer.start() if not self._results_handler.is_alive(): self._results_handler.start() - task = Task(next(self._counter), callback) + task = Task(next(self._counter), None, callback, timeout) self._queue.put((task, function, args, kwargs)) return task
some further progress in ProcessPool
noxdafox_pebble
train
b56573d5f6dbf01507f18bafda62ba31f39ef944
diff --git a/cilium-net-daemon/main.go b/cilium-net-daemon/main.go index <HASH>..<HASH> 100644 --- a/cilium-net-daemon/main.go +++ b/cilium-net-daemon/main.go @@ -138,6 +138,16 @@ func init() { setupLOG() + if nodeAddrStr == "" { + var err error + nodeAddrStr, err = common.GenerateV6Prefix() + if err != nil { + log.Fatalf("Unable to generate IPv6 prefix: %s\n", err) + } + + log.Infof("Generated IPv6 prefix: %s\n", nodeAddrStr) + } + addr := net.ParseIP(nodeAddrStr) if addr == nil { log.Fatalf("Invalid node address \"%s\", please specifcy node address using -n", nodeAddrStr) diff --git a/cilium-net-daemon/run.sh b/cilium-net-daemon/run.sh index <HASH>..<HASH> 100755 --- a/cilium-net-daemon/run.sh +++ b/cilium-net-daemon/run.sh @@ -1,12 +1,5 @@ #!/bin/bash -V4=$(ip -4 a show scope global | \ - grep -oEm 1 '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | \ - head -1) +echo "Running ./cilium-net-daemon $*" -HEX=$(printf '%02X' ${V4//./ }) - -V6="beef::${HEX:0:4}:${HEX:4}:0" -echo "Running ./cilium-net-daemon -n $V6 $*" - -./cilium-net-daemon -n $V6 $* +./cilium-net-daemon $* diff --git a/common/utils.go b/common/utils.go index <HASH>..<HASH> 100644 --- a/common/utils.go +++ b/common/utils.go @@ -2,6 +2,10 @@ package common import ( "fmt" + "net" + "syscall" + + "github.com/noironetworks/cilium-net/Godeps/_workspace/src/github.com/vishvananda/netlink" ) func GoArray2C(array []byte) string { @@ -25,3 +29,35 @@ func FmtDefineAddress(name string, addr []byte) string { func FmtDefineArray(name string, array []byte) string { return fmt.Sprintf("#define %s %s\n", name, GoArray2C(array)) } + +func firstGlobalV4Addr() (net.IP, error) { + addr, err := netlink.AddrList(nil, netlink.FAMILY_V4) + if err != nil { + return nil, err + } + + for _, a := range addr { + if a.Scope == syscall.RT_SCOPE_UNIVERSE { + return a.IP, nil + } + } + + return nil, fmt.Errorf("No IPv4 address configured") +} + +func fmtV6Prefix(prefix string, ip net.IP) string { + if len(ip) < 4 { + return "<nil>" + } + + return fmt.Sprintf("%s:%x%x:%x%x:0", prefix, ip[0], ip[1], ip[2], ip[3]) +} + +func GenerateV6Prefix() (string, error) { + ip, err := firstGlobalV4Addr() + if err != nil { + return "", err + } + + return fmtV6Prefix("beef:", ip), nil +} diff --git a/common/utils_test.go b/common/utils_test.go index <HASH>..<HASH> 100644 --- a/common/utils_test.go +++ b/common/utils_test.go @@ -18,3 +18,8 @@ func (s *CommonSuite) TestFmtDefineAddress(c *C) { c.Assert(FmtDefineAddress("foo", []byte{1, 2, 3}), Equals, "#define foo { .addr = { 0x1, 0x2, 0x3 } }\n") c.Assert(FmtDefineAddress("foo", []byte{}), Equals, "#define foo { .addr = { } }\n") } + +func (s *CommonSuite) TestfmtV6Prefix(c *C) { + c.Assert(fmtV6Prefix("beef:", []byte{}), Equals, "<nil>") + c.Assert(fmtV6Prefix("beef:", []byte{1, 2, 3, 4}), Equals, "beef::12:34:0") +} diff --git a/docker-plugin/run.sh b/docker-plugin/run.sh index <HASH>..<HASH> 100755 --- a/docker-plugin/run.sh +++ b/docker-plugin/run.sh @@ -1,12 +1,5 @@ #!/bin/bash -V4=$(ip -4 a show scope global | \ - grep -oEm 1 '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | \ - head -1) +echo "Running ./cilium-docker -d $*" -HEX=$(printf '%02X' ${V4//./ }) - -V6="beef::${HEX:0:4}:${HEX:4}:0" -echo "Running ./cilium-docker -d -n $V6 $*" - -./cilium-docker -d -n $V6 $* +./cilium-docker -d $*
Automatically derive node address in daemon and plugin
cilium_cilium
train
46b881c090ced191c71d7c9bf974f82f10907992
diff --git a/LiSE/rule.py b/LiSE/rule.py index <HASH>..<HASH> 100644 --- a/LiSE/rule.py +++ b/LiSE/rule.py @@ -151,48 +151,32 @@ class RuleBook(MutableSequence): def __init__(self, engine, name): self.engine = engine self.name = name - self._cache = {} - - def _cache_at(self, branch, tick): - if branch not in self._cache: - self._cache[branch] = {} - if tick not in self._cache[branch]: - if tick - 1 in self._cache[branch]: - self._cache[branch][tick] = list( - self._cache[branch][tick-1] - ) - else: - self._cache[branch][tick] = [ - self.engine.rule[rule] - for rule in self.engine.db.rulebook_rules(self.name) - ] + if self.engine.caching: + self._cache = [ + self.engine.rule[rule] for rule in + self.engine.db.rulebook_rules + ] def __iter__(self): - if not self.engine.caching: - for rule in self.engine.db.rulebook_rules(self.name): - yield self.engine.rule[rule] - (branch, tick) = self.engine.time - self._cache_at(branch, tick) - return iter(self._cache[branch][tick]) + if self.engine.caching: + return iter(self._cache) + for rule in self.engine.db.rulebook_rules(self.name): + yield self.engine.rule[rule] def __len__(self): - if not self.engine.caching: - return self.engine.db.ct_rulebook_rules(self.name) - (branch, tick) = self.engine.time - self._cache_at(branch, tick) - return len(self._cache[branch][tick]) + if self.engine.caching: + return len(self._cache) + return self.engine.db.ct_rulebook_rules(self.name) def __getitem__(self, i): - if not self.engine.caching: - return self.engine.rule[ - self.engine.db.rulebook_get( - self.name, - i - ) - ] - (branch, tick) = self.engine.time - self._cache_at(branch, tick) - return self._cache[branch][tick] + if self.engine.caching: + return self._cache[i] + return self.engine.rule[ + self.engine.db.rulebook_get( + self.name, + i + ) + ] def __setitem__(self, i, v): if isinstance(v, Rule): @@ -201,26 +185,18 @@ class RuleBook(MutableSequence): rule = self.engine.rule[v] else: rule = Rule(self.engine, v) - if not self.engine.caching: - self.engine.db.rulebook_set(self.name, i, rule.name) - return - (branch, tick) = self.engine.time - self._cache_at(branch, tick) self.engine.db.rulebook_set(self.name, i, rule.name) - self._cache[branch][tick][i] = rule + if self.engine.caching: + self._cache[i] = rule def insert(self, i, v): self.engine.db.rulebook_decr(self.name, i) self[i] = v def __delitem__(self, i): - if not self.engine.caching: - self.engine.db.rulebook_del(self.name, i) - return - (branch, tick) = self.engine.time - self._cache_at(branch, tick) self.engine.db.rulebook_del(self.name, i) - del self._cache[branch][tick][i] + if self.engine.caching: + del self._cache[i] class RuleMapping(MutableMapping):
Take advantage of the timeless nature of RuleBook to make its cache simpler. Still no obvious speed improvement.
LogicalDash_LiSE
train
28f5ec9c11f7ffe9c7fa80a53433622fef7dc24f
diff --git a/js/analyzer.js b/js/analyzer.js index <HASH>..<HASH> 100644 --- a/js/analyzer.js +++ b/js/analyzer.js @@ -261,6 +261,7 @@ YoastSEO.Analyzer.prototype.stopwords = function() { /** * calculate Flesch Reading score + * formula: 206.835 - 1.015 (total words / total sentences) - 84.6 ( total syllables / total words); * @returns {result object} */ YoastSEO.Analyzer.prototype.fleschReading = function() { @@ -298,6 +299,8 @@ YoastSEO.Analyzer.prototype.fleschReading = function() { * { * total: number, internal: { * total: number, + * totalNaKeyword: number, + * totalKeyword: number, * dofollow: number, * nofollow: number * }, external: { @@ -448,6 +451,7 @@ YoastSEO.Analyzer.prototype.imageCount = function() { if ( this.imageAlttagKeyword( alttag ) ) { imageCount.altKeyword++; } else { + //this counts all alt-tags w/o the keyword when a keyword is set. imageCount.alt++; } } else { @@ -571,7 +575,7 @@ YoastSEO.Analyzer.prototype.paragraphChecker = function( textString, regexp ) { */ YoastSEO.Analyzer.prototype.metaDescriptionKeyword = function() { var result = [ { test: "metaDescriptionKeyword", result: 0 } ]; - if ( typeof this.config.meta !== "undefined" && this.config.meta.length > 0 ) { + if ( typeof this.config.meta !== "undefined" && this.config.meta.length > 0 && this.config.keyword !== "") { result[ 0 ].result = this.stringHelper.countMatches( this.config.meta, this.keywordRegex );
Added comments to functions added check for empty keyword on metadescription keyword test
Yoast_YoastSEO.js
train
9100e5852d1152360a6044788639338325d2c628
diff --git a/rig/bitfield.py b/rig/bitfield.py index <HASH>..<HASH> 100644 --- a/rig/bitfield.py +++ b/rig/bitfield.py @@ -416,6 +416,42 @@ class BitField(object): """ return self.fields.get_field(field, self.field_values).tags.copy() + def get_location_and_length(self, field): + """Get the location and length of a field within the bitfield. + + .. note:: + The named field must be accessible given the current set of values + defined. + + Parameters + ---------- + field : str + The field of interest. + + Returns + ------- + location, length + A pair of integers defining the bit-number of the least-significant + bit in the field and the total number of bits in the field + respectively. + + Raises + ------ + ValueError + If a field's length or position has not been defined. (e.g. + :py:meth:`.assign_fields` has not been called). + UnavailableFieldError + If the field does not exist or is not available. + """ + field_obj = self.fields.get_field(field, self.field_values) + + if field_obj.length is None or field_obj.start_at is None: + raise ValueError( + "Field '{}' does not have a fixed size/position.".format( + field)) + + return (field_obj.start_at, field_obj.length) + def assign_fields(self): """Assign a position & length to any fields which do not have one. diff --git a/tests/test_bitfield.py b/tests/test_bitfield.py index <HASH>..<HASH> 100644 --- a/tests/test_bitfield.py +++ b/tests/test_bitfield.py @@ -849,6 +849,36 @@ class TestFullAuto(object): assert ks_h(s=1, s1=1).get_mask(field="s11") == 0x00000001 +def test_get_location_and_length(): + ks = BitField(32) + ks.add_field("foo") + ks.add_field("bar", length=5) + ks.add_field("baz", start_at=1) + ks.add_field("qux", start_at=10, length=5) + + # Getting non-existant fields should fail + with pytest.raises(UnavailableFieldError): + ks.get_location_and_length("norf") + + # Getting fields whose location/size is not known should fail + with pytest.raises(ValueError): + ks.get_location_and_length("foo") + with pytest.raises(ValueError): + ks.get_location_and_length("bar") + with pytest.raises(ValueError): + ks.get_location_and_length("baz") + + # Getting fields whose location was predefined should work + assert ks.get_location_and_length("qux") == (10, 5) + + # Fixing everything should allow other fields to be determined too + ks.assign_fields() + assert ks.get_location_and_length("foo") == (0, 1) + assert ks.get_location_and_length("bar") == (2, 5) + assert ks.get_location_and_length("baz") == (1, 1) + assert ks.get_location_and_length("qux") == (10, 5) + + def test_eq(): # Check that two bit fields with the same fields and values (but defined # seperately) are not equivilent.
Add get_location_and_length to BitField This new method allows the direct querying of the size and location allocated to fields in a bit field, without having to deconstruct a mask.
project-rig_rig
train
06a69cf4252d9a167d1981000475cef5d53adb79
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -109,8 +109,7 @@ Return a user from the database. #### user.verifyPassword(password, cb) * password {String} the password to verify * cb {Function} first parameter will be an error or null, second parameter - contains a boolean about whether the password is valid or not, third parameter - contains user object or null on error or on invalid password. + contains a boolean about whether the password is valid or not. Verify if the given password is valid. diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -29,6 +29,7 @@ var bcrypt = require('bcrypt'); * @return {undefined} */ function _checkAllWithPassword(db, username, password, realm, cb) { + /*jshint maxcomplexity:11*/ if (typeof db !== 'object') { throw new TypeError('db must be an object'); } if (typeof username !== 'string') { throw new TypeError('username must be a string'); } if (typeof password !== 'string') { throw new TypeError('password must be a string'); } @@ -155,8 +156,7 @@ User.exists = exists; * @param {String, default: _default} [realm] optional realm the user belongs to * @param {Function} cb first parameter will be an error or null, second parameter * contains a boolean about whether the password is valid or - * not, third parameter contains user object or null on error - * or on invalid password. + * not. */ function verifyPassword(db, username, password, realm, cb) { if (typeof realm === 'function') { @@ -177,9 +177,9 @@ function verifyPassword(db, username, password, realm, cb) { bcrypt.compare(password, user.password, function(err, res) { if (err) { cb(err); return; } - if (res === true) { cb(null, true, user); return; } + if (res === true) { cb(null, true); return; } - cb(null, false, null); + cb(null, false); }); }); } diff --git a/test/index.js b/test/index.js index <HASH>..<HASH> 100644 --- a/test/index.js +++ b/test/index.js @@ -232,20 +232,26 @@ describe('User', function () { }); it('should find that the password is invalid', function(done) { - User.verifyPassword(db, 'foo', 'secret', 'verifyPasswordRealm', function(err, valid, user) { + User.verifyPassword(db, 'foo', 'secret', 'verifyPasswordRealm', function(err, valid) { if (err) { throw err; } should.strictEqual(valid, false); - should.strictEqual(user, null); done(); }); }); it('should find that the password is valid', function(done) { + User.verifyPassword(db, 'foo', 'secr3t', 'verifyPasswordRealm', function(err, valid) { + if (err) { throw err; } + should.strictEqual(valid, true); + done(); + }); + }); + + it('should not return the user when password is valid', function(done) { User.verifyPassword(db, 'foo', 'secr3t', 'verifyPasswordRealm', function(err, valid, user) { if (err) { throw err; } should.strictEqual(valid, true); - should.strictEqual(user.realm, 'verifyPasswordRealm'); - should.strictEqual(user.username, 'foo'); + should.strictEqual(user, undefined); done(); }); }); @@ -260,10 +266,9 @@ describe('User', function () { }); it('should find that the password is invalid for users in non-existant realms', function(done) { - User.verifyPassword(db, 'foo', 'secr3t', 'verifyPasswordRealm2', function(err, valid, user) { + User.verifyPassword(db, 'foo', 'secr3t', 'verifyPasswordRealm2', function(err, valid) { if (err) { throw err; } should.strictEqual(valid, false); - should.strictEqual(user, null); done(); }); });
fixes #5: removed user from cb verifyPassword Removed returning user as third parameter of callback of verifyPassword.
timkuijsten_node-bcrypt-user
train
88dce620048696a15db26ee98c3a8e78a17a3cae
diff --git a/cartoframes/data/services/isolines.py b/cartoframes/data/services/isolines.py index <HASH>..<HASH> 100644 --- a/cartoframes/data/services/isolines.py +++ b/cartoframes/data/services/isolines.py @@ -128,7 +128,7 @@ class Isolines(Service): input_dataframe = None if isinstance(source, pd.DataFrame): input_dataframe = source - source = Dataset(input_dataframe, credentials=self._credentials) + source = Dataset(input_dataframe) if dry_run: num_rows = source.get_num_rows()
Remove unnecessary credentials Dataframe datasets ignore the constructor credentials, and, in any case, for dataframes we're setting the Geocoder credentials to upload them.
CartoDB_cartoframes
train
fec9af264b30f0ecf5c87840570846a8c330efb5
diff --git a/lib/haml/precompiler.rb b/lib/haml/precompiler.rb index <HASH>..<HASH> 100644 --- a/lib/haml/precompiler.rb +++ b/lib/haml/precompiler.rb @@ -162,8 +162,9 @@ END end if old_line.spaces != old_line.tabs * 2 - raise SyntaxError.new("Illegal indentation: only two space characters are allowed as tabulation.", - 1 + old_line.index - @index) + raise SyntaxError.new(<<END.strip, 1 + old_line.index - @index) +#{old_line.spaces} space#{old_line.spaces == 1 ? ' was' : 's were'} used for indentation. Haml must be indented using two spaces. +END end unless old_line.text.empty? || @haml_comment @@ -171,8 +172,9 @@ END end if !flat? && line.tabs - old_line.tabs > 1 - raise SyntaxError.new("Illegal indentation: indenting more than once per line is illegal.", - 1 + old_line.index - @index) + raise SyntaxError.new(<<END.strip, 1 + old_line.index - @index) +#{line.spaces} spaces were used for indentation. Haml must be indented using two spaces. +END end old_line = line newline @@ -723,7 +725,10 @@ END spaces = line.index(/([^ ]|$)/) if line[spaces] == ?\t return nil if line.strip.empty? - raise SyntaxError.new("Illegal indentation: only two space characters are allowed as tabulation.", 2) + raise SyntaxError.new(<<END.strip, 2) +A tab character was used for indentation. Haml must be indented using two spaces. +Are you sure you have soft tabs enabled in your editor? +END end [spaces, spaces/2] end diff --git a/test/haml/engine_test.rb b/test/haml/engine_test.rb index <HASH>..<HASH> 100644 --- a/test/haml/engine_test.rb +++ b/test/haml/engine_test.rb @@ -13,9 +13,13 @@ class EngineTest < Test::Unit::TestCase "~" => "Tag has no content.", "=" => "Tag has no content.", "%p/\n a" => "Illegal nesting: nesting within an atomic tag is illegal.", - "%p\n\ta" => "Illegal indentation: only two space characters are allowed as tabulation.", - "%p\n a" => "Illegal indentation: only two space characters are allowed as tabulation.", - "%p\n a" => "Illegal indentation: indenting more than once per line is illegal.", + "%p\n\ta" => <<END.strip, +A tab character was used for indentation. Haml must be indented using two spaces. +Are you sure you have soft tabs enabled in your editor? +END + "%p\n a" => "1 space was used for indentation. Haml must be indented using two spaces.", + "%p\n a" => "3 spaces were used for indentation. Haml must be indented using two spaces.", + "%p\n a" => "4 spaces were used for indentation. Haml must be indented using two spaces.", ":a\n b" => 'Filter "a" is not defined.', ":a= b" => 'Invalid filter name ":a= b".', "." => "Illegal element: classes and ids must have values.",
Change the text for the Haml indentation errors.
sass_ruby-sass
train
8a2deeb06c55edf7c7f860209a54dbe4cdc78ad6
diff --git a/shared/reducers/dev.js b/shared/reducers/dev.js index <HASH>..<HASH> 100644 --- a/shared/reducers/dev.js +++ b/shared/reducers/dev.js @@ -28,6 +28,7 @@ export default function (state: DevState = initialState, action: DevAction): Sta if (action.type === updateReloading && !action.error) { return { + ...state, reloading: action.payload.reloading, } }
Fix my mistake that breaks hmr (#<I>)
keybase_client
train
39cc8d65bbc100f3d8bde1eeed08d6e74721a589
diff --git a/lib/gds_api/support.rb b/lib/gds_api/support.rb index <HASH>..<HASH> 100644 --- a/lib/gds_api/support.rb +++ b/lib/gds_api/support.rb @@ -13,6 +13,10 @@ class GdsApi::Support < GdsApi::Base post_json!("#{base_url}/named_contacts", { :named_contact => request_details }, options[:headers] || {}) end + def create_anonymous_long_form_contact(request_details, options = {}) + post_json!("#{base_url}/anonymous_feedback/long_form_contacts", { :long_form_contact => request_details }, options[:headers] || {}) + end + private def base_url endpoint diff --git a/lib/gds_api/test_helpers/support.rb b/lib/gds_api/test_helpers/support.rb index <HASH>..<HASH> 100644 --- a/lib/gds_api/test_helpers/support.rb +++ b/lib/gds_api/test_helpers/support.rb @@ -21,6 +21,12 @@ module GdsApi post_stub.to_return(:status => 201) end + def stub_support_long_form_anonymous_contact_creation(request_details = nil) + post_stub = stub_http_request(:post, "#{SUPPORT_ENDPOINT}/anonymous_feedback/long_form_contacts") + post_stub.with(:body => { long_form_contact: request_details }) unless request_details.nil? + post_stub.to_return(:status => 201) + end + def support_isnt_available stub_request(:post, /#{SUPPORT_ENDPOINT}\/.*/).to_return(:status => 503) end diff --git a/test/support_api_test.rb b/test/support_api_test.rb index <HASH>..<HASH> 100644 --- a/test/support_api_test.rb +++ b/test/support_api_test.rb @@ -50,6 +50,18 @@ describe GdsApi::Support do assert_requested(stub_post) end + it "can submit long-form anonymous feedback" do + request_details = {certain: "details"} + + stub_post = stub_request(:post, "#{@base_api_url}/anonymous_feedback/long_form_contacts"). + with(:body => {"long_form_contact" => request_details}.to_json). + to_return(:status => 201) + + @api.create_anonymous_long_form_contact(request_details) + + assert_requested(stub_post) + end + it "can add a custom header onto the problem_report request to the support app" do stub_request(:post, "#{@base_api_url}/anonymous_feedback/problem_reports")
support: add endpoint for anonymous long-form contacts
alphagov_gds-api-adapters
train
a387eeb5f74f0f37109f6e3d0e6b2d9bef7a5720
diff --git a/src/Hashing/BcryptHasher.php b/src/Hashing/BcryptHasher.php index <HASH>..<HASH> 100644 --- a/src/Hashing/BcryptHasher.php +++ b/src/Hashing/BcryptHasher.php @@ -60,4 +60,15 @@ class BcryptHasher implements HasherInterface return password_needs_rehash($hashedValue, PASSWORD_DEFAULT, array('cost' => $cost)); } + + /** + * Set the default crypt cost factor. + * + * @param int $rounds + * @return void + */ + public function setRounds($rounds) + { + $this->rounds = (int) $rounds; + } }
Add the method Nova\Hashing\BcryptHasher@setRounds
nova-framework_system
train
f80112c07891bf88f36cba63db991377288402f4
diff --git a/dist/schemaobject.js b/dist/schemaobject.js index <HASH>..<HASH> 100644 --- a/dist/schemaobject.js +++ b/dist/schemaobject.js @@ -1145,7 +1145,7 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons return; } - //If property has a value, is a boolean set to false, or if it's falsy and falsy values are allowed + //Skip if property has a value, is a boolean set to false, or if it's falsy and falsy values are allowed if (_this9[index] || typeof _this9[index] === 'boolean' || _this9[_privateKey]._options.allowFalsyValues && _this9[index] !== undefined) { return; } diff --git a/lib/schemaobject.js b/lib/schemaobject.js index <HASH>..<HASH> 100644 --- a/lib/schemaobject.js +++ b/lib/schemaobject.js @@ -984,7 +984,7 @@ return; } - //If property has a value, is a boolean set to false, or if it's falsy and falsy values are allowed + //Skip if property has a value, is a boolean set to false, or if it's falsy and falsy values are allowed if ( this[index] || typeof this[index] === 'boolean' || diff --git a/test/tests.js b/test/tests.js index <HASH>..<HASH> 100644 --- a/test/tests.js +++ b/test/tests.js @@ -737,24 +737,24 @@ describe('any type', function () { o.isErrors().should.equal(true); }); - it('should not reject if field is required and a boolean false value is provided and allowFalsyValues is false', function () { - var SO = new SchemaObject({ - myBoolean: { - type: Boolean, - required: true - } - }, { - allowFalsyValues: false - }); + it('should not reject if field is required and a boolean false value is provided and allowFalsyValues is false', function () { + var SO = new SchemaObject({ + myBoolean: { + type: Boolean, + required: true + } + }, { + allowFalsyValues: false + }); - var o = new SO(); - o.myBoolean = false; + var o = new SO(); + o.myBoolean = false; - o.getErrors().length.should.equal(0); - o.isErrors().should.equal(false); - should.exist(o.toObject().myBoolean); - o.toObject().myBoolean.should.equal(false); - }); + o.getErrors().length.should.equal(0); + o.isErrors().should.equal(false); + should.exist(o.toObject().myBoolean); + o.toObject().myBoolean.should.equal(false); + }); it('should reject if field is required, provided, and then removed', function () { var SO = new SchemaObject({
Fix spacing issue in test, clarify comment
scotthovestadt_schema-object
train
d463d6dd74b84347106bbaf71f75caba3068f0d2
diff --git a/tools/synthesis/src/main/java/kg/apc/jmeter/vizualizers/AggregateReportGui.java b/tools/synthesis/src/main/java/kg/apc/jmeter/vizualizers/AggregateReportGui.java index <HASH>..<HASH> 100644 --- a/tools/synthesis/src/main/java/kg/apc/jmeter/vizualizers/AggregateReportGui.java +++ b/tools/synthesis/src/main/java/kg/apc/jmeter/vizualizers/AggregateReportGui.java @@ -50,6 +50,8 @@ public class AggregateReportGui extends AbstractGraphPanelVisualizer { "average", "aggregate_report_median", "aggregate_report_90%_line", + "aggregate_report_95%_line", + "aggregate_report_99%_line", "aggregate_report_min", "aggregate_report_max", "aggregate_report_error%", @@ -80,6 +82,10 @@ public class AggregateReportGui extends AbstractGraphPanelVisualizer { new Functor("getMedian"), new Functor("getPercentPoint", new Object[]{new Float(.900)}), + new Functor("getPercentPoint", + new Object[]{new Float(.950)}), + new Functor("getPercentPoint", + new Object[]{new Float(.990)}), new Functor("getMin"), new Functor("getMax"), new Functor("getErrorPercentage"), @@ -106,6 +112,8 @@ public class AggregateReportGui extends AbstractGraphPanelVisualizer { null, // Mean null, // median null, // 90% + null, // 95% + null, // 99% null, // Min null, // Max new NumberRenderer("#0.00%"), // Error %age @@ -122,6 +130,8 @@ public class AggregateReportGui extends AbstractGraphPanelVisualizer { null, // Mean null, // median null, // 90% + null, // 95% + null, // 99% null, // Min null, // Max new DecimalFormat("#0.00%"), // Error %age
Add <I>%, and <I>% data in aggregate report (#<I>) There's <I>% and <I>% response time data in aggregate report in GUI, but there's only <I>% response time data in command line. For better data statistics, It'd be better to have <I>% response time data.
undera_jmeter-plugins
train
31c0d346c3d9614e1c1c23fa2e418eb76d742e24
diff --git a/test/unit/voldemort/store/AbstractStoreTest.java b/test/unit/voldemort/store/AbstractStoreTest.java index <HASH>..<HASH> 100644 --- a/test/unit/voldemort/store/AbstractStoreTest.java +++ b/test/unit/voldemort/store/AbstractStoreTest.java @@ -252,10 +252,10 @@ public abstract class AbstractStoreTest<K, V> extends TestCase { store.put(key, Versioned.value(value)); List<Versioned<V>> versioneds = store.get(key); List<Version> versions = store.getVersions(key); - assertTrue(versioneds.size() > 0); - assertEquals(versioneds.size(), versions.size()); - for(int i = 0; i < versioneds.size(); i++) - assertEquals(versioneds.get(i).getVersion(), versions.get(i)); + assertEquals(1, versioneds.size()); + assertTrue(versions.size() > 0); + for(int i = 0; i < versions.size(); i++) + assertEquals(versioneds.get(0).getVersion(), versions.get(i)); assertEquals(0, store.getVersions(keys.get(1)).size()); }
Adapt test to the fact that InconsistencyResolvingStore does not override getVersions anymore.
voldemort_voldemort
train
5eb35d7fa904ace64348faa48ff4ace583466d00
diff --git a/structr-ui/src/main/resources/structr/js/flows.js b/structr-ui/src/main/resources/structr/js/flows.js index <HASH>..<HASH> 100644 --- a/structr-ui/src/main/resources/structr/js/flows.js +++ b/structr-ui/src/main/resources/structr/js/flows.js @@ -174,6 +174,11 @@ var _Flows = { return packages.result.length > 0 ? packages.result[0] : null; } + document.querySelector('#name-input').onkeydown = ((event) => { + if (event.key === "Enter") { + createFlow(document.getElementById('name-input')); + } + }); document.querySelector('#create-new-flow').onclick = () => createFlow(document.getElementById('name-input')); document.querySelector('.reset_view_icon').onclick = () => editor.resetView();
Enables keybinds for flow creation input in flow page.
structr_structr
train
3555f42940a98eb672cc1c545cf75ed17a3b14e0
diff --git a/bcbio/broad/__init__.py b/bcbio/broad/__init__.py index <HASH>..<HASH> 100644 --- a/bcbio/broad/__init__.py +++ b/bcbio/broad/__init__.py @@ -22,9 +22,9 @@ class BroadRunner: self._picard_ref = config_utils.expand_path(picard_ref) self._gatk_dir = config_utils.expand_path(gatk_dir) or config_utils.expand_path(picard_ref) self._config = config - self._gatk_version, self._picard_version = self._default_versions(config) + self._gatk_version, self._picard_version = None, None - def _default_versions(self, config): + def _set_default_versions(self, config): """Retrieve pre-computed version information for expensive to retrieve versions. Starting up GATK takes a lot of resources so we do it once at start of analysis. """ @@ -35,7 +35,7 @@ class BroadRunner: except KeyError: v = None out.append(v) - return out + self._gatk_version, self._picard_version = out def new_resources(self, program): """Set new resource usage for the given program. @@ -85,6 +85,8 @@ class BroadRunner: do.run(cl, "Picard {0}".format(command), None) def get_picard_version(self, command): + if self._picard_version is None: + self._set_default_versions(self._config) if self._picard_version: return self._picard_version if os.path.isdir(self._picard_ref): @@ -162,6 +164,8 @@ class BroadRunner: Calling version can be expensive due to all the startup and shutdown of JVMs, so we prefer cached version information. """ + if self._gatk_version is None: + self._set_default_versions(self._config) if self._gatk_version is not None: return self._gatk_version else: diff --git a/bcbio/pipeline/genome.py b/bcbio/pipeline/genome.py index <HASH>..<HASH> 100644 --- a/bcbio/pipeline/genome.py +++ b/bcbio/pipeline/genome.py @@ -29,9 +29,10 @@ def get_resources(genome, ref_file): # ## Utilities -def abs_file_paths(xs, base_dir=None): +def abs_file_paths(xs, base_dir=None, ignore_keys=None): """Normalize any file paths found in a subdirectory of configuration input. """ + ignore_keys = set([]) if ignore_keys is None else set(ignore_keys) if not isinstance(xs, dict): return xs if base_dir is None: @@ -40,7 +41,7 @@ def abs_file_paths(xs, base_dir=None): os.chdir(base_dir) out = {} for k, v in xs.iteritems(): - if v and isinstance(v, basestring) and os.path.exists(v): + if k not in ignore_keys and v and isinstance(v, basestring) and os.path.exists(v): out[k] = os.path.normpath(os.path.join(base_dir, v)) else: out[k] = v diff --git a/bcbio/pipeline/run_info.py b/bcbio/pipeline/run_info.py index <HASH>..<HASH> 100644 --- a/bcbio/pipeline/run_info.py +++ b/bcbio/pipeline/run_info.py @@ -239,7 +239,8 @@ def _run_info_from_yaml(fc_dir, run_info_yaml, config): upload["fc_date"] = fc_date upload["run_id"] = "" item["upload"] = upload - item["algorithm"] = genome.abs_file_paths(item["algorithm"]) + item["algorithm"] = genome.abs_file_paths(item["algorithm"], + ignore_keys=["variantcaller"]) item["rgnames"] = prep_rg_names(item, config, fc_name, fc_date) run_details.append(item) _check_sample_config(run_details, run_info_yaml) diff --git a/bcbio/variation/genotype.py b/bcbio/variation/genotype.py index <HASH>..<HASH> 100644 --- a/bcbio/variation/genotype.py +++ b/bcbio/variation/genotype.py @@ -260,7 +260,7 @@ def _variant_filtration_snp(snp_file, ref_file, vrn_files, config): config["algorithm"]["coverage_interval"] = "regional" return _variant_filtration_snp(snp_file, ref_file, vrn_files, config) if not file_exists(recal_file): - assert "train_hapmap" in vrn_files and "train_1000g_omin" in vrn_files, \ + assert "train_hapmap" in vrn_files and "train_1000g_omni" in vrn_files, \ "Need HapMap and 1000 genomes training files" with file_transaction(recal_file, tranches_file) as (tx_recal, tx_tranches): params.extend(["--recal_file", tx_recal,
Bug fixes for typo in VariantRecalibration and incorrect normalization in algorithm variantcaller parameter. Speed up for re-starts by avoiding initial version detection for GATK/Picard
bcbio_bcbio-nextgen
train
85ebdad46e83d25819ff797c41fa069219b99a27
diff --git a/app/lib/actions/pulp/abstract_async_task.rb b/app/lib/actions/pulp/abstract_async_task.rb index <HASH>..<HASH> 100644 --- a/app/lib/actions/pulp/abstract_async_task.rb +++ b/app/lib/actions/pulp/abstract_async_task.rb @@ -102,6 +102,7 @@ module Actions private def external_task=(external_task_data) + external_task_data = [] if external_task_data.nil? external_task_data = [external_task_data] if external_task_data.is_a?(Hash) new_tasks = [] diff --git a/app/lib/actions/pulp/consumer/generate_applicability.rb b/app/lib/actions/pulp/consumer/generate_applicability.rb index <HASH>..<HASH> 100644 --- a/app/lib/actions/pulp/consumer/generate_applicability.rb +++ b/app/lib/actions/pulp/consumer/generate_applicability.rb @@ -12,6 +12,7 @@ module Actions pulp_resources.consumer.regenerate_applicability_by_id(input[:uuids].first) rescue RestClient::ResourceNotFound Rails.logger.warn("Pulp consumer %s not found." % input[:uuids].first) + nil end else pulp_extensions.consumer.regenerate_applicability_by_ids(input[:uuids])
Fixes #<I> - ignore <I> on gen applicability
Katello_katello
train
aea2950ba9d3581a44197c5b53a850e1104408b6
diff --git a/tests/Database/Test/DatabaseConnectionTest.php b/tests/Database/Test/DatabaseConnectionTest.php index <HASH>..<HASH> 100644 --- a/tests/Database/Test/DatabaseConnectionTest.php +++ b/tests/Database/Test/DatabaseConnectionTest.php @@ -18,7 +18,7 @@ use Josantonius\Database\Database, final class DatabaseConnectionTest extends TestCase { - public static $db; + private $db; /** * Get connection test. @@ -29,7 +29,7 @@ final class DatabaseConnectionTest extends TestCase { */ public function testGetConnection() { - self::$db = Database::getConnection( + $this->db = Database::getConnection( 'identifier', 'PDOprovider', @@ -40,12 +40,12 @@ final class DatabaseConnectionTest extends TestCase { array('charset' => 'utf8') ); - $this->assertContains('identifier', self::$db::$id); + $this->assertContains('identifier', $this->db::$id); $this->assertContains( 'Josantonius\Database\Database', - get_class(self::$db) + get_class($this->db) ); } @@ -75,14 +75,14 @@ final class DatabaseConnectionTest extends TestCase { ] ]); - self::$db = Database::getConnection('Eliasis'); + $this->db = Database::getConnection('Eliasis'); - $this->assertContains('Eliasis', self::$db::$id); + $this->assertContains('Eliasis', $this->db::$id); $this->assertContains( 'Josantonius\Database\Provider\PDOprovider\PDOprovider', - get_class(self::$db->_provider) + get_class($this->db->_provider) ); } @@ -99,7 +99,7 @@ final class DatabaseConnectionTest extends TestCase { */ public function testExceptionWhenProviderNotExists() { - self::$db = Database::getConnection( + $this->db = Database::getConnection( 'provider-exception', '?', @@ -124,7 +124,7 @@ final class DatabaseConnectionTest extends TestCase { */ public function testExceptionNameOrServiceNotKnown() { - self::$db = Database::getConnection( + $this->db = Database::getConnection( 'connection-exception', 'PDOprovider', @@ -149,7 +149,7 @@ final class DatabaseConnectionTest extends TestCase { */ public function testExceptionAccessDeniedForUser() { - self::$db = Database::getConnection( + $this->db = Database::getConnection( 'user-exception', 'PDOprovider', @@ -174,7 +174,7 @@ final class DatabaseConnectionTest extends TestCase { */ public function testExceptionAccessDeniedForUserPassword() { - self::$db = Database::getConnection( + $this->db = Database::getConnection( 'password-exception', 'PDOprovider', @@ -199,7 +199,7 @@ final class DatabaseConnectionTest extends TestCase { */ public function testExceptionAccessDeniedForUserName() { - self::$db = Database::getConnection( + $this->db = Database::getConnection( 'name-exception', 'PDOprovider', diff --git a/tests/Database/Test/DatabaseCreateTest.php b/tests/Database/Test/DatabaseCreateTest.php index <HASH>..<HASH> 100644 --- a/tests/Database/Test/DatabaseCreateTest.php +++ b/tests/Database/Test/DatabaseCreateTest.php @@ -17,7 +17,7 @@ use Josantonius\Database\Database, final class DatabaseCreateTest extends TestCase { - public static $db; + private $db; /** * Get connection test. @@ -28,9 +28,9 @@ final class DatabaseCreateTest extends TestCase { */ public function testGetConnection() { - self::$db = Database::getConnection('identifier'); + $this->db = Database::getConnection('identifier'); - $this->assertContains('identifier', self::$db::$id); + $this->assertContains('identifier', $this->db::$id); }
Updated to <I> version
Josantonius_PHP-Database
train
8ee1b0afabbeb4b18b0c699e826d6e110b4ac7b6
diff --git a/lib/moodlelib.php b/lib/moodlelib.php index <HASH>..<HASH> 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -383,18 +383,6 @@ function unregister_globals () { $_SERVER = $SERVER; } -/** - * Improved ensure a variable is set - * Issue a (custom) error message if not - * @param mixed $var the variable - * @param string $error optional additional error message - */ -function assert_var_set( $var, $error='' ) { - if (! isset($var)) { - error( "a required variable is not set - $error" ); - } -} - /** * Ensure that a variable is set
Removed assert_var_exists() function that did nothing useful.
moodle_moodle
train
12f5b6d7a2b865d979e54b39b225afb88499af26
diff --git a/sonar-db/src/main/java/org/sonar/db/version/v53/FixMsSqlCollation.java b/sonar-db/src/main/java/org/sonar/db/version/v53/FixMsSqlCollation.java index <HASH>..<HASH> 100644 --- a/sonar-db/src/main/java/org/sonar/db/version/v53/FixMsSqlCollation.java +++ b/sonar-db/src/main/java/org/sonar/db/version/v53/FixMsSqlCollation.java @@ -138,6 +138,7 @@ public class FixMsSqlCollation extends DdlChange { .addVarcharColumn("name", 200) .addVarcharColumn("status", 40) .addVarcharColumn("language", 20) + .addClobColumn("note_data") .addVarcharColumn("note_user_login", 255) .addVarcharColumn("remediation_function", 20) .addVarcharColumn("default_remediation_function", 20) @@ -183,6 +184,7 @@ public class FixMsSqlCollation extends DdlChange { new UpdateTableCollation(context, db, "properties") .addIndex("properties_key", "prop_key") .addVarcharColumn("prop_key", 512) + .addClobColumn("text_value") .execute(); // project_links @@ -317,6 +319,7 @@ public class FixMsSqlCollation extends DdlChange { .addIndex("measure_filters_name", "name") .addNotNullableVarcharColumn("name", 100) .addVarcharColumn("description", 4000) + .addClobColumn("data") .execute(); // issues @@ -362,6 +365,7 @@ public class FixMsSqlCollation extends DdlChange { .addNotNullableVarcharColumn("name", 100) .addVarcharColumn("user_login", 255) .addVarcharColumn("description", 4000) + .addClobColumn("data") .execute(); // issue_filter_favourites @@ -396,6 +400,7 @@ public class FixMsSqlCollation extends DdlChange { .addVarcharColumn("log_type", 250) .addVarcharColumn("log_action", 250) .addVarcharColumn("log_message", 250) + .addClobColumn("data_field") .execute(); // file_sources @@ -404,6 +409,7 @@ public class FixMsSqlCollation extends DdlChange { .addUniqueIndex("file_sources_uuid_type", "file_uuid", "data_type") .addNotNullableVarcharColumn("project_uuid", 50) .addNotNullableVarcharColumn("file_uuid", 50) + .addClobColumn("line_hashes") .addVarcharColumn("data_type", 20) .addVarcharColumn("data_hash", 50) .addVarcharColumn("src_hash", 50)
SONAR-<I> Add missing clob columns migration The following columns were not migrated activities.data_field, file_sources .line_hashes, issue_filters.data, measure_filters.data, properties.text_value and rules.note_data
SonarSource_sonarqube
train
28f7f01d5066d93fcaa7229a93c00aa27e232047
diff --git a/src/org/jgroups/JChannel.java b/src/org/jgroups/JChannel.java index <HASH>..<HASH> 100644 --- a/src/org/jgroups/JChannel.java +++ b/src/org/jgroups/JChannel.java @@ -67,7 +67,7 @@ import java.util.Vector; * the construction of the stack will be aborted. * * @author Bela Ban - * @version $Id: JChannel.java,v 1.101 2006/10/23 12:30:33 belaban Exp $ + * @version $Id: JChannel.java,v 1.102 2006/10/23 16:11:09 vlada Exp $ */ public class JChannel extends Channel { @@ -424,9 +424,8 @@ public class JChannel extends Channel { //if FLUSH is used do not return from connect() until UNBLOCK event is received boolean singletonMember = my_view != null && my_view.size() == 1; - boolean needToWaitOnFlushCompletion = flush_supported && !singletonMember && !flush_unblock_promise.hasResult(); - - if(needToWaitOnFlushCompletion){ + boolean shouldWaitForUnblock = flush_supported && receive_blocks && !singletonMember && !flush_unblock_promise.hasResult(); + if(shouldWaitForUnblock){ try{ flush_unblock_promise.getResultWithTimeout(FLUSH_UNBLOCK_TIMEOUT); } @@ -1386,7 +1385,8 @@ public class JChannel extends Channel { Boolean state_transfer_successfull=(Boolean)state_promise.getResult(info.timeout); //if FLUSH is used do not return from getState() until UNBLOCK event is received - if(flush_supported){ + boolean shouldWaitForUnblock = flush_supported && receive_blocks; + if(shouldWaitForUnblock){ try{ flush_unblock_promise.getResultWithTimeout(FLUSH_UNBLOCK_TIMEOUT); }
handle Channel.BLOCK (on/off) and FLUSH combinations properly
belaban_JGroups
train
288fa3be1331544bbe6dc2ce721527a2b75d50df
diff --git a/lib/neo4j/active_node/dependent/association_methods.rb b/lib/neo4j/active_node/dependent/association_methods.rb index <HASH>..<HASH> 100644 --- a/lib/neo4j/active_node/dependent/association_methods.rb +++ b/lib/neo4j/active_node/dependent/association_methods.rb @@ -28,7 +28,8 @@ module Neo4j end def dependent_delete_orphans_callback(object) - object.as(:self).unique_nodes(self, :self, :n, :other_rel).query.delete(:n, :other_rel).exec + unique_query = object.as(:self).unique_nodes(self, :self, :n, :other_rel) + unique_query.query.detach_delete(:n).exec if unique_query end def dependent_destroy_callback(object) diff --git a/spec/e2e/association_dependency_spec.rb b/spec/e2e/association_dependency_spec.rb index <HASH>..<HASH> 100644 --- a/spec/e2e/association_dependency_spec.rb +++ b/spec/e2e/association_dependency_spec.rb @@ -36,7 +36,7 @@ describe 'association dependent delete/destroy' do after_destroy lambda { CALL_COUNT[:called] += 1 } property :city has_many :in, :routes, model_class: 'Route', origin: :stops - has_many :out, :comments, model_class: 'Comment', type: 'HAS_COMMENT', dependent: :destroy + has_many :out, :comments, model_class: 'Comment', type: 'HAS_COMMENT', dependent: :delete_orphans has_one :out, :poorly_modeled_thing, model_class: 'BadModel', type: 'HAS_TERRIBLE_MODEL', dependent: :delete has_many :out, :poorly_modeled_things, model_class: 'BadModel', type: 'HAS_TERRIBLE_MODELS', dependent: :delete end
Change association methods and test to show/fix error
neo4jrb_neo4j
train
ffa42d4015c25d234d8449697d59c6a74d1b14aa
diff --git a/octodns/cmds/args.py b/octodns/cmds/args.py index <HASH>..<HASH> 100644 --- a/octodns/cmds/args.py +++ b/octodns/cmds/args.py @@ -43,9 +43,7 @@ class ArgumentParser(_Base): return args def _setup_logging(self, args, default_log_level): - # TODO: if/when things are multi-threaded add [%(thread)d] in to the - # format - fmt = '%(asctime)s %(levelname)-5s %(name)s %(message)s' + fmt = '%(asctime)s [%(thread)d] %(levelname)-5s %(name)s %(message)s' formatter = Formatter(fmt=fmt, datefmt='%Y-%m-%dT%H:%M:%S ') stream = stdout if args.log_stream_stdout else stderr handler = StreamHandler(stream=stream)
Add thread-id to log format
github_octodns
train
c9aff970bf4a4bebf504a89718109812a30b1a20
diff --git a/addons/content-index/src/main/java/org/commonjava/indy/content/index/IndexingContentManagerDecorator.java b/addons/content-index/src/main/java/org/commonjava/indy/content/index/IndexingContentManagerDecorator.java index <HASH>..<HASH> 100644 --- a/addons/content-index/src/main/java/org/commonjava/indy/content/index/IndexingContentManagerDecorator.java +++ b/addons/content-index/src/main/java/org/commonjava/indy/content/index/IndexingContentManagerDecorator.java @@ -371,7 +371,7 @@ public abstract class IndexingContentManagerDecorator if ( storePath != null ) { - Transfer transfer = delegate.getTransfer( storeKey, path, op ); + Transfer transfer = delegate.getTransfer( storePath.getStoreKey(), path, op ); if ( transfer == null || !transfer.exists() ) { logger.trace( "Found obsolete index entry: {}. De-indexing from: {} and {}", storeKey, topKey );
[Content Index] Fix wrong usage of the indexed store key
Commonjava_indy
train
cf44558ca3490127f088998b63419eb0d4ada303
diff --git a/src/Site_Command.php b/src/Site_Command.php index <HASH>..<HASH> 100644 --- a/src/Site_Command.php +++ b/src/Site_Command.php @@ -651,6 +651,82 @@ class Site_Command extends \WP_CLI\CommandWithDBObject { $this->update_site_status( $args, 'spam', 0 ); } + /** + * Set one or more sites to mature. + * + * ## OPTIONS + * + * <id>... + * : One or more IDs of sites to set as mature. + * + * ## EXAMPLES + * + * $ wp site mature 123 + * Success: Site 123 set to mature. + * + * @subcommand mature + */ + public function mature( $args ) { + $this->update_site_status( $args, 'mature', 1 ); + } + + /** + * Set one or more sites for general audience. + * + * ## OPTIONS + * + * <id>... + * : One or more IDs of sites to set for general audience. + * + * ## EXAMPLES + * + * $ wp site general 123 + * Success: Site 123 marked for general audience. + * + * @subcommand general + */ + public function general( $args ) { + $this->update_site_status( $args, 'mature', 1 ); + } + + /** + * Set one or more sites to public. + * + * ## OPTIONS + * + * <id>... + * : One or more IDs of sites to set as public. + * + * ## EXAMPLES + * + * $ wp site public 123 + * Success: Site 123 marked as public. + * + * @subcommand public + */ + public function set_public( $args ) { + $this->update_site_status( $args, 'public', 1 ); + } + + /** + * Set one or more sites to private. + * + * ## OPTIONS + * + * <id>... + * : One or more IDs of sites to set as private. + * + * ## EXAMPLES + * + * $ wp site private 123 + * Success: Site 123 marked as private. + * + * @subcommand private + */ + public function set_private( $args ) { + $this->update_site_status( $args, 'public', 0 ); + } + private function update_site_status( $ids, $pref, $value ) { if ( $pref == 'archived' && $value == 1 ) { $action = 'archived'; @@ -664,6 +740,14 @@ class Site_Command extends \WP_CLI\CommandWithDBObject { $action = 'marked as spam'; } else if ( $pref == 'spam' && $value == 0 ) { $action = 'removed from spam'; + } else if ( $pref == 'public' && $value == 1 ) { + $action = 'marked as public'; + } else if ( $pref == 'public' && $value == 0 ) { + $action = 'marked as private'; + } else if ( $pref == 'mature' && $value == 1 ) { + $action = 'set to mature'; + } else if ( $pref == 'mature' && $value == 0 ) { + $action = 'marked for general audience'; } foreach ( $ids as $site_id ) {
GH#<I> Added support for mature and public status types
wp-cli_entity-command
train
426cef30b73edf157a94ff39cabeda82e2112ee2
diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java index <HASH>..<HASH> 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java @@ -38,20 +38,13 @@ import java.util.LinkedList; */ public final class SelectEncryptItemTokenGenerator implements CollectionSQLTokenGenerator<EncryptRule> { - private EncryptRule encryptRule; - - private OptimizedStatement optimizedStatement; - - private boolean isQueryWithCipherColumn; - @Override public Collection<SelectEncryptItemToken> generateSQLTokens(final OptimizedStatement optimizedStatement, final ParameterBuilder parameterBuilder, final EncryptRule rule, final boolean isQueryWithCipherColumn) { if (!isNeedToGenerateSQLToken(optimizedStatement)) { return Collections.emptyList(); } - initParameters(rule, optimizedStatement, isQueryWithCipherColumn); - return createSelectCipherItemTokens(); + return createSelectCipherItemTokens(rule, optimizedStatement, isQueryWithCipherColumn); } private boolean isNeedToGenerateSQLToken(final OptimizedStatement optimizedStatement) { @@ -66,20 +59,14 @@ public final class SelectEncryptItemTokenGenerator implements CollectionSQLToken return optimizedStatement.getSQLStatement() instanceof SelectStatement && !optimizedStatement.getTables().isEmpty(); } - private void initParameters(final EncryptRule rule, final OptimizedStatement optimizedStatement, final boolean isQueryWithCipherColumn) { - encryptRule = rule; - this.optimizedStatement = optimizedStatement; - this.isQueryWithCipherColumn = isQueryWithCipherColumn; - } - - private Collection<SelectEncryptItemToken> createSelectCipherItemTokens() { + private Collection<SelectEncryptItemToken> createSelectCipherItemTokens(final EncryptRule encryptRule, final OptimizedStatement optimizedStatement, final boolean isQueryWithCipherColumn) { Collection<SelectEncryptItemToken> result = new LinkedList<>(); SelectItemsSegment selectItemsSegment = optimizedStatement.getSQLStatement().findSQLSegment(SelectItemsSegment.class).get(); String tableName = optimizedStatement.getTables().getSingleTableName(); Collection<String> logicColumns = encryptRule.getLogicColumns(tableName); for (SelectItemSegment each : selectItemsSegment.getSelectItems()) { if (isLogicColumn(each, logicColumns)) { - result.add(createSelectCipherItemToken(each, tableName)); + result.add(createSelectCipherItemToken(each, tableName, encryptRule, isQueryWithCipherColumn)); } } return result; @@ -89,7 +76,7 @@ public final class SelectEncryptItemTokenGenerator implements CollectionSQLToken return each instanceof ColumnSelectItemSegment && logicColumns.contains(((ColumnSelectItemSegment) each).getName()); } - private SelectEncryptItemToken createSelectCipherItemToken(final SelectItemSegment each, final String tableName) { + private SelectEncryptItemToken createSelectCipherItemToken(final SelectItemSegment each, final String tableName, final EncryptRule encryptRule, final boolean isQueryWithCipherColumn) { String columnName = ((ColumnSelectItemSegment) each).getName(); Optional<String> plainColumn = encryptRule.getPlainColumn(tableName, columnName); if (!isQueryWithCipherColumn && plainColumn.isPresent()) {
delete members for SelectEncryptItemTokenGenerator
apache_incubator-shardingsphere
train
7c519f3896cf522b3083226c9f65c76f756f3532
diff --git a/src/Contracts/Refinery.php b/src/Contracts/Refinery.php index <HASH>..<HASH> 100644 --- a/src/Contracts/Refinery.php +++ b/src/Contracts/Refinery.php @@ -16,9 +16,10 @@ interface Refinery * Refine a collection of raw items. * * @param mixed $raw + * @param boolean $retainKey * @return array */ - public function refineCollection($raw); + public function refineCollection($raw, $retainKey); /** * Set the attachments you want to bring with the refined items. diff --git a/src/Refinery.php b/src/Refinery.php index <HASH>..<HASH> 100644 --- a/src/Refinery.php +++ b/src/Refinery.php @@ -2,10 +2,10 @@ namespace Michaeljennings\Refinery; -use Traversable; -use Michaeljennings\Refinery\Exceptions\RefineryMethodNotFound; -use Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound; use Michaeljennings\Refinery\Contracts\Refinery as RefineryContract; +use Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound; +use Michaeljennings\Refinery\Exceptions\RefineryMethodNotFound; +use Traversable; abstract class Refinery implements RefineryContract { @@ -31,6 +31,13 @@ abstract class Refinery implements RefineryContract protected $attributes = []; /** + * If we are iterating through a collection this will be the key of the current item. + * + * @var mixed + */ + protected $key; + + /** * Set the template the refinery will use for each item passed to it * * @param mixed $item @@ -42,12 +49,13 @@ abstract class Refinery implements RefineryContract * Refine the item(s) using the set template. * * @param mixed $raw + * @param bool $retainKey * @return mixed */ - public function refine($raw) + public function refine($raw, $retainKey = false) { if ((is_array($raw) && $this->isMultidimensional($raw)) || $raw instanceof Traversable) { - return $this->refineCollection($raw); + return $this->refineCollection($raw, $retainKey); } return $this->refineItem($raw); @@ -74,14 +82,20 @@ abstract class Refinery implements RefineryContract * Refine a collection of raw items. * * @param mixed $raw + * @param boolean $retainKey * @return array */ - public function refineCollection($raw) + public function refineCollection($raw, $retainKey) { $refined = []; - foreach ($raw as $item) { - $refined[] = $this->refineItem($item); + foreach ($raw as $key => $item) { + if ($retainKey) { + $this->key = $key; + $refined[ $key ] = $this->refineItem($item); + } else { + $refined[] = $this->refineItem($item); + } } return $refined; @@ -375,6 +389,16 @@ abstract class Refinery implements RefineryContract } /** + * Get the current key. + * + * @return mixed + */ + public function getKey() + { + return $this->key; + } + + /** * Use the __get magic method to access the items within the $attributes * array is if you were accessing a property on the class. *
modified Refinery class to optionally retain the key of the object being refined
michaeljennings_refinery
train
b78f64d4b76555581491ee258c92f143dbb0edfa
diff --git a/eZ/Publish/Core/REST/Server/Tests/Input/Parser/Criterion/LogicalAndTest.php b/eZ/Publish/Core/REST/Server/Tests/Input/Parser/Criterion/LogicalAndTest.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/REST/Server/Tests/Input/Parser/Criterion/LogicalAndTest.php +++ b/eZ/Publish/Core/REST/Server/Tests/Input/Parser/Criterion/LogicalAndTest.php @@ -53,9 +53,9 @@ class LogicalAndTest extends BaseTest ], ]; - $criterionMock = $this->getMock(Content\Query\Criterion::class, [], [], '', false); + $criterionMock = $this->createMock(Content\Query\Criterion::class, [], [], '', false); - $parserMock = $this->getMock(\eZ\Publish\Core\REST\Common\Input\Parser::class); + $parserMock = $this->createMock(\eZ\Publish\Core\REST\Common\Input\Parser::class); $parserMock->method('parse')->willReturn($criterionMock); $result = $this->internalGetParser()->parse($logicalAndParsedFromXml, new ParsingDispatcher([ diff --git a/eZ/Publish/Core/REST/Server/Tests/Input/Parser/Criterion/LogicalOrTest.php b/eZ/Publish/Core/REST/Server/Tests/Input/Parser/Criterion/LogicalOrTest.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/REST/Server/Tests/Input/Parser/Criterion/LogicalOrTest.php +++ b/eZ/Publish/Core/REST/Server/Tests/Input/Parser/Criterion/LogicalOrTest.php @@ -65,9 +65,9 @@ class LogicalOrTest extends BaseTest ], ]; - $criterionMock = $this->getMock(Content\Query\Criterion::class, [], [], '', false); + $criterionMock = $this->createMock(Content\Query\Criterion::class, [], [], '', false); - $parserMock = $this->getMock(\eZ\Publish\Core\REST\Common\Input\Parser::class); + $parserMock = $this->createMock(\eZ\Publish\Core\REST\Common\Input\Parser::class); $parserMock->method('parse')->willReturn($criterionMock); $result = $this->internalGetParser()->parse($logicalOrParsedFromXml, new ParsingDispatcher([
Aligned unit tests of REST parsers for logical op. to use createMock
ezsystems_ezpublish-kernel
train
3d596e1dd69cb13976209e23524bd1b4e70ef497
diff --git a/unit_systems.py b/unit_systems.py index <HASH>..<HASH> 100644 --- a/unit_systems.py +++ b/unit_systems.py @@ -109,10 +109,16 @@ class UnitSystem(object): repr += " %s: %s\n" % (key, self.units_map[dim]) return repr -def create_code_unit_system(ds): - code_unit_system = UnitSystem(str(ds), "code_length", "code_mass", "code_time", - "code_temperature", registry=ds.unit_registry) +def create_code_unit_system(ds, current_mks_unit=None): + code_unit_system = UnitSystem( + str(ds), "code_length", "code_mass", "code_time", "code_temperature", + current_mks_unit=current_mks_unit, registry=ds.unit_registry) code_unit_system["velocity"] = "code_velocity" + if current_mks_unit: + code_unit_system["magnetic_field_mks"] = "code_magnetic" + else: + code_unit_system["magnetic_field_cgs"] = "code_magnetic" + code_unit_system["pressure"] = "code_pressure" cgs_unit_system = UnitSystem("cgs", "cm", "g", "s") cgs_unit_system["energy"] = "erg"
Make it possible to create a code unit system with MKS base units --HG-- branch : yt
yt-project_unyt
train
68b805288483cd58267bb1ded9e2adb7793936a2
diff --git a/indra/tests/test_pybel_api.py b/indra/tests/test_pybel_api.py index <HASH>..<HASH> 100644 --- a/indra/tests/test_pybel_api.py +++ b/indra/tests/test_pybel_api.py @@ -160,8 +160,8 @@ def test_get_agent_sfam(): ) agent = pb.get_agent(node_data) assert isinstance(agent, Agent) - assert len(agent.db_refs) == 2 - assert agent.db_refs['SFAM'] == 'PRKC Family' + assert len(agent.db_refs) == 2, agent.db_refs + assert agent.db_refs['SFAM'] == 'F0198', agent.db_refs assert agent.db_refs['FPLX'] == 'PKC' assert agent.name == 'PKC' @@ -172,7 +172,7 @@ def test_get_agent_sdis(): assert isinstance(agent, Agent) assert agent.name == 'metastasis' assert len(agent.db_refs) == 1 - assert agent.db_refs['SDIS'] == 'metastasis' + assert agent.db_refs['SDIS'] == 'D0340', agent.db_refs def test_get_agent_chebi(): @@ -189,8 +189,8 @@ def test_get_agent_schem(): agent = pb.get_agent(node_data) assert isinstance(agent, Agent) assert agent.name == 'Promegestone' - assert len(agent.db_refs) == 1 - assert agent.db_refs['SCHEM'] == 'Promegestone' + assert len(agent.db_refs) == 2, agent.db_refs + assert agent.db_refs['SCHEM'] == 'A2173', agent.db_refs def test_get_agent_mirna():
Use Selventa IDs in tests
sorgerlab_indra
train
bfca50332d6dd5524ff6c1cde8545e3824ad6fcd
diff --git a/client.go b/client.go index <HASH>..<HASH> 100644 --- a/client.go +++ b/client.go @@ -19,6 +19,8 @@ type Client struct { roles int listeners map[ID]chan Message events map[ID]EventHandler + calls map[ID]chan Message + welcome chan Message requestCount uint } @@ -32,15 +34,36 @@ func NewWebsocketClient(serialization int, url string, realm URI, roles int) (*C ReceiveTimeout: 5 * time.Second, roles: roles, listeners: make(map[ID]chan Message), + calls: make(map[ID]chan Message), events: make(map[ID]EventHandler), + welcome: make(chan Message), requestCount: 0, } go c.Receive() - // TODO: add roles to hello - c.Send(&Hello{Realm: realm}) + + roles_map := make(map[string]interface{}) + roles_map["publisher"] = make(map[string]interface{}) + roles_map["subscriber"] = make(map[string]interface{}) + roles_map["callee"] = make(map[string]interface{}) + roles_map["caller"] = make(map[string]interface{}) + + details := make(map[string]interface{}) + details["roles"] = roles_map + + c.Send(&Hello{Realm: realm, Details: details}) return c, nil } +func (c *Client) WaitForSession() (msg Message, err error) { + // wait to receive WELCOME message + select { + case msg := <-c.welcome: + return msg, nil + case <-time.After(c.ReceiveTimeout): + return nil, fmt.Errorf("timeout while waiting for message") + } +} + func (c *Client) nextID() ID { c.requestCount++ return ID(c.requestCount) @@ -55,6 +78,17 @@ func (c *Client) Receive() { } else { log.Println("no handler registered for subscription:", msg.Subscription) } + + case *Result: + if l, ok := c.calls[msg.Request]; ok { + l <- msg + } else { + log.Println("no handler registered for call:", msg.Request) + } + + case *Welcome: + c.welcome <- msg + case *Subscribed: if l, ok := c.listeners[msg.Request]; ok { l <- msg @@ -120,3 +154,28 @@ func (c *Client) Publish(topic URI, args []interface{}, kwargs map[string]interf ArgumentsKw: kwargs, }) } + +func (c *Client) Call(procedure URI, args []interface{}, kwargs map[string]interface{}) (msg Message, err error) { + callId := c.nextID() + result := make(chan Message, 1) + + c.calls[callId] = result + + if err := c.Send(&Call{ + Request: callId, + Procedure: procedure, + Options: make(map[string]interface{}), + Arguments: args, + ArgumentsKw: kwargs, + }); err != nil { + return nil, err + } + + // wait to receive RESULT message + select { + case msg = <-result: + return msg, nil + case <-time.After(c.ReceiveTimeout): + return nil, fmt.Errorf("timeout while waiting for message") + } +}
Begin work on adding RPC support: - Add the Call method for invoking a remote RPC - Have the HELLO message include the roles - Add a WaitForSession method which waits for the session WELCOME message. Callers can use this to make sure a valid session exists before starting RPC calls.
gngeorgiev_gowamp
train
d51802916fb65bd595481ed54d10f90d300b4897
diff --git a/ccmlib/node.py b/ccmlib/node.py index <HASH>..<HASH> 100644 --- a/ccmlib/node.py +++ b/ccmlib/node.py @@ -512,6 +512,8 @@ class Node(object): common.check_socket_available(itf) if wait_other_notice: + if not join_ring: + raise NodeError("Other nodes will never see this node %s as UP when join_ring=False" % self.name) marks = [(node, node.mark_log()) for node in list(self.cluster.nodes.values()) if node.is_live()] self.mark = self.mark_log()
Assert that wait_other_notice and join_ring are not used together.
riptano_ccm
train
ef02f4336850986da6a53a8e6d067503e008f0fe
diff --git a/libvcs/shortcuts.py b/libvcs/shortcuts.py index <HASH>..<HASH> 100644 --- a/libvcs/shortcuts.py +++ b/libvcs/shortcuts.py @@ -6,8 +6,7 @@ from typing import Union from libvcs import GitProject, MercurialProject, SubversionProject from libvcs._internal.run import ProgressCallbackProtocol from libvcs.exc import InvalidPipURL, InvalidVCS - -VCSLiteral = t.Literal["git", "svn", "hg"] +from libvcs.types import VCSLiteral @t.overload
chore(shortcuts): Import VCSLiteral from typings
vcs-python_libvcs
train
921dc0675511d65fe4446f8575abe34b79f6fc17
diff --git a/lib/intl-phone-number.js b/lib/intl-phone-number.js index <HASH>..<HASH> 100644 --- a/lib/intl-phone-number.js +++ b/lib/intl-phone-number.js @@ -5,8 +5,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.IntlPhoneNumber = undefined; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // import { phoneUtil } from 'libphonenumber'; - +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _googleLibphonenumber = require('google-libphonenumber');
chore(*): compiled es6 src for publishing
Dashride_mongoose-intl-phone-number
train
e0df12243ee08a4d6fca3241142212428dfd632e
diff --git a/src/Guzzle/Http/Message/Response.php b/src/Guzzle/Http/Message/Response.php index <HASH>..<HASH> 100644 --- a/src/Guzzle/Http/Message/Response.php +++ b/src/Guzzle/Http/Message/Response.php @@ -883,7 +883,7 @@ class Response extends AbstractMessage implements \Serializable libxml_clear_errors(); try { - $xml = new \SimpleXMLElement((string) $this->body ?: '<root />'); + $xml = new \SimpleXMLElement((string) $this->body ?: '<root />', LIBXML_NONET); if ($error = libxml_get_last_error()) { $errorMessage = $error->message; }
Disabling network access when loading XML responses
guzzle_guzzle3
train
d0ef976fc9099ab1692256a10aa76ad11a2069b7
diff --git a/lib/mobilize-base/models/user.rb b/lib/mobilize-base/models/user.rb index <HASH>..<HASH> 100644 --- a/lib/mobilize-base/models/user.rb +++ b/lib/mobilize-base/models/user.rb @@ -27,6 +27,22 @@ module Mobilize return u.runner.jobs end + def creds(gdrive_slot) + u = self + creds_path = "#{u.runner.path.split("/").first}/creds" + begin + creds_sheet = Gsheet.find_by_path(creds_path,gdrive_slot) + cred_array = creds_sheet.read(u.name).tsv_to_hash_array.map{|h| {h['name']=>{'user'=>h['user'],'password'=>h['password']}}} + result = {} + cred_array.each do |cred| + result[cred.keys.first] = cred.values.first + end + return result + rescue + return {} + end + end + def runner_path u = self prefix = "Runner_" diff --git a/lib/mobilize-base/tasks.rb b/lib/mobilize-base/tasks.rb index <HASH>..<HASH> 100644 --- a/lib/mobilize-base/tasks.rb +++ b/lib/mobilize-base/tasks.rb @@ -2,15 +2,13 @@ namespace :mobilize_base do desc "Start a Resque worker" task :work do require 'mobilize-base' - begin - #require specified mobilize gems - Mobilize::Base.config('jobtracker')['extensions'].each do |e| + Mobilize::Base.config('jobtracker')['extensions'].each do |e| + begin require e + rescue Exception=>exc + #do nothing end - rescue Exception=>exc - #do nothing end - begin worker = Resque::Worker.new(Mobilize::Resque.config['queue_name']) rescue Resque::NoQueueError diff --git a/lib/mobilize-base/version.rb b/lib/mobilize-base/version.rb index <HASH>..<HASH> 100644 --- a/lib/mobilize-base/version.rb +++ b/lib/mobilize-base/version.rb @@ -1,5 +1,5 @@ module Mobilize module Base - VERSION = "1.1.0" + VERSION = "1.1.01" end end
added creds, fixed startup process, bumped version
DeNA_mobilize-base
train
871c0e631d25a7c6d70813aa6c21b6e97193e2a9
diff --git a/test/lib/roster.js b/test/lib/roster.js index <HASH>..<HASH> 100644 --- a/test/lib/roster.js +++ b/test/lib/roster.js @@ -123,6 +123,10 @@ describe('Roster', function() { ) }) + it('Can handle roster add with additional data', function(done) { + done('Need to include groups and name in request') + }) + }) }) })
Broken test so I can remember where I am next time I start coding
xmpp-ftw_xmpp-ftw
train
1673dd7ee7a8ee640ab8ede969a9d3718c1a2300
diff --git a/mqlight.js b/mqlight.js index <HASH>..<HASH> 100644 --- a/mqlight.js +++ b/mqlight.js @@ -816,7 +816,14 @@ var Client = function(service, id, securityOptions) { } logger.log('data', client.id, 'attempting to connect to: ' + logUrl); - var rc = client.messenger.connect(url.parse(service), + var connectUrl = url.parse(service); + // remove any path elements from the URL (for ipv6 which appends /) + if (connectUrl.path) { + var hrefLength = connectUrl.href.length - connectUrl.path.length; + connectUrl.href = connectUrl.href.substr(0, hrefLength); + connectUrl.pathname = connectUrl.path = null; + } + var rc = client.messenger.connect(connectUrl, securityOptions.sslTrustCertificate, securityOptions.sslVerifyName); if (rc) { @@ -1802,8 +1809,8 @@ Client.prototype.checkForMessages = function() { protonMsg.linkAddress.indexOf('share:') === 0) { //starting after the share: look for the next : denoting the end //of the share name and get everything past that - var linkNoShare = protonMsg.linkAddress.slice - (protonMsg.linkAddress.indexOf(':', 7) + 1); + var linkNoShare = protonMsg.linkAddress.slice( + protonMsg.linkAddress.indexOf(':', 7) + 1); if (addressNoService === linkNoShare) { return el; }
strip trailing path from url.parse(service) before passing it to messenger.connect
mqlight_nodejs-mqlight
train
a5584ca843fc95b2aa68d075d2a5e589d8dfa3c2
diff --git a/src/Sylius/Bundle/AdminBundle/Resources/private/js/sylius-lazy-choice-tree.js b/src/Sylius/Bundle/AdminBundle/Resources/private/js/sylius-lazy-choice-tree.js index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/AdminBundle/Resources/private/js/sylius-lazy-choice-tree.js +++ b/src/Sylius/Bundle/AdminBundle/Resources/private/js/sylius-lazy-choice-tree.js @@ -155,13 +155,13 @@ checkboxElement.checkbox({ onChecked: function() { var value = checkboxElement.data('value'); - var checkedValues = $input.val().split(",").filter(x => x); + var checkedValues = $input.val().split(",").filter(function(x) { return x; }); checkedValues.push(value); $input.val(checkedValues.join()); }, onUnchecked: function() { var value = checkboxElement.data('value'); - var checkedValues = $input.val().split(",").filter(x => x); + var checkedValues = $input.val().split(",").filter(function(x) { return x; }); var i = checkedValues.indexOf(value); if(i != -1) { checkedValues.splice(i, 1);
Fix #<I> by removing lambdas in JS file
Sylius_Sylius
train
a90b8cc578679bb9f3f4f7cb97b1ec4eaaba8b76
diff --git a/tests/test_typeddict.py b/tests/test_typeddict.py index <HASH>..<HASH> 100644 --- a/tests/test_typeddict.py +++ b/tests/test_typeddict.py @@ -38,6 +38,7 @@ class TestTypeddictLoad(unittest.TestCase): o = {'name': 'pino', 'age': 1.1} assert load(o, Person) == o assert load({'val': 3}, A) == {'val': '3'} + assert load({'val': 3, 'vil': 4}, A) == {'val': '3'} with self.assertRaises(ValueError): o.pop('age')
Make sure that extra values for TypedDict are discarded
ltworf_typedload
train
8817db4f25af24abd48af099bfd6bf97f07ea0cd
diff --git a/zappa/cli.py b/zappa/cli.py index <HASH>..<HASH> 100644 --- a/zappa/cli.py +++ b/zappa/cli.py @@ -348,13 +348,13 @@ class ZappaCLI(object): if self.zappa_settings[self.api_stage].get('events'): events = self.zappa_settings[self.api_stage]['events'] - if type(events) != list: + if not isinstance(events, list) print("Events must be supplied as a list.") return try: function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name) - except botocore.exceptions.ClientError as e: + except botocore.exceptions.ClientError as e: # pragma: no cover print("Function does not exist, please deploy first. Ex: zappa deploy {}".format(self.api_stage)) return @@ -375,7 +375,7 @@ class ZappaCLI(object): if self.zappa_settings[self.api_stage].get('events', None): events = self.zappa_settings[self.api_stage]['events'] - if type(events) != type([]): + if not isinstance(events, list): print("Events must be supplied as a list.") return
Add pragma / refactor
Miserlou_Zappa
train
5ab9e61169cb552bffeea60143c6d55f9ed46b18
diff --git a/src/IP.php b/src/IP.php index <HASH>..<HASH> 100644 --- a/src/IP.php +++ b/src/IP.php @@ -3,7 +3,7 @@ * Piwik - free/libre analytics platform * * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL v3 or later */ namespace Piwik\Network; diff --git a/src/IPUtils.php b/src/IPUtils.php index <HASH>..<HASH> 100644 --- a/src/IPUtils.php +++ b/src/IPUtils.php @@ -3,7 +3,7 @@ * Piwik - free/libre analytics platform * * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL v3 or later */ namespace Piwik\Network; diff --git a/src/IPv4.php b/src/IPv4.php index <HASH>..<HASH> 100644 --- a/src/IPv4.php +++ b/src/IPv4.php @@ -3,7 +3,7 @@ * Piwik - free/libre analytics platform * * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL v3 or later */ namespace Piwik\Network; diff --git a/src/IPv6.php b/src/IPv6.php index <HASH>..<HASH> 100644 --- a/src/IPv6.php +++ b/src/IPv6.php @@ -3,7 +3,7 @@ * Piwik - free/libre analytics platform * * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL v3 or later */ namespace Piwik\Network; diff --git a/tests/IPTest.php b/tests/IPTest.php index <HASH>..<HASH> 100644 --- a/tests/IPTest.php +++ b/tests/IPTest.php @@ -3,7 +3,7 @@ * Piwik - free/libre analytics platform * * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL v3 or later */ namespace Tests\Piwik\Network; diff --git a/tests/IPUtilsTest.php b/tests/IPUtilsTest.php index <HASH>..<HASH> 100644 --- a/tests/IPUtilsTest.php +++ b/tests/IPUtilsTest.php @@ -3,7 +3,7 @@ * Piwik - free/libre analytics platform * * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL v3 or later */ namespace Tests\Piwik\Network; diff --git a/tests/IPv4Test.php b/tests/IPv4Test.php index <HASH>..<HASH> 100644 --- a/tests/IPv4Test.php +++ b/tests/IPv4Test.php @@ -3,7 +3,7 @@ * Piwik - free/libre analytics platform * * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL v3 or later */ namespace Tests\Piwik\Network; diff --git a/tests/IPv6Test.php b/tests/IPv6Test.php index <HASH>..<HASH> 100644 --- a/tests/IPv6Test.php +++ b/tests/IPv6Test.php @@ -3,7 +3,7 @@ * Piwik - free/libre analytics platform * * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL v3 or later */ namespace Tests\Piwik\Network;
#2 Fixed license in phpdocs
matomo-org_component-network
train
5cb41f6359c3203fd955fa08fed7c314a099994a
diff --git a/src/Composer/Package.php b/src/Composer/Package.php index <HASH>..<HASH> 100644 --- a/src/Composer/Package.php +++ b/src/Composer/Package.php @@ -242,6 +242,11 @@ class Package { * TRUE if the package is an asset library, otherwise FALSE. */ protected function isLibrary(array $package) { + // Add Swiftmailer support. + if ($package['name'] == 'swiftmailer/swiftmailer') { + $package['type'] = 'drupal-library'; + } + $package_types = [ 'drupal-library', 'bower-asset',
Add Swiftmailer support to distribution package script
govCMS_govCMS8
train
11f14edd3ab4fb852a13574071fe616bbb41c720
diff --git a/CHANGES.md b/CHANGES.md index <HASH>..<HASH> 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,7 +4,7 @@ rerNews 0.7.6 ----- -*Release date: TBD* +*Release date: 2017-08-TBD* * Bug Fixes * Case-sensitive command parsing was completely broken and has been fixed @@ -14,6 +14,7 @@ rerNews * Enhancements * Enhanced tab-completion of cmd2 command names to support case-insensitive completion * Added an example showing how to remove unused commands + * Improved how transcript testing handles prompts with ANSI escape codes by stripping them 0.7.5 ----- diff --git a/cmd2.py b/cmd2.py index <HASH>..<HASH> 100755 --- a/cmd2.py +++ b/cmd2.py @@ -75,7 +75,7 @@ try: except ImportError: pass -__version__ = '0.7.6a' +__version__ = '0.7.6' # Pyparsing enablePackrat() can greatly speed up parsing, but problems have been seen in Python 3 in the past pyparsing.ParserElement.enablePackrat() diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -62,7 +62,7 @@ author = 'Catherine Devlin and Todd Leonhardt' # The short X.Y version. version = '0.7' # The full version, including alpha/beta/rc tags. -release = '0.7.5' +release = '0.7.6' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ Setuptools setup file, used to install or test 'cmd2' """ from setuptools import setup -VERSION = '0.7.6a' +VERSION = '0.7.6' DESCRIPTION = "cmd2 - a tool for building interactive command line applications in Python" LONG_DESCRIPTION = """cmd2 is a tool for building interactive command line applications in Python. Its goal is to make it quick and easy for developers to build feature-rich and user-friendly interactive command line applications. It diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index <HASH>..<HASH> 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -22,7 +22,7 @@ from conftest import run_cmd, normalize, BASE_HELP, HELP_HISTORY, SHORTCUTS_TXT, def test_ver(): - assert cmd2.__version__ == '0.7.6a' + assert cmd2.__version__ == '0.7.6' def test_empty_statement(base_app):
Updated CHANGES and bumped version in preparation for <I> release
python-cmd2_cmd2
train
86a66cd71552f771e54b0f52730e087a4c4ae089
diff --git a/lib/codemirror.js b/lib/codemirror.js index <HASH>..<HASH> 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -1303,8 +1303,6 @@ var CodeMirror = (function() { return line; } function setLineClass(handle, className) { - if (typeof handle != "number" && handle.parent == null) - console.log(handle == getLine(0)); return changeLine(handle, function(line) { if (line.className != className) { line.className = className;
Remove debug statement that got left behind
codemirror_CodeMirror
train
b92879a9c4ecead55d9a836206db129e120a55f7
diff --git a/application/tests/_ci_phpunit_test/functions.php b/application/tests/_ci_phpunit_test/functions.php index <HASH>..<HASH> 100644 --- a/application/tests/_ci_phpunit_test/functions.php +++ b/application/tests/_ci_phpunit_test/functions.php @@ -24,6 +24,14 @@ function load_class_instance($classname, $instance) */ function reset_instance() { + // Close db connection + $CI =& get_instance(); + if (isset($CI->db)) + { + $CI->db->close(); + $CI->db = null; + } + // Reset loaded classes load_class('', '', NULL, TRUE); is_loaded('', TRUE);
Close db connection in reset_instance()
kenjis_ci-phpunit-test
train
37b5f14a5d0673a95f332cec47664eddc50c5f13
diff --git a/client/me/concierge/shared/upsell.js b/client/me/concierge/shared/upsell.js index <HASH>..<HASH> 100644 --- a/client/me/concierge/shared/upsell.js +++ b/client/me/concierge/shared/upsell.js @@ -1,4 +1,4 @@ -import { Button, CompactCard } from '@automattic/components'; +import { CompactCard } from '@automattic/components'; import { localize } from 'i18n-calypso'; import PropTypes from 'prop-types'; import { Component } from 'react'; @@ -25,13 +25,7 @@ class Upsell extends Component { <Site siteId={ site.ID } /> </CompactCard> <CompactCard> - <p> - { translate( 'You do not have any available Quick Start sessions.' ) }{ ' ' } - { translate( 'Click the button to purchase a new session.' ) } - </p> - <Button href={ `/checkout/offer-quickstart-session/${ site.slug }` } primary> - { translate( 'Learn More' ) } - </Button> + <span>{ translate( 'You do not have any available Quick Start sessions.' ) }</span> </CompactCard> </div> );
Remove Quick Start upsell CTA from booking page (#<I>)
Automattic_wp-calypso
train
8767e1dc9bd161556abfdb9323a3d74d89779db9
diff --git a/lib/marginalia.rb b/lib/marginalia.rb index <HASH>..<HASH> 100644 --- a/lib/marginalia.rb +++ b/lib/marginalia.rb @@ -8,12 +8,12 @@ module Marginalia def self.included(instrumented_class) Marginalia::Comment.components = [:application, :controller, :action] instrumented_class.class_eval do - if defined? :execute + if instrumented_class.method_defined? :execute alias_method :execute_without_marginalia, :execute alias_method :execute, :execute_with_marginalia end - if defined? :exec_query + if instrumented_class.method_defined? :exec_query alias_method :exec_query_without_marginalia, :exec_query alias_method :exec_query, :exec_query_with_marginalia end
actually check to see if the class defines the execute/exec_query methods defined?(<symbol>) doesn't seem to do anything.
basecamp_marginalia
train
497826af8a6099661126b1c3142aa39476406c52
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - Fixed the bug where the Pyxel Editor cursor malfunctions - Added new API descriptions to the example #3 - Updated the screenshot of the example #3 +- Change not to add unnecessary undo history of the editors ## 0.8.9 - Fixed the tilemap to allow the tiles of #256 or higher diff --git a/pyxel/editor/drawing_panel.py b/pyxel/editor/drawing_panel.py index <HASH>..<HASH> 100644 --- a/pyxel/editor/drawing_panel.py +++ b/pyxel/editor/drawing_panel.py @@ -65,7 +65,9 @@ class DrawingPanel(Widget): def _add_post_history(self, canvas): data = self._history_data data["after"] = canvas.copy() - self.parent.add_history(data) + + if (data["before"] != data["after"]).any(): + self.parent.add_history(data) def _screen_to_view(self, x, y): x = min(max((x - self.x - 1) // 8, 0), 15) diff --git a/pyxel/editor/music_editor.py b/pyxel/editor/music_editor.py index <HASH>..<HASH> 100644 --- a/pyxel/editor/music_editor.py +++ b/pyxel/editor/music_editor.py @@ -91,6 +91,9 @@ class MusicEditor(Editor): data["after"] = self.field_cursor.data.copy() self.add_history(self._history_data) + if data["before"] != data["after"]: + self.add_history(self._history_data) + def _play(self): self._is_playing = True diff --git a/pyxel/editor/sound_editor.py b/pyxel/editor/sound_editor.py index <HASH>..<HASH> 100644 --- a/pyxel/editor/sound_editor.py +++ b/pyxel/editor/sound_editor.py @@ -101,7 +101,9 @@ class SoundEditor(Editor): data = self._history_data data["cursor_after"] = (x, y) data["after"] = self.field_cursor.data.copy() - self.add_history(self._history_data) + + if data["before"] != data["after"]: + self.add_history(self._history_data) def _play(self): self._is_playing = True
Change not to add unnecessary undo history of the editors
kitao_pyxel
train
10c05e16a8d3e399dfa3ea2e102daef9477d7936
diff --git a/cmd/buildinfo.go b/cmd/buildinfo.go index <HASH>..<HASH> 100644 --- a/cmd/buildinfo.go +++ b/cmd/buildinfo.go @@ -6,6 +6,7 @@ import ( "github.com/choria-io/go-choria/build" "github.com/choria-io/go-protocol/protocol" + gnatsd "github.com/nats-io/gnatsd/server" ) type buildinfoCommand struct { @@ -30,7 +31,8 @@ func (b *buildinfoCommand) Run(wg *sync.WaitGroup) (err error) { fmt.Printf(" License: %s\n", build.License) fmt.Println("") fmt.Println("Network Broker Settings:") - fmt.Printf(" Maximum Network Clients: %d\n", build.MaxBrokerClients()) + fmt.Printf(" Maximum Network Clients: %d\n", build.MaxBrokerClients()) + fmt.Printf(" Embedded NATS Server Version: %s\n", gnatsd.VERSION) fmt.Println("") fmt.Println("Server Settings:") fmt.Printf(" Provisioning Brokers: %s\n", build.ProvisionBrokerURLs)
(#<I>) show the embedded gnatsd version in buildinfo
choria-io_go-choria
train
5e8be51bc33394f29a00d15c6bf0070f86df3f3d
diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -90,16 +90,6 @@ module TestDatabase assert_equal 23, User.group_by_hour_of_day(:created_at).order("hour_of_day DESC").count.keys.first end - def test_order_hour_of_day_reverse - skip if ActiveRecord::VERSION::MAJOR == 5 - assert_equal 23, User.group_by_hour_of_day(:created_at).reverse_order.count.keys.first - end - - def test_order_hour_of_day_order_reverse - skip if ActiveRecord::VERSION::MAJOR == 5 - assert_equal 0, User.group_by_hour_of_day(:created_at).order("hour_of_day desc").reverse_order.count.keys.first - end - def test_table_name # This test is to ensure there's not an error when using the table # name as part of the column name.
Make Rails <I> behavior consistent with Rails 5+
ankane_groupdate
train
bbe5edd8ddce7bae9fa4026fee7694ba6afe9d8f
diff --git a/lib/Scanner.js b/lib/Scanner.js index <HASH>..<HASH> 100644 --- a/lib/Scanner.js +++ b/lib/Scanner.js @@ -38,7 +38,7 @@ function readComment($) { expect($, '--'); let index = $.text.indexOf('-->', $.pos); if (index === -1) { - throw lexicalError('Unterminated comment', start); + throw syntaxError('Unterminated comment', start); } $.pos = index + 3; return { type: 'comment', start }; @@ -78,7 +78,7 @@ function readTag($) { // (object, string) => void function expect($, str) { if (!accept($, str)) { - throw lexicalError('Unexpected character', $.pos); + throw syntaxError('Unexpected character', $.pos); } } @@ -95,7 +95,7 @@ function accept($, str) { function expectRE($, regexp) { let str = acceptRE($, regexp); if (str === null) { - throw lexicalError('Unexpected character', $.pos); + throw syntaxError('Unexpected character', $.pos); } return str; } @@ -112,9 +112,9 @@ function acceptRE($, regexp) { } // (string, number) => object -function lexicalError(message, pos) { +function syntaxError(message, pos) { let err = Error(message); - err.name = 'LexicalError'; + err.name = 'SyntaxError'; err.pos = pos; return err; }
Replace “LexicalError” with “SyntaxError” in Scanner
cranbee_template
train
cf2dbfc25920a605167d35d85193bdca7d6f4544
diff --git a/lib/www_applet.rb b/lib/www_applet.rb index <HASH>..<HASH> 100644 --- a/lib/www_applet.rb +++ b/lib/www_applet.rb @@ -126,7 +126,7 @@ class WWW_Applet @head = tag(:head) @body = tag(:body) - @parents = [@body] + @tree = [@body] @state = [] @ids = {} end @@ -162,7 +162,7 @@ class WWW_Applet def first_class return nil unless tag[:attrs] return nil unless tag[:attrs][:class] - tag[:attrs][:class].split.first + tag[:attrs][:class].first end def html_element? e @@ -211,13 +211,13 @@ class WWW_Applet # # def selector_id - start = parents.size - 1 + start = @tree.size - 1 i = start id_given = false classes = [] while i > -1 - curr = parents[i] + curr = @tree[i] id = dom_id(curr) tag = curr[:tag] @@ -264,13 +264,13 @@ class WWW_Applet return parent[:css_id] end - start = parents.size - 1 + start = @tree.size - 1 i = start id_given = false classes = [] while i > -1 - curr = parents[i] + curr = @tree[i] id = dom_id(curr) css_class = if start == i && str_class str_class @@ -304,48 +304,45 @@ class WWW_Applet end def parents - @parents + @tree.take(@tree.size - 1) end def parent? tag - parent[:tag] == tag + parent && parent[:tag] == tag end def parent - @parents.last + @tree[-2] end def target temp - @parents.push temp + @tree.push temp result = yield - @parents.pop + @tree.pop result end - def tag *args - return parent if args.empty? && !block_given? + def tag! + @tree.last + end - if block_given? - new_child(:html, *args) { yield } - else - new_child(:html, *args) - end + def tag? tag_sym + tag![:tag] == tag_sym end - def tag name, attrs={} + def tag sym_name, *args e = { type: :html, - tag: name, - attrs: attrs, + tag: sym_name, + attrs: {}, text: nil, - childs: [] + childs: [], + args: args } - target(e) do - if block_given - update_tag(attrs) { yield } - else - update_tag(attrs) + if block_given + target(e) do + yield end end @@ -364,11 +361,21 @@ class WWW_Applet html end - def attrs key, name - fail("Id already taken: #{name.inspect}") if ids[name] - ids[name] = true - tag[:attrs][:id] = name - end + ::WWW_Applet::Sanitize_Config[:attributes].reject { |k| k == :all }.values.uniq.each { |raw_meth| + eval %^ + def #{raw_meth.gsub('-', '_')} val + attrs = ::WWW_Applet::Sanitize_Config[:attributes][tag![:tag].to_str] + return super unless attrs && attrs.include?(#{meth.inspect}) + tag![:attrs][:#{meth}] = val + + if block_given? + close_tag { yield } + else + self + end + end + ^ + } # # Example: @@ -377,43 +384,28 @@ class WWW_Applet def ^ *names tag[:attrs][:class] ||= [] tag[:attrs][:class].concat(names).uniq! - end - - def update_tag attrs={} - e = parent - if attrs - e[:attrs].merge! attrs - end if block_given? - result = target(e) { - yield - } - - e[:text] = result if result.is_a?(String) + close_tag { yield } + else + self end - - e end def no_title - title { 'No title' } + page_title { 'No title' } end - def title &blok - @page_title = true + def page_title + return super unless tag?(:body) - c = tag(:title, &blok) - if parent?(:body) - @head[:childs].push c - else - parent[:childs].push c - end - c + @page_title = true + @head[:childs].push tag(:title) + close_tag { yield } end def meta *args - fail "Not allowed outside of :head" unless parent?(:body) + fail "Not allowed outside of :head" unless tag?(:body) c = tag(:meta, *args) @head[:childs].push c c
Dev. checkpoint: Added: attrs methods, other touchups.
da99_www_app
train
d414c51b1799fbbc72c85ee8f00f476e60020257
diff --git a/modules/MatchProvider.js b/modules/MatchProvider.js index <HASH>..<HASH> 100644 --- a/modules/MatchProvider.js +++ b/modules/MatchProvider.js @@ -47,7 +47,7 @@ class MatchProvider extends React.Component { parent: this.state.parent, matches: this.state.matches, - matchFound: this.state.matches.length > 0 + matchFound: () => this.state.matches.length > 0 } } } diff --git a/modules/Miss.js b/modules/Miss.js index <HASH>..<HASH> 100644 --- a/modules/Miss.js +++ b/modules/Miss.js @@ -23,7 +23,7 @@ class Miss extends React.Component { if (!match) { // don't render if out of context (probably a unit test) return null - } else if (!match.matchFound) { + } else if (!match.matchFound()) { // side-effect in render, only happens on the server // and calling it multiple times should be fine if (serverRouter) diff --git a/modules/__tests__/Miss-test.js b/modules/__tests__/Miss-test.js index <HASH>..<HASH> 100644 --- a/modules/__tests__/Miss-test.js +++ b/modules/__tests__/Miss-test.js @@ -2,7 +2,7 @@ import expect from 'expect' import React from 'react' import Miss from '../Miss' import { renderToString } from 'react-dom/server' -import MatchCountProvider from '../MatchCountProvider' +import MatchProvider from '../MatchProvider' describe('Miss', () => { const TEXT = 'TEXT' @@ -10,12 +10,12 @@ describe('Miss', () => { it('renders a Component prop', () => { const Page = () => <div>{TEXT}</div> const html = renderToString( - <MatchCountProvider> + <MatchProvider> <Miss location={{}} component={Page} /> - </MatchCountProvider> + </MatchProvider> ) expect(html).toContain(TEXT) }) @@ -23,14 +23,14 @@ describe('Miss', () => { it('renders a render prop passes a location', () => { const loc = { state: TEXT } const html = renderToString( - <MatchCountProvider> + <MatchProvider> <Miss location={loc} render={({ location }) => ( <div>{location.state}</div> )} /> - </MatchCountProvider> + </MatchProvider> ) expect(html).toContain(TEXT) }) @@ -46,4 +46,3 @@ describe('Miss', () => { expect(html).toNotContain(TEXT) }) }) -
Fix up some minor things after rebasing.
ReactTraining_react-router
train