hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
9c6797a915736e6eb95b2d396e160d91a4487121
diff --git a/src/main/java/org/jinstagram/Instagram.java b/src/main/java/org/jinstagram/Instagram.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/jinstagram/Instagram.java +++ b/src/main/java/org/jinstagram/Instagram.java @@ -193,7 +193,7 @@ public class Instagram { * through the review process. * See changelog on Nov 17, 2015 * - * use getUsersRecentMedia() instead + * use getUserRecentMedia() instead */ @Deprecated public MediaFeed getUserFeeds() throws InstagramException { @@ -209,8 +209,8 @@ public class Instagram { * @throws InstagramException * @author tolstovdmit */ - public MediaFeed getUsersRecentMedia() throws InstagramException{ - LogHelper.logEntrance(logger, "getUsersRecentMedia", null); + public MediaFeed getUserRecentMedia() throws InstagramException{ + LogHelper.logEntrance(logger, "getUserRecentMedia", null); logger.info("Getting current user recent media..."); return createInstagramObject(Verbs.GET, MediaFeed.class, Methods.USERS_SELF_RECENT_MEDIA, null); @@ -227,8 +227,8 @@ public class Instagram { * @throws InstagramException * @author tolstovdmit */ - public MediaFeed getUsersRecentMedia(int count, String minId, String maxId) throws InstagramException { - LogHelper.logEntrance(logger, "getUsersRecentMedia", "[ count : " + count + ", minId : " + minId + ", maxId : " + maxId + "]"); + public MediaFeed getUserRecentMedia(int count, String minId, String maxId) throws InstagramException { + LogHelper.logEntrance(logger, "getUserRecentMedia", "[ count : " + count + ", minId : " + minId + ", maxId : " + maxId + "]"); logger.info("Getting current user recent media..."); Map<String, String> params = new HashMap<String, String>(); @@ -263,7 +263,7 @@ public class Instagram { * through the review process. * See changelog on Nov 17, 2015 * - * use getUsersRecentMedia(int count, String minId, String maxId) instead + * use getUserRecentMedia(int count, String minId, String maxId) instead */ @Deprecated public MediaFeed getUserFeeds(String maxId, String minId, long count) throws InstagramException { diff --git a/src/test/java/org/jinstagram/InstagramTest.java b/src/test/java/org/jinstagram/InstagramTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/jinstagram/InstagramTest.java +++ b/src/test/java/org/jinstagram/InstagramTest.java @@ -249,8 +249,8 @@ public class InstagramTest { } @Test - public void testGetUsersRecentMedia() throws Exception{ - MediaFeed mf = instagram.getUsersRecentMedia(); + public void testGetUserRecentMedia() throws Exception{ + MediaFeed mf = instagram.getUserRecentMedia(); List<MediaFeedData> mediaFeedDataList = mf.getData(); @@ -259,9 +259,9 @@ public class InstagramTest { } @Test - public void testGetUsersRecentMediaWithParams() throws Exception{ + public void testGetUserRecentMediaWithParams() throws Exception{ - MediaFeed mf = instagram.getUsersRecentMedia(2, null, null); + MediaFeed mf = instagram.getUserRecentMedia(2, null, null); List<MediaFeedData> mediaFeedDataList = mf.getData(); Assert.assertEquals(mediaFeedDataList.size(), 2);
Minor. Methods was misspelled.
sachin-handiekar_jInstagram
train
ce4af4c6fbab34265e69492281a7e13e1d26914b
diff --git a/src/Canvas.js b/src/Canvas.js index <HASH>..<HASH> 100644 --- a/src/Canvas.js +++ b/src/Canvas.js @@ -17,39 +17,36 @@ const HAS_MATRIX = (function (div) { })(document.createElement('div')) export default class Canvas { - constructor(img, opts) { + constructor(element, opts) { // make this object observable o(this) this.opts = opts - this.img = img - this.wrapper = img.parentNode + this.element = element + this.wrapper = element.parentNode this.isLoaded = false // store the initial image properties - deep clone - this.initial = img.cloneNode(true) + this.initial = element.cloneNode(true) } /** * Load the image * @returns { Object } - Canvas */ load() { - const isImage = this.img.complete !== undefined; + const isImage = this.element.complete !== undefined; + const isImageReady = isImage && this.element.width && this.element.height && this.element.complete; - if (!this.img.width || !this.img.height || !this.img.complete) { - if (isImage) { - this.img.onload = () => this.onImageLoaded() - } else { - this.onImageLoaded(); - } + if (isImage && !isImageReady) { + this.element.onload = () => this.onImageLoaded(); } else { - this.onImageLoaded() + this.onImageLoaded(); } return this } destroy() { - this.img.parentNode.replaceChild(this.initial, this.img) + this.element.parentNode.replaceChild(this.initial, this.element) this.off('*') } @@ -60,8 +57,8 @@ export default class Canvas { onImageLoaded() { this.isLoaded = true this.update() - this.img.style.willChange = 'transform' - this.trigger('loaded', this.img) + this.element.style.willChange = 'transform' + this.trigger('loaded', this.element) return this } /** @@ -69,8 +66,8 @@ export default class Canvas { * @returns { Object } - Canvas */ update() { - const iw = this.img.naturalWidth || this.img.width || this.offsetWidth, - ih = this.img.naturalHeight || this.img.height || this.offsetHeight, + const iw = this.element.naturalWidth || this.element.width || this.offsetWidth, + ih = this.element.naturalHeight || this.element.height || this.offsetHeight, ratio = iw / ih, size = this.size @@ -96,10 +93,10 @@ export default class Canvas { offsetTop = -~~((nh - size.height) / 2) offsetLeft = -~~((nw - size.width) / 2) - this.img.width = nw - this.img.height = nh - this.img.style.top = `${offsetTop}px` - this.img.style.left = `${offsetLeft}px` + this.element.width = nw + this.element.height = nh + this.element.style.top = `${offsetTop}px` + this.element.style.left = `${offsetLeft}px` return this } @@ -116,9 +113,9 @@ export default class Canvas { perc = (this.offset.top + size.height * this.opts.center + height / 2 - scrollTop) / height - 1, // increase the percentage effect according to the intensity // and the current image height - offset = ~~(perc * (this.img.height / size.height / 2 * this.opts.intensity) * 10) + offset = ~~(perc * (this.element.height / size.height / 2 * this.opts.intensity) * 10) - this.img.style[TRANSFORM_PREFIX] = HAS_MATRIX ? `matrix(1,0,0,1, 0, ${-offset})` : `translate(0, ${-offset}px)` + this.element.style[TRANSFORM_PREFIX] = HAS_MATRIX ? `matrix(1,0,0,1, 0, ${-offset})` : `translate(0, ${-offset}px)` return this } diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100755 --- a/src/index.js +++ b/src/index.js @@ -48,7 +48,7 @@ class Parallax { } if (!this.canvases.length && this.selector !== null) { - console.warn(`-- No images were found with the selector "${this.selector}"`) + console.warn(`No images were found with the selector "${this.selector}"`) } else { this.imagesLoaded = 0 this.bind()
Refactored load function in Canvas Updated Canvas with element instead of img as the library can now handle more than just images Removed -- from console message
GianlucaGuarini_parallax
train
82befbfdac64302bf0b7c9b71a84165a1de04a70
diff --git a/lib/bitly/v3/url.rb b/lib/bitly/v3/url.rb index <HASH>..<HASH> 100644 --- a/lib/bitly/v3/url.rb +++ b/lib/bitly/v3/url.rb @@ -11,7 +11,7 @@ module Bitly if opts @short_url = opts['url'] @long_url = opts['long_url'] - @user_hash = opts['hash'] + @user_hash = opts['hash'] || opts['user_hash'] @global_hash = opts['global_hash'] @new_hash = (opts['new_hash'] == 1) @user_clicks = opts['user_clicks'] diff --git a/lib/bitly/version.rb b/lib/bitly/version.rb index <HASH>..<HASH> 100644 --- a/lib/bitly/version.rb +++ b/lib/bitly/version.rb @@ -1,3 +1,3 @@ module Bitly - VERSION = '0.5.0' + VERSION = '0.5.1' end \ No newline at end of file
Fixes issue with expanding short urls in v3 API
jonstorer_bitly-oauth
train
7abbb0f57e8ac9c57ab0c0fbf1d1f89faa181eda
diff --git a/builtin/providers/aws/resource_aws_elastic_beanstalk_environment.go b/builtin/providers/aws/resource_aws_elastic_beanstalk_environment.go index <HASH>..<HASH> 100644 --- a/builtin/providers/aws/resource_aws_elastic_beanstalk_environment.go +++ b/builtin/providers/aws/resource_aws_elastic_beanstalk_environment.go @@ -462,7 +462,7 @@ func fetchAwsElasticBeanstalkEnvironmentSettings(d *schema.ResourceData, meta in return nil, fmt.Errorf("Error reading environment settings: option setting with no name: %v", optionSetting) } - if optionSetting.ResourceName != nil { + if *optionSetting.Namespace == "aws:autoscaling:scheduledaction" && optionSetting.ResourceName != nil { m["resource"] = *optionSetting.ResourceName } @@ -647,8 +647,10 @@ func extractOptionSettings(s *schema.Set) []*elasticbeanstalk.ConfigurationOptio OptionName: aws.String(setting.(map[string]interface{})["name"].(string)), Value: aws.String(setting.(map[string]interface{})["value"].(string)), } - if v, ok := setting.(map[string]interface{})["resource"].(string); ok && v != "" { - optionSetting.ResourceName = aws.String(v) + if *optionSetting.Namespace == "aws:autoscaling:scheduledaction" { + if v, ok := setting.(map[string]interface{})["resource"].(string); ok && v != "" { + optionSetting.ResourceName = aws.String(v) + } } settings = append(settings, &optionSetting) }
provider/aws: fix Elastic Beanstalk settings diff (#<I>) Fixes an issue where terraform plan or apply will always have a diff. The Elastic Beanstalk API returns data for the `resource` attribute for some settings that are not documented. This limits the `resource` attribute to settings in the `aws:autoscaling:scheduledaction` namespace.
hashicorp_terraform
train
8dead7b99ba1518cacc5f44dc62c1a83f8d998c9
diff --git a/simulator/src/main/java/com/hazelcast/simulator/worker/TestContainer.java b/simulator/src/main/java/com/hazelcast/simulator/worker/TestContainer.java index <HASH>..<HASH> 100644 --- a/simulator/src/main/java/com/hazelcast/simulator/worker/TestContainer.java +++ b/simulator/src/main/java/com/hazelcast/simulator/worker/TestContainer.java @@ -61,12 +61,16 @@ public class TestContainer { OptionalTestProperties(String propertyName) { this.propertyName = propertyName; } + + public String getPropertyName() { + return propertyName; + } } static { Set<String> optionalTestProperties = new HashSet<String>(); for (OptionalTestProperties optionalTestProperty : OptionalTestProperties.values()) { - optionalTestProperties.add(optionalTestProperty.propertyName); + optionalTestProperties.add(optionalTestProperty.getPropertyName()); } OPTIONAL_TEST_PROPERTIES = Collections.unmodifiableSet(optionalTestProperties); } @@ -265,7 +269,7 @@ public class TestContainer { } private void invokeRunWithWorkerMethod() throws Exception { - bindOptionalProperty(this, testCase, OptionalTestProperties.THREAD_COUNT.propertyName); + bindOptionalProperty(this, testCase, OptionalTestProperties.THREAD_COUNT.getPropertyName()); LOGGER.info(format("Spawning %d worker threads for test %s", threadCount, testContext.getTestId())); if (threadCount <= 0) { @@ -307,7 +311,7 @@ public class TestContainer { injectObjectToInstance(worker, workerProbeField, probe); } - bindOptionalProperty(worker, testCase, OptionalTestProperties.LOG_FREQUENCY.propertyName); + bindOptionalProperty(worker, testCase, OptionalTestProperties.LOG_FREQUENCY.getPropertyName()); spawner.spawn(worker); }
Fixed "singular field" issue from SonarQube.
hazelcast_hazelcast-simulator
train
7328c4f92b32803f2d8fb3a2272b45eb2f86ee8e
diff --git a/aggregate_root/lib/aggregate_root/instrumented_repository.rb b/aggregate_root/lib/aggregate_root/instrumented_repository.rb index <HASH>..<HASH> 100644 --- a/aggregate_root/lib/aggregate_root/instrumented_repository.rb +++ b/aggregate_root/lib/aggregate_root/instrumented_repository.rb @@ -30,6 +30,18 @@ module AggregateRoot store(aggregate, stream_name) end + def method_missing(method_name, *arguments, **keywords, &block) + if respond_to?(method_name) + repository.public_send(method_name, *arguments, **keywords, &block) + else + super + end + end + + def respond_to_missing?(method_name, _include_private) + repository.respond_to?(method_name) + end + private attr_reader :instrumentation, :repository diff --git a/aggregate_root/spec/instrumented_repostory_spec.rb b/aggregate_root/spec/instrumented_repostory_spec.rb index <HASH>..<HASH> 100644 --- a/aggregate_root/spec/instrumented_repostory_spec.rb +++ b/aggregate_root/spec/instrumented_repostory_spec.rb @@ -138,6 +138,28 @@ module AggregateRoot end end + specify "method unknown by instrumentation but known by repository" do + some_repository = double("Some repository", custom_method: 42) + instrumented_repository = InstrumentedRepository.new(some_repository, ActiveSupport::Notifications) + block = -> { "block" } + instrumented_repository.custom_method("arg", keyword: "keyarg", &block) + + expect(instrumented_repository).to respond_to(:custom_method) + expect(some_repository).to have_received(:custom_method).with("arg", keyword: "keyarg") do |&received_block| + expect(received_block).to be(block) + end + end + + specify "method unknown by instrumentation and unknown by repository" do + some_repository = instance_double(Repository) + instrumented_repository = InstrumentedRepository.new(some_repository, ActiveSupport::Notifications) + + expect(instrumented_repository).not_to respond_to(:arbitrary_method_name) + expect do + instrumented_repository.arbitrary_method_name + end.to raise_error(NoMethodError, /undefined method `arbitrary_method_name' for #<AggregateRoot::InstrumentedRepository:/) + end + def subscribe_to(name) received_payloads = [] callback = ->(_name, _start, _finish, _id, payload) { received_payloads << payload }
Pass through unknown methods to AggregateRepository from instrumentation
RailsEventStore_rails_event_store
train
2fa18851867e99e065f083de74be8ab8adad4b41
diff --git a/pylint/reporters/text.py b/pylint/reporters/text.py index <HASH>..<HASH> 100644 --- a/pylint/reporters/text.py +++ b/pylint/reporters/text.py @@ -191,9 +191,7 @@ class ColorizedTextReporter(TextReporter): self.color_mapping = color_mapping or \ dict(ColorizedTextReporter.COLOR_MAPPING) ansi_terms = ['xterm-16color', 'xterm-256color'] - try: - assert os.environ['TERM'] in ansi_terms - except (KeyError, AssertionError): + if os.environ.get('TERM') not in ansi_terms: if sys.platform == 'win32': import colorama self.out = colorama.AnsiToWin32(self.out)
Simplify the code to not use assertion and exceptions.
PyCQA_pylint
train
73278bfdab81569405d6ad458cd00a755cee0955
diff --git a/test/connection_test.rb b/test/connection_test.rb index <HASH>..<HASH> 100644 --- a/test/connection_test.rb +++ b/test/connection_test.rb @@ -10,6 +10,7 @@ class ConnectionTest < Test::Unit::TestCase @response_ok = Net::HTTPOK.new("1.1", "200", "OK") @response_not_found = Net::HTTPNotFound.new("1.1", "404", "Not Found") @response_error = Net::HTTPInternalServerError.new("1.1", "500", "Internal Server Error") + @response_temporary_redirect = Net::HTTPInternalServerError.new("1.1", "307", "Temporary Redirect") @connection.stubs(:http).returns(@http_request) @http_request.stubs(:start).returns(@response_ok) @@ -167,4 +168,43 @@ class ConnectionTest < Test::Unit::TestCase ) assert_equal expected, actual end + + test "response.body is nil on TemporaryRedirect" do + @http_request.stubs(:start).returns(@response_temporary_redirect) + @response_temporary_redirect.stubs(:body).returns(nil) + + assert_nothing_raised do + response = @connection.request( + :get, + :host => "data.example.com.s3.amazonaws.com", + :path => "/" + ) + assert_equal nil, response + end + end + + test "response body with new host on TemporaryRedirect" do + response_body = <<-EOFakeBody + "<?xml version=\"1.0\" encoding=\"UTF-8\"?> + <Error> + <Code>TemporaryRedirect</Code> + <Message>Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.</Message> + <RequestId>24A0BB91158D470B</RequestId> + <Bucket>data.example.com</Bucket> + <HostId>DFcq9ktw5HvWZLduutz8fnVzqtXLwIZcAezc7mgyS7lJ2ux+RChY4qAJGa2fQDjV</HostId> + <Endpoint>data.example.com.s3-external-3.amazonaws.com</Endpoint> + </Error>" + EOFakeBody + + @response_temporary_redirect.stubs(:body).returns(response_body) + + assert_nothing_raised do + response = @connection.request( + :get, + :host => "data.example.com.s3.amazonaws.com", + :path => "/" + ) + assert_equal @response_ok, response + end + end end
Added tests for TemporaryRedirect error
megamsys_radosgw-s3
train
cadd80dd25375317c1826638d7d3c332eac42b07
diff --git a/app.js b/app.js index <HASH>..<HASH> 100644 --- a/app.js +++ b/app.js @@ -30,9 +30,9 @@ var _ = require('lodash'), var MongoStore = connectMongo(express.session), httpEnabled = settings.http && settings.http.enable, httpsEnabled = settings.https && settings.https.enable, - models = all('./app/models'), - middlewares = all('./app/middlewares'), - controllers = all('./app/controllers'), + models = all(__dirname+'/app/models'), + middlewares = all(__dirname+'/app/middlewares'), + controllers = all(__dirname+'/app/controllers'), app; //
Changed require-tree constructor argument with fullpath directory
sdelements_lets-chat
train
68e4ce16cf8a1072fc7514b4edb3b0a0298f3b15
diff --git a/wordfreq/tokens.py b/wordfreq/tokens.py index <HASH>..<HASH> 100644 --- a/wordfreq/tokens.py +++ b/wordfreq/tokens.py @@ -101,7 +101,7 @@ DIGIT_RE = regex.compile('\d') MULTI_DIGIT_RE = regex.compile('\d[\d.,]+') -def simple_tokenize(text, include_punctuation=False, combine_numbers=False): +def simple_tokenize(text, include_punctuation=False): """ Tokenize the given text using a straightforward, Unicode-aware token expression. @@ -121,11 +121,6 @@ def simple_tokenize(text, include_punctuation=False, combine_numbers=False): such as emoji. If `include_punctuation` is True, it outputs all non-space tokens. - - If `combine_numbers` is True, then multi-digit numbers will be replaced - by strings of zeroes. When looking up word frequencies, this allows all - numbers of the same length to be treated as the same "word", avoiding - unnecessarily sparse data. - - It breaks on all spaces, even the "non-breaking" ones. - It aims to keep marks together with words, so that they aren't erroneously @@ -136,23 +131,18 @@ def simple_tokenize(text, include_punctuation=False, combine_numbers=False): would end up in its own token, which is worse. """ text = unicodedata.normalize('NFC', text) - if combine_numbers: - postprocess = smash_numbers - else: - postprocess = _identity if include_punctuation: return [ - postprocess(token.casefold()) + token.casefold() for token in TOKEN_RE_WITH_PUNCTUATION.findall(text) ] else: return [ - postprocess(token.strip("'").casefold()) + token.strip("'").casefold() for token in TOKEN_RE.findall(text) ] -def tokenize_mecab_language(text, lang, include_punctuation=False, - combine_numbers=False): +def tokenize_mecab_language(text, lang, include_punctuation=False): """ Tokenize Japanese or Korean text, initializing the MeCab tokenizer if necessary. """ @@ -161,32 +151,21 @@ def tokenize_mecab_language(text, lang, include_punctuation=False, raise ValueError("Only Japanese and Korean can be tokenized using MeCab") if mecab_tokenize is None: from wordfreq.mecab import mecab_tokenize - if combine_numbers: - postprocess = smash_numbers - else: - postprocess = _identity tokens = mecab_tokenize(text, lang) token_expr = TOKEN_RE_WITH_PUNCTUATION if include_punctuation else TOKEN_RE - return [postprocess(token.casefold()) for token in tokens - if token_expr.match(token)] + return [token.casefold() for token in tokens if token_expr.match(token)] -def chinese_tokenize(text, include_punctuation=False, external_wordlist=False, - combine_numbers=False): +def chinese_tokenize(text, include_punctuation=False, external_wordlist=False): """ Tokenize Chinese text, initializing the Jieba tokenizer if necessary. """ global jieba_tokenize if jieba_tokenize is None: from wordfreq.chinese import jieba_tokenize - if combine_numbers: - postprocess = smash_numbers - else: - postprocess = _identity tokens = jieba_tokenize(text, external_wordlist=external_wordlist) token_expr = TOKEN_RE_WITH_PUNCTUATION if include_punctuation else TOKEN_RE - return [postprocess(token.casefold()) for token in tokens - if token_expr.match(token)] + return [token.casefold() for token in tokens if token_expr.match(token)] def remove_marks(text): @@ -274,13 +253,6 @@ def smash_numbers(text): return MULTI_DIGIT_RE.sub(sub_zeroes, text) -def _identity(text): - """ - The identity function, as an alternative to smashing numbers. - """ - return text - - def tokenize(text, lang, include_punctuation=False, external_wordlist=False, combine_numbers=False): """ @@ -393,20 +365,23 @@ def tokenize(text, lang, include_punctuation=False, external_wordlist=False, # language lang = lang.split('-')[0] if lang == 'ja' or lang == 'ko': - return tokenize_mecab_language(text, lang, include_punctuation, combine_numbers) + result = tokenize_mecab_language(text, lang, include_punctuation) elif lang == 'zh': - return chinese_tokenize(text, include_punctuation, external_wordlist, combine_numbers) + result = chinese_tokenize(text, include_punctuation, external_wordlist) elif lang == 'tr': - return simple_tokenize(preprocess_turkish(text), include_punctuation, combine_numbers) + result = simple_tokenize(preprocess_turkish(text), include_punctuation) elif lang == 'ro': - return simple_tokenize(preprocess_romanian(text), include_punctuation, combine_numbers) + result = simple_tokenize(preprocess_romanian(text), include_punctuation) elif lang == 'sr' or lang == 'sh' or lang == 'hbs': # These are the three language codes that could include Serbian text, # which could be in Cyrillic. - return simple_tokenize(preprocess_serbian(text), include_punctuation, combine_numbers) + result = simple_tokenize(preprocess_serbian(text), include_punctuation) elif lang in ABJAD_LANGUAGES: text = remove_marks(unicodedata.normalize('NFKC', text)) - return simple_tokenize(text, include_punctuation, combine_numbers) + result = simple_tokenize(text, include_punctuation) else: - return simple_tokenize(text, include_punctuation, combine_numbers) + result = simple_tokenize(text, include_punctuation) + if combine_numbers: + result = [smash_numbers(token) for token in result] + return result
Handle smashing numbers only at the end of tokenize(). This does make the code a lot clearer.
LuminosoInsight_wordfreq
train
a378495803d5481debba490e6f1cf9249e7ef980
diff --git a/lenstronomy/Workflow/lens_param.py b/lenstronomy/Workflow/lens_param.py index <HASH>..<HASH> 100644 --- a/lenstronomy/Workflow/lens_param.py +++ b/lenstronomy/Workflow/lens_param.py @@ -644,7 +644,7 @@ class LensParam(object): high.append(+np.pi) if model in ['SERSIC', 'SERSIC_ELLIPSE', 'COMPOSITE']: if not 'n_sersic' in kwargs_fixed: - low.append(0.1) + low.append(0.5) high.append(8) if not 'r_eff' in kwargs_fixed: low.append(0.0001) @@ -667,7 +667,7 @@ class LensParam(object): low.append(0) high.append(100) if not 'Rs' in kwargs_fixed: - low.append(0.01) + low.append(0.05) high.append(60) if model in ['PJAFFE', 'PJAFFE_ELLIPSE']: if not 'Ra' in kwargs_fixed:
sersic bounds for lens model changed
sibirrer_lenstronomy
train
4608717cb9a1be2fec26a34c4e72ce4bec37f6f3
diff --git a/confuse/core.py b/confuse/core.py index <HASH>..<HASH> 100644 --- a/confuse/core.py +++ b/confuse/core.py @@ -649,11 +649,12 @@ class Configuration(RootView): os.makedirs(appdir) return appdir - def set_file(self, filename): + def set_file(self, filename, base_for_paths=False): """Parses the file as YAML and inserts it into the configuration sources with highest priority. """ - self.set(YamlSource(filename, loader=self.loader)) + self.set(YamlSource(filename, base_for_paths=base_for_paths, + loader=self.loader)) def dump(self, full=True, redact=False): """Dump the Configuration object to a YAML file.
Expand set_file method to allow using source's dir for relative paths
sampsyo_confuse
train
18a43c83923a909ee5da698e735928b8a204a631
diff --git a/taxtastic.py b/taxtastic.py index <HASH>..<HASH> 100755 --- a/taxtastic.py +++ b/taxtastic.py @@ -89,7 +89,7 @@ def main(): dbname = arguments.dbfile if pth else os.path.join(arguments.dest_dir, fname) if not os.access(dbname, os.F_OK) or arguments.new_database: - zfile = taxtastic.ncbi.fetch_data(dest_dir=arguments.dest_dir, + zfile, downloaded = taxtastic.ncbi.fetch_data(dest_dir=arguments.dest_dir, clobber=True) log.warning('creating new database in %s using data in %s' % (dbname, zfile)) con = taxtastic.ncbi.db_connect(dbname, clobber=False) diff --git a/tests/test_taxtastic.py b/tests/test_taxtastic.py index <HASH>..<HASH> 100644 --- a/tests/test_taxtastic.py +++ b/tests/test_taxtastic.py @@ -67,3 +67,20 @@ class TestCreate(TestScriptBase): # fails the second time because package already exists self.cmd_fails('create -P %(package)s -l 16s') + + +class TestTaxTable(TestScriptBase): + """ + Unit tests for the taxtable sub-command. + """ + def test01(self): + """ + Minimal test that downloads ncbi taxdump and create a taxonomy db. + """ + self.cmd_ok('taxtable') + + def test02(self): + """ + Invalid arguments should cause a failure. + """ + self.cmd_fails('taxtable --not-an-argument')
tracked down and fixed a taxtastic taxtable bug, stubbed out taxtastic.py taxtable test class with a couple of basic tests
fhcrc_taxtastic
train
8facf88881ed843163e5c5b1bc53bd6bac9502b1
diff --git a/ecommerce_worker/email/v1/braze/client.py b/ecommerce_worker/email/v1/braze/client.py index <HASH>..<HASH> 100644 --- a/ecommerce_worker/email/v1/braze/client.py +++ b/ecommerce_worker/email/v1/braze/client.py @@ -300,6 +300,11 @@ class BrazeClient: ): """ Sends the message via Braze Rest API /messages/send + The "override_frequency_capping" key in the request payload is important; + it tells Braze to ignore the global campaign message frequency cap + for the message we're sending in this method. Since this is a transactional + message, we'd like the recipient to receive it regardless of what/how-many + other campaign messages they have received. Arguments: email_ids (list): e.g. ['test1@example.com', 'test2@example.com'] @@ -318,6 +323,7 @@ class BrazeClient: { "external_user_ids": [ "user1@example.com", "user2@example.org" ], "campaign_id": "some-campaign-identifier", + "override_frequency_capping": true, "messages": { "email": { "app_id": "99999999-9999-9999-9999-999999999999", @@ -374,12 +380,15 @@ class BrazeClient: message = { 'user_aliases': user_aliases, 'external_user_ids': external_ids, - 'campaign_id': campaign_id, 'recipient_subscription_state': 'all', 'messages': { 'email': email } } + if campaign_id: + message['campaign_id'] = campaign_id + message['override_frequency_capping'] = True + # Scrub the app_id from the log message cleaned_message = copy.deepcopy(message) cleaned_app_id = '{}...{}'.format(cleaned_message['messages']['email']['app_id'][0:4], diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -36,7 +36,7 @@ def is_requirement(line): setup( name='edx-ecommerce-worker', - version='3.1.1', + version='3.1.2', description='Celery tasks supporting the operations of edX\'s ecommerce service', long_description=long_description, classifiers=[
fix: ignore Braze frequency capping for ent emails
edx_ecommerce-worker
train
ceae5786617a532a17f357605232491995ffb436
diff --git a/SQL.py b/SQL.py index <HASH>..<HASH> 100644 --- a/SQL.py +++ b/SQL.py @@ -11,9 +11,9 @@ Copyright """ __author__ = 'Jason R. Coombs <jaraco@sandia.gov>' -__version__ = '$Revision: 55 $a'[11:-2] +__version__ = '$Revision: 56 $a'[11:-2] __vssauthor__ = '$Author: Jaraco $'[9:-2] -__date__ = '$Modtime: 9-12-04 13:14 $'[10:-2] +__date__ = '$Modtime: 9-12-04 13:16 $'[10:-2] import types, time, datetime import string, re, sys, logging, binascii @@ -48,6 +48,8 @@ class Binary( str ): ASCII = property( _GetASCIIRepresentation ) def CreateFromASCIIRepresentation( s ): + if re.match( '0x', s ): + s = s[2:] return Binary( binascii.a2b_hex( s ) ) CreateFromASCIIRepresentation = staticmethod( CreateFromASCIIRepresentation )
Restored '0x' initialization of Binary.
jaraco_jaraco.util
train
8283bf8058974d9935e2614e03bc58ced44a3713
diff --git a/lib/Opauth/OpauthStrategy.php b/lib/Opauth/OpauthStrategy.php index <HASH>..<HASH> 100644 --- a/lib/Opauth/OpauthStrategy.php +++ b/lib/Opauth/OpauthStrategy.php @@ -171,7 +171,7 @@ class OpauthStrategy{ $iteration = intval($iteration); if ($iteration <= 0) return false; - for ($i = 0; $i < $iteration; ++$i) $input = sha1($input.$salt.$timestamp); + for ($i = 0; $i < $iteration; ++$i) $input = base_convert(sha1($input.$salt.$timestamp), 16, 36); return $input; }
base_convert to <I> for each interations
opauth_opauth
train
c9ea31ed375e15948396581b7df34df3ae835d03
diff --git a/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/servers/AbstractServersSdkTest.java b/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/servers/AbstractServersSdkTest.java index <HASH>..<HASH> 100644 --- a/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/servers/AbstractServersSdkTest.java +++ b/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/servers/AbstractServersSdkTest.java @@ -21,7 +21,7 @@ public class AbstractServersSdkTest extends AbstractSdkTest { return list(new AuthModule(), new ServersModule()); } - protected ServerMetadata createDefaultServerWithName(ServerService serverService, String name) throws Exception { + protected ServerMetadata createDefaultServerWithName(ServerService serverService, String name) { return serverService.create(anyServerConfig().name(name)).waitUntilComplete().getResult(); } diff --git a/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/servers/services/ServerPowerOperationsServiceTest.java b/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/servers/services/ServerPowerOperationsServiceTest.java index <HASH>..<HASH> 100644 --- a/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/servers/services/ServerPowerOperationsServiceTest.java +++ b/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/servers/services/ServerPowerOperationsServiceTest.java @@ -4,54 +4,53 @@ import com.centurylink.cloud.sdk.servers.AbstractServersSdkTest; import com.centurylink.cloud.sdk.servers.client.domain.server.metadata.ServerMetadata; import com.google.inject.Inject; import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static com.centurylink.cloud.sdk.tests.TestGroups.INTEGRATION; import static com.centurylink.cloud.sdk.tests.TestGroups.LONG_RUNNING; -import static java.util.Arrays.asList; @Test(groups = {INTEGRATION, LONG_RUNNING}) public class ServerPowerOperationsServiceTest extends AbstractServersSdkTest { - private ServerMetadata server1; + private ServerMetadata server; @Inject ServerService serverService; - @BeforeMethod - public void setUp() throws Exception { - server1 = createDefaultServerWithName(serverService, "ser-1"); - } - @AfterClass public void tearDown() { - cleanUpCreatedResources(serverService, server1.asRefById()); + cleanUpCreatedResources(serverService, server.asRefById()); + } + + private ServerMetadata loadActualMetadata(ServerMetadata server) { + return serverService.findByRef(server.asRefById()); } - public void testStartServerMaintenance() { + public void testPowerOff() { + server = createDefaultServerWithName(serverService, "pwrtst"); + serverService - .powerOn(server1.asRefById()) + .powerOff(server.asRefById()) .waitUntilComplete(); - ServerMetadata server = serverService.findByRef(server1.asRefById()); - assertNotNull(server); - assertNotNull(server.getDetails()); - assertEquals(server.getDetails().getPowerState(), "started"); + ServerMetadata resultServer = loadActualMetadata(this.server); + assertNotNull(resultServer); + assertNotNull(resultServer.getDetails()); + assertEquals(resultServer.getDetails().getPowerState(), "stopped"); } @Test - public void testStopServerMaintenance() { - testStartServerMaintenance(); + public void testPowerOn() { + testPowerOff(); serverService - .powerOff(server1.asRefById()) + .powerOn(server.asRefById()) .waitUntilComplete(); - ServerMetadata server = serverService.findByRef(server1.asRefById()); + ServerMetadata server = loadActualMetadata(this.server); assertNotNull(server); assertNotNull(server.getDetails()); - assertNotNull(server.getDetails().getPowerState(), "stopped"); + assertNotNull(server.getDetails().getPowerState(), "started"); } }
<I> Implement possibilities to power on server
CenturyLinkCloud_clc-java-sdk
train
ebcafcf135f3906cd5ced58cca0991245cc218ac
diff --git a/packages/amount-selectors/README.md b/packages/amount-selectors/README.md index <HASH>..<HASH> 100644 --- a/packages/amount-selectors/README.md +++ b/packages/amount-selectors/README.md @@ -10,16 +10,17 @@ npm install @crave/farmblocks-amount-selectors ## API -| Property | Description | Type | -|----------|-------------|------| -| value | initial value of the selector | number | -| step | interval of increases or decreases | number | -| min | minimum amount available | number | -| max | maximum amount available | number | -| onChange | function to handle the input onChange event | function | -| disableTyping | disables direct typing | bool | -| enforceStep | disable both buttons when a number outside of the step is typed | bool | -| size | size of the amount selector | one of selectorSizes.SMALL or selectorSizes.MEDIUM | +| Property | Description | Type | +| ------------- | --------------------------------------------------------------- | -------------------------------------------------- | +| value | initial value of the selector | number | +| step | interval of increases or decreases | number | +| min | minimum amount available | number | +| max | maximum amount available | number | +| onChange | function to handle the input onChange event | function | +| disableTyping | disables direct typing | bool | +| enforceStep | disable both buttons when a number outside of the step is typed | bool | +| size | size of the amount selector | one of selectorSizes.SMALL or selectorSizes.MEDIUM | +| disabled | disables both buttons and input | boolean | ## License diff --git a/packages/amount-selectors/src/components/AmountSelectors.js b/packages/amount-selectors/src/components/AmountSelectors.js index <HASH>..<HASH> 100644 --- a/packages/amount-selectors/src/components/AmountSelectors.js +++ b/packages/amount-selectors/src/components/AmountSelectors.js @@ -102,6 +102,7 @@ class AmountSelectors extends React.Component { }; render() { + const { disabled } = this.props; return ( <Wrapper size={this.props.size} className={this.props.className}> <Button @@ -110,7 +111,9 @@ class AmountSelectors extends React.Component { size={selectorSizeToButtonSize[this.props.size]} icon="wg-minus" disabled={ - this.state.disableBoth || this.state.value <= this.props.min + disabled || + this.state.disableBoth || + this.state.value <= this.props.min } onClick={this.decrement} tooltipText={this.state.tooltipText} @@ -128,6 +131,7 @@ class AmountSelectors extends React.Component { onChange={this.onChange} onBlur={this.updateDisplayValue} fontSize={selectorSizeToFontSize[this.props.size]} + disabled={disabled} /> </div> <Button @@ -136,7 +140,9 @@ class AmountSelectors extends React.Component { size={selectorSizeToButtonSize[this.props.size]} icon="wg-add" disabled={ - this.state.disableBoth || this.state.value >= this.props.max + disabled || + this.state.disableBoth || + this.state.value >= this.props.max } onClick={this.increment} tooltipText={this.state.tooltipText} @@ -151,6 +157,7 @@ class AmountSelectors extends React.Component { min: PropTypes.number, max: PropTypes.number, enforceStep: PropTypes.bool, + disabled: PropTypes.bool, onChange: PropTypes.func, disableTyping: PropTypes.bool, size: PropTypes.oneOf(values(selectorSizes)), diff --git a/packages/amount-selectors/src/components/AmountSelectors.story.js b/packages/amount-selectors/src/components/AmountSelectors.story.js index <HASH>..<HASH> 100644 --- a/packages/amount-selectors/src/components/AmountSelectors.story.js +++ b/packages/amount-selectors/src/components/AmountSelectors.story.js @@ -25,6 +25,7 @@ storiesOf("Amount selectors", module) } return <MyStory />; }) + .add("Disabled", () => <AmountSelectors disabled />) .add("With 0.5 steps", () => <AmountSelectors value={2} step={0.5} />) .add("With 0.5 steps and step mismatch validation (browser)", () => ( <AmountSelectors value={2} step={0.5} enforceStep />
feat(amount-selectors): add disabled property affects: @crave/farmblocks-amount-selectors ISSUES CLOSED: #<I>
CraveFood_farmblocks
train
09703e54e567c117a88c50589839206f9ed6dda7
diff --git a/ontobio/io/gpaddiffer.py b/ontobio/io/gpaddiffer.py index <HASH>..<HASH> 100644 --- a/ontobio/io/gpaddiffer.py +++ b/ontobio/io/gpaddiffer.py @@ -19,7 +19,7 @@ from ontobio.io.assocparser import Report def compare_files(file1, file2, output, count_by, exclude_details, file_type): print("Starting comparison ") print("") - df_file1, df_file2, assocs1, assocs2 = get_parser(file1, file2, count_by, exclude_details, file_type) + df_file1, df_file2, assocs1, assocs2 = get_parser(file1, file2, count_by) processed_lines = 0 exact_matches = 0 close_matches = 0
add report structure to report lines with only close as warning, no match as error
biolink_ontobio
train
888181950f89092759020f7540cae64b47951c23
diff --git a/agent/spec/unit/apply_plan/job_spec.rb b/agent/spec/unit/apply_plan/job_spec.rb index <HASH>..<HASH> 100644 --- a/agent/spec/unit/apply_plan/job_spec.rb +++ b/agent/spec/unit/apply_plan/job_spec.rb @@ -120,7 +120,6 @@ describe Bosh::Agent::ApplyPlan::Job do bin_dir = File.join(job.install_path, "bin") File.directory?(bin_dir).should be_true - File.stat(bin_dir).mode.to_s(8).should == "40755" File.read(File.join(job.install_path, "bin", "foo")). should == "value1"
job_spec should not check explicit file mode as we don't set an explicit umask in the agent code, the spec inherits the user umask, which when it is not <I> would cause a test to fail checking if the directory gets created is enough Change-Id: I<I>a6b5ee<I>be<I>dc5af<I>dbe<I>e<I>
cloudfoundry_bosh
train
ec090c8279d77c867199dab7b7c9e29b0b3de295
diff --git a/spec/unit/metadata_spec.rb b/spec/unit/metadata_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/metadata_spec.rb +++ b/spec/unit/metadata_spec.rb @@ -62,8 +62,7 @@ module Omnibus end it_behaves_like 'a version manipulator', 'aix', '7.1', '7.1' - it_behaves_like 'a version manipulator', 'arch', '2009.02', '2009.02' - it_behaves_like 'a version manipulator', 'arch', '2014.06.01', '2014.06' + it_behaves_like 'a version manipulator', 'arch', 'rolling' it_behaves_like 'a version manipulator', 'centos', '5.9.6', '5' it_behaves_like 'a version manipulator', 'debian', '7.1', '7' it_behaves_like 'a version manipulator', 'debian', '6.9', '6'
Update test for platform_version in metadata to check for 'rolling' as /etc/arch-release no longer contains a version hint (deprecated some time ago).
chef_omnibus
train
ddf32456778b71dcef91636306a996f9d8dc7d16
diff --git a/erasure-readfile.go b/erasure-readfile.go index <HASH>..<HASH> 100644 --- a/erasure-readfile.go +++ b/erasure-readfile.go @@ -175,6 +175,11 @@ func parallelRead(volume, path string, readDisks []StorageAPI, orderedDisks []St // then written to given writer. This function also supports bit-rot detection by // verifying checksum of individual block's checksum. func erasureReadFile(writer io.Writer, disks []StorageAPI, volume string, path string, partName string, eInfos []erasureInfo, offset int64, length int64, totalLength int64) (int64, error) { + // Offset and length cannot be negative. + if offset < 0 || length < 0 { + return 0, errUnexpected + } + // Pick one erasure info. eInfo := pickValidErasureInfo(eInfos) diff --git a/erasure-utils.go b/erasure-utils.go index <HASH>..<HASH> 100644 --- a/erasure-utils.go +++ b/erasure-utils.go @@ -74,6 +74,11 @@ func getDataBlockLen(enBlocks [][]byte, dataBlocks int) int { // Writes all the data blocks from encoded blocks until requested // outSize length. Provides a way to skip bytes until the offset. func writeDataBlocks(dst io.Writer, enBlocks [][]byte, dataBlocks int, outOffset int64, outSize int64) (int64, error) { + // Offset and out size cannot be negative. + if outOffset < 0 || outSize < 0 { + return 0, errUnexpected + } + // Do we have enough blocks? if len(enBlocks) < dataBlocks { return 0, reedsolomon.ErrTooFewShards diff --git a/fs-v1.go b/fs-v1.go index <HASH>..<HASH> 100644 --- a/fs-v1.go +++ b/fs-v1.go @@ -217,6 +217,10 @@ func (fs fsObjects) GetObject(bucket, object string, offset int64, length int64, if !IsValidObjectName(object) { return ObjectNameInvalid{Bucket: bucket, Object: object} } + // Offset and length cannot be negative. + if offset < 0 || length < 0 { + return toObjectErr(errUnexpected, bucket, object) + } var totalLeft = length bufSize := int64(readSizeV1) if length > 0 && bufSize > length { diff --git a/xl-v1-object.go b/xl-v1-object.go index <HASH>..<HASH> 100644 --- a/xl-v1-object.go +++ b/xl-v1-object.go @@ -48,7 +48,10 @@ func (xl xlObjects) GetObject(bucket, object string, startOffset int64, length i if !IsValidObjectName(object) { return ObjectNameInvalid{Bucket: bucket, Object: object} } - + // Start offset and length cannot be negative. + if startOffset < 0 || length < 0 { + return toObjectErr(errUnexpected, bucket, object) + } // Lock the object before reading. nsMutex.RLock(bucket, object) defer nsMutex.RUnlock(bucket, object)
xl/fs: offset and length cannot be negative. (#<I>) Fixes #<I>
minio_minio
train
abea8101280c87238609a2798f2380e2ae35ab7b
diff --git a/Slim/App.php b/Slim/App.php index <HASH>..<HASH> 100644 --- a/Slim/App.php +++ b/Slim/App.php @@ -289,16 +289,14 @@ class App */ public function run($silent = false) { + $response = $this->container->get('response'); + try { - $request = $this->container->get('request'); + $response = $this->process($this->container->get('request'), $response); } catch (InvalidMethodException $e) { - $request = $e->getRequest(); + $response = $this->processInvalidMethod($e->getRequest(), $response); } - $response = $this->container->get('response'); - - $response = !isset($e) ? $this->process($request, $response) : $this->processInvalidMethod($request, $response); - if (!$silent) { $this->respond($response); }
Clean up control flow in App::run() by pulling $response def. first Changes execution order a bit, but won't matter unless folks are doing something really weird interaction-wise between container request and response objects. And maybe not even then!
slimphp_Slim
train
4ec303ec4aaddc22be44976eb33140f1eef00545
diff --git a/lib/TextBox.js b/lib/TextBox.js index <HASH>..<HASH> 100644 --- a/lib/TextBox.js +++ b/lib/TextBox.js @@ -21,7 +21,7 @@ export class TextBox extends Input { create(init) { super.create(init) this.children = [ - new Box(this._edit = new Edit({ + this._box = new Box(this._edit = new Edit({ contentEditable : true, onblur : event => this.onBlur(event), onfocus : event => this.onFocus(event), @@ -58,7 +58,9 @@ export class TextBox extends Input { if(this.disabled) { event.stopImmediatePropagation() } - else this.focus() + else if([this._box, ...this.labelledBy].some(label => label.contains(event.target))) { + this.focus() + } } /** @@ -199,7 +201,7 @@ export class TextBox extends Input { } /** - * @return {string} + * @return {string} */ get name() { return this._input.name
TextBox: focus only on box and labels click
aristov_ariamodule
train
cc215f734725d5fa06c9e275462acf3255059738
diff --git a/src/Symfony/Component/OptionsResolver/OptionsResolver.php b/src/Symfony/Component/OptionsResolver/OptionsResolver.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/OptionsResolver/OptionsResolver.php +++ b/src/Symfony/Component/OptionsResolver/OptionsResolver.php @@ -883,7 +883,7 @@ class OptionsResolver implements Options $invalidValues = array_filter( // Filter out valid values, keeping invalid values in the resulting array $value, function ($value) use ($type) { - return (function_exists($isFunction = 'is_'.$type) && !$isFunction($value)) || !$value instanceof $type; + return !self::isValueValidType($type, $value); } ); @@ -896,7 +896,7 @@ class OptionsResolver implements Options return false; } - if ((function_exists($isFunction = 'is_'.$type) && $isFunction($value)) || $value instanceof $type) { + if (self::isValueValidType($type, $value)) { return true; } @@ -1073,4 +1073,9 @@ class OptionsResolver implements Options return implode(', ', $values); } + + private static function isValueValidType($type, $value) + { + return (function_exists($isFunction = 'is_'.$type) && $isFunction($value)) || $value instanceof $type; + } } diff --git a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php +++ b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php @@ -486,6 +486,15 @@ class OptionsResolverTest extends TestCase $this->resolver->setAllowedTypes('foo', 'string'); } + public function testResolveTypedArray() + { + $this->resolver->setDefined('foo'); + $this->resolver->setAllowedTypes('foo', 'string[]'); + $options = $this->resolver->resolve(array('foo' => array('bar', 'baz'))); + + $this->assertSame(array('foo' => array('bar', 'baz')), $options); + } + /** * @expectedException \Symfony\Component\OptionsResolver\Exception\AccessException */
Fix options resolver with array allowed types
symfony_symfony
train
bb98768023a7821324f2a08941f1364e221862ae
diff --git a/src/utilities/__tests__/findBreakingChanges-test.js b/src/utilities/__tests__/findBreakingChanges-test.js index <HASH>..<HASH> 100644 --- a/src/utilities/__tests__/findBreakingChanges-test.js +++ b/src/utilities/__tests__/findBreakingChanges-test.js @@ -32,6 +32,7 @@ import { findTypesRemovedFromUnions, findTypesThatChangedKind, findValuesRemovedFromEnums, + findValuesAddedToEnums, findArgChanges, findInterfacesRemovedFromObjectTypes, } from '../findBreakingChanges'; @@ -1349,7 +1350,63 @@ describe('findDangerousChanges', () => { }); }); + it('should detect if a value was added to an enum type', () => { + const oldEnumType = new GraphQLEnumType({ + name: 'EnumType1', + values: { + VALUE0: { value: 0 }, + VALUE1: { value: 1 }, + } + }); + const newEnumType = new GraphQLEnumType({ + name: 'EnumType1', + values: { + VALUE0: { value: 0 }, + VALUE1: { value: 1 }, + VALUE2: { value: 2 }, + } + }); + + const oldSchema = new GraphQLSchema({ + query: queryType, + types: [ + oldEnumType, + ] + }); + const newSchema = new GraphQLSchema({ + query: queryType, + types: [ + newEnumType, + ] + }); + + expect(findValuesAddedToEnums(oldSchema, newSchema)).to.eql( + [ + { + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: 'VALUE2 was added to enum type EnumType1.', + } + ] + ); + }); + it('should find all dangerous changes', () => { + const enumThatGainsAValueOld = new GraphQLEnumType({ + name: 'EnumType1', + values: { + VALUE0: { value: 0 }, + VALUE1: { value: 1 }, + } + }); + const enumThatGainsAValueNew = new GraphQLEnumType({ + name: 'EnumType1', + values: { + VALUE0: { value: 0 }, + VALUE1: { value: 1 }, + VALUE2: { value: 2 }, + } + }); + const oldType = new GraphQLObjectType({ name: 'Type1', fields: { @@ -1384,6 +1441,7 @@ describe('findDangerousChanges', () => { query: queryType, types: [ oldType, + enumThatGainsAValueOld ] }); @@ -1391,6 +1449,7 @@ describe('findDangerousChanges', () => { query: queryType, types: [ newType, + enumThatGainsAValueNew ] }); @@ -1398,6 +1457,10 @@ describe('findDangerousChanges', () => { { description: 'Type1.field1 arg name has changed defaultValue', type: 'ARG_DEFAULT_VALUE_CHANGE' + }, + { + description: 'VALUE2 was added to enum type EnumType1.', + type: 'VALUE_ADDED_TO_ENUM', } ]; diff --git a/src/utilities/findBreakingChanges.js b/src/utilities/findBreakingChanges.js index <HASH>..<HASH> 100644 --- a/src/utilities/findBreakingChanges.js +++ b/src/utilities/findBreakingChanges.js @@ -44,6 +44,7 @@ export const BreakingChangeType = { export const DangerousChangeType = { ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE', + VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM' }; export type BreakingChange = { @@ -85,6 +86,7 @@ export function findDangerousChanges( ): Array<DangerousChange> { return [ ...findArgChanges(oldSchema, newSchema).dangerousChanges, + ...findValuesAddedToEnums(oldSchema, newSchema) ]; } @@ -542,6 +544,42 @@ export function findValuesRemovedFromEnums( return valuesRemovedFromEnums; } +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding values to an enum type. + */ +export function findValuesAddedToEnums( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema +): Array<DangerousChange> { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const valuesAddedToEnums = []; + Object.keys(oldTypeMap).forEach(typeName => { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!(oldType instanceof GraphQLEnumType) || + !(newType instanceof GraphQLEnumType)) { + return; + } + + const valuesInOldEnum = Object.create(null); + oldType.getValues().forEach(value => { + valuesInOldEnum[value.name] = true; + }); + newType.getValues().forEach(value => { + if (!valuesInOldEnum[value.name]) { + valuesAddedToEnums.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${value.name} was added to enum type ${typeName}.` + }); + } + }); + }); + return valuesAddedToEnums; +} + export function findInterfacesRemovedFromObjectTypes( oldSchema: GraphQLSchema, newSchema: GraphQLSchema
Adding a value to an enum is now a dangerous change.
graphql_graphql-js
train
b9a400040a1b8a186986a03222e9e2210ef6478c
diff --git a/conn_test.go b/conn_test.go index <HASH>..<HASH> 100644 --- a/conn_test.go +++ b/conn_test.go @@ -149,7 +149,8 @@ func TestEncodeDecode(t *testing.T) { '\x000102'::bytea, 'foobar'::text, NULL::integer, - '2000-1-1 01:02:03.04-7'::timestamptz + '2000-1-1 01:02:03.04-7'::timestamptz, + 0::boolean WHERE '\x000102'::bytea = $1 AND 'foobar'::text = $2 @@ -177,8 +178,9 @@ func TestEncodeDecode(t *testing.T) { var got2 string var got3 = sql.NullInt64{Valid: true} var got4 time.Time + var got5 interface{} - err = r.Scan(&got1, &got2, &got3, &got4) + err = r.Scan(&got1, &got2, &got3, &got4, &got5) if err != nil { t.Fatal(err) } @@ -198,6 +200,10 @@ func TestEncodeDecode(t *testing.T) { if got4.Year() != 2000 { t.Fatal("wrong year") } + + if got5 != false { + t.Fatalf("expected false, got %q", got5) + } } func TestNoData(t *testing.T) {
Add test for scanning boolean into interface{}
bmizerany_pq
train
5f0925a2941193281459617f89df6aea0ebe7bd3
diff --git a/test/e2e/common/node/container_probe.go b/test/e2e/common/node/container_probe.go index <HASH>..<HASH> 100644 --- a/test/e2e/common/node/container_probe.go +++ b/test/e2e/common/node/container_probe.go @@ -406,17 +406,18 @@ var _ = SIGDescribe("Probing container", func() { ginkgo.It("should be ready immediately after startupProbe succeeds", func() { // Probe workers sleep at Kubelet start for a random time which is at most PeriodSeconds // this test requires both readiness and startup workers running before updating statuses - // to avoid flakes, ensure sleep before startup (22s) > readinessProbe.PeriodSeconds - cmd := []string{"/bin/sh", "-c", "echo ok >/tmp/health; sleep 22; echo ok >/tmp/startup; sleep 600"} + // to avoid flakes, ensure sleep before startup (32s) > readinessProbe.PeriodSeconds + cmd := []string{"/bin/sh", "-c", "echo ok >/tmp/health; sleep 32; echo ok >/tmp/startup; sleep 600"} readinessProbe := &v1.Probe{ Handler: execHandler([]string{"/bin/cat", "/tmp/health"}), InitialDelaySeconds: 0, - PeriodSeconds: 20, + PeriodSeconds: 30, } startupProbe := &v1.Probe{ Handler: execHandler([]string{"/bin/cat", "/tmp/startup"}), InitialDelaySeconds: 0, - FailureThreshold: 60, + FailureThreshold: 120, + PeriodSeconds: 5, } p := podClient.Create(startupPodSpec(startupProbe, readinessProbe, nil, cmd)) @@ -445,8 +446,8 @@ var _ = SIGDescribe("Probing container", func() { if readyIn < 0 { framework.Failf("Pod became ready before startupProbe succeeded") } - if readyIn > 5*time.Second { - framework.Failf("Pod became ready in %v, more than 5s after startupProbe succeeded. It means that the delay readiness probes were not initiated immediately after startup finished.", readyIn) + if readyIn > 25*time.Second { + framework.Failf("Pod became ready in %v, more than 25s after startupProbe succeeded. It means that the delay readiness probes were not initiated immediately after startup finished.", readyIn) } })
Flake #<I> increase delay for ready state propagation
kubernetes_kubernetes
train
d80c07a6ae0543a48e1af842704d7b9f0208e116
diff --git a/lib/sprockets/loader.rb b/lib/sprockets/loader.rb index <HASH>..<HASH> 100644 --- a/lib/sprockets/loader.rb +++ b/lib/sprockets/loader.rb @@ -308,8 +308,10 @@ module Sprockets history = cache.get(key) || [] history.each_with_index do |deps, index| - deps.map! { |path| path.start_with?("file-digest://") ? expand_from_root(path) : path } - if asset = yield(deps) + expanded_deps = deps.map do |path| + path.start_with?("file-digest://") ? expand_from_root(path) : path + end + if asset = yield(expanded_deps) cache.set(key, history.rotate!(index)) if index > 0 return asset end
Prevent expanded paths from getting into the history cache Currently dependencies are mutated after they're pulled out of the cache. These same dependencies can then be re-stored later ``` cache.set(key, history.unshift(deps).take(limit)) ``` This makes it possible for a project to load the wrong asset.
rails_sprockets
train
06998d015fd04f6411a897d43a78a7da4ff432f1
diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php index <HASH>..<HASH> 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php @@ -16,9 +16,15 @@ class DDC3634Test extends OrmFunctionalTestCase { protected function setUp() { parent::setUp(); + $metadata = $this->_em->getClassMetadata(DDC3634Entity::CLASSNAME); + + if (! $metadata->idGenerator->isPostInsertGenerator()) { + $this->markTestSkipped('Need a post-insert ID generator in order to make this test work correctly'); + } + try { $this->_schemaTool->createSchema([ - $this->_em->getClassMetadata(DDC3634Entity::CLASSNAME), + $metadata, $this->_em->getClassMetadata(DDC3634JTIBaseEntity::CLASSNAME), $this->_em->getClassMetadata(DDC3634JTIChildEntity::CLASSNAME), ]);
Skipping DDC-<I> tests when a post-insert generator is unavailable
doctrine_orm
train
b244bec8c538837dc16d3f19fa7535d47e089a1c
diff --git a/Gemfile.lock b/Gemfile.lock index <HASH>..<HASH> 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,92 +1,92 @@ PATH remote: . specs: - built_in_data (1.1.0) + built_in_data (1.1.1) rails (>= 4.0.0) GEM remote: https://rubygems.org/ specs: - actioncable (5.0.2) - actionpack (= 5.0.2) - nio4r (>= 1.2, < 3.0) + actioncable (5.1.1) + actionpack (= 5.1.1) + nio4r (~> 2.0) websocket-driver (~> 0.6.1) - actionmailer (5.0.2) - actionpack (= 5.0.2) - actionview (= 5.0.2) - activejob (= 5.0.2) + actionmailer (5.1.1) + actionpack (= 5.1.1) + actionview (= 5.1.1) + activejob (= 5.1.1) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 2.0) - actionpack (5.0.2) - actionview (= 5.0.2) - activesupport (= 5.0.2) + actionpack (5.1.1) + actionview (= 5.1.1) + activesupport (= 5.1.1) rack (~> 2.0) rack-test (~> 0.6.3) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.0.2) - actionview (5.0.2) - activesupport (= 5.0.2) + actionview (5.1.1) + activesupport (= 5.1.1) builder (~> 3.1) - erubis (~> 2.7.0) + erubi (~> 1.4) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.0.3) - activejob (5.0.2) - activesupport (= 5.0.2) + activejob (5.1.1) + activesupport (= 5.1.1) globalid (>= 0.3.6) - activemodel (5.0.2) - activesupport (= 5.0.2) - activerecord (5.0.2) - activemodel (= 5.0.2) - activesupport (= 5.0.2) - arel (~> 7.0) - activesupport (5.0.2) + activemodel (5.1.1) + activesupport (= 5.1.1) + activerecord (5.1.1) + activemodel (= 5.1.1) + activesupport (= 5.1.1) + arel (~> 8.0) + activesupport (5.1.1) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (~> 0.7) minitest (~> 5.1) tzinfo (~> 1.1) - arel (7.1.4) + arel (8.0.0) builder (3.2.3) concurrent-ruby (1.0.5) - erubis (2.7.0) - globalid (0.3.7) - activesupport (>= 4.1.0) - i18n (0.8.1) + erubi (1.6.0) + globalid (0.4.0) + activesupport (>= 4.2.0) + i18n (0.8.4) loofah (2.0.3) nokogiri (>= 1.5.9) - mail (2.6.4) + mail (2.6.6) mime-types (>= 1.16, < 4) method_source (0.8.2) mime-types (3.1) mime-types-data (~> 3.2015) mime-types-data (3.2016.0521) - mini_portile2 (2.1.0) - minitest (5.10.1) - nio4r (2.0.0) - nokogiri (1.7.1) - mini_portile2 (~> 2.1.0) - rack (2.0.1) + mini_portile2 (2.2.0) + minitest (5.10.2) + nio4r (2.1.0) + nokogiri (1.8.0) + mini_portile2 (~> 2.2.0) + rack (2.0.3) rack-test (0.6.3) rack (>= 1.0) - rails (5.0.2) - actioncable (= 5.0.2) - actionmailer (= 5.0.2) - actionpack (= 5.0.2) - actionview (= 5.0.2) - activejob (= 5.0.2) - activemodel (= 5.0.2) - activerecord (= 5.0.2) - activesupport (= 5.0.2) + rails (5.1.1) + actioncable (= 5.1.1) + actionmailer (= 5.1.1) + actionpack (= 5.1.1) + actionview (= 5.1.1) + activejob (= 5.1.1) + activemodel (= 5.1.1) + activerecord (= 5.1.1) + activesupport (= 5.1.1) bundler (>= 1.3.0, < 2.0) - railties (= 5.0.2) + railties (= 5.1.1) sprockets-rails (>= 2.0.0) - rails-dom-testing (2.0.2) - activesupport (>= 4.2.0, < 6.0) - nokogiri (~> 1.6) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) rails-html-sanitizer (1.0.3) loofah (~> 2.0) - railties (5.0.2) - actionpack (= 5.0.2) - activesupport (= 5.0.2) + railties (5.1.1) + actionpack (= 5.1.1) + activesupport (= 5.1.1) method_source rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) @@ -115,4 +115,4 @@ DEPENDENCIES sqlite3 (~> 1.3) BUNDLED WITH - 1.14.6 + 1.15.1 diff --git a/lib/built_in_data.rb b/lib/built_in_data.rb index <HASH>..<HASH> 100644 --- a/lib/built_in_data.rb +++ b/lib/built_in_data.rb @@ -29,6 +29,11 @@ module BuiltInData built_in_object_ids[key] end + def delete_all + @built_in_object_ids = nil + super + end + private def prepare_objects_hash(hash) diff --git a/lib/built_in_data/version.rb b/lib/built_in_data/version.rb index <HASH>..<HASH> 100644 --- a/lib/built_in_data/version.rb +++ b/lib/built_in_data/version.rb @@ -1,3 +1,3 @@ module BuiltInData - VERSION = "1.1.0" + VERSION = "1.1.1" end diff --git a/test/built_in_data_test.rb b/test/built_in_data_test.rb index <HASH>..<HASH> 100644 --- a/test/built_in_data_test.rb +++ b/test/built_in_data_test.rb @@ -87,6 +87,13 @@ class BuiltInDataTest < ActiveSupport::TestCase load_hash_data assert_equal NationalPark.where(name: 'Yellowstone National Park').first.id, NationalPark.built_in_object_id(:test) end + + test 'should clear built_in_object_ids cache when delete_all is called' do + NationalPark.instance_variable_set('@built_in_object_ids', 'testing') + + NationalPark.delete_all + assert_nil NationalPark.instance_variable_get('@built_in_object_ids') + end private
clear built_in_object_ids on delete_all
wwidea_built_in_data
train
47cf2e3b907fea41e5919b004e34f119b53cd74e
diff --git a/tests/TestCase/View/Helper/MenuHelperTest.php b/tests/TestCase/View/Helper/MenuHelperTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/View/Helper/MenuHelperTest.php +++ b/tests/TestCase/View/Helper/MenuHelperTest.php @@ -13,10 +13,4 @@ class MenuHelperTest extends TestCase $View = new View(); $this->Menu = new MenuHelper($View); } - - public function testgetMenu() - { - $menu = $this->Menu->getMenu('main'); - $this->assertTrue(is_array($menu)); - } }
remove unit test for obsolete method (task #<I>)
QoboLtd_cakephp-menu
train
e44f719a15eaa253bcda14298aa932ded8fc5aef
diff --git a/xurls.go b/xurls.go index <HASH>..<HASH> 100644 --- a/xurls.go +++ b/xurls.go @@ -25,7 +25,7 @@ const ( webURL = hostName + `(:[0-9]{1,5})?` + path email = `[a-zA-Z0-9._%\-+]+@` + hostName - comScheme = `[a-zA-Z.\-+]+://` + comScheme = `[a-zA-Z][a-zA-Z.\-+]*://` scheme = `(` + comScheme + `|` + otherScheme + `)` strict = `(\b|^)` + scheme + pathCont relaxed = strict + `|` + webURL + `|` + email diff --git a/xurls_test.go b/xurls_test.go index <HASH>..<HASH> 100644 --- a/xurls_test.go +++ b/xurls_test.go @@ -76,8 +76,8 @@ var constantTestCases = []regexTestCase{ {` http://foo.com/bar more`, `http://foo.com/bar`}, {`<http://foo.com/bar>`, `http://foo.com/bar`}, {`<http://foo.com/bar>more`, `http://foo.com/bar`}, - {`,http://foo.com/bar.`, `http://foo.com/bar`}, - {`,http://foo.com/bar.more`, `http://foo.com/bar.more`}, + {`.http://foo.com/bar.`, `http://foo.com/bar`}, + {`.http://foo.com/bar.more`, `http://foo.com/bar.more`}, {`,http://foo.com/bar,`, `http://foo.com/bar`}, {`,http://foo.com/bar,more`, `http://foo.com/bar,more`}, {`(http://foo.com/bar)`, `http://foo.com/bar`},
Fix the scheme regex regarding a starting non-letter
mvdan_xurls
train
1d7be3a81a789469c859b44e0949dc952ac04782
diff --git a/src/peltak/commands/appengine.py b/src/peltak/commands/appengine.py index <HASH>..<HASH> 100644 --- a/src/peltak/commands/appengine.py +++ b/src/peltak/commands/appengine.py @@ -121,7 +121,7 @@ def _get_appengine_sdk_path(): ' directly.', '^0' ) - log.cprint('\n'.join(msg_lines)) + shell.cprint('\n'.join(msg_lines)) sys.exit(1) return sdk_path diff --git a/src/peltak/commands/docker.py b/src/peltak/commands/docker.py index <HASH>..<HASH> 100644 --- a/src/peltak/commands/docker.py +++ b/src/peltak/commands/docker.py @@ -15,9 +15,9 @@ import requests # local imports from peltak.commands import cli from peltak.core import conf +from peltak.core import log from peltak.core import shell from peltak.core import versioning -from peltak.core import log @cli.group('docker') @@ -120,7 +120,7 @@ def docker_list(registry_pass): r = requests.get(tags_url.format(repo), auth=auth) images[repo] = reversed(sorted(r.json()['tags'])) - log.cprint("^32Images in ^34{} ^32registry:^0", registry_url) + shell.cprint("^32Images in ^34{} ^32registry:^0", registry_url) for image, tags in images.items(): for tag in tags: - log.cprint(' {}:^35{}^0', image, tag) + shell.cprint(' {}:^35{}^0', image, tag) diff --git a/src/peltak/core/log.py b/src/peltak/core/log.py index <HASH>..<HASH> 100644 --- a/src/peltak/core/log.py +++ b/src/peltak/core/log.py @@ -8,14 +8,6 @@ from __future__ import absolute_import, unicode_literals from . import shell -def cprint(msg, *args, **kw): - """ Print colored message to stdout. """ - if len(args) or len(kw): - msg = msg.format(*args, **kw) - - print(shell.fmt(msg)) - - def info(msg, *args, **kw): """ Print sys message to stdout. diff --git a/src/peltak/core/shell.py b/src/peltak/core/shell.py index <HASH>..<HASH> 100644 --- a/src/peltak/core/shell.py +++ b/src/peltak/core/shell.py @@ -32,6 +32,14 @@ def fmt(msg, *args, **kw): return re.sub(r'\^(\d{1,2})', OPCODE_SUBST, msg) +def cprint(msg, *args, **kw): + """ Print colored message to stdout. """ + if len(args) or len(kw): + msg = msg.format(*args, **kw) + + print(fmt(msg)) + + def run(cmd, capture=False, shell=True, env=None, exit_on_error=True): """ Run a shell command.
Move cprint from core.log to core.shell Seems to fit there better
novopl_peltak
train
cb6ffd627d86ace9ed6b679add3e27f315234c2d
diff --git a/src/list.js b/src/list.js index <HASH>..<HASH> 100644 --- a/src/list.js +++ b/src/list.js @@ -1,7 +1,7 @@ 'use strict' const assert = require('assert') -const ExtDate = require('./date') +const Date = require('./date') const ExtDateTime = require('./interface') const { isArray } = Array @@ -77,10 +77,10 @@ class List extends ExtDateTime { push(value) { if (isArray(value)) { assert.equal(2, value.length) - return this.values.push(value.map(v => ExtDate.from(v))) + return this.values.push(value.map(v => Date.from(v))) } - return this.values.push(ExtDate.from(value)) + return this.values.push(Date.from(value)) } *[Symbol.iterator]() {
Rename ExtDate -> Date
inukshuk_edtf.js
train
cc302057d45ef83f37d4d69026c03aa6c202776a
diff --git a/nipap-www/nipapwww/public/nipap.js b/nipap-www/nipapwww/public/nipap.js index <HASH>..<HASH> 100644 --- a/nipap-www/nipapwww/public/nipap.js +++ b/nipap-www/nipapwww/public/nipap.js @@ -1043,10 +1043,10 @@ function insertPrefix(prefix, prev_prefix) { if (prev_prefix.match == false && prefix.match == true) { - // switching into a match from a non-match, so we should display a - // "expand upwards" arrow - // Place after previous prefix's parent (a hidden container). - reference = $("#prefix_entry" + prev_prefix.id).parent(); + // Switching into a match from a non-match, so we should display a + // "expand upwards" arrow. Place after the element after previous + // prefix's parent (the hidden container's text). + reference = $("#prefix_entry" + prev_prefix.id).parent().next(); offset = 'after'; // if there are not very many elements in hidden container, show it
Modified placement of match after non-match Nodified placement of matching prefix after a non-matching prefix of the same indent level. Previously the prefix was placed directly after the hidden container when it should be placed after the element after (the "hidden prefixes"-text container).
SpriteLink_NIPAP
train
59b7ab5bceb8e8dbc28306e7d2a437ec3a8e2a38
diff --git a/dvc/version.py b/dvc/version.py index <HASH>..<HASH> 100644 --- a/dvc/version.py +++ b/dvc/version.py @@ -49,4 +49,4 @@ def is_dirty(dir_path): return True -__version__ = generate_version(base_version="0.34.2") +__version__ = generate_version(base_version="0.35.0")
dvc: bump to <I>
iterative_dvc
train
88864a977955cfc93d34b603049619fbd9643b43
diff --git a/lib/podio/models/organization.rb b/lib/podio/models/organization.rb index <HASH>..<HASH> 100644 --- a/lib/podio/models/organization.rb +++ b/lib/podio/models/organization.rb @@ -103,5 +103,12 @@ class Podio::Organization < ActivePodio::Base Podio.connection.post("/org/#{id}/upgrade").body end + def set_joined_as(org_id, joined_as_type, joined_as_id) + Podio.connection.post { |req| + req.url "/org/#{org_id}/joined_as" + req.body = {:type => joined_as_type, :id => joined_as_id} + }.body + end + end end
Added set_joined_as to Organization model (internal API operation)
podio_podio-rb
train
0d5146bedab229756caafdd477659f94d4f26c3d
diff --git a/pipeline/__init__.py b/pipeline/__init__.py index <HASH>..<HASH> 100644 --- a/pipeline/__init__.py +++ b/pipeline/__init__.py @@ -4,59 +4,33 @@ from functools import partial class Pipeline: def __init__(self): - self.tail = None self.results = [] + self._queue = [] def queue(self, task): print("queued") - task._depends_on = self.tail - task._written = False - self.tail = task + self._queue.append(task) - self._task_done(None, task) + task.add_done_callback(self._task_done) - def _resolve_dependency(self, task): - current = task._depends_on + def _task_done(self, task): + print('Done', task.result()) - while current: - if not current.done(): + pop_idx = 0 + for task in self._queue: + if not task.done(): break - current = current._depends_on - - task._depends_on = current - - - def _gc(self): - while self.tail: - if not self.tail._written: - break - - self.tail = self.tail._depends_on - - - def _task_done(self, this_task, task): - if this_task == task: - print('Done', task.result()) - if this_task and (not task._depends_on or task._depends_on._written): self.write(task) - self._gc() - return - - self._resolve_dependency(task) - - if this_task: - depends_on = task._depends_on - else: - depends_on = task - depends_on.add_done_callback(partial(self._task_done, task=task)) + pop_idx += 1 + if pop_idx: + self._queue[:pop_idx] = [] def write(self, task): self.results.append(task.result()) - task._written = True print('Written', task.result())
simplify, on done always traverse from beginning
squeaky-pl_japronto
train
7ef8fa720782a02eb14ceda1a16c0cad856c4574
diff --git a/pkg/apis/networking/validation/validation_test.go b/pkg/apis/networking/validation/validation_test.go index <HASH>..<HASH> 100644 --- a/pkg/apis/networking/validation/validation_test.go +++ b/pkg/apis/networking/validation/validation_test.go @@ -2072,6 +2072,67 @@ func TestValidateIngressTLS(t *testing.T) { } } +// TestValidateEmptyIngressTLS verifies that an empty TLS configuration can be +// specified, which ingress controllers may interpret to mean that TLS should be +// used with a default certificate that the ingress controller furnishes. +func TestValidateEmptyIngressTLS(t *testing.T) { + pathTypeImplementationSpecific := networking.PathTypeImplementationSpecific + serviceBackend := &networking.IngressServiceBackend{ + Name: "defaultbackend", + Port: networking.ServiceBackendPort{ + Number: 443, + }, + } + defaultBackend := networking.IngressBackend{ + Service: serviceBackend, + } + newValid := func() networking.Ingress { + return networking.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + Namespace: metav1.NamespaceDefault, + }, + Spec: networking.IngressSpec{ + Rules: []networking.IngressRule{ + { + Host: "foo.bar.com", + IngressRuleValue: networking.IngressRuleValue{ + HTTP: &networking.HTTPIngressRuleValue{ + Paths: []networking.HTTPIngressPath{ + { + PathType: &pathTypeImplementationSpecific, + Backend: defaultBackend, + }, + }, + }, + }, + }, + }, + }, + } + } + + validCases := map[string]networking.Ingress{} + goodEmptyTLS := newValid() + goodEmptyTLS.Spec.TLS = []networking.IngressTLS{ + {}, + } + validCases[fmt.Sprintf("spec.tls[0]: Valid value: %v", goodEmptyTLS.Spec.TLS[0])] = goodEmptyTLS + goodEmptyHosts := newValid() + goodEmptyHosts.Spec.TLS = []networking.IngressTLS{ + { + Hosts: []string{}, + }, + } + validCases[fmt.Sprintf("spec.tls[0]: Valid value: %v", goodEmptyHosts.Spec.TLS[0])] = goodEmptyHosts + for k, v := range validCases { + errs := validateIngress(&v, IngressValidationOptions{}, networkingv1beta1.SchemeGroupVersion) + if len(errs) != 0 { + t.Errorf("expected success for %q", k) + } + } +} + func TestValidateIngressStatusUpdate(t *testing.T) { serviceBackend := &networking.IngressServiceBackend{ Name: "defaultbackend",
Verify that an ingress with empty TLS is valid Add a test that verifies that an ingress with an empty TLS value or with a TLS value that specifies an empty list of hosts passes validation. * pkg/apis/networking/validation/validation_test.go (TestValidateEmptyIngressTLS): New test.
kubernetes_kubernetes
train
4bfd1857c1dd38592459f8653c4c2818c2978b5e
diff --git a/grakn-graph/src/main/java/ai/grakn/factory/SystemKeyspace.java b/grakn-graph/src/main/java/ai/grakn/factory/SystemKeyspace.java index <HASH>..<HASH> 100644 --- a/grakn-graph/src/main/java/ai/grakn/factory/SystemKeyspace.java +++ b/grakn-graph/src/main/java/ai/grakn/factory/SystemKeyspace.java @@ -92,10 +92,7 @@ public class SystemKeyspace<M extends GraknGraph, T extends Graph> { openSpaces.computeIfAbsent(keyspace, name -> { try (GraknGraph graph = factory.getGraph(false)) { ResourceType<String> keyspaceName = graph.getType(KEYSPACE_RESOURCE); - Resource<String> resource = keyspaceName.getResource(keyspace); - if (resource == null) { - resource = keyspaceName.putResource(keyspace); - } + Resource<String> resource = keyspaceName.putResource(keyspace); if (resource.owner() == null) { graph.<EntityType>getType(KEYSPACE_ENTITY).addEntity().hasResource(resource); }
One tiny optimisation of the system keyspace (#<I>)
graknlabs_grakn
train
355454913bd2816fe1e8c168c915ee94ac10b383
diff --git a/src/Excel.php b/src/Excel.php index <HASH>..<HASH> 100644 --- a/src/Excel.php +++ b/src/Excel.php @@ -237,10 +237,6 @@ class Excel { */ protected static function initializeFile( $path ) { - if( false === is_writable($path)): - throw new UnableToInitializeOutputFile( "Path is not writable. Unable to write to the file at " . $path ); - endif; - $bytes_written = file_put_contents( $path, '' ); if ( FALSE === $bytes_written ): throw new UnableToInitializeOutputFile( "Unable to write to the file at " . $path );
Removed a check that was causing issues in certain scenarios.
DPRMC_Excel
train
7ed39ef2fa9d815219c7e40efac4caba45636278
diff --git a/lib/events/api.go b/lib/events/api.go index <HASH>..<HASH> 100644 --- a/lib/events/api.go +++ b/lib/events/api.go @@ -20,6 +20,7 @@ import ( "context" "fmt" "io" + "math" "time" "github.com/gravitational/teleport/lib/session" @@ -169,6 +170,15 @@ const ( // ResizeEvent means that some user resized PTY on the client ResizeEvent = "resize" TerminalSize = "size" // expressed as 'W:H' + + // SessionUploadIndex is a very large number of the event index + // to indicate that this is the last event in the chain + // used for the last event of the sesion - session upload + SessionUploadIndex = math.MaxInt32 + // SessionDataIndex is a very large number of the event index + // to indicate one of the last session events, used to report + // data transfer + SessionDataIndex = math.MaxInt32 - 1 ) const ( diff --git a/lib/events/auditlog.go b/lib/events/auditlog.go index <HASH>..<HASH> 100644 --- a/lib/events/auditlog.go +++ b/lib/events/auditlog.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "math" "os" "path/filepath" "sort" @@ -348,7 +347,7 @@ func (l *AuditLog) UploadSessionRecording(r SessionRecording) error { return l.EmitAuditEvent(SessionUpload, EventFields{ SessionEventID: string(r.SessionID), URL: url, - EventIndex: math.MaxInt32, + EventIndex: SessionUploadIndex, }) } diff --git a/lib/srv/ctx.go b/lib/srv/ctx.go index <HASH>..<HASH> 100644 --- a/lib/srv/ctx.go +++ b/lib/srv/ctx.go @@ -485,6 +485,7 @@ func (c *ServerContext) reportStats(conn utils.Stater) { events.EventUser: c.Identity.TeleportUser, events.LocalAddr: c.Conn.LocalAddr().String(), events.RemoteAddr: c.Conn.RemoteAddr().String(), + events.EventIndex: events.SessionDataIndex, } if c.session != nil { eventFields[events.SessionEventID] = c.session.id
Fix event index for session data. Session Data transfer event missed event index, effectively setting it to 0. It is not a mistake by itself, however on Dynamo it resulted this event overwriting SessionStart event, resulting in incomplete session event records. This is not a perfect fix, as the same problem could be introduced at any other point, so something more robust should be added in the future to prevent similar problems from happening.
gravitational_teleport
train
2ce7cdda189f6cf65281ef715124cb89df3c19d0
diff --git a/webit-script/src/main/java/webit/script/loaders/AbstractLoader.java b/webit-script/src/main/java/webit/script/loaders/AbstractLoader.java index <HASH>..<HASH> 100644 --- a/webit-script/src/main/java/webit/script/loaders/AbstractLoader.java +++ b/webit-script/src/main/java/webit/script/loaders/AbstractLoader.java @@ -4,12 +4,14 @@ package webit.script.loaders; import jodd.io.FileNameUtil; import jodd.util.StringUtil; +import webit.script.Configurable; +import webit.script.Engine; /** * * @author Zqq */ -public abstract class AbstractLoader implements Loader { +public abstract class AbstractLoader implements Loader, Configurable { protected String encoding; protected String root = null; @@ -55,4 +57,10 @@ public abstract class AbstractLoader implements Loader { public void setEncoding(String encoding) { this.encoding = encoding; } + + public void init(Engine engine) { + if (encoding == null) { + encoding = engine.getEncoding(); + } + } }
Loaders use engine.encoding as default
febit_wit
train
9c236908b6e72eac74a05f407adb5b19fa6acc05
diff --git a/src/Controller/Controller.php b/src/Controller/Controller.php index <HASH>..<HASH> 100644 --- a/src/Controller/Controller.php +++ b/src/Controller/Controller.php @@ -346,7 +346,7 @@ class Controller implements EventListenerInterface, EventDispatcherInterface ]; if (isset($deprecated[$name])) { $method = $deprecated[$name]; - deprecationWarning(sprintf('Controller::$%s is deprecated. Use $this->%s instead.', $name, $method)); + deprecationWarning(sprintf('Controller::$%s is deprecated. Use $this->%s() instead.', $name, $method)); return $this->{$method}(); }
fix Controller <I> deprecated message from class attribute to method
cakephp_cakephp
train
d03021603b250549637de00f8a88aef5e27b57bc
diff --git a/lib/media/media_source_engine.js b/lib/media/media_source_engine.js index <HASH>..<HASH> 100644 --- a/lib/media/media_source_engine.js +++ b/lib/media/media_source_engine.js @@ -32,7 +32,7 @@ goog.require('shaka.util.PublicPromise'); * internally synchronized and serialized as needed. Operations that can * be done in parallel will be done in parallel. * - * @param {!MediaSource} mediaSource The MediaSource, which must be in the + * @param {MediaSource} mediaSource The MediaSource, which must be in the * 'open' state. * @param {TextTrack} textTrack The TextTrack to use for subtitles/captions. * diff --git a/lib/media/playhead.js b/lib/media/playhead.js index <HASH>..<HASH> 100644 --- a/lib/media/playhead.js +++ b/lib/media/playhead.js @@ -32,7 +32,7 @@ goog.require('shaka.util.IDestroyable'); * restricting seeking to valid time ranges, and stopping playback for startup * and re- buffering. * - * @param {!HTMLVideoElement} video + * @param {HTMLMediaElement} video * @param {!shaka.media.PresentationTimeline} timeline * @param {number} minBufferTime * @param {number} startTime The time, in seconds, to start the presentation. @@ -48,7 +48,7 @@ goog.require('shaka.util.IDestroyable'); */ shaka.media.Playhead = function( video, timeline, minBufferTime, startTime, onBuffering, onSeek) { - /** @private {HTMLVideoElement} */ + /** @private {HTMLMediaElement} */ this.video_ = video; /** @private {shaka.media.PresentationTimeline} */ @@ -151,9 +151,8 @@ shaka.media.Playhead.prototype.setBuffering = function(buffering) { * @private */ shaka.media.Playhead.prototype.onLoadedMetadata_ = function() { - var video = /** @type {!HTMLVideoElement} */(this.video_); - this.eventManager_.unlisten(video, 'loadedmetadata'); - this.eventManager_.listen(video, 'seeking', this.onSeeking_.bind(this)); + this.eventManager_.unlisten(this.video_, 'loadedmetadata'); + this.eventManager_.listen(this.video_, 'seeking', this.onSeeking_.bind(this)); // Trigger call to onSeeking_(). this.video_.currentTime = this.clampTime_(this.startTime_); diff --git a/lib/media/streaming_engine.js b/lib/media/streaming_engine.js index <HASH>..<HASH> 100644 --- a/lib/media/streaming_engine.js +++ b/lib/media/streaming_engine.js @@ -65,7 +65,7 @@ goog.require('shaka.util.IDestroyable'); * ownership. * @param {!shaka.media.MediaSourceEngine} mediaSourceEngine The * MediaSourceEngine. The caller retains ownership. - * @param {!shaka.net.NetworkingEngine} netEngine + * @param {shaka.net.NetworkingEngine} netEngine * @param {shakaExtern.Manifest} manifest * @param {function(!shakaExtern.Period)} onCanSwitch Called when Streams * within the given Period can be switched to. diff --git a/lib/util/event_manager.js b/lib/util/event_manager.js index <HASH>..<HASH> 100644 --- a/lib/util/event_manager.js +++ b/lib/util/event_manager.js @@ -58,7 +58,7 @@ shaka.util.EventManager.prototype.destroy = function() { /** * Attaches an event listener to an event target. - * @param {!EventTarget} target The event target. + * @param {EventTarget} target The event target. * @param {string} type The event type. * @param {shaka.util.EventManager.ListenerType} listener The event listener. */ @@ -70,7 +70,7 @@ shaka.util.EventManager.prototype.listen = function(target, type, listener) { /** * Detaches an event listener from an event target. - * @param {!EventTarget} target The event target. + * @param {EventTarget} target The event target. * @param {string} type The event type. */ shaka.util.EventManager.prototype.unlisten = function(target, type) { @@ -104,7 +104,7 @@ shaka.util.EventManager.prototype.removeAll = function() { /** * Creates a new Binding_ and attaches the event listener to the event target. - * @param {!EventTarget} target The event target. + * @param {EventTarget} target The event target. * @param {string} type The event type. * @param {shaka.util.EventManager.ListenerType} listener The event listener. * @constructor
Make types nullable, use HTMLMediaElement Non-nullability on some types forces us to use casts everywhere, at which point the compiler is just trusting us. So they might as well be nullable and save us some typing. Also, change HTMLVideoElement to the more general HTMLMediaElement. Change-Id: Iaf<I>bfbf<I>b<I>ad8cd7a7a<I>a6caffd<I>bc
google_shaka-player
train
6659e38a68f2f9f6a76070fd2a7177e5f8a403c4
diff --git a/server.js b/server.js index <HASH>..<HASH> 100644 --- a/server.js +++ b/server.js @@ -24,7 +24,6 @@ const serverVarsFactory = function () { return get(this.store, key); }, inject: function () { - console.log(this.store); var stringified = '<script>window.__SERVER_VARS__ = ' + // safely embed JSON within HTML
removed console.log to minimize server output (#<I>)
1stdibs_serverVars
train
e018980ddd3dc86ccf3fb6a7d02739ee057aec3b
diff --git a/backtrader/brokers/bbroker.py b/backtrader/brokers/bbroker.py index <HASH>..<HASH> 100644 --- a/backtrader/brokers/bbroker.py +++ b/backtrader/brokers/bbroker.py @@ -519,7 +519,7 @@ class BackBroker(bt.BrokerBase): return pref - def submit(self, order): + def submit(self, order, check=True): pref = self._take_children(order) if pref is None: # order has not been taken return order @@ -529,13 +529,13 @@ class BackBroker(bt.BrokerBase): if order.transmit: # if single order, sent and queue cleared # if parent-child, the parent will be sent, the other kept - rets = [self.transmit(x) for x in pc] + rets = [self.transmit(x, check=check) for x in pc] return rets[-1] # last one is the one triggering transmission return order - def transmit(self, order): - if self.p.checksubmit: + def transmit(self, order, check=True): + if check and self.p.checksubmit: order.submit() self.submitted.append(order) self.orders.append(order) @@ -629,7 +629,7 @@ class BackBroker(bt.BrokerBase): exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, - histnotify=False, + histnotify=False, _checksubmit=True, **kwargs): order = BuyOrder(owner=owner, data=data, @@ -642,14 +642,14 @@ class BackBroker(bt.BrokerBase): order.addinfo(**kwargs) self._ocoize(order, oco) - return self.submit(order) + return self.submit(order, check=_checksubmit) def sell(self, owner, data, size, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, - histnotify=False, + histnotify=False, _checksubmit=True, **kwargs): order = SellOrder(owner=owner, data=data, @@ -662,7 +662,7 @@ class BackBroker(bt.BrokerBase): order.addinfo(**kwargs) self._ocoize(order, oco) - return self.submit(order) + return self.submit(order, check=_checksubmit) def _execute(self, order, ago=None, price=None, cash=None, position=None, dtcoc=None): @@ -1087,17 +1087,15 @@ class BackBroker(bt.BrokerBase): o = self.buy(owner=owner, data=d, size=size, price=price, exectype=Order.Historical, - histnotify=uhnotify) - - self.pending.append(o) + histnotify=uhnotify, + _checksubmit=False) elif size < 0: o = self.sell(owner=owner, data=d, size=abs(size), price=price, exectype=Order.Historical, - histnotify=uhnotify) - - self.pending.append(o) + histnotify=uhnotify, + _checksubmit=False) # update to next potential order uhist[0] = uhorder = next(uhorders, None)
Enable submission on order history without submission check
backtrader_backtrader
train
10a36def968a4e642b1afec74e3f0be602c79f58
diff --git a/src/Psalm/Internal/Analyzer/Statements/ExpressionAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/ExpressionAnalyzer.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Internal/Analyzer/Statements/ExpressionAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/ExpressionAnalyzer.php @@ -639,7 +639,7 @@ class ExpressionAnalyzer ); if ($existing_type->getId() !== 'array<empty, empty>') { - $context->vars_in_scope[$var_id] = $by_ref_type; + $context->vars_in_scope[$var_id] = clone $by_ref_type; if (!isset($stmt->inferredType) || $stmt->inferredType->isEmpty()) { $stmt->inferredType = clone $by_ref_type; diff --git a/tests/ArrayAccessTest.php b/tests/ArrayAccessTest.php index <HASH>..<HASH> 100644 --- a/tests/ArrayAccessTest.php +++ b/tests/ArrayAccessTest.php @@ -236,6 +236,28 @@ class ArrayAccessTest extends TestCase $b = $as[0]->arr;', ], + 'arrayAccessAfterPassByref' => [ + '<?php + class Arr { + /** + * @param mixed $c + * @return mixed + */ + public static function pull(array &$a, string $b, $c = null) { + return $a[$b] ?? $c; + } + } + + function _renderButton(array $settings): void { + Arr::pull($settings, "a", true); + + if (isset($settings["b"])) { + Arr::pull($settings, "b"); + } + + if (isset($settings["c"])) {} + }' + ], ]; }
Fix issue with by-ref args
vimeo_psalm
train
d5154974738160dbb0f8d48d978d9168bdd8f9ff
diff --git a/src/admin/messages/fr/cmsadmin.php b/src/admin/messages/fr/cmsadmin.php index <HASH>..<HASH> 100644 --- a/src/admin/messages/fr/cmsadmin.php +++ b/src/admin/messages/fr/cmsadmin.php @@ -140,14 +140,14 @@ return [ 'button_update_version' => 'Modifier une version', 'menu_group_item_env_permission' => 'Permissions de la page', -// rc1 + /* rc1 */ 'page_update_actions_deepcopy_text' => 'Créer une copie de la page en cours comprenant son contenu. Toutes les langues seront copiés mais, seulement la version publiée sera visible.', 'page_update_actions_deepcopy_btn' => 'Créer une copie', -// rc2 + /* rc2 */ 'model_navitem_title_tag_label' => 'Titre (SEO)', -// rc3 + /* rc3 */ 'model_navitempage_empty_draft_id' => 'Impossible de créer une page à partir d\'un modèle de brouillon vide', 'view_update_variation_select' => 'Aucun bloc de variation sélectionné', 'menu_group_item_env_config' => 'Configuration', @@ -173,6 +173,6 @@ return [ 'view_update_block_tooltip_delete' => 'Supprimer', 'view_update_block_tooltip_close' => 'Fermer l\'édition', -// 1.0.0 - 'cmsadmin_dashboard_lastupdate' => 'Last page updates' + /* 1.0.0 */ + 'cmsadmin_dashboard_lastupdate' => 'Dernières modifications' ];
FR Translation (#<I>) * Update admin.php * Update cmsadmin.php
luyadev_luya-module-cms
train
f6ff183e5a87d3ee8c372a4e90a9c39a3bb9d337
diff --git a/resources/lang/en/resources.php b/resources/lang/en/resources.php index <HASH>..<HASH> 100644 --- a/resources/lang/en/resources.php +++ b/resources/lang/en/resources.php @@ -8,9 +8,10 @@ return [ 'save_and_return' => 'Save and Return', 'save' => 'Save', 'back_to_list' => 'Back', - 'number' => 'No', + 'nr' => 'No', 'mass_form_title' => 'Update :count items', 'mass_edit' => 'Mass edit', + 'check_to_change' => 'Check to save ":input" field', 'cancel' => 'Cancel', 'status' => [ 'enabled' => 'Enabled', diff --git a/src/Admin/Grid/Builder.php b/src/Admin/Grid/Builder.php index <HASH>..<HASH> 100644 --- a/src/Admin/Grid/Builder.php +++ b/src/Admin/Grid/Builder.php @@ -2,12 +2,13 @@ namespace Arbory\Base\Admin\Grid; +use App\Models\Product; use Arbory\Base\Admin\Grid; use Arbory\Base\Admin\Widgets\Pagination; use Arbory\Base\Admin\Layout\Footer; use Arbory\Base\Admin\Layout\Footer\Tools; use Arbory\Base\Admin\Widgets\Link; -use Arbory\Base\Admin\Widgets\SearchField; +use Arbory\Base\Html\Elements\Inputs\CheckBox; use Arbory\Base\Html\Elements\Content; use Arbory\Base\Html\Elements\Element; use Arbory\Base\Html\Html; @@ -71,6 +72,22 @@ class Builder implements Renderable } /** + * @return Column + */ + protected function addBulkColumn(){ + return $this->grid->column('id', trans('arbory::resources.nr'), 1) + ->checkable(true) + ->display(function($value, Column $column){ + $cellContent = Html::span(); + $checkbox = new CheckBox($value); + $checkbox->setValue($value); + $checkbox->addClass('mass-row'); + $checkbox->setName('ids[]'); + return $cellContent->append($checkbox); + }); + } + + /** * @return \Illuminate\Support\Collection */ protected function getTableColumns() diff --git a/src/Admin/Traits/Bulk.php b/src/Admin/Traits/Bulk.php index <HASH>..<HASH> 100644 --- a/src/Admin/Traits/Bulk.php +++ b/src/Admin/Traits/Bulk.php @@ -97,57 +97,61 @@ trait Bulk } /** - * @param $form + * @param Form $form */ - protected function addCheckboxesToEachInput($form){ + protected function addCheckboxesToEachInput(Form $form){ //change original $originalFields = $form->fields(); //iterate clone $clonedFields = clone $originalFields; + $items = $originalFields->getFields(); + //count when iput added only, cache adjunctions in collection $counter = 0; - $clonedFields->each(function($field, $key) use ($originalFields, &$counter){ + foreach($clonedFields->getIterator() as $key => $field) { $type = $field->getFieldTypeName(); if($type != 'type-hidden'){ $checkbox = new Form\Fields\Checkbox($field->getName().'_control'); $checkbox->addAttributes(['data-target' => $field->getName()]); $checkbox->addClass('bulk-control'); $checkbox->setFieldSet($originalFields); + $checkbox->setLabel(trans('arbory::resources.check_to_change', ['input' => $field->getLabel()])); //Empty checkboxes if($type != 'type-checkbox') - $originalFields[$key+$counter]->rules('required_with:resource.'.$field->getName().'_control'); - $originalFields[$key+$counter]->addAttributes(['disabled' => 'disabled']); + $originalFields->offsetGet($key+$counter)->rules('required_with:resource.'.$field->getName().'_control'); + $originalFields->offsetGet($key+$counter)->addAttributes(['disabled' => 'disabled']); //Add ckeckbox before input - $originalFields->splice($key+$counter, 0, [$checkbox]); + $items->splice($key+$counter, 0, [$checkbox]); $counter++; } - }); + }; } /** * @param $form */ - protected function preprocessMassUpdate($form) + protected function preprocessMassUpdate(Form $form) { $request = request(); //change original - $originalFields = $form->fields(); + $originalFields = $form->fields()->getFields(); //iterate clone - $clonedFields = clone $originalFields; - - $clonedFields->each(function($field, $key) use ($originalFields, $request){ + $clonedFields = clone $originalFields->getIterator(); + foreach ($clonedFields as $key => $field){ + $name = $field->getName(); + $nameSpace = $form->getNamespace(); + $fieldName = $nameSpace.'.'.$name.'_control'; if($field->getFieldTypeName() != 'type-hidden' && - !$request->has($originalFields->getNamespace().'.'.$field->getName().'_control')) { + !$request->has($fieldName)) { $originalFields->forget($key); } - }); - + } } /**
Make it work with changes from layout branch.
arbory_arbory
train
925ef1f9292769065b780917e32c676147c3cd22
diff --git a/tests/Mollie/API/Resources/InvoiceTest.php b/tests/Mollie/API/Resources/InvoiceTest.php index <HASH>..<HASH> 100644 --- a/tests/Mollie/API/Resources/InvoiceTest.php +++ b/tests/Mollie/API/Resources/InvoiceTest.php @@ -20,6 +20,7 @@ class InvoiceTest extends TestCase { $invoice = new Invoice($this->createMock(MollieApiClient::class)); $invoice->status = $status; + $this->assertEquals($expected_boolean, $invoice->{$function}()); } public function dpTestInvoiceStatuses()
Fixed wrong test variable names (part 2)
mollie_mollie-api-php
train
0dc532c33b54aefbfad81131a0f4cbfef2174cde
diff --git a/fabfile.py b/fabfile.py index <HASH>..<HASH> 100644 --- a/fabfile.py +++ b/fabfile.py @@ -26,4 +26,4 @@ def clean(): def test(): - local('nosetests -w test/') + local('nosetests -v -w test/') diff --git a/test/test_project.py b/test/test_project.py index <HASH>..<HASH> 100644 --- a/test/test_project.py +++ b/test/test_project.py @@ -27,6 +27,12 @@ class ProjectTests(unittest.TestCase): self.assertIsInstance(self.long_proj, Project) self.assertIsInstance(self.reg_proj, Project) + def test_normal_attrs(self): + """Ensure projects are created with all normal attrs""" + for attr in ('metadata', 'field_names', 'field_labels', 'forms', + 'events', 'arm_names', 'arm_nums', 'def_field'): + self.assertTrue(hasattr(self.reg_proj, attr)) + def test_long_attrs(self): """proj.events/arm_names/arm_nums should not be empty in long projects""" self.assertIsNotNone(self.long_proj.events)
Update test suite with project attrs; make testing verbose in fabfile
redcap-tools_PyCap
train
a1f0b481d2018fe55ede12c4b9c70c08ca1076c0
diff --git a/examples/logging_query.py b/examples/logging_query.py index <HASH>..<HASH> 100755 --- a/examples/logging_query.py +++ b/examples/logging_query.py @@ -15,6 +15,7 @@ url = 'https://apigw-qa6.us.paloaltonetworks.com' # `export ACCESS_TOKEN=<access token>` access_token = os.environ['ACCESS_TOKEN'] +print(access_token) # Create Logging Service instance ls = LoggingService( @@ -28,7 +29,7 @@ ls = LoggingService( ) data = { # Prepare 'query' data - "q": "select * from panw.traffic limit 1", + "query": "select * from panw.traffic limit 1", "startTime": 0, # 1970 "endTime": 1609459200, # 2021 "maxWaitTime": 0 # no logs in initial response diff --git a/pancloud/httpclient.py b/pancloud/httpclient.py index <HASH>..<HASH> 100644 --- a/pancloud/httpclient.py +++ b/pancloud/httpclient.py @@ -98,16 +98,6 @@ class HTTPClient(object): ', '.join('%s=%r' % x for x in self.kwargs.items()) ) - @property - def pyopenssl(self): - """Check if pyopenssl module exists. - - Returns: - module: pyopenssl module - - """ - return requests.pyopenssl - def request(self, **kwargs): """Generate HTTP request using given parameters.
Remove pyopenssl property method
PaloAltoNetworks_pancloud
train
8fb29fd485a85e431c60a7a1af6d97b9da251995
diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index <HASH>..<HASH> 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -403,7 +403,7 @@ class TestDataFrameFormatting(unittest.TestCase): # Python 2.5 just wants me to be sad. And debian 32-bit #sys.version_info[0] == 2 and sys.version_info[1] < 6: - if '%.4g' % 1.7e8 == '1.7e+008': + if _three_digit_exp(): expected = (' x\n0 0.00000e+000\n1 2.50000e-001\n' '2 3.45600e+003\n3 1.20000e+046\n4 1.64000e+006\n' '5 1.70000e+008\n6 1.25346e+000\n7 3.14159e+000\n' @@ -430,7 +430,7 @@ class TestDataFrameFormatting(unittest.TestCase): df_s = df.to_string() # Python 2.5 just wants me to be sad. And debian 32-bit #sys.version_info[0] == 2 and sys.version_info[1] < 6: - if '%.4g' % 1.7e8 == '1.7e+008': + if _three_digit_exp(): expected = (' x\n' '0 1.000000e+009\n' '1 2.512000e-001') @@ -782,7 +782,10 @@ class TestDataFrameFormatting(unittest.TestCase): 2.03954217305e+10, 5.59897817305e+10] skip = True for line in repr(DataFrame({'A': vals})).split('\n'): - self.assert_(('+10' in line) or skip) + if _three_digit_exp(): + self.assert_(('+010' in line) or skip) + else: + self.assert_(('+10' in line) or skip) skip = False def test_dict_entries(self): @@ -881,7 +884,10 @@ class TestSeriesFormatting(unittest.TestCase): vals = [2.08430917305e+10, 3.52205017305e+10, 2.30674817305e+10, 2.03954217305e+10, 5.59897817305e+10] for line in repr(Series(vals)).split('\n'): - self.assert_('+10' in line) + if _three_digit_exp(): + self.assert_('+010' in line) + else: + self.assert_('+10' in line) def test_timedelta64(self): Series(np.array([1100, 20], dtype='timedelta64[s]')).to_string() @@ -1088,6 +1094,8 @@ class TestEngFormatter(unittest.TestCase): result = formatter(0) self.assertEqual(result, u' 0.000') +def _three_digit_exp(): + return '%.4g' % 1.7e8 == '1.7e+008' class TestFloatArrayFormatter(unittest.TestCase):
BUG: account for different fp exponent formatting in some pythons
pandas-dev_pandas
train
72e2b6c9441ffd927fcb81e4102cc6687abe4eaa
diff --git a/lib/shopify_api/session.rb b/lib/shopify_api/session.rb index <HASH>..<HASH> 100644 --- a/lib/shopify_api/session.rb +++ b/lib/shopify_api/session.rb @@ -7,6 +7,8 @@ module ShopifyAPI end class Session + SECONDS_IN_A_DAY = 24 * 60 * 60 + cattr_accessor :api_key, :secret, :myshopify_domain self.myshopify_domain = 'myshopify.com' @@ -106,7 +108,8 @@ module ShopifyAPI def request_token(params) return token if token - unless self.class.validate_signature(params) && params[:timestamp].to_i > 24.hours.ago.utc.to_i + twenty_four_hours_ago = Time.now.utc.to_i - SECONDS_IN_A_DAY + unless self.class.validate_signature(params) && params[:timestamp].to_i > twenty_four_hours_ago raise ShopifyAPI::ValidationException, "Invalid Signature: Possible malicious login" end diff --git a/test/session_test.rb b/test/session_test.rb index <HASH>..<HASH> 100644 --- a/test/session_test.rb +++ b/test/session_test.rb @@ -3,6 +3,8 @@ require 'test_helper' require 'timecop' class SessionTest < Test::Unit::TestCase + SECONDS_IN_A_DAY = 24 * 60 * 60 + def setup super ShopifyAPI::Session.secret = 'secret' @@ -373,7 +375,7 @@ class SessionTest < Test::Unit::TestCase end test "raise error if timestamp is too old" do - params = { code: "any-code", timestamp: Time.now - 2.days } + params = { code: "any-code", timestamp: Time.now - 2 * SECONDS_IN_A_DAY } signature = generate_signature(params) params[:foo] = 'world' assert_raises(ShopifyAPI::ValidationException) do
Avoid depending on ActiveSupport (#<I>)
Shopify_shopify_api
train
b2785fb2fffcc690aaeffc423bd6b68682035bf7
diff --git a/spec/views/articles/index_spec.rb b/spec/views/articles/index_spec.rb index <HASH>..<HASH> 100644 --- a/spec/views/articles/index_spec.rb +++ b/spec/views/articles/index_spec.rb @@ -1,8 +1,11 @@ require File.dirname(__FILE__) + '/../../spec_helper' # test standard view and all themes -[ nil, "dirtylicious", "scribbish", "standard_issue", "typographic" ].each do |theme| - view_path = theme ? "#{RAILS_ROOT}/themes/#{theme}/views" : "" +[ nil, "true-blue-3", "dirtylicious", "scribbish", "standard_issue", "typographic" ].each do |theme| + view_path = theme ? "#{RAILS_ROOT}/themes/#{theme}/views" : "" + if File.exists?("#{RAILS_ROOT}/themes/#{theme}/helpers/theme_helper.rb") + require "#{RAILS_ROOT}/themes/#{theme}/helpers/theme_helper.rb" + end describe "#{view_path}/articles/index" do before(:each) do @controller.view_paths = [ "#{RAILS_ROOT}/themes/#{theme}/views" ] if theme @@ -15,18 +18,18 @@ require File.dirname(__FILE__) + '/../../spec_helper' alias :tag_links :article_links end end - + context "normally" do before(:each) do @controller.action_name = "index" assigns[:articles] = Article.paginate(:all, :page => 2, :per_page => 4) render "articles/index" end - + it "should not have pagination link to page 2 without q param" do response.should_not have_tag("a[href=?]", "/page/2") end - + it "should have pagination link to page 1 without q param if on page 2" do response.should have_tag("a[href=?]", "/page/1") end @@ -36,7 +39,7 @@ require File.dirname(__FILE__) + '/../../spec_helper' response.should_not have_tag("p>p", "body") end end - + # *notice # this assumptions has "&amp;", i don`t know why, but we want only to test the q= param in link and have separated this test from controller context "when search" do @@ -48,14 +51,14 @@ require File.dirname(__FILE__) + '/../../spec_helper' assigns[:articles] = Blog.default.articles_matching(params[:q], :page => 2, :per_page => 4) render "articles/index" end - + it "should not have pagination link to page 2 with q param" do response.should_not have_tag("a[href=?]", "/search/body?page=2") # *notice end - + it "should have pagination link to page 1 with q param if on page 2" do response.should have_tag("a[href=?]", "/search/body?page=1") # *notice - end + end end end end
test true-blue-3 themes in article views spec
publify_publify
train
020fa7f7a5be021210f2f5628f6fd46901e641d7
diff --git a/app/jobs/update_group_members_completion_score_job.rb b/app/jobs/update_group_members_completion_score_job.rb index <HASH>..<HASH> 100644 --- a/app/jobs/update_group_members_completion_score_job.rb +++ b/app/jobs/update_group_members_completion_score_job.rb @@ -9,4 +9,8 @@ class UpdateGroupMembersCompletionScoreJob < ActiveJob::Base UpdateGroupMembersCompletionScoreJob.perform_later(group.parent) end end + + def max_attempts + 3 + end end diff --git a/spec/jobs/update_group_members_completion_score_job_spec.rb b/spec/jobs/update_group_members_completion_score_job_spec.rb index <HASH>..<HASH> 100644 --- a/spec/jobs/update_group_members_completion_score_job_spec.rb +++ b/spec/jobs/update_group_members_completion_score_job_spec.rb @@ -5,6 +5,14 @@ RSpec.describe UpdateGroupMembersCompletionScoreJob, type: :job do let(:parent) { nil } let(:group) { double(parent: parent) } + context 'config' do + subject(:job) { described_class.new } + it "enqueues with appropriate config settings" do + expect(job.queue_name).to eq 'low_priority' + expect(job.max_attempts).to eq 3 + end + end + context 'when called' do before do allow(group).to receive(:update_members_completion_score!)
reduce the number of times the Job in question is attempted sentry errors raised as a result of a group being deleted before background jobs to update the groups score were run, by which time of course the group did not exist.
ministryofjustice_peoplefinder
train
fb8a989d2fdd06d7ccb12272b54abe29a43ddd04
diff --git a/lib/lita/mailgun_dropped_rate.rb b/lib/lita/mailgun_dropped_rate.rb index <HASH>..<HASH> 100644 --- a/lib/lita/mailgun_dropped_rate.rb +++ b/lib/lita/mailgun_dropped_rate.rb @@ -30,7 +30,7 @@ module Lita private def result_to_message(result) - "[mailgun] [#{result.domain}] #{result.dropped}/#{result.total} (#{result.dropped_rate.to_s("F")}%) recent emails dropped" + "[mailgun] [#{result.domain}] recent emails dropped: #{result.dropped}/#{result.total} (#{result.dropped_rate.to_s("F")}%) uniq addresses: #{result.uniq_dropped}" end def repository
include uniq dropped addresss in log message
conversation_lita-mailgun
train
138c4b2a77859ce27ee7868e42138e02e7761e6a
diff --git a/libnetwork/controller.go b/libnetwork/controller.go index <HASH>..<HASH> 100644 --- a/libnetwork/controller.go +++ b/libnetwork/controller.go @@ -714,7 +714,9 @@ func (c *controller) NewNetwork(networkType, name string, id string, options ... joinCluster(network) if !c.isDistributedControl() { + c.Lock() arrangeIngressFilterRule() + c.Unlock() } return network, nil diff --git a/libnetwork/drivers/bridge/setup_ip_tables.go b/libnetwork/drivers/bridge/setup_ip_tables.go index <HASH>..<HASH> 100644 --- a/libnetwork/drivers/bridge/setup_ip_tables.go +++ b/libnetwork/drivers/bridge/setup_ip_tables.go @@ -114,7 +114,10 @@ func (n *bridgeNetwork) setupIPTables(config *networkConfiguration, i *bridgeInt n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName()) } - if err := ensureJumpRule("FORWARD", IsolationChain); err != nil { + d.Lock() + err = ensureJumpRule("FORWARD", IsolationChain) + d.Unlock() + if err != nil { return err }
Serialize non-atomic jump rule programming in bridge
moby_moby
train
5b9de7bf2c8a4fb5b5eecadf098b40484b48d9a0
diff --git a/pkg/build/controller/build/build_controller.go b/pkg/build/controller/build/build_controller.go index <HASH>..<HASH> 100644 --- a/pkg/build/controller/build/build_controller.go +++ b/pkg/build/controller/build/build_controller.go @@ -1387,7 +1387,7 @@ func setBuildCompletionData(build *buildapi.Build, pod *v1.Pod, update *buildUpd update.setDuration(now.Rfc3339Copy().Time.Sub(startTime.Rfc3339Copy().Time)) } - if build.Status.Phase == buildapi.BuildPhaseFailed && len(build.Status.LogSnippet) == 0 && + if (build.Status.Phase == buildapi.BuildPhaseFailed || (update.phase != nil && *update.phase == buildapi.BuildPhaseFailed)) && len(build.Status.LogSnippet) == 0 && pod != nil && len(pod.Status.ContainerStatuses) != 0 && pod.Status.ContainerStatuses[0].State.Terminated != nil { msg := pod.Status.ContainerStatuses[0].State.Terminated.Message if len(msg) != 0 {
update logsnippet on initial transition to failing state
openshift_origin
train
b17bd30183dca551dac996c4dc2557ec18d0fae5
diff --git a/Wikimate.php b/Wikimate.php index <HASH>..<HASH> 100644 --- a/Wikimate.php +++ b/Wikimate.php @@ -183,7 +183,8 @@ class Wikimate * @param array $headers Optional extra headers to send with the request * @param boolean $post True to send a POST request, otherwise GET * @return Requests_Response The API response - * @throw WikimateException If lagged and ran out of retries + * @throw WikimateException If lagged and ran out of retries, + * or got an unexpected API response */ private function request($data, $headers = array(), $post = false) { @@ -193,7 +194,12 @@ class Wikimate if (is_array($data)) { $data['format'] = 'json'; $data['maxlag'] = $this->getMaxlag(); + $action = $data['action']; + } else { + $action = 'upload'; } + // Define type of HTTP request for messages + $httptype = $post ? 'POST' : 'GET'; // Send appropriate type of request, once or multiple times do { @@ -231,9 +237,20 @@ class Wikimate // Throw exception if we ran out of retries if ($server_lagged) { throw new WikimateException("Server lagged ($retries consecutive maxlag responses)"); - } else { - return $response; } + + // Check if we got the API doc page (invalid request) + if (strpos($response->body, "This is an auto-generated MediaWiki API documentation page") !== false) { + throw new WikimateException("The API could not understand the $action $httptype request"); + } + + // Check if we got a JSON result + $result = json_decode($response->body, true); + if ($result === null) { + throw new WikimateException("The API did not return the $action JSON response"); + } + + return $response; } /** @@ -275,20 +292,7 @@ class Wikimate // Send the token request $response = $this->request($details, array(), true); - // Check if we got an API result or the API doc page (invalid request) - if (strpos($response->body, "This is an auto-generated MediaWiki API documentation page") !== false) { - $this->error = array(); - $this->error['token'] = 'The API could not understand the token request'; - return null; - } - $tokenResult = json_decode($response->body, true); - // Check if we got a JSON result - if ($tokenResult === null) { - $this->error = array(); - $this->error['token'] = 'The API did not return the token response'; - return null; - } if ($this->debugMode) { echo "Token request:\n"; @@ -337,20 +341,7 @@ class Wikimate // Send the login request $response = $this->request($details, array(), true); - // Check if we got an API result or the API doc page (invalid request) - if (strpos($response->body, "This is an auto-generated MediaWiki API documentation page") !== false) { - $this->error = array(); - $this->error['auth'] = 'The API could not understand the login request'; - return false; - } - $loginResult = json_decode($response->body, true); - // Check if we got a JSON result - if ($loginResult === null) { - $this->error = array(); - $this->error['auth'] = 'The API did not return the login response'; - return false; - } if ($this->debugMode) { echo "Login request:\n"; @@ -399,20 +390,7 @@ class Wikimate // Send the logout request $response = $this->request($details, array(), true); - // Check if we got an API result or the API doc page (invalid request) - if (strpos($response->body, "This is an auto-generated MediaWiki API documentation page") !== false) { - $this->error = array(); - $this->error['auth'] = 'The API could not understand the logout request'; - return false; - } - $logoutResult = json_decode($response->body, true); - // Check if we got a JSON result - if ($logoutResult === null) { - $this->error = array(); - $this->error['auth'] = 'The API did not return the logout response'; - return false; - } if ($this->debugMode) { echo "Logout request:\n";
Centralize checks for API errors in Wikimate::request()
hamstar_Wikimate
train
adcecc268fb80cf46027aa0eaacb53c6886843dc
diff --git a/app/lib/helpers/banner.js b/app/lib/helpers/banner.js index <HASH>..<HASH> 100644 --- a/app/lib/helpers/banner.js +++ b/app/lib/helpers/banner.js @@ -19,6 +19,10 @@ module.exports = function (argv, cmd, details) { Pkg @quasar/app... ${green('v' + cliAppVersion)} Debugging......... ${cmd === 'dev' || argv.debug ? green('enabled') : grey('no')}` + if (cmd === 'build') { + banner += `\n Publishing........ ${argv.publish !== void 0 ? green('yes') : grey('no')}` + } + if (details) { banner += ` ==================
feat(app): Addition to onPublish hooks
quasarframework_quasar
train
dcd90ebfadee150893a44fb314e60a461c0b4c75
diff --git a/referenceConf.js b/referenceConf.js index <HASH>..<HASH> 100644 --- a/referenceConf.js +++ b/referenceConf.js @@ -65,7 +65,7 @@ exports.config = { suites: { smoke: 'spec/smoketests/*.js', full: 'spec/*.js' - } + }, // ----- Capabilities to be passed to the webdriver instance ---- //
fix(configuration): update referenceConf.js with a missing comma
angular_protractor
train
e30d46e9472fe7a8af3164e87f52655589f1baf1
diff --git a/internal/shareable/image.go b/internal/shareable/image.go index <HASH>..<HASH> 100644 --- a/internal/shareable/image.go +++ b/internal/shareable/image.go @@ -187,9 +187,13 @@ func (i *Image) isShared() bool { return i.node != nil } -func (i *Image) ensureNotShared() { +func (i *Image) resetNonUpdatedCount() { i.nonUpdatedCount = 0 delete(imagesToMakeShared, i) +} + +func (i *Image) ensureNotShared() { + i.resetNonUpdatedCount() if i.backend == nil { i.allocate(false) @@ -419,6 +423,9 @@ func (i *Image) replacePixels(pix []byte) { if i.disposed { panic("shareable: the image must not be disposed at replacePixels") } + + i.resetNonUpdatedCount() + if i.backend == nil { if pix == nil { return diff --git a/internal/shareable/image_test.go b/internal/shareable/image_test.go index <HASH>..<HASH> 100644 --- a/internal/shareable/image_test.go +++ b/internal/shareable/image_test.go @@ -204,6 +204,7 @@ func TestReshared(t *testing.T) { } } + // img1 is on a shared image again. img0.DrawTriangles([graphics.ShaderImageNum]*Image{img1}, vs, is, nil, driver.CompositeModeCopy, driver.FilterNearest, driver.AddressUnsafe, driver.Region{}, [graphics.ShaderImageNum - 1][2]float32{}, nil, nil) if got, want := img1.IsSharedForTesting(), true; got != want { t.Errorf("got: %v, want: %v", got, want) @@ -227,7 +228,34 @@ func TestReshared(t *testing.T) { } } - // Use img3 as a render source. img3 never uses a shared texture. + // Use img1 as a render target again. + img1.DrawTriangles([graphics.ShaderImageNum]*Image{img2}, vs, is, nil, driver.CompositeModeCopy, driver.FilterNearest, driver.AddressUnsafe, driver.Region{}, [graphics.ShaderImageNum - 1][2]float32{}, nil, nil) + if got, want := img1.IsSharedForTesting(), false; got != want { + t.Errorf("got: %v, want: %v", got, want) + } + + // Use img1 as a render source, but call ReplacePixels. + for i := 0; i < MaxCountForShare; i++ { + if err := MakeImagesSharedForTesting(); err != nil { + t.Fatal(err) + } + img1.ReplacePixels(make([]byte, 4*size*size)) + img0.DrawTriangles([graphics.ShaderImageNum]*Image{img1}, vs, is, nil, driver.CompositeModeCopy, driver.FilterNearest, driver.AddressUnsafe, driver.Region{}, [graphics.ShaderImageNum - 1][2]float32{}, nil, nil) + if got, want := img1.IsSharedForTesting(), false; got != want { + t.Errorf("got: %v, want: %v", got, want) + } + } + if err := MakeImagesSharedForTesting(); err != nil { + t.Fatal(err) + } + + // img1 is not on a shared image due to ReplacePixels. + img0.DrawTriangles([graphics.ShaderImageNum]*Image{img1}, vs, is, nil, driver.CompositeModeCopy, driver.FilterNearest, driver.AddressUnsafe, driver.Region{}, [graphics.ShaderImageNum - 1][2]float32{}, nil, nil) + if got, want := img1.IsSharedForTesting(), false; got != want { + t.Errorf("got: %v, want: %v", got, want) + } + + // Use img3 as a render source. As img3 is volatile, img3 never uses a shared texture. for i := 0; i < MaxCountForShare*2; i++ { if err := MakeImagesSharedForTesting(); err != nil { t.Fatal(err)
shareable: Reset non-updated-count at ReplacePixels Before this change, ReplacePixels didn't affect the non-updated-count, and an image using ReplacePixels tended to be on a shared image. This was OK, but as lazy pixel loading is going to be introduced, ReplacePixels also needs to reset the count. Updates #<I>
hajimehoshi_ebiten
train
611e8f9263477711f291cbd5de2d1d672c76db64
diff --git a/tests/ZfcUserTest/Mapper/UserHydratorTest.php b/tests/ZfcUserTest/Mapper/UserHydratorTest.php index <HASH>..<HASH> 100644 --- a/tests/ZfcUserTest/Mapper/UserHydratorTest.php +++ b/tests/ZfcUserTest/Mapper/UserHydratorTest.php @@ -15,7 +15,7 @@ class UserHydratorTest extends \PHPUnit_Framework_TestCase } /** - * @covers ZfcUser\Mapper\User::extract + * @covers ZfcUser\Mapper\UserHydrator::extract * @expectedException ZfcUser\Mapper\Exception\InvalidArgumentException */ public function testExtractWithInvalidUserObject() @@ -25,8 +25,8 @@ class UserHydratorTest extends \PHPUnit_Framework_TestCase } /** - * @covers ZfcUser\Mapper\User::extract - * @covers ZfcUser\Mapper\User::mapField + * @covers ZfcUser\Mapper\UserHydrator::extract + * @covers ZfcUser\Mapper\UserHydrator::mapField */ public function testExtractWithValidUserObject() { @@ -54,7 +54,7 @@ class UserHydratorTest extends \PHPUnit_Framework_TestCase } /** - * @covers ZfcUser\Mapper\User::hydrate + * @covers ZfcUser\Mapper\UserHydrator::hydrate * @expectedException ZfcUser\Mapper\Exception\InvalidArgumentException */ public function testHydrateWithInvalidUserObject() @@ -64,8 +64,8 @@ class UserHydratorTest extends \PHPUnit_Framework_TestCase } /** - * @covers ZfcUser\Mapper\User::hydate - * @covers ZfcUser\Mapper\User::mapField + * @covers ZfcUser\Mapper\UserHydrator::hydate + * @covers ZfcUser\Mapper\UserHydrator::mapField */ public function testHydrateWithValidUserObject() {
Fix cover methods for UserHydrator
ZF-Commons_ZfcUser
train
9b37b4c2ff5206967ee63218dd7534f5719cdef3
diff --git a/lib/rest_pki/pdf_mark.rb b/lib/rest_pki/pdf_mark.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/pdf_mark.rb +++ b/lib/rest_pki/pdf_mark.rb @@ -26,5 +26,56 @@ module RestPki pageOptionNumber: @page_option_number, } end + + #region FluentApi + + def on_container(container) + @container = container + self + end + + def with_border_width(border_width) + @border_width = border_width + self + end + + def on_all_pages() + @page_option = PdfMarkPageOptions::ALL_PAGES + self + end + + def on_new_page() + @page_option = PdfMarkPageOptions::NEW_PAGE + self + end + + def on_single_page(page_number) + @page_option = PdfMarkPageOptions::SINGLE_PAGE + @page_option_number = page_number + self + end + + def on_single_page_from_end(page_number) + @page_option = PdfMarkPageOptions::SINGLE_PAGE_FROM_END + @page_option_number = page_number + self + end + + def add_element(element) + @elements.push(element) + self + end + + def with_border_color(border_color) + @border_color = border_color + self + end + + def with_background_color(background_color) + @background_color = background_color + self + end + #endregion + end end \ No newline at end of file diff --git a/lib/rest_pki/pdf_mark_element.rb b/lib/rest_pki/pdf_mark_element.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/pdf_mark_element.rb +++ b/lib/rest_pki/pdf_mark_element.rb @@ -17,5 +17,38 @@ module RestPki opacity: @opacity, } end + + #region FluentApi + def on_container(relative_container) + @relative_container = relative_container + self + end + + def with_rotation(rotation) + @rotation = rotation + self + end + + def rotate90_clockwise() + @rotation = 270 + self + end + + def rotate90_counter_clockwise() + @rotation = 90 + self + end + + def rotate180() + @rotation = 180 + self + end + + def with_opacity(opacity) + @opacity = opacity + self + end + + #endregion end end \ No newline at end of file diff --git a/lib/rest_pki/pdf_mark_image_element.rb b/lib/rest_pki/pdf_mark_image_element.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/pdf_mark_image_element.rb +++ b/lib/rest_pki/pdf_mark_image_element.rb @@ -14,5 +14,20 @@ module RestPki end model end + + #region FluentApi + + def with_image(image) + @image = image + self + end + + def with_image(image_content, mime_type) + @image = PdfMarkImage.new(image_content, mime_type) + self + end + + #endregion + end end \ No newline at end of file diff --git a/lib/rest_pki/pdf_mark_qr_code_element.rb b/lib/rest_pki/pdf_mark_qr_code_element.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/pdf_mark_qr_code_element.rb +++ b/lib/rest_pki/pdf_mark_qr_code_element.rb @@ -14,5 +14,19 @@ module RestPki model['qrCodeDataDrawQuietZones'] = @draw_quiet_zone model end + + #region FluentApi + + def with_qr_code_data(qr_code_data) + @qr_code_data = qr_code_data + self + end + + def draw_quiet_zone() + @draw_quiet_zone = true + self + end + + #endregion end end \ No newline at end of file diff --git a/lib/rest_pki/pdf_mark_text_element.rb b/lib/rest_pki/pdf_mark_text_element.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/pdf_mark_text_element.rb +++ b/lib/rest_pki/pdf_mark_text_element.rb @@ -14,5 +14,34 @@ module RestPki model['align'] = @align model end + + #region FluentApi + + def align_text_left() + @align = 'Left' + self + end + + def align_text_right() + @align = 'Right' + self + end + + def align_text_center() + @align = 'Center' + self + end + + def add_section(section) + @text_sections.push(section) + self + end + + def add_section(text) + @text_sections.push(PdfTextSection.new(text)) + self + end + + #endregion end end \ No newline at end of file diff --git a/lib/rest_pki/pdf_text_section.rb b/lib/rest_pki/pdf_text_section.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/pdf_text_section.rb +++ b/lib/rest_pki/pdf_text_section.rb @@ -24,5 +24,34 @@ module RestPki fontSize: @font_size, } end + + #region FluentApi + + def with_font_size(font_size) + @font_size = font_size + self + end + + def with_text(text) + @text = text + self + end + + def bold() + @style = PdfTextStyle::BOLD + self + end + + def italic() + @style = PdfTextStyle::ITALIC + self + end + + def with_color(color) + @color = color + self + end + + #endregion end end \ No newline at end of file
Added fluent API to PDF mark
LacunaSoftware_RestPkiRubyClient
train
0bfd68b43b60f869a5c48bcc282bfc6ad4e3a910
diff --git a/cordova-lib/spec-cordova/fixtures/platforms/cordova-browser/bin/lib/create.js b/cordova-lib/spec-cordova/fixtures/platforms/cordova-browser/bin/lib/create.js index <HASH>..<HASH> 100644 --- a/cordova-lib/spec-cordova/fixtures/platforms/cordova-browser/bin/lib/create.js +++ b/cordova-lib/spec-cordova/fixtures/platforms/cordova-browser/bin/lib/create.js @@ -46,8 +46,6 @@ module.exports.createProject = function(project_path,package_name,project_name){ process.exit(2); } - // console.log('Creating Browser project. Path: ' + path.relative(process.cwd(),project_path)); - //copy template directory shjs.cp('-r', path.join(ROOT, 'bin', 'templates', 'project', 'www'), project_path);
remove commented code This closes #<I>
apache_cordova-lib
train
0eed47a8f8c2575a34a067585dc0853d91943ac4
diff --git a/middleware.go b/middleware.go index <HASH>..<HASH> 100644 --- a/middleware.go +++ b/middleware.go @@ -139,10 +139,13 @@ func createHTTPRequest(c *Client, r *Request) (err error) { r.RawRequest, err = http.NewRequest(r.Method, r.URL, r.bodyBuf) } - if err == nil { - r.RawRequest.Close = c.closeConnection + if err != nil { + return } + // Assign close connection option + r.RawRequest.Close = c.closeConnection + // Add headers into http request r.RawRequest.Header = r.Header @@ -151,6 +154,7 @@ func createHTTPRequest(c *Client, r *Request) (err error) { r.RawRequest.AddCookie(cookie) } + // it's for non-http scheme option if r.RawRequest.URL != nil && r.RawRequest.URL.Scheme == "" { r.RawRequest.URL.Scheme = c.scheme r.RawRequest.URL.Host = r.URL
code improvement at middleware#createHTTPRequest
go-resty_resty
train
f61f6f5dd89ccb6ad04550b526d52171b84787e2
diff --git a/shared/pinentry/index.desktop.js b/shared/pinentry/index.desktop.js index <HASH>..<HASH> 100644 --- a/shared/pinentry/index.desktop.js +++ b/shared/pinentry/index.desktop.js @@ -44,6 +44,7 @@ class Pinentry extends Component<Props, State> { _onSubmit = () => { this.props.onSubmit(this.state.passphrase) + this.setState({passphrase: ''}) } componentDidMount() { @@ -103,6 +104,7 @@ class Pinentry extends Component<Props, State> { onChangeText: passphrase => this.setState({passphrase}), onEnterKeyDown: this._onSubmit, type: this.state.showTyping ? 'passwordVisible' : 'password', + value: this.state.passphrase, ...typeStyle, }} checkboxContainerStyle={{paddingLeft: 60, paddingRight: 60, ...checkboxContainerStyle}}
Clear passphrase when being asked to verify it (#<I>)
keybase_client
train
34f3aa516cfa04269387c6dc5788a942cd919896
diff --git a/lib/jazzy/source_mark.rb b/lib/jazzy/source_mark.rb index <HASH>..<HASH> 100644 --- a/lib/jazzy/source_mark.rb +++ b/lib/jazzy/source_mark.rb @@ -37,5 +37,10 @@ module Jazzy self.has_start_dash = other.has_start_dash self.has_end_dash = other.has_end_dash end + + # Can we merge the contents of another mark into our own? + def can_merge?(other) + other.empty? || other.name == name + end end end diff --git a/lib/jazzy/sourcekitten.rb b/lib/jazzy/sourcekitten.rb index <HASH>..<HASH> 100644 --- a/lib/jazzy/sourcekitten.rb +++ b/lib/jazzy/sourcekitten.rb @@ -124,6 +124,18 @@ module Jazzy end end + # Merge consecutive sections with the same mark into one section + def self.merge_consecutive_marks(docs) + prev_mark = nil + docs.each do |doc| + if prev_mark && prev_mark.can_merge?(doc.mark) + doc.mark = prev_mark + end + prev_mark = doc.mark + merge_consecutive_marks(doc.children) + end + end + def self.sanitize_filename(doc) unsafe_filename = doc.url_name || doc.name sanitzation_enabled = Config.instance.use_safe_filenames @@ -870,6 +882,7 @@ module Jazzy docs = docs.reject { |doc| doc.type.swift_enum_element? } ungrouped_docs = docs docs = group_docs(docs) + merge_consecutive_marks(docs) make_doc_urls(docs) autolink(docs, ungrouped_docs) [docs, @stats]
Merge consecutive MARK sections when possible The main effect of this is to avoid inconsistent vertical whitespace when items on the same page are pulled in from multiple files or from extensions.
realm_jazzy
train
5451483b7f0bf913f96e8e2c2dab55e68e0fa5d7
diff --git a/examples/delayed.js b/examples/delayed.js index <HASH>..<HASH> 100644 --- a/examples/delayed.js +++ b/examples/delayed.js @@ -36,7 +36,11 @@ jobs.create('email', { jobs.promote(); - +jobs.process('email', 5, function(job, done){ + setTimeout(function(){ + done(); + }, Math.random() * 5000); +}); // start the UI kue.app.listen(3000);
added job processing to delayed example thought something was broken :D
Automattic_kue
train
228662b60cf62817d24e817ebfedcf89ad7720de
diff --git a/lib/knife-cloudformation/knife/template.rb b/lib/knife-cloudformation/knife/template.rb index <HASH>..<HASH> 100644 --- a/lib/knife-cloudformation/knife/template.rb +++ b/lib/knife-cloudformation/knife/template.rb @@ -64,8 +64,10 @@ module KnifeCloudformation ) end if(!Chef::Config[:knife][:cloudformation][:file] && Chef::Config[:knife][:cloudformation][:file_path_prompt]) - root = Chef::Config[:knife][:cloudformation].fetch(:base_directory, - File.join(Dir.pwd, 'cloudformation') + root = File.expand_path( + Chef::Config[:knife][:cloudformation].fetch(:base_directory, + File.join(Dir.pwd, 'cloudformation') + ) ).split('/') bucket = root.pop root = root.join('/') @@ -73,10 +75,12 @@ module KnifeCloudformation :provider => :local, :local_root => root ).directories.get(bucket) - Chef::Config[:knife][:cloudformation][:file] = prompt_for_file(directory, - :directories_name => 'Collections', - :files_name => 'Templates', - :ignore_directories => TEMPLATE_IGNORE_DIRECTORIES + Chef::Config[:knife][:cloudformation][:file] = File.join(root, + prompt_for_file(directory, + :directories_name => 'Collections', + :files_name => 'Templates', + :ignore_directories => TEMPLATE_IGNORE_DIRECTORIES + ) ) else unless(Pathname(Chef::Config[:knife][:cloudformation][:file].to_s).absolute?)
Ensure we are working with expanded path and set full path when discovered
sparkleformation_sfn
train
2b022fb1fe4c99c67be9630f8cf1a9f22577dcef
diff --git a/h2o-automl/src/main/java/ai/h2o/automl/FrameMeta.java b/h2o-automl/src/main/java/ai/h2o/automl/FrameMeta.java index <HASH>..<HASH> 100644 --- a/h2o-automl/src/main/java/ai/h2o/automl/FrameMeta.java +++ b/h2o-automl/src/main/java/ai/h2o/automl/FrameMeta.java @@ -14,16 +14,13 @@ import water.fvec.Vec; import water.util.ArrayUtils; import water.util.AtomicUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import java.util.*; /** * Cache common questions asked upon the frame. */ public class FrameMeta extends Iced { - public final String _datasetName; + final String _datasetName; public final Frame _fr; public int[] _catFeats; public int[] _numFeats; @@ -31,7 +28,7 @@ public class FrameMeta extends Iced { public int[] _dblCols; public int[] _binaryCols; public int[] _intNotBinaryCols; - private final int _response; + final int _response; private long _naCnt=-1; // count of nas across whole frame private int _numFeat=-1; // count of numerical features private int _catFeat=-1; // count of categorical features @@ -119,7 +116,6 @@ public class FrameMeta extends Iced { _dblCols = intListToA(dblCols); _binaryCols = intListToA(binCols); _intNotBinaryCols = intListToA(intNotBinCols); - return (_numFeat=cnt); } @@ -170,6 +166,15 @@ public class FrameMeta extends Iced { _fr=fr; _response=response; _cols = new ColMeta[_fr.numCols()]; + if( _includeCols==null ) + for (int i = 0; i < _fr.numCols(); ++i) + _cols[i] = new ColMeta(_fr.vec(i),_fr.name(i),i,i==_response); + else { + HashSet<String> preds = new HashSet<>(); + Collections.addAll(preds,_includeCols); + for(int i=0;i<_fr.numCols();++i) + _cols[i] = new ColMeta(_fr.vec(i),_fr.name(i),i,i==_response,!preds.contains(_fr.name(i))); + } } public FrameMeta(Frame fr, int response, String datasetName, boolean isClassification) {
pass predictors thru and compute colmeta only for non-ignored columns
h2oai_h2o-3
train
084ad2e93fdeb79281c1b3e21976cd815f0cb0d2
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -11,8 +11,8 @@ emails = '' packages = ['helium'] requires = [ "future>=0.15", - "requests >= 2.9.0", - "uritemplate >= 0.6", + "requests==2.10.0", + "uritemplate>=0.6", ] setup( diff --git a/tests/util.py b/tests/util.py index <HASH>..<HASH> 100644 --- a/tests/util.py +++ b/tests/util.py @@ -11,7 +11,7 @@ import helium Betamax.register_serializer(pretty_json.PrettyJSONSerializer) Betamax.register_request_matcher(json_body.JSONBodyMatcher) if os.environ.get('TRAVIS'): - API_TOKEN = 'X'*10 + API_TOKEN = 'X' * 10 else: API_TOKEN = os.environ.get('HELIUM_TEST_API_KEY') assert API_TOKEN, 'Please set HELIUM_TEST_API_KEY to a valid API key'
Try to work around <I> requests issue
helium_helium-python
train
0f6443c2b64f2ed373ae97d59fc413417babaa3a
diff --git a/safe_qgis/tools/minimum_needs/needs_profile.py b/safe_qgis/tools/minimum_needs/needs_profile.py index <HASH>..<HASH> 100644 --- a/safe_qgis/tools/minimum_needs/needs_profile.py +++ b/safe_qgis/tools/minimum_needs/needs_profile.py @@ -39,15 +39,20 @@ class NeedsProfile(MinimumNeeds): def load(self): """Load the minimum needs from the QSettings object. """ - minimum_needs = self.settings.value('MinimumNeeds', type=dict) - # if hasattr(minimum_needs, 'toPyObject'): - # minimum_needs = minimum_needs.toPyObject() - if not minimum_needs: - profiles = self.get_profiles() - self.read_from_file( - '%s/minimum_needs/%s.json' % (self.root_directory, profiles)) - if minimum_needs is None or minimum_needs == {}: + minimum_needs = None + try: + minimum_needs = self.settings.value('MinimumNeeds', type=dict) + if not minimum_needs and minimum_needs != u'': + profiles = self.get_profiles() + self.read_from_file( + '%s/minimum_needs/%s.json' % ( + self.root_directory, profiles)) + except TypeError: minimum_needs = self._defaults() + + if not minimum_needs and minimum_needs != u'': + minimum_needs = self._defaults() + self.minimum_needs = minimum_needs def load_profile(self, profile):
fix for crash on start when reading minimum needs from QSettings
inasafe_inasafe
train
e85b8aa5c53256acde71e2685faaac74990da3f8
diff --git a/go/vt/vtgate/executor.go b/go/vt/vtgate/executor.go index <HASH>..<HASH> 100644 --- a/go/vt/vtgate/executor.go +++ b/go/vt/vtgate/executor.go @@ -129,6 +129,9 @@ func (e *Executor) Execute(ctx context.Context, method string, safeSession *Safe logStats := NewLogStats(ctx, method, sql, bindVars) result, err = e.execute(ctx, safeSession, sql, bindVars, logStats) logStats.Error = err + if result != nil && len(result.Rows) > *warnMemoryRows { + warnings.Add("ResultsExceeded", 1) + } // The mysql plugin runs an implicit rollback whenever a connection closes. // To avoid spamming the log with no-op rollback records, ignore it if diff --git a/go/vt/vtgate/executor_test.go b/go/vt/vtgate/executor_test.go index <HASH>..<HASH> 100644 --- a/go/vt/vtgate/executor_test.go +++ b/go/vt/vtgate/executor_test.go @@ -46,6 +46,37 @@ import ( vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc" ) +func TestExecutorResultsExceeded(t *testing.T) { + save := *warnMemoryRows + *warnMemoryRows = 3 + defer func() { *warnMemoryRows = save }() + + executor, _, _, sbclookup := createExecutorEnv() + session := NewSafeSession(&vtgatepb.Session{TargetString: "@master"}) + + initial := warnings.Counts()["ResultsExceeded"] + + result1 := sqltypes.MakeTestResult(sqltypes.MakeTestFields("col", "int64"), "1") + result2 := sqltypes.MakeTestResult(sqltypes.MakeTestFields("col", "int64"), "1", "2", "3", "4") + sbclookup.SetResults([]*sqltypes.Result{result1, result2}) + + _, err := executor.Execute(context.Background(), "TestExecutorResultsExceeded", session, "select * from main1", nil) + if err != nil { + t.Fatal(err) + } + if got, want := warnings.Counts()["ResultsExceeded"], initial; got != want { + t.Errorf("warnings count: %v, want %v", got, want) + } + + _, err = executor.Execute(context.Background(), "TestExecutorResultsExceeded", session, "select * from main1", nil) + if err != nil { + t.Fatal(err) + } + if got, want := warnings.Counts()["ResultsExceeded"], initial+1; got != want { + t.Errorf("warnings count: %v, want %v", got, want) + } +} + func TestExecutorTransactionsNoAutoCommit(t *testing.T) { executor, _, _, sbclookup := createExecutorEnv() session := NewSafeSession(&vtgatepb.Session{TargetString: "@master"}) diff --git a/go/vt/vtgate/vtgate.go b/go/vt/vtgate/vtgate.go index <HASH>..<HASH> 100644 --- a/go/vt/vtgate/vtgate.go +++ b/go/vt/vtgate/vtgate.go @@ -60,7 +60,8 @@ var ( streamBufferSize = flag.Int("stream_buffer_size", 32*1024, "the number of bytes sent from vtgate for each stream call. It's recommended to keep this value in sync with vttablet's query-server-config-stream-buffer-size.") queryPlanCacheSize = flag.Int64("gate_query_cache_size", 10000, "gate server query cache size, maximum number of queries to be cached. vtgate analyzes every incoming query and generate a query plan, these plans are being cached in a lru cache. This config controls the capacity of the lru cache.") disableLocalGateway = flag.Bool("disable_local_gateway", false, "if specified, this process will not route any queries to local tablets in the local cell") - maxMemoryRows = flag.Int("max_memory_rows", 30000, "Maximum number of rows that will be held in memory for intermediate results as well as the final result.") + maxMemoryRows = flag.Int("max_memory_rows", 300000, "Maximum number of rows that will be held in memory for intermediate results as well as the final result.") + warnMemoryRows = flag.Int("warn_memory_rows", 30000, "Warning threshold for in-memory results. A row count higher than this amount will cause the VtGateWarnings.ResultsExceeded counter to be incremented.") ) func getTxMode() vtgatepb.TransactionMode { @@ -229,7 +230,7 @@ func Init(ctx context.Context, hc discovery.HealthCheck, serv srvtopo.Server, ce errorsByDbType = stats.NewRates("ErrorsByDbType", stats.CounterForDimension(errorCounts, "DbType"), 15, 1*time.Minute) errorsByCode = stats.NewRates("ErrorsByCode", stats.CounterForDimension(errorCounts, "Code"), 15, 1*time.Minute) - warnings = stats.NewCountersWithSingleLabel("VtGateWarnings", "Vtgate warnings", "type", "IgnoredSet") + warnings = stats.NewCountersWithSingleLabel("VtGateWarnings", "Vtgate warnings", "type", "IgnoredSet", "ResultsExceeded") servenv.OnRun(func() { for _, f := range RegisterVTGates {
vtgate: warning threshold for in-memory rows
vitessio_vitess
train
a3d34faa126e029cc2ec7af3f31e28f64a2619bd
diff --git a/elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/saturation/conclusions/visitors/HybridLocalRuleApplicationConclusionVisitor.java b/elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/saturation/conclusions/visitors/HybridLocalRuleApplicationConclusionVisitor.java index <HASH>..<HASH> 100644 --- a/elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/saturation/conclusions/visitors/HybridLocalRuleApplicationConclusionVisitor.java +++ b/elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/saturation/conclusions/visitors/HybridLocalRuleApplicationConclusionVisitor.java @@ -39,10 +39,11 @@ import org.semanticweb.elk.reasoner.saturation.rules.RuleVisitor; * applications. * * When applying local rules, to the visited {@link Conclusion}, local premises - * (premises with the same source) are taken from the local {@link Context} and - * other premises from the corresponding {@link Context} in the main saturation - * state. This is done to ensure that every rule is applied at most once and no - * inference is lost when processing only local {@link Conclusion}s. + * (premises with the same source as the {@link Conclusion}) are taken from the + * local {@link Context} and other premises from the corresponding + * {@link Context} in the main saturation state. This is done to ensure that + * every rule is applied at most once and no inference is lost when processing + * only local {@link Conclusion}s. * * @author "Yevgeny Kazakov" * @@ -81,20 +82,20 @@ public class HybridLocalRuleApplicationConclusionVisitor extends @Override protected Boolean defaultVisit(Conclusion conclusion, Context input) { - IndexedClassExpression root = input.getRoot(); - if (conclusion.getSourceRoot(root) == root) { - // applying rules for hybrid premises - ContextPremises hybridPremises = new HybridContextPremises(input, - mainState_.getContext(input.getRoot())); - conclusion.accept(nonRedundantLocalRuleApplicator_, hybridPremises); - conclusion.accept(redundantLocalRuleApplicator_, hybridPremises); - } else { - // applying rules with non-local premises - ContextPremises mainPremises = mainState_.getContext(input - .getRoot()); - conclusion.accept(nonRedundantLocalRuleApplicator_, mainPremises); - conclusion.accept(redundantLocalRuleApplicator_, mainPremises); - } + ContextPremises premises = getPremises(conclusion, input); + conclusion.accept(nonRedundantLocalRuleApplicator_, premises); + conclusion.accept(redundantLocalRuleApplicator_, premises); return true; } + + private ContextPremises getPremises(Conclusion conclusion, Context input) { + IndexedClassExpression root = input.getRoot(); + ContextPremises mainPremises = mainState_.getContext(root); + if (conclusion.getSourceRoot(root) != root) + // there are currently no rules which can use other context premises + // with the same source, so we can just take all main premises + return mainPremises; + // else + return new HybridContextPremises(input, mainPremises); + } }
HybridLocalRuleApplicationConclusionVisitor slightly simplified
liveontologies_elk-reasoner
train
4878eaee1d6faa783c985bbf2ecd488420b21ced
diff --git a/api/pagination.go b/api/pagination.go index <HASH>..<HASH> 100644 --- a/api/pagination.go +++ b/api/pagination.go @@ -41,7 +41,11 @@ func decodePageToken(value string) (*PageToken, error) { db := bytes.NewBuffer(dec) var tok PageToken - binary.Read(db, binary.LittleEndian, &tok) + err = binary.Read(db, binary.LittleEndian, &tok) + if err != nil { + return nil, err + } + return &tok, nil } diff --git a/api/pagination_test.go b/api/pagination_test.go index <HASH>..<HASH> 100644 --- a/api/pagination_test.go +++ b/api/pagination_test.go @@ -47,7 +47,12 @@ func TestPageTokenDecode(t *testing.T) { }{ {"_wMAAA==", &PageToken{Limit: 1023}}, {"LQAJAA==", &PageToken{Limit: 45, Page: 9}}, + + // incorrectly base64-encoded data {"basdfasdf", nil}, + + // empty string is valid base64, but fails binary decode + {"", nil}, } for i, tt := range tests {
fix(API): Handle failed binary decode
coreos_fleet
train
256eec2086a7eb42d6056b45b440f7057a67f472
diff --git a/lambda/lambda.go b/lambda/lambda.go index <HASH>..<HASH> 100644 --- a/lambda/lambda.go +++ b/lambda/lambda.go @@ -26,9 +26,16 @@ func main() { sqsurl := os.Args[4] awsregion := os.Args[5] clientTimeout, _ := time.ParseDuration("1s") - if len(os.Args) >= 7 { - clientTimeout, _ = time.ParseDuration(os.Args[6]) + if len(os.Args) > 6 { + newClientTimeout, err := time.ParseDuration(os.Args[6]) + if err == nil { + clientTimeout = newClientTimeout + } else { + fmt.Printf("Error parsing timeout: %s\n", err) + return + } } + fmt.Printf("Using a timeout of %d nanoseconds\n", clientTimeout.Nanoseconds()) if err != nil { fmt.Printf("ERROR %s\n", err) return
Parse client timeout from command line
goadapp_goad
train
c52b74a68d7d42fac61d35a75bafa6a94beef98d
diff --git a/safe_qgis/impact_statistics/aggregator.py b/safe_qgis/impact_statistics/aggregator.py index <HASH>..<HASH> 100644 --- a/safe_qgis/impact_statistics/aggregator.py +++ b/safe_qgis/impact_statistics/aggregator.py @@ -941,6 +941,18 @@ class Aggregator(QtCore.QObject): line_attribute_dict[self.sum_field_name()] = \ line_attribute_dict[LENGTH_COLUMN] + if isinstance( + line_attribute_dict[self.target_field], + QtCore.QPyNullVariant): + message = m.Paragraph( + self.tr( + 'The target_field contains Null values.' + ' The impact function should define this.') + ) + LOGGER.debug('Skipping postprocessing due to: %s' % message) + self.error_message = message + return + # Postprocessor will sum all impacted length, # (remember, if line_attribute_dict[self.target_field]==0, # then the line is not impacted), so to keep the impacted
Add cheking for null target field
inasafe_inasafe
train
1e27b533490d5b375c4656d2dd67961baaa1dced
diff --git a/torchvision/models/mobilenet.py b/torchvision/models/mobilenet.py index <HASH>..<HASH> 100644 --- a/torchvision/models/mobilenet.py +++ b/torchvision/models/mobilenet.py @@ -151,7 +151,8 @@ class MobileNetV2(nn.Module): # This exists since TorchScript doesn't support inheritance, so the superclass method # (this one) needs to have a name other than `forward` that can be accessed in a subclass x = self.features(x) - x = x.mean([2, 3]) + # Cannot use "squeeze" as batch-size can be 1 => must use reshape with x.shape[0] + x = nn.functional.adaptive_avg_pool2d(x, 1).reshape(x.shape[0], -1) x = self.classifier(x) return x
replaced mean on dimensions 2,3 by adaptive_avg_pooling2d (#<I>) * replaced mean on dimensions 2,3 by adaptive_avg_pooling2d with destination of 1, to remove hardcoded dimension ordering * replaced reshape command by torch.squeeze after global_avg_pool2d, which is cleaner * reshape rather than squeeze for BS=1 * remove import torch
pytorch_vision
train
d9f6a6065d8eaad53c7929a7b3b166705d02a7b2
diff --git a/kundera-core/src/test/java/com/impetus/kundera/metadata/processor/MetaModelBuilderTest.java b/kundera-core/src/test/java/com/impetus/kundera/metadata/processor/MetaModelBuilderTest.java index <HASH>..<HASH> 100644 --- a/kundera-core/src/test/java/com/impetus/kundera/metadata/processor/MetaModelBuilderTest.java +++ b/kundera-core/src/test/java/com/impetus/kundera/metadata/processor/MetaModelBuilderTest.java @@ -377,6 +377,8 @@ public class MetaModelBuilderTest Assert.assertEquals(AssociationBiEntity.class, managedType.getJavaType()); Assert.assertEquals(AssociationBiEntity.class.getDeclaredFields().length, managedType.getDeclaredAttributes().size()); assertOnIdAttribute(managedType,"assoRowKey",String.class); + + // assert on owner attribute Attribute<? super X, ?> ownerAttribute = (Attribute<? super X, ?>)managedType.getAttribute("owner"); Assert.assertNotNull(ownerAttribute); Assert.assertEquals(PersistentAttributeType.ONE_TO_ONE, ownerAttribute.getPersistentAttributeType()); @@ -384,6 +386,11 @@ public class MetaModelBuilderTest Assert.assertEquals(true, ownerAttribute.isAssociation()); Assert.assertEquals(AssociationBiEntity.class, ownerAttribute.getDeclaringType().getJavaType()); Assert.assertEquals("owner",ownerAttribute.getName()); + Assert.assertEquals(managedTypes.get(AssociationBiEntity.class),ownerAttribute.getDeclaringType()); + Assert.assertEquals(AssociationBiEntity.class, ownerAttribute.getJavaMember().getDeclaringClass()); + Assert.assertEquals(OToOOwnerBiEntity.class, ownerAttribute.getJavaType()); + Assert.assertEquals(managedTypes.get(OToOOwnerBiEntity.class),((SingularAttribute<? super X, ?>)ownerAttribute).getType()); + } /** * Assert on embeddable type.
Added more assertions on OneToOne bi association.
Impetus_Kundera
train
a2a89b94e479f45e8ce77b4fad46af705cd8f5f7
diff --git a/nameko/standalone/rpc.py b/nameko/standalone/rpc.py index <HASH>..<HASH> 100644 --- a/nameko/standalone/rpc.py +++ b/nameko/standalone/rpc.py @@ -70,7 +70,8 @@ class SingleThreadedReplyListener(ReplyListener): @contextmanager -def rpc_proxy(container_service_name, nameko_config): +def rpc_proxy(container_service_name, nameko_config, context_data=None, + worker_ctx_cls=WorkerContext): """ Yield a single-threaded RPC proxy to a named service. Method calls to the proxy are converted into RPC calls, with responses returned directly. @@ -91,7 +92,8 @@ def rpc_proxy(container_service_name, nameko_config): container = ProxyContainer(nameko_config) - worker_ctx = WorkerContext(container, service=None, method_name=None) + worker_ctx = worker_ctx_cls(container, service=None, method_name=None, + data=context_data) reply_listener = SingleThreadedReplyListener() diff --git a/test/standalone/test_rpc_proxy.py b/test/standalone/test_rpc_proxy.py index <HASH>..<HASH> 100644 --- a/test/standalone/test_rpc_proxy.py +++ b/test/standalone/test_rpc_proxy.py @@ -1,19 +1,78 @@ +from nameko.containers import WorkerContext +from nameko.dependencies import injection, InjectionProvider, DependencyFactory from nameko.rpc import rpc from nameko.standalone.rpc import rpc_proxy +class ContextReader(InjectionProvider): + """ Access values from the worker context data. + + This is a test facilty! Write specific InjectionProviders to make use of + values in ``WorkerContext.data``, don't expose it directly. + """ + def acquire_injection(self, worker_ctx): + def get_context_value(key): + return worker_ctx.data.get(key) + return get_context_value + + +@injection +def context_reader(): + return DependencyFactory(ContextReader) + + class FooService(object): name = 'foobar' + get_context_value = context_reader() + @rpc def spam(self, ham): return ham + @rpc + def get_context_data(self, name): + return self.get_context_value(name) + + +class CustomWorkerContext(WorkerContext): + data_keys = ("custom_header",) + def test_proxy(container_factory, rabbit_config): - config = rabbit_config - container = container_factory(FooService, config) + container = container_factory(FooService, rabbit_config) container.start() - with rpc_proxy('foobar', config) as foo: + + with rpc_proxy('foobar', rabbit_config) as foo: assert foo.spam(ham='eggs') == 'eggs' + + +def test_proxy_context_data(container_factory, rabbit_config): + + container = container_factory(FooService, rabbit_config) + container.start() + + context_data = {'language': 'en'} + with rpc_proxy('foobar', rabbit_config, context_data) as foo: + assert foo.get_context_data('language') == 'en' + + context_data = {'language': 'fr'} + with rpc_proxy('foobar', rabbit_config, context_data) as foo: + assert foo.get_context_data('language') == 'fr' + + +def test_proxy_worker_context(container_factory, rabbit_config): + + container = container_factory(FooService, rabbit_config, + CustomWorkerContext) + container.start() + + context_data = {'custom_header': 'custom_value'} + + with rpc_proxy('foobar', rabbit_config, context_data, + CustomWorkerContext) as foo: + assert foo.get_context_data('custom_header') == "custom_value" + + with rpc_proxy('foobar', rabbit_config, context_data) as foo: + assert foo.get_context_data('custom_header') is None
standalone rpc proxy now accepts context_data and worker_ctx_cls
nameko_nameko
train
6e17809da204802c17507d7ca3e1098f7a29eb7a
diff --git a/rcon.php b/rcon.php index <HASH>..<HASH> 100644 --- a/rcon.php +++ b/rcon.php @@ -112,7 +112,7 @@ class Rcon { return false; // send command packet - $this->write_packet(Rcon::PACKET_COMMAND, Rcon::SERVERDATA_EXECCOMMAND, $command); + $this->writePacket(Rcon::PACKET_COMMAND, Rcon::SERVERDATA_EXECCOMMAND, $command); // get response $response_packet = $this->readPacket(); @@ -134,7 +134,7 @@ class Rcon { */ private function authorize() { - $this->write_packet(Rcon::PACKET_AUTHORIZE, Rcon::SERVERDATA_AUTH, $this->password); + $this->writePacket(Rcon::PACKET_AUTHORIZE, Rcon::SERVERDATA_AUTH, $this->password); $response_packet = $this->readPacket(); if ($response_packet['type'] == Rcon::SERVERDATA_AUTH_RESPONSE) { @@ -158,7 +158,7 @@ class Rcon { * * @return void */ - private function write_packet($packet_id, $packet_type, $packet_body) + private function writePacket($packet_id, $packet_type, $packet_body) { /* Size 32-bit little-endian Signed Integer Varies, see below. @@ -206,4 +206,51 @@ class Rcon { return $packet_pack; } + + // Below are the deprecated functions for reverse compatibility + + /** + * @deprecated + * @see Rcon::getResponse() + */ + public function get_response() + { + return $this->getResponse(); + } + + /** + * @deprecated + * @see Rcon::isConnected() + */ + public function is_connected() + { + return $this->isConnected(); + } + + /** + * @deprecated + * @see Rcon::sendCommand() + */ + public function send_command($command) + { + return $this->sendCommand($command) ; + } + + /** + * @deprecated + * @see Rcon::readPacket() + */ + private function read_packet() + { + return $this->readPacket(); + } + + /** + * @deprecated + * @see Rcon::writePacket() + */ + private function write_packet($packet_id, $packet_type, $packet_body) + { + return $this->writePacket($packet_id, $packet_type, $packet_body); + } }
Added original functions as deprecated functions, and tidy of others get_response, is_connected, send_command, read_packet, write_packet are now deprecated in favor of Camel Case. write_packet has been replaced with writePacket
thedudeguy_PHP-Minecraft-Rcon
train
bf1bd0b8fed26b37c642e2648b17acf8ecf1b1e9
diff --git a/math/src/main/java/breeze/linalg/operators/DenseVectorSupportMethods.java b/math/src/main/java/breeze/linalg/operators/DenseVectorSupportMethods.java index <HASH>..<HASH> 100644 --- a/math/src/main/java/breeze/linalg/operators/DenseVectorSupportMethods.java +++ b/math/src/main/java/breeze/linalg/operators/DenseVectorSupportMethods.java @@ -17,25 +17,26 @@ final public class DenseVectorSupportMethods { * @return */ public static double smallDotProduct_Double(double[] a, double[] b, int length) { - double sum = 0.0; + double sumA = 0.0; + double sumB = 0.0; switch (length) { case 7: - sum = a[6] * b[6]; + sumA = a[6] * b[6]; case 6: - sum += a[5] * b[5]; + sumB = a[5] * b[5]; case 5: - sum += a[4] * b[4]; + sumA += a[4] * b[4]; case 4: - sum += a[3] * b[3]; + sumB += a[3] * b[3]; case 3: - sum += a[2] * b[2]; + sumA += a[2] * b[2]; case 2: - sum += a[1] * b[1]; + sumB += a[1] * b[1]; case 1: - sum += a[0] * b[0]; + sumA += a[0] * b[0]; case 0: default: - return sum; + return sumA + sumB; } } @@ -82,25 +83,26 @@ final public class DenseVectorSupportMethods { * @return */ public static float smallDotProduct_Float(float[] a, float[] b, int length) { - float sum = 0.0f; + float sumA = 0.0f; + float sumB = 0.0f; switch (length) { case 7: - sum = a[6] * b[6]; + sumA = a[6] * b[6]; case 6: - sum += a[5] * b[5]; + sumB = a[5] * b[5]; case 5: - sum += a[4] * b[4]; + sumA += a[4] * b[4]; case 4: - sum += a[3] * b[3]; + sumB += a[3] * b[3]; case 3: - sum += a[2] * b[2]; + sumA += a[2] * b[2]; case 2: - sum += a[1] * b[1]; + sumB += a[1] * b[1]; case 1: - sum += a[0] * b[0]; + sumA += a[0] * b[0]; case 0: default: - return sum; + return sumA + sumB; } }
use sumA and sumB instead of just sum
scalanlp_breeze
train
7b15a008e766eb6fa975a5b1547cde1d4fd49a2f
diff --git a/PJV.js b/PJV.js index <HASH>..<HASH> 100644 --- a/PJV.js +++ b/PJV.js @@ -257,43 +257,47 @@ PJV.validateUrlOrMailto = function (name, obj) { "url" : "http://barnyrubble.tumblr.com/" } -Or asingle string like this: +Or a single string like this: "Barney Rubble <b@rubble.com> (http://barnyrubble.tumblr.com/) +Or an array of either of the above. + */ PJV.validatePeople = function (name, obj) { var errors = []; function validatePerson(obj) { - if (!obj.name) { - errors.push(name + " field should have name"); - } - if (!obj.email && !obj.url) { - errors.push(name + " field should have email or url"); - } - if (obj.email && !PJV.emailFormat.test(obj.email)) { - errors.push("Email not valid for " + name + ": " + obj.email); - } - if (obj.url && !PJV.urlFormat.test(obj.url)) { - errors.push("Url not valid for " + name + ": " + obj.url); - } - if (obj.web && !PJV.urlFormat.test(obj.web)) { - errors.push("Url not valid for " + name + ": " + obj.web); + if (typeof obj == "string") { + if (!/[^<]+<\S+@\S+>/.test(obj)) { + errors.push("String not valid for " + name + ", expected format is Barney Rubble <b@rubble.com> (http://barnyrubble.tumblr.com/)"); + } + } else if (typeof obj == "object") { + if (!obj.name) { + errors.push(name + " field should have name"); + } + if (!obj.email && !obj.url) { + errors.push(name + " field should have email or url"); + } + if (obj.email && !PJV.emailFormat.test(obj.email)) { + errors.push("Email not valid for " + name + ": " + obj.email); + } + if (obj.url && !PJV.urlFormat.test(obj.url)) { + errors.push("Url not valid for " + name + ": " + obj.url); + } + if (obj.web && !PJV.urlFormat.test(obj.web)) { + errors.push("Url not valid for " + name + ": " + obj.web); + } + } else { + errors.push("People field must be an object or a string"); } } - if (typeof obj == "string") { - if (!/[^<]+<\S+@\S+>/.test(obj)) { - errors.push("String not valid for " + name + ", expected format is Barney Rubble <b@rubble.com> (http://barnyrubble.tumblr.com/)"); - } - } else if (obj instanceof Array) { + if (obj instanceof Array) { for (var i = 0; i < obj.length; i++) { validatePerson(obj[i]); } - } else if (typeof obj == "object") { - validatePerson(obj); } else { - errors.push("Type for field " + name + " should be a string or an object"); + validatePerson(obj); } return errors; };
Handle people fields with a single string. This fixes #3
gorillamania_package.json-validator
train
e00dd3ebfdba9816b3ee670c9321c1d38d26ea5c
diff --git a/seqcluster/libs/cluster.py b/seqcluster/libs/cluster.py index <HASH>..<HASH> 100644 --- a/seqcluster/libs/cluster.py +++ b/seqcluster/libs/cluster.py @@ -12,6 +12,7 @@ import numpy as np import pandas as pd from bcbio.utils import file_exists +from bcbio import bam import logger as mylog from classes import * @@ -49,7 +50,7 @@ def clean_bam_file(bam_in, mask=None): pybedtools.BedTool(bam_file).intersect(b=mask, v=True).saveas(mask_file) bam_in = mask_file out_file = op.splitext(bam_in)[0] + "_rmlw.bam" - pysam.index(bam_in, catch_stdout=False) + bam.index(bam_in, {'algorithm':{}}) bam = pysam.AlignmentFile(bam_in, "rb") with pysam.AlignmentFile(out_file, "wb", template=bam) as out_handle: for read in bam.fetch():
use bcbio fn for index
lpantano_seqcluster
train
064dd117319bcfcc210c60a67f091330da66c209
diff --git a/src/Helper/ArgvHelper.php b/src/Helper/ArgvHelper.php index <HASH>..<HASH> 100644 --- a/src/Helper/ArgvHelper.php +++ b/src/Helper/ArgvHelper.php @@ -47,10 +47,13 @@ class ArgvHelper extends Helper { // Get a blank ArgvInput object so we can use the 'escapeToken' method. $argv = new ArgvInput(); - // If the string contains '=', expand it into the option and value. + // If the string contains '=', and the part before the '=' could be an + // option name, expand it into the option and value. if (strpos($arg, '=')) { list($option, $value) = explode('=', $arg, 2); - return $option . '=' . $argv->escapeToken($value); + if (preg_match('{^[\w-]+$}', $option)) { + return $option . '=' . $argv->escapeToken($value); + } } if (strpos($arg, '-') === 0) { return $arg;
Accommodate drush/ssh commands containing an = character.
platformsh_platformsh-cli
train
e265f8f44a832db587617278adbb5364ed877cdb
diff --git a/test/integration/generated_pango_test.rb b/test/integration/generated_pango_test.rb index <HASH>..<HASH> 100644 --- a/test/integration/generated_pango_test.rb +++ b/test/integration/generated_pango_test.rb @@ -10,7 +10,15 @@ describe Pango do describe Pango::Language do it "has a working method get_scripts" do lang = Pango::Language.from_string 'ja' - scripts = lang.get_scripts + result = lang.get_scripts + + if GLib::SizedArray === result + scripts = result + else + ptr, size = *result + scripts = GLib::SizedArray.new Pango::Script, size, ptr + end + scripts.to_a.must_equal [:han, :katakana, :hiragana] end end
Make Pango integration test work with older introspection data
mvz_gir_ffi
train
6cdbe7fb6495f07cbade8128f19c37affbcc57f6
diff --git a/vm/vm.go b/vm/vm.go index <HASH>..<HASH> 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -360,6 +360,11 @@ func invokeExpr(expr ast.Expr, env *Env) (reflect.Value, error) { if err != nil { return NilValue, newError(err, expr) } + if rv.Kind() == reflect.Array || rv.Kind() == reflect.Slice { + if rv.Len() > 0 { + rv = rv.Index(0) + } + } if env.Set(e.Name, rv) != nil { env.Define(e.Name, rv) }
a = b, c, a should be b not slice of b, c
mattn_anko
train
a38d46b352337b2e32709af4b37b59202200b9ce
diff --git a/test/test_processing.py b/test/test_processing.py index <HASH>..<HASH> 100644 --- a/test/test_processing.py +++ b/test/test_processing.py @@ -15,7 +15,7 @@ import unittest import numpy as np -from ctd import DataFrame, lp_filter +from ctd import DataFrame, lp_filter, derive_cnv class BasicProcessingTests(unittest.TestCase): @@ -34,7 +34,7 @@ class BasicProcessingTests(unittest.TestCase): # Despike. def test_despike(self): - dirty = self.prc['c0s/m'].split()[0] # Looking at downcast only. + dirty = self.prc['c0S/m'].split()[0] # Looking at downcast only. clean = dirty.despike(n1=2, n2=20, block=500) spikes = clean.isnull() equal = (dirty[~spikes] == clean[~spikes]).all() @@ -51,7 +51,7 @@ class BasicProcessingTests(unittest.TestCase): # Pressure check. def test_press_check(self): - unchecked = self.raw['t090c'] + unchecked = self.raw['t090C'] press_checked = unchecked.press_check() reversals = press_checked.isnull() equal = (unchecked[~reversals] == press_checked[~reversals]).all() @@ -59,19 +59,25 @@ class BasicProcessingTests(unittest.TestCase): def test_bindata(self): delta = 1. - down = self.prc['t090c'].split()[0] + down = self.prc['t090C'].split()[0] down = down.bindata(delta=delta) self.assertTrue(np.unique(np.diff(down.index.values)) == delta) # PostProcessingTests. def test_smooth(self): - pass + pass # TODO def test_mixed_layer_depth(self): - pass + pass # TODO def test_barrier_layer_thickness(self): - pass + pass # TODO + + def derive_cnv(self): + derived = derive_cnv(self.raw) + new_cols = set(derived).symmetric_difference(self.raw.columns) + self.assertTrue(['CT', 'SA', 'SP', 'SR', 'sigma0_CT', 'z'] == + sorted(new_cols)) def main():
Fixed capitalized columns names. Added derive_cnv test.
pyoceans_python-ctd
train
0576d3be8c1a802db5c72d55a5142c5684914f12
diff --git a/lib/models.js b/lib/models.js index <HASH>..<HASH> 100644 --- a/lib/models.js +++ b/lib/models.js @@ -930,12 +930,12 @@ class Value { } get effectiveCard() { - let eCard = this.card; + let eCard = this.card.clone(); // First check if there is a cardinality constraint and use it if it's there const cardConstraints = this.constraintsFilter.own.card.constraints; if (cardConstraints.length > 0) { - eCard = cardConstraints[cardConstraints.length - 1].card; + eCard = cardConstraints[cardConstraints.length - 1].card.clone(); } // Now look at includes type constraints, because any that have lower card > 0 may affect this card
Fix bug for assigning vs cloning cards The new effectiveCard code made the mistake of assigning a new card by reference. As a result, modificatons to the new card also affected the original card. Oops! This is fixed by cloning instead.
standardhealth_shr-models
train
5316e503de37b461bf8222f2c7f95f25be0515ed
diff --git a/core/src/main/java/me/prettyprint/cassandra/service/template/ColumnFamilyResultWrapper.java b/core/src/main/java/me/prettyprint/cassandra/service/template/ColumnFamilyResultWrapper.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/me/prettyprint/cassandra/service/template/ColumnFamilyResultWrapper.java +++ b/core/src/main/java/me/prettyprint/cassandra/service/template/ColumnFamilyResultWrapper.java @@ -1,6 +1,7 @@ package me.prettyprint.cassandra.service.template; import java.nio.ByteBuffer; +import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; @@ -37,8 +38,15 @@ public class ColumnFamilyResultWrapper<K,N> extends AbstractResultWrapper<K,N> { this.rows = executionResult.get().entrySet().iterator(); next(); } - - + + /** + * All the column names we know about in the current iterator position + * @return + */ + public Collection<N> getColumnNames() { + return columns.keySet(); + } + public ByteBuffer getColumnValue( N columnName) { HColumn<N,ByteBuffer> col = getColumn( columnName ); return col != null ? col.getValue() : null;
added get for columnnames on result set
hector-client_hector
train
3777f381aa5ff4b14b4e0a29e06f2b0b6a4b6f43
diff --git a/lib/agent/index.js b/lib/agent/index.js index <HASH>..<HASH> 100644 --- a/lib/agent/index.js +++ b/lib/agent/index.js @@ -109,13 +109,13 @@ var Agent = self = { this.check_delay(60); // if any actions were requested through the command line - if(program.actions) + if (program.actions) this.start_actions_by_name(program.actions.split(',')); this.check_connection(1, function(connected){ // only check for updates if enabled and run via trigger - if(!connected || self.interactive || !config.get('auto_update')) + if (!connected || self.interactive || !config.get('auto_update')) return callback(connected); updater.check(function(err, new_version){ @@ -259,7 +259,11 @@ var Agent = self = { }, update_setting: function(key, value){ - self.log('Setting new value for ' + key + ": " + value); + console.log('Updating setting: ' + key + " -> " + value); + + if (key.trim() == 'delay') + return self.check_delay(value); + config.update(key, value, function(err){ if (err) self.log_error(err); else hooks.trigger('event', 'setting_updated', key, value); @@ -270,9 +274,13 @@ var Agent = self = { // make sure delay gets set only when running non-interactively // so that we avoid creating multiple crontabs in unices + if (this.interactive) return; -// if (!this.interactive) - // delay.set(requested_delay); + delay.set(requested_delay, function(err, current){ + if (err) return self.log_error('Unable to update delay: ' + err.message); + + self.log("Delay updated from " + current + " to " + requested_delay); + }); }, @@ -391,6 +399,7 @@ var Agent = self = { if (err) return; module.options = options; + module.name = trigger_name; actions.initialize_and_start([module]); }); },
Call delay, as god intended too.
prey_prey-node-client
train
e0fba7473bc4d03071ddc9e857f5e2bb91fbb3a3
diff --git a/test/k8sT/DatapathConfiguration.go b/test/k8sT/DatapathConfiguration.go index <HASH>..<HASH> 100644 --- a/test/k8sT/DatapathConfiguration.go +++ b/test/k8sT/DatapathConfiguration.go @@ -272,21 +272,22 @@ var _ = Describe("K8sDatapathConfig", func() { }) Context("DirectRouting", func() { + BeforeEach(func() { + SkipIfIntegration(helpers.CIIntegrationFlannel) + SkipIfIntegration(helpers.CIIntegrationGKE) + }) + directRoutingOptions := map[string]string{ "global.tunnel": "disabled", "global.autoDirectNodeRoutes": "true", } It("Check connectivity with automatic direct nodes routes", func() { - SkipIfIntegration(helpers.CIIntegrationFlannel) - deployCilium(directRoutingOptions) Expect(testPodConnectivityAcrossNodes(kubectl)).Should(BeTrue(), "Connectivity test between nodes failed") }) It("Check direct connectivity with per endpoint routes", func() { - SkipIfIntegration(helpers.CIIntegrationFlannel) - directRoutingOptions["global.endpointRoutes.enabled"] = "true" directRoutingOptions["global.ipv6.enabled"] = "false" deployCilium(directRoutingOptions) @@ -319,6 +320,7 @@ var _ = Describe("K8sDatapathConfig", func() { BeforeEach(func() { SkipIfBenchmark() + SkipIfIntegration(helpers.CIIntegrationGKE) }) AfterEach(func() { @@ -389,6 +391,7 @@ var _ = Describe("K8sDatapathConfig", func() { Context("Transparent encryption DirectRouting", func() { It("Check connectivity with transparent encryption and direct routing", func() { SkipIfIntegration(helpers.CIIntegrationFlannel) + SkipIfIntegration(helpers.CIIntegrationGKE) SkipItIfNoKubeProxy() privateIface, err := kubectl.GetPrivateIface()
test: Skip autoDirectNodeRoutes on GKE GKE on GCE dosn't guarantee a flat L2 network so autoDirectNodeRoute tests need to be disabled. Fixes: #<I>
cilium_cilium
train
e99e4d2b826ab5ac86a2323b643555a1c430bad5
diff --git a/src/main/java/net/emaze/dysfunctional/options/Maybe.java b/src/main/java/net/emaze/dysfunctional/options/Maybe.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/emaze/dysfunctional/options/Maybe.java +++ b/src/main/java/net/emaze/dysfunctional/options/Maybe.java @@ -1,10 +1,13 @@ package net.emaze.dysfunctional.options; +import java.util.Iterator; import net.emaze.dysfunctional.contracts.dbc; import net.emaze.dysfunctional.dispatching.delegates.Delegate; import net.emaze.dysfunctional.dispatching.delegates.Provider; import net.emaze.dysfunctional.equality.EqualsBuilder; import net.emaze.dysfunctional.hashing.HashCodeBuilder; +import net.emaze.dysfunctional.iterations.EmptyIterator; +import net.emaze.dysfunctional.iterations.SingletonIterator; /** * Holds an optional value. @@ -12,7 +15,7 @@ import net.emaze.dysfunctional.hashing.HashCodeBuilder; * @param <E> the value type * @author rferranti */ -public class Maybe<E> { +public class Maybe<E> implements Iterable<E> { private final E element; private final boolean hasValue; @@ -46,15 +49,21 @@ public class Maybe<E> { return Either.left(nothing.provide()); } - public E orElse(E otherwise){ - if(hasValue){ - return element; + public E orElse(E otherwise) { + if (hasValue) { + return element; + } + return otherwise; + } + + public Maybe<E> orElse(Maybe<E> otherwise) { + if (hasValue) { + return this; } return otherwise; } - private static Maybe<Object> NOTHING = new Maybe<Object>(null, false); - + public static <E> Maybe<E> nothing() { return (Maybe<E>) NOTHING; } @@ -88,4 +97,12 @@ public class Maybe<E> { } return String.format("Just %s", element); } + + @Override + public Iterator<E> iterator() { + if (!hasValue) { + return new EmptyIterator<E>(); + } + return new SingletonIterator<E>(element); + } }
enh: Maybe is now an Iterable
cybazeitalia_emaze-dysfunctional
train
69c6cfadaaddf717fdac55d0deb6e76c3721439f
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -11,6 +11,7 @@ module.exports = { init() { this._super.init && this._super.init.apply(this, arguments); + this.overrideTestCommandFilter(); this.setTestGenerator(); }, @@ -98,6 +99,36 @@ module.exports = { }); }, + overrideTestCommandFilter() { + let TestCommand = this.project.require('ember-cli/lib/commands/test'); + + TestCommand.prototype.buildTestPageQueryString = function(options) { + let params = []; + + if (options.filter) { + params.push(`grep=${options.filter}`); + + if (options.invert) { + params.push('invert=1'); + } + } + + if (options.query) { + params.push(options.query); + } + + return params.join('&'); + }; + + TestCommand.prototype.availableOptions.push({ + name: 'invert', + type: Boolean, + default: false, + description: 'Invert the filter specified by the --filter argument', + aliases: ['i'] + }); + }, + setTestGenerator() { this.project.generateTestFile = function(moduleName, tests) { var output = `describe('${moduleName}', function() {\n`;
Add missing `overrideTestCommandFilter()` method This was missed when we migrated the functionality from `ember-cli-mocha` into `ember-mocha`
emberjs_ember-mocha
train
b247a98ad61f955b12d43610e3d4d2dc783c6c0c
diff --git a/uproot/write/TFile.py b/uproot/write/TFile.py index <HASH>..<HASH> 100644 --- a/uproot/write/TFile.py +++ b/uproot/write/TFile.py @@ -328,7 +328,7 @@ class TFileRecreate(TFileUpdate): c1 = (compressedbytes >> 0) & 0xff c2 = (compressedbytes >> 8) & 0xff c3 = (compressedbytes >> 16) & 0xff - # method = ? + method = lz4.library_version_number()//(100 * 100) # Add LZ4 checksum bytes - 8 bytes cursor.write_fields(self._sink, _header, algo, method, c1, c2, c3, u1, u2, u3) cursor.write_data(self._sink, lz4.frame.compress(uproot.write.streamers.streamers))
Need to figure out lz4 checksum
scikit-hep_uproot
train
87821bec10d25a1fb9e3b174e773fa7c4791e083
diff --git a/Application.py b/Application.py index <HASH>..<HASH> 100644 --- a/Application.py +++ b/Application.py @@ -143,7 +143,8 @@ def print_stack_all(): not sub_code[-1].endswith("self.__cond.release()") and \ not sub_code[-1].endswith("_sleep(delay)") and \ not "thread_event.wait" in sub_code[-1] and \ - not "time.sleep" in sub_code[-1]: + not "time.sleep" in sub_code[-1] and \ + not "_wait_semaphore.acquire" in sub_code[-1]: code.extend(sub_code) for line in code: logging.debug(line) diff --git a/PlugInManager.py b/PlugInManager.py index <HASH>..<HASH> 100644 --- a/PlugInManager.py +++ b/PlugInManager.py @@ -75,7 +75,7 @@ def loadPlugIns(): cls = getattr(member[1], maybe_a_class[0]) _testSuites.append(unittest.TestLoader().loadTestsFromTestCase(cls)) logging.info("Plug-in '" + plugin_dir + "' loaded." + (" Tests: " + ",".join(tests) if len(tests) > 0 else "")) - except ImportError, ex: + except Exception as e: logging.info("Plug-in '" + plugin_dir + "' NOT loaded.") logging.info(traceback.format_exc()) logging.info("--------")
Handle more _bt ignores; and improve plug-in loading error handling. svn r<I>
nion-software_nionswift
train