hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
3011da261a1a8be2adef713063584fb8bf2fab94
diff --git a/scvelo/preprocessing/__init__.py b/scvelo/preprocessing/__init__.py index <HASH>..<HASH> 100644 --- a/scvelo/preprocessing/__init__.py +++ b/scvelo/preprocessing/__init__.py @@ -49,14 +49,14 @@ def read_loom_layers(file_name, backup_url=None): return adata -def recipe_velocity(adata, min_counts=10, n_top_genes=3000, copy=False): +def recipe_velocity(adata, min_counts=10, n_top_genes=3000, n_neighbors=15, copy=False): from scanpy.api.pp import \ filter_genes, filter_genes_dispersion, normalize_per_cell, pca, neighbors filter_genes(adata, min_counts=min_counts) filter_genes_dispersion(adata, n_top_genes=n_top_genes) normalize_per_cell(adata, layers='all') pca(adata, n_comps=30) - neighbors(adata, n_neighbors=30, use_rep='X_pca') + neighbors(adata, n_neighbors=n_neighbors, use_rep='X_pca') moments(adata) return adata if copy else None
add n_neighbors attr to recipe_velocity
theislab_scvelo
train
3393be722c8860d6d607467fa379f5fc86857c68
diff --git a/tests/consist.py b/tests/consist.py index <HASH>..<HASH> 100644 --- a/tests/consist.py +++ b/tests/consist.py @@ -59,7 +59,7 @@ def run(command): hashes = set() for key, val in data.items(): has = hashlib.md5(str(val)).hexdigest() - if not has in hashes: + if has not in hashes: print('{0}:'.format(has)) pprint.pprint(val) hashes.add(has)
Fix PEP8 E<I> - test for membership should be "not in"
saltstack_salt
train
49c7a29f13fe4e066899a3e4948468602b28f89b
diff --git a/core/basic.py b/core/basic.py index <HASH>..<HASH> 100644 --- a/core/basic.py +++ b/core/basic.py @@ -40,6 +40,9 @@ class BasicTokenUtil(object): return result def ascii2token(self, ascii_code, debug=False): + """ + TODO: replace no tokens in comments and strings + """ log.critical(repr(ascii_code)) parts = self.regex.split(ascii_code) log.critical(repr(parts))
TODO: Don't replace reversed words into tokens in comments and strings.
6809_dragonlib
train
b4bd65562b407fcfc2b652ea0030e9840a7db208
diff --git a/src/tests/work-item/work-item-list/work-item-detail.page.js b/src/tests/work-item/work-item-list/work-item-detail.page.js index <HASH>..<HASH> 100644 --- a/src/tests/work-item/work-item-list/work-item-detail.page.js +++ b/src/tests/work-item/work-item-list/work-item-detail.page.js @@ -307,9 +307,104 @@ value: function () { if (!append) {this.workItemDetailAssignee.clear(newAssigneeString)}; return this.workItemDetailAssignee.sendKeys(newAssigneeString); } }, - */ + /* The following UI elements support the assignment of a user to a work item */ + + /* Icon for the user assigned to the workitem */ + workItemDetailAssigneeIcon: { + get: function () + { return element(by.css(".user-assign-icon")); } + }, + + clickworkItemDetailAssigneeIcon: { + value: function () + { return this.workItemDetailAssigneeIcon.click(); } + }, + + /* The user assigned to the workitem */ + workItemDetailAssignee: { + get: function () + { return element(by.xpath(".//*[contains(@class,'detail-assignee-name')]")); } + }, + + clickWorkItemDetailAssignee: { + get: function () + { return this.workItemDetailAssignee.click(); } + }, + + /* Search string box for the user to assign to the workitem */ + workItemDetailAssigneeSearch: { + get: function () + { return element(by.css(".list-container>input")); } + }, + + setWorkItemDetailAssigneeSearch: { + value: function (newSearchString, append) + { + if (!append) { this.workItemDetailAssigneeSearch.clear(newSearchString) }; + return this.workItemDetailAssigneeSearch.sendKeys(newSearchString); } + }, + + /* The list of users to whom work items can be assigned */ + workItemDetailAssigneeList: { + get: function () + { return element(by.css(".user-list")); } + }, + + clickworkItemDetailAssigneeList: { + get: function () + { return this.workItemDetailAssigneeList.click(); } + }, + + /* The first username in the list of users */ + workItemDetailFirstUser: { + get: function () + { return element(by.css(".item-li.first-item")); } + }, + + clickworkItemDetailFirstUser: { + get: function () + { return this.workItemDetailFirstUser.click(); } + }, + + /* Select the assigned user by name */ + assignedUserDropDownList: { + value: function (userName) + { + return element(by.xpath(".//*[@id='wi-detail-form']//li[.//text()[contains(.,'" + userName + "')]]")); + } + }, + + clickAssignedUserDropDownList: { + value: function (userName) + { + return this.assignedUserDropDownList(userName).click(); + } + }, + + /* The Unassign button */ + workItemDetailUnassignButton: { + get: function () + { return element(by.xpath(".//*[contains(@class,'action-item') and contains(text(),'Unassign')]")); } + }, + + clickworkItemDetailUnassignButton: { + value: function () + { return this.workItemDetailUnassignButton.click(); } + }, + + /* The Cancel button */ + workItemDetailCancelButton: { + get: function () + { return element(by.xpath(".//*[contains(@class,'action-item') and contains(text(),'Cancel')]")); } + }, + + clickworkItemDetailCancelButton: { + value: function () + { return this.workItemDetailCancelButton.click(); } + } + }); module.exports = WorkItemDetailPage;
Cleaned up multiple commits - related to adding UI elements in Detail page Object model for assigning users to work items
fabric8-ui_fabric8-planner
train
cc9008c23a4a8451bf699715f6a2a9fa724dcc11
diff --git a/grimoire_elk/enriched/gerrit.py b/grimoire_elk/enriched/gerrit.py index <HASH>..<HASH> 100644 --- a/grimoire_elk/enriched/gerrit.py +++ b/grimoire_elk/enriched/gerrit.py @@ -33,6 +33,7 @@ from grimoirelab_toolkit.datetime import (str_to_datetime, MAX_SIZE_BULK_ENRICHED_ITEMS = 200 REVIEW_TYPE = 'review' COMMENT_TYPE = 'comment' +PATCHSET_TYPE = 'patchset' logger = logging.getLogger(__name__) @@ -304,6 +305,68 @@ class GerritEnrich(Enrich): return ecomments + def get_rich_item_patchsets(self, patchsets, eitem): + epatchesets = [] + + for patchset in patchsets: + epatcheset = {} + + for f in self.RAW_FIELDS_COPY: + epatcheset[f] = eitem[f] + + # Copy data from the enriched review + epatcheset['url'] = eitem['url'] + epatcheset['summary'] = eitem['summary'] + epatcheset['repository'] = eitem['repository'] + epatcheset['branch'] = eitem['branch'] + epatcheset['review_number'] = eitem['number'] + + # Add author info + epatcheset["patchset_author_name"] = None + epatcheset["patchset_author_domain"] = None + if 'author' in patchset and 'name' in patchset['author']: + epatcheset["patchset_author_name"] = patchset['author']['name'] + if 'email' in patchset['author']: + if '@' in patchset['author']['email']: + epatcheset["patchset_author_domain"] = patchset['author']['email'].split("@")[1] + + # Add uploader info + epatcheset["patchset_uploader_name"] = None + epatcheset["patchset_uploader_domain"] = None + if 'uploader' in patchset and 'name' in patchset['uploader']: + epatcheset["patchset_uploader_name"] = patchset['uploader']['name'] + if 'email' in patchset['uploader']: + if '@' in patchset['uploader']['email']: + epatcheset["patchset_uploader_domain"] = patchset['uploader']['email'].split("@")[1] + + # Add patchset-specific data + created = str_to_datetime(patchset['createdOn']) + epatcheset['created'] = created.isoformat() + epatcheset['isDraft'] = patchset['isDraft'] + epatcheset['number'] = patchset['number'] + epatcheset['kind'] = patchset['kind'] + epatcheset['ref'] = patchset['ref'] + epatcheset['revision'] = patchset['revision'] + epatcheset['sizeDeletions'] = patchset['sizeDeletions'] + epatcheset['sizeInsertions'] = patchset['sizeInsertions'] + + # Add id info to allow to coexistence of items of different types in the same index + epatcheset['id'] = '{}_patchset_{}'.format(epatcheset['review_number'], epatcheset['number']) + epatcheset['type'] = PATCHSET_TYPE + + if self.sortinghat: + epatcheset.update(self.get_item_sh(patchset, ['author', 'uploader'], 'createdOn')) + + if self.prjs_map: + epatcheset.update(self.get_item_project(epatcheset)) + + epatcheset.update(self.get_grimoire_fields(patchset['createdOn'], PATCHSET_TYPE)) + + self.add_metadata_filter_raw(epatcheset) + epatchesets.append(epatcheset) + + return epatchesets + def get_field_unique_id(self): return "id" @@ -322,6 +385,11 @@ class GerritEnrich(Enrich): rich_item_comments = self.get_rich_item_comments(comments, eitem) items_to_enrich.extend(rich_item_comments) + patchsets = item['data'].get('patchSets', []) + if patchsets: + rich_item_patchsets = self.get_rich_item_patchsets(patchsets, eitem) + items_to_enrich.extend(rich_item_patchsets) + if len(items_to_enrich) < MAX_SIZE_BULK_ENRICHED_ITEMS: continue
[enriched-gerrit] Add patchsets as enriched items This code includes the patchsets to the enriched index. After creating the enriched review, the patchsets in the raw items are processed and linked to the enriched review by adding the url, summary, repository, branch and number of the review.
chaoss_grimoirelab-elk
train
e517d1dfa4d75f082d7e2cc2ec4dc01290f9fdf6
diff --git a/android/src/main/java/com/dieam/reactnativepushnotification/modules/RNPushNotificationHelper.java b/android/src/main/java/com/dieam/reactnativepushnotification/modules/RNPushNotificationHelper.java index <HASH>..<HASH> 100644 --- a/android/src/main/java/com/dieam/reactnativepushnotification/modules/RNPushNotificationHelper.java +++ b/android/src/main/java/com/dieam/reactnativepushnotification/modules/RNPushNotificationHelper.java @@ -618,12 +618,10 @@ public class RNPushNotificationHelper { List<RunningAppProcessInfo> processInfos = activityManager.getRunningAppProcesses(); if (processInfos != null) { for (RunningAppProcessInfo processInfo : processInfos) { - if (processInfo.processName.equals(context.getPackageName())) { - if (processInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { - for (String d : processInfo.pkgList) { - return true; - } - } + if (processInfo.processName.equals(context.getPackageName()) + && processInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND + && processInfo.pkgList.length > 0) { + return true; } } }
simplifying isApplicationInForeground check
zo0r_react-native-push-notification
train
a772cc8e8254dd16b28cca76ebf28edccb7c65db
diff --git a/spiketoolkit/postprocessing/postprocessing_tools.py b/spiketoolkit/postprocessing/postprocessing_tools.py index <HASH>..<HASH> 100644 --- a/spiketoolkit/postprocessing/postprocessing_tools.py +++ b/spiketoolkit/postprocessing/postprocessing_tools.py @@ -845,9 +845,11 @@ def compute_channel_spiking_activity(recording, channel_ids=None, detect_thresho chunk_size=chunk_size, chunk_mb=chunk_mb, verbose=verbose) - for i, unit in enumerate(sort_detect.get_unit_ids()): - spike_rates[i] = sort_detect.get_unit_property(unit, 'spike_rate') - spike_amplitudes[i] = sort_detect.get_unit_property(unit, 'spike_amplitude') + for channel in recording.get_channel_ids(): + channel_idx = recording.get_channel_ids().index(channel) + if channel in sort_detect.get_unit_ids(): + spike_rates[channel_idx] = sort_detect.get_unit_property(channel, 'spike_rate') + spike_amplitudes[channel_idx] = sort_detect.get_unit_property(channel, 'spike_amplitude') if save_property_or_features: for i, ch in enumerate(recording.get_channel_ids()):
Fix channel idxs in spike detection
SpikeInterface_spiketoolkit
train
ed5b63e11de5c3095d87c9dbf7ac4322dcf4ddfe
diff --git a/platform/bb/RubyVM/src/com/xruby/runtime/builtin/ArrayPacker.java b/platform/bb/RubyVM/src/com/xruby/runtime/builtin/ArrayPacker.java index <HASH>..<HASH> 100644 --- a/platform/bb/RubyVM/src/com/xruby/runtime/builtin/ArrayPacker.java +++ b/platform/bb/RubyVM/src/com/xruby/runtime/builtin/ArrayPacker.java @@ -133,6 +133,8 @@ class ArrayPacker { */ private static final String b64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static final int[] b64_xtable = new int[256]; + private static final String sHexDigits = "0123456789abcdef0123456789ABCDEFx"; + static{ // b64_xtable for decoding Base 64 @@ -224,6 +226,25 @@ class ArrayPacker { } break; + case 'H': + { + int bits = 0; + StringBuffer lElem = new StringBuffer(len); + + for (int lCurByte = 0; lCurByte < len; lCurByte++) { + if ((lCurByte & 1) != 0) + bits <<= 4; + else + bits = str.charAt(s++); + + char c = sHexDigits.charAt((bits >>> 4) & 15); + lElem.append( c ); + } + + ary.add(ObjectFactory.createString(lElem)); + + break; + } case 's': while (len-- > 0) { short tmp = 0; diff --git a/platform/bb/RubyVM/src/com/xruby/runtime/builtin/RubyString.java b/platform/bb/RubyVM/src/com/xruby/runtime/builtin/RubyString.java index <HASH>..<HASH> 100644 --- a/platform/bb/RubyVM/src/com/xruby/runtime/builtin/RubyString.java +++ b/platform/bb/RubyVM/src/com/xruby/runtime/builtin/RubyString.java @@ -165,6 +165,11 @@ public class RubyString extends RubyBasic { return ObjectFactory.createFixnum(sb_.length()); } + //@RubyLevelMethod(name="bytesize") + public RubyFixnum rubyBytesize() { + return ObjectFactory.createFixnum(sb_.length()); + } + //@RubyLevelMethod(name="intern", alias="to_sym") public RubySymbol intern() { if (this.sb_.length() <= 0) { diff --git a/platform/bb/RubyVM/src2/com/xruby/GeneratedMethods/RubyString_Methods.java b/platform/bb/RubyVM/src2/com/xruby/GeneratedMethods/RubyString_Methods.java index <HASH>..<HASH> 100644 --- a/platform/bb/RubyVM/src2/com/xruby/GeneratedMethods/RubyString_Methods.java +++ b/platform/bb/RubyVM/src2/com/xruby/GeneratedMethods/RubyString_Methods.java @@ -160,6 +160,11 @@ klass.defineMethod( "length", new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ){ return ((RubyString)receiver).rubyLength();} }); +klass.defineMethod( "bytesize", new RubyNoArgMethod(){ + protected RubyValue run(RubyValue receiver, RubyBlock block ){ + return ((RubyString)receiver).rubyBytesize();} +}); + klass.defineMethod( "capitalize!", new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ){ return ((RubyString)receiver).capitalizeBang();} diff --git a/platform/bb/rhodes/src/rhomobile/sync/SyncManager.java b/platform/bb/rhodes/src/rhomobile/sync/SyncManager.java index <HASH>..<HASH> 100644 --- a/platform/bb/rhodes/src/rhomobile/sync/SyncManager.java +++ b/platform/bb/rhodes/src/rhomobile/sync/SyncManager.java @@ -81,8 +81,8 @@ public class SyncManager { long len = connection.getLength(); - if ( len > 1024*100) - return null; +// if ( len > 1024*100) +// return null; buffer = readFully(is); }finally{
[#<I>] - BB: wikipedia does not work
rhomobile_rhodes
train
667823d629c1a58a85d2928b31460fc01f3c6ef6
diff --git a/entry_types/scrolled/package/src/testHelpers/rendering.js b/entry_types/scrolled/package/src/testHelpers/rendering.js index <HASH>..<HASH> 100644 --- a/entry_types/scrolled/package/src/testHelpers/rendering.js +++ b/entry_types/scrolled/package/src/testHelpers/rendering.js @@ -1,6 +1,6 @@ import React, {useEffect} from 'react'; import {render} from '@testing-library/react'; -import {renderHook} from '@testing-library/react-hooks'; +import {renderHook} from '@testing-library/react-hooks/dom'; import {Consent} from 'pageflow/frontend'; import {useEntryStateDispatch, RootProviders} from 'pageflow-scrolled/frontend';
Fix storybook Exporting the test helpers from the package in #<I>, caused the storybook to raise an error of the form "Could not auto-detect a React renderer" during rendering. The Percy related actions failed silently.
codevise_pageflow
train
e14012e613ba36b12970b09a363dc22e5151693b
diff --git a/src/convnet_trainers.js b/src/convnet_trainers.js index <HASH>..<HASH> 100644 --- a/src/convnet_trainers.js +++ b/src/convnet_trainers.js @@ -86,7 +86,7 @@ var xsumi = this.xsum[i]; if(this.method === 'adam') { // adam update - var bt1 = this.beta1 * Math.pow(this.lambda, this.k); // decay first moment running average coefficient + var bt1 = this.beta1 * Math.pow(this.lambda, this.k-1); // decay first moment running average coefficient gsumi[j] = gsumi[j] * bt1 + (1-bt1) * gij; // update biased first moment estimate xsumi[j] = xsumi[j] * this.beta2 + (1-this.beta2) * gij * gij; // update biased second moment estimate var denom = Math.sqrt(xsumi[j]) + this.eps;
Add -1 to Adam for correctness
karpathy_convnetjs
train
398b733fa47fc9618576257e319f184bfc394996
diff --git a/seccomp_internal.go b/seccomp_internal.go index <HASH>..<HASH> 100644 --- a/seccomp_internal.go +++ b/seccomp_internal.go @@ -116,8 +116,7 @@ const uint32_t C_ACT_NOTIFY = SCMP_ACT_NOTIFY; // The libseccomp SCMP_FLTATR_CTL_LOG member of the scmp_filter_attr enum was // added in v2.4.0 -#if (SCMP_VER_MAJOR < 2) || \ - (SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 4) +#if SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 4 #define SCMP_FLTATR_CTL_LOG _SCMP_FLTATR_MIN #endif #if SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 5 @@ -176,8 +175,7 @@ unsigned int get_micro_version() #endif // The libseccomp API level functions were added in v2.4.0 -#if (SCMP_VER_MAJOR < 2) || \ - (SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 4) +#if SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 4 const unsigned int seccomp_api_get(void) { // libseccomp-golang requires libseccomp v2.2.0, at a minimum, which @@ -220,8 +218,7 @@ void add_struct_arg_cmp( } // The seccomp notify API functions were added in v2.5.0 -#if (SCMP_VER_MAJOR < 2) || \ - (SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 5) +#if SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 5 struct seccomp_data { int nr;
all: simplify version checks As the code errors out earlier if seccomp version is less than <I>, there is no need to check for SCMP_VER_MAJOR < 2. Drop it.
seccomp_libseccomp-golang
train
d82379b11981c32ae25cafc61b1ddc33e89b573c
diff --git a/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncCustomizer.java b/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncCustomizer.java index <HASH>..<HASH> 100644 --- a/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncCustomizer.java +++ b/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncCustomizer.java @@ -44,10 +44,14 @@ public class LazyTraceAsyncCustomizer extends AsyncConfigurerSupport { @Override public Executor getAsyncExecutor() { - if (this.delegate.getAsyncExecutor() instanceof LazyTraceExecutor) { - return this.delegate.getAsyncExecutor(); + Executor executor = this.delegate.getAsyncExecutor(); + if (executor instanceof LazyTraceExecutor) { + return executor; } - return LazyTraceExecutor.wrap(this.beanFactory, this.delegate.getAsyncExecutor()); + else if (executor == null) { + return null; + } + return LazyTraceExecutor.wrap(this.beanFactory, executor); } @Override diff --git a/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/jdbc/SpanNameProvider.java b/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/jdbc/SpanNameProvider.java index <HASH>..<HASH> 100644 --- a/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/jdbc/SpanNameProvider.java +++ b/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/jdbc/SpanNameProvider.java @@ -26,6 +26,7 @@ import static java.util.regex.Pattern.compile; class SpanNameProvider { private static final String DEFAULT_SPAN_NAME = "query"; + private static final Pattern PATTERN_MATCHING_FIRST_WORD_OF_SQL = compile("^([a-zA-Z]+)[^a-zA-Z]?.*$"); String getSpanNameFor(String sql) { @@ -47,4 +48,5 @@ class SpanNameProvider { return spanName; } + } diff --git a/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncCustomizerTest.java b/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncCustomizerTest.java index <HASH>..<HASH> 100644 --- a/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncCustomizerTest.java +++ b/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/async/LazyTraceAsyncCustomizerTest.java @@ -54,4 +54,13 @@ public class LazyTraceAsyncCustomizerTest { BDDAssertions.then(executor).isExactlyInstanceOf(LazyTraceExecutor.class); } + @Test + public void should_return_null_when_executor_null() throws Exception { + BDDMockito.given(this.asyncConfigurer.getAsyncExecutor()).willReturn(null); + + Executor executor = this.lazyTraceAsyncCustomizer.getAsyncExecutor(); + + BDDAssertions.then(executor).isNull(); + } + } diff --git a/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/jdbc/SpanNameProviderTest.java b/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/jdbc/SpanNameProviderTest.java index <HASH>..<HASH> 100644 --- a/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/jdbc/SpanNameProviderTest.java +++ b/spring-cloud-sleuth-instrumentation/src/test/java/org/springframework/cloud/sleuth/instrument/jdbc/SpanNameProviderTest.java @@ -15,6 +15,7 @@ */ package org.springframework.cloud.sleuth.instrument.jdbc; + import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -22,9 +23,13 @@ import static org.assertj.core.api.Assertions.assertThat; public class SpanNameProviderTest { private static final String DEFAULT_SPAN_NAME = "query"; + private static final String SPAN_NAME_FOR_SELECTS = "select"; + private static final String SPAN_NAME_FOR_UPDATES = "update"; + private static final String SPAN_NAME_FOR_INSERTS = "insert"; + private static final String SPAN_NAME_FOR_DELETES = "delete"; @Test @@ -124,4 +129,5 @@ public class SpanNameProviderTest { assertThat(result).isEqualTo(expectedResult); } + }
Added NPE guard for null async executor; fixes gh-<I>
spring-cloud_spring-cloud-sleuth
train
859586cbd303771f03b1d9c2def7949a0f8ca73f
diff --git a/petrel/petrel/cmdline.py b/petrel/petrel/cmdline.py index <HASH>..<HASH> 100644 --- a/petrel/petrel/cmdline.py +++ b/petrel/petrel/cmdline.py @@ -22,7 +22,7 @@ def get_sourcejar(): 'petrel/generated/storm-petrel-%s-SNAPSHOT.jar' % storm_version) return sourcejar -def submit(sourcejar, destjar, config, venv=None, name=None, definition=None, logdir=None): +def submit(sourcejar, destjar, config, venv, name, definition, logdir, extrastormcp): # Build a topology jar and submit it to Storm. if not sourcejar: sourcejar = get_sourcejar() @@ -33,11 +33,23 @@ def submit(sourcejar, destjar, config, venv=None, name=None, definition=None, lo definition=definition, venv=venv, logdir=logdir) - submit_args = ['', 'jar', destjar, 'storm.petrel.GenericTopology'] - + storm_class_path = [ subprocess.check_output(["storm","classpath"]).strip(), destjar ] + if extrastormcp is not None: + storm_class_path = [ extrastormcp ] + storm_class_path + storm_home = os.path.dirname(os.path.dirname( + subprocess.check_output(['which', 'storm']))) + submit_args = [ + "", + "-client", + "-Dstorm.options=", + "-Dstorm.home=%s" % storm_home, + "-cp",":".join(storm_class_path), + "-Dstorm.jar=%s" % destjar, + "storm.petrel.GenericTopology", + ] if name: submit_args += [name] - os.execvp('storm', submit_args) + os.execvp('java', submit_args) def kill(name, config): config = read_yaml(config) @@ -65,6 +77,8 @@ def main(): help='An existing virtual environment to reuse on the server') parser_submit.add_argument('--logdir', dest='logdir', help='Root directory for logfiles (default: the storm supervisor directory)') + parser_submit.add_argument('--extrastormcp', dest='extrastormcp', + help='Extra jars on the storm classpath, useful for controlling log4j') parser_submit.add_argument('name', const=None, nargs='?', help='name of the topology. If provided, the topology is submitted to the cluster. ' + 'If omitted, the topology runs in local mode.')
Implement pull request <I> from sinjax
AirSage_Petrel
train
f8413bafe76c5125ce1343a617b9a9c5a28cfd39
diff --git a/src/main/java/org/jboss/wsf/spi/metadata/webservices/PortComponentMetaData.java b/src/main/java/org/jboss/wsf/spi/metadata/webservices/PortComponentMetaData.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/jboss/wsf/spi/metadata/webservices/PortComponentMetaData.java +++ b/src/main/java/org/jboss/wsf/spi/metadata/webservices/PortComponentMetaData.java @@ -77,7 +77,16 @@ public class PortComponentMetaData // ----------------------------------------- // JAX-WS additions - private boolean enableMtom; + // The optional <adressing> element + private boolean addressingEnabled; + private boolean addressingRequired; + private String addressingResponses = "ALL"; + // The optional <enable-mtom> element + private boolean mtomEnabled; + // The optional <mtom-threshold> element + private int mtomThreshold; + // @RespectBinding annotation metadata + private boolean respectBindingEnabled; private QName wsdlService; private String protocolBinding; private UnifiedHandlerChainsMetaData handlerChains; @@ -180,14 +189,75 @@ public class PortComponentMetaData this.secureWSDLAccess = secureWSDLAccess; } + /** + * @deprecated Use {@link #isMtomEnabled()} instead. + */ + @Deprecated public boolean isEnableMtom() { - return enableMtom; + return mtomEnabled; } + /** + * @deprecated Use {@link #setMtomEnabled(boolean)} instead. + */ + @Deprecated public void setEnableMtom(boolean enableMtom) { - this.enableMtom = enableMtom; + this.mtomEnabled = enableMtom; + } + + public void setAddressingEnabled(final boolean addressingEnabled) { + this.addressingEnabled = addressingEnabled; + } + + public boolean isAddressingEnabled() { + return this.addressingEnabled; + } + + public void setAddressingRequired(final boolean addressingRequired) { + this.addressingRequired = addressingRequired; + } + + public boolean isAddressingRequired() { + return this.addressingRequired; + } + + public void setAddressingResponses(final String responsesTypes) + { + if (!"ANONYMOUS".equals(responsesTypes) && !"NON_ANONYMOUS".equals(responsesTypes) && !"ALL".equals(responsesTypes)) + throw new IllegalArgumentException("Only ALL, ANONYMOUS or NON_ANONYMOUS strings are allowed"); + + this.addressingResponses = responsesTypes; + } + + public String getAddressingResponses() { + return this.addressingResponses; + } + + public void setMtomEnabled(final boolean mtomEnabled) { + this.mtomEnabled = mtomEnabled; + } + + public boolean isMtomEnabled() { + return this.mtomEnabled; + } + + public void setMtomThreshold(final int mtomThreshold) + { + this.mtomThreshold = mtomThreshold; + } + + public int getMtomThreshold() { + return this.mtomThreshold; + } + + public void setRespectBindingEnabled(final boolean respectBindingEnabled) { + this.respectBindingEnabled = respectBindingEnabled; + } + + public boolean isRespectBindingEnabled() { + return this.respectBindingEnabled; } public QName getWsdlService() diff --git a/src/main/java/org/jboss/wsf/spi/metadata/webservices/WebservicesFactory.java b/src/main/java/org/jboss/wsf/spi/metadata/webservices/WebservicesFactory.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/jboss/wsf/spi/metadata/webservices/WebservicesFactory.java +++ b/src/main/java/org/jboss/wsf/spi/metadata/webservices/WebservicesFactory.java @@ -291,9 +291,21 @@ public class WebservicesFactory implements ObjectModelFactory portComponent.setWsdlService(navigator.resolveQName(value)); else if (localName.equals("protocol-binding")) portComponent.setProtocolBinding(value); + // @Addressing related elements + else if (localName.equals("enabled")) + portComponent.setAddressingEnabled(Boolean.valueOf(value)); + else if (localName.equals("required")) + portComponent.setAddressingRequired(Boolean.valueOf(value)); + else if (localName.equals("responses")) + portComponent.setAddressingResponses(value); + // @MTOM related elements else if (localName.equals("enable-mtom")) - portComponent.setEnableMtom(Boolean.valueOf(value)); - + portComponent.setMtomEnabled(Boolean.valueOf(value)); + else if (localName.equals("mtom-threshold")) + portComponent.setMtomThreshold(Integer.valueOf(value)); + // @RespectBinding related elements + else if (localName.equals("respect-binding")) + portComponent.setRespectBindingEnabled(Boolean.valueOf(value)); } /**
[JBWS-<I>][JBWS-<I>] implementing parsing of <addressing> <enable-mtom> <mtom-threshold> & <respect-binding> elements and updated MD accordingly
jbossws_jbossws-spi
train
a1a0fead295bb6a882b13086858c0445e260c190
diff --git a/quantrisk/bayesian.py b/quantrisk/bayesian.py index <HASH>..<HASH> 100644 --- a/quantrisk/bayesian.py +++ b/quantrisk/bayesian.py @@ -330,8 +330,6 @@ def plot_bayes_cone(df_train, df_test, bmark=None, model='t', bmark=bmark, samples=samples) score = compute_consistency_score(df_test, trace['returns_missing']) - corrco = mean_corrcoef(trace['returns_missing'],df_test) - corrco_cum = mean_corrcoef(np.cumprod(trace['returns_missing'] + 1, 1),cum_returns(df_test, starting_value=1.)) ax = _plot_bayes_cone(df_train, df_test, trace['returns_missing'], plot_train_len=plot_train_len, ax=ax) ax.text(0.40, 0.90, 'Consistency score: %.1f' % score, verticalalignment='bottom', horizontalalignment='right', transform=ax.transAxes,)
BUG Remove stray usage of correlation measure.
quantopian_pyfolio
train
b5d1826a0650452c3bcf62fd88a052b9525613b7
diff --git a/rope/base/exceptions.py b/rope/base/exceptions.py index <HASH>..<HASH> 100644 --- a/rope/base/exceptions.py +++ b/rope/base/exceptions.py @@ -31,4 +31,17 @@ class NameNotFoundError(RopeError): class ModuleSyntaxError(RopeError): - """Module has syntax errors""" + """Module has syntax errors + + The `filename` and `lineno` fields indicate where the error has + occurred. + + """ + + def __init__(self, filename, lineno, message): + self.filename = filename + self.lineno = lineno + self.message = message + super(ModuleSyntaxError, self).__init__( + 'Syntax error in file <%s> line <%s>: %s' % + (filename, lineno, message)) diff --git a/rope/base/pyobjects.py b/rope/base/pyobjects.py index <HASH>..<HASH> 100644 --- a/rope/base/pyobjects.py +++ b/rope/base/pyobjects.py @@ -424,9 +424,7 @@ class PyModule(_PyModule): filename = 'string' if resource: filename = resource.path - raise exceptions.ModuleSyntaxError( - 'Syntax error in file <%s> line <%s>: %s' % - (filename, e.lineno, e.msg)) + raise exceptions.ModuleSyntaxError(filename, e.lineno, e.msg) else: ast_node = ast.parse('\n') self.star_imports = [] diff --git a/ropetest/pycoretest.py b/ropetest/pycoretest.py index <HASH>..<HASH> 100644 --- a/ropetest/pycoretest.py +++ b/ropetest/pycoretest.py @@ -486,6 +486,12 @@ class PyCoreTest(unittest.TestCase): def test_syntax_errors_in_code(self): mod = self.pycore.get_string_module('xyx print\n') + def test_holding_error_location_information(self): + try: + mod = self.pycore.get_string_module('xyx print\n') + except exceptions.ModuleSyntaxError, e: + self.assertEquals(1, e.lineno) + class PyCoreInProjectsTest(unittest.TestCase):
Added filename and lineno fields to ModuleSyntaxError
python-rope_rope
train
58ee9faaa75afd29885595fa7178b8630f903811
diff --git a/src/test/java/net/leanix/api/test/WorkspaceSetupRule.java b/src/test/java/net/leanix/api/test/WorkspaceSetupRule.java index <HASH>..<HASH> 100644 --- a/src/test/java/net/leanix/api/test/WorkspaceSetupRule.java +++ b/src/test/java/net/leanix/api/test/WorkspaceSetupRule.java @@ -94,6 +94,7 @@ public class WorkspaceSetupRule extends ExternalResource { // this is workspace dependent! protected Workspace workspace; protected ApiClient leanixApiClient; + protected UUID apiTokenId; protected String apiSetup = "professional-v1"; @@ -143,10 +144,6 @@ public class WorkspaceSetupRule extends ExternalResource { return getProperty("api.clientSecret"); } - protected String getPersonalAccessToken() { - return getProperty("api.pat"); - } - protected net.leanix.dropkit.apiclient.ApiClient createMtmApiClient() { net.leanix.dropkit.apiclient.ApiClientBuilder builder = new net.leanix.dropkit.apiclient.ApiClientBuilder() .withBasePath(String.format("https://%s/services/mtm/v1", getApiHostName())) @@ -186,16 +183,17 @@ public class WorkspaceSetupRule extends ExternalResource { Contract contract = lookupContract(account.getId(), CONTRACT_DISPLAY_NAME); this.workspace = createNewWorkspace(contract.getId()); - String apiKey = addUserToWorkspace(account, workspace); + String apiToken = addUserToWorkspace(account, workspace); - this.leanixApiClient = createLeanixApiClient(workspace.getName(), apiKey, getApiMtmHostName()); + this.leanixApiClient = createLeanixApiClient(workspace.getName(), apiToken, getApiMtmHostName()); } // cannot delete workspaces due to referential integrity constraints already immediately after creation of the workspace @Override protected void after() { + this.deleteApiToken(this.apiTokenId); this.deleteWorkspace(this.workspace); } @@ -338,9 +336,21 @@ public class WorkspaceSetupRule extends ExternalResource { return null; } token = rp.body().getData(); + apiTokenId = token.getId(); return token.getToken(); } + protected void deleteApiToken(UUID apiTokenId) { + Retrofit retrofit = getRetrofit(mtmApiClient.getBasePath(), readAccessToken(mtmApiClient)); + PersonalAccessTokenApi tokenApi = retrofit.create(PersonalAccessTokenApi.class); + + try { + tokenApi.deletePersonalAccessToken(apiTokenId).execute(); + } catch (IOException e) { + throw new RuntimeException("cannot delete api token", e); + } + } + private String readAccessToken(net.leanix.dropkit.apiclient.ApiClient apiClient) { Authentication auth = apiClient.getAuthentication("token"); String token; diff --git a/src/test/java/net/leanix/api/test/helpers/PersonalAccessTokenApi.java b/src/test/java/net/leanix/api/test/helpers/PersonalAccessTokenApi.java index <HASH>..<HASH> 100644 --- a/src/test/java/net/leanix/api/test/helpers/PersonalAccessTokenApi.java +++ b/src/test/java/net/leanix/api/test/helpers/PersonalAccessTokenApi.java @@ -4,7 +4,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.joda.time.Instant; import retrofit2.Call; import retrofit2.http.Body; +import retrofit2.http.DELETE; import retrofit2.http.POST; +import retrofit2.http.Path; import java.util.UUID; @@ -12,6 +14,9 @@ public interface PersonalAccessTokenApi { @POST("/services/mtm/v1/personalAccessTokens") public Call<PersonalAccessTokenResponse> createPersonalAccessToken(@Body PersonalAccessToken token); + @DELETE("/services/mtm/v1/personalAccessTokens/{id}") + public Call<Void> deletePersonalAccessToken(@Path("id") UUID id); + @JsonIgnoreProperties(ignoreUnknown = true) public static class PersonalAccessTokenResponse { private PersonalAccessToken data; @@ -27,6 +32,7 @@ public interface PersonalAccessTokenApi { @JsonIgnoreProperties(ignoreUnknown = true) public static class PersonalAccessToken { + private UUID id; private String token; private UUID userId; private UUID workspaceId; @@ -34,6 +40,14 @@ public interface PersonalAccessTokenApi { private Instant expiry; private String description; + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + public String getToken() { return token; }
remove API token after test, before deleting the workspace.
leanix_leanix-sdk-java
train
3194a4eddde059033dc3d2536e4af9c8cdab1729
diff --git a/packages/eslint-config-loanmarket-base/index.js b/packages/eslint-config-loanmarket-base/index.js index <HASH>..<HASH> 100644 --- a/packages/eslint-config-loanmarket-base/index.js +++ b/packages/eslint-config-loanmarket-base/index.js @@ -51,6 +51,16 @@ module.exports = { "prefer-destructuring": 0, "function-paren-newline": 0, "object-curly-newline": 0, - "padded-blocks": ["warn", "never"] + "padded-blocks": ["warn", "never"], + "comma-dangle": [ + "error", + { + "arrays": "always-multiline", + "objects": "always-multiline", + "imports": "always-multiline", + "exports": "always-multiline", + "functions": "ignore" + } + ] } };
Ignore comma-dangle for functions.
loanmarket_javascript
train
651aa1cf4c6030a47b981125b5a29931122b5970
diff --git a/drools-workbench-models/drools-workbench-models-test-scenarios/src/main/java/org/drools/workbench/models/testscenarios/backend/ScenarioRunner.java b/drools-workbench-models/drools-workbench-models-test-scenarios/src/main/java/org/drools/workbench/models/testscenarios/backend/ScenarioRunner.java index <HASH>..<HASH> 100644 --- a/drools-workbench-models/drools-workbench-models-test-scenarios/src/main/java/org/drools/workbench/models/testscenarios/backend/ScenarioRunner.java +++ b/drools-workbench-models/drools-workbench-models-test-scenarios/src/main/java/org/drools/workbench/models/testscenarios/backend/ScenarioRunner.java @@ -112,7 +112,7 @@ public class ScenarioRunner { private Set<String> getImports(Scenario scenario) { Set<String> imports = new HashSet<String>(); imports.addAll(scenario.getImports().getImportStrings()); - if(scenario.getPackageName() !=null && scenario.getPackageName().isEmpty()){ + if(scenario.getPackageName() != null && !scenario.getPackageName().isEmpty()){ imports.add(scenario.getPackageName()+".*"); } return imports;
BZ-<I> - Test scenario cannot find facts from the same package
kiegroup_drools
train
0859dcb02100d040d8d2dd5c323cceb636bdae4e
diff --git a/updates.js b/updates.js index <HASH>..<HASH> 100755 --- a/updates.js +++ b/updates.js @@ -64,11 +64,12 @@ const dependencyTypes = [ ]; let pkg, pkgStr; +const deps = {}; try { pkgStr = fs.readFileSync(packageFile, "utf8"); } catch (err) { - finish(new Error("Unable to open package.json.")); + finish(new Error("Unable to open package.json")); } try { @@ -77,8 +78,6 @@ try { finish(new Error("Error parsing package.json:" + err.message)); } -const deps = {}; - dependencyTypes.forEach(function(key) { if (pkg[key]) { Object.keys(pkg[key]).forEach(function(name) {
Fix error handling when package.json does not exist
silverwind_updates
train
097231dadcdd49fc079a9840fb456c0ddc985967
diff --git a/src/LoggerCommandBus.php b/src/LoggerCommandBus.php index <HASH>..<HASH> 100644 --- a/src/LoggerCommandBus.php +++ b/src/LoggerCommandBus.php @@ -4,7 +4,10 @@ declare(strict_types = 1); namespace Innmind\CommandBus; use Innmind\CommandBus\Exception\InvalidArgumentException; -use Innmind\Reflection\ReflectionObject as InnmindReflectionObject; +use Innmind\Reflection\{ + ReflectionObject as InnmindReflectionObject, + ExtractionStrategy\ReflectionStrategy +}; use Psr\Log\LoggerInterface; use Ramsey\Uuid\Uuid; @@ -59,7 +62,12 @@ final class LoggerCommandBus implements CommandBusInterface $properties[] = $property->getName(); } - return (new InnmindReflectionObject($object)) + return (new InnmindReflectionObject( + $object, + null, + null, + new ReflectionStrategy + )) ->extract($properties) ->map(function(string $property, $value) { if (is_object($value)) { diff --git a/tests/LoggerCommandBusTest.php b/tests/LoggerCommandBusTest.php index <HASH>..<HASH> 100644 --- a/tests/LoggerCommandBusTest.php +++ b/tests/LoggerCommandBusTest.php @@ -7,6 +7,7 @@ use Innmind\CommandBus\{ LoggerCommandBus, CommandBusInterface }; +use Innmind\Immutable\Str; use Psr\Log\LoggerInterface; use PHPUnit\Framework\TestCase; @@ -37,6 +38,7 @@ class LoggerCommandBusTest extends TestCase }; $command->baz = $baz = new \stdClass; $baz->wat = 'wat'; + $baz->str = new Str('watever'); $class = get_class($command); $reference = null; $logger = $this->createMock(LoggerInterface::class); @@ -51,9 +53,13 @@ class LoggerCommandBusTest extends TestCase return $data['class'] === $class && $data['data'] === [ 'foo' => 'bar', - 'bar' => 42, + 'bar' => null, 'baz' => [ 'wat' => 'wat', + 'str' => [ + 'value' => 'watever', + 'encoding' => 'UTF-8', + ], ], ]; })
only use reflection to extract command data (otherwise it may lead to infinite recursion
Innmind_CommandBus
train
92c3de996d928691c6705209eea6f03cc09c2019
diff --git a/tests/main.py b/tests/main.py index <HASH>..<HASH> 100644 --- a/tests/main.py +++ b/tests/main.py @@ -46,16 +46,13 @@ Available tasks: def exposes_hosts_flag_in_help(self): expect("--help", "-H STRING, --hosts=STRING", test=assert_contains) - @mock_remote() - def executes_remainder_as_anonymous_task(self, chan): - # Because threading arbitrary mocks into @mock_remote is kinda hard - with patch('fabric.main.Connection', spec=Context) as Connection: - fab_program.run("fab -H myhost,otherhost -- lol a command", exit=False) - # Did we connect to the hosts? - eq_(Connection.call_args_list[0][1]['host'], 'myhost') - eq_(Connection.call_args_list[1][1]['host'], 'otherhost') - # Did we execute the command on both? - # TODO: how to tell these apart exactly ,do we need to update - # mock_remote? =/ - chan.exec_command.assert_called_with("lol a command") - chan.exec_command.assert_called_with("lol a command") + @patch('fabric.main.Connection', spec=Context) + def executes_remainder_as_anonymous_task(self, Connection): + fab_program.run("fab -H myhost,otherhost -- lol a command", exit=False) + # Did we connect to the hosts? + eq_(Connection.call_args_list[0][1]['host'], 'myhost') + eq_(Connection.call_args_list[1][1]['host'], 'otherhost') + # Did we execute the command on both? (given same mock, just means + # "did it run twice". Meh.) + eq_(Connection.return_value.run.call_args_list[0][0][0], "lol a command") + eq_(Connection.return_value.run.call_args_list[1][0][0], "lol a command")
And now we prove it calls run() as expected
fabric_fabric
train
784ff7b05ac6597108987ec1b0f6d51de05d13ff
diff --git a/lib/genevalidator/blast.rb b/lib/genevalidator/blast.rb index <HASH>..<HASH> 100644 --- a/lib/genevalidator/blast.rb +++ b/lib/genevalidator/blast.rb @@ -13,10 +13,13 @@ require 'yaml' class BlastUtils + EVALUE = 1e-5 + ## # Calls blast from standard input with specific parameters # Params: - # +command+: blast command in String format (e.g 'blastx' or 'blastp') + # +blastpath+: location of blast binaries + # +blastcmd+: blast command in String format (e.g 'blastx' or 'blastp') # +query+: String containing the the query in fasta format # +gapopen+: gapopen blast parameter # +gapextend+: gapextend blast parameter @@ -24,27 +27,24 @@ class BlastUtils # +nr_hits+: max number of hits # Output: # String with the blast xml output - def self.call_blast_from_stdin(blastpath, blast_type, query, db, gapopen=11, gapextend=1, nr_hits=200) - if blastpath == nil - command = blast_type - else - command = File.join(blastpath, blast_type) - end - raise TypeError unless command.is_a? String and query.is_a? String - - evalue = "1e-5" - - #output format = 5 (XML Blast output) - blast_cmd = "#{command} -db #{db} -evalue #{evalue} -outfmt 5 -max_target_seqs #{nr_hits} -gapopen #{gapopen} -gapextend #{gapextend}" - cmd = "echo \"#{query}\" | #{blast_cmd}" - output = %x[#{cmd} 2>/dev/null] - - if output == "" - raise ClasspathError.new - end - - return output - + def self.call_blast_from_stdin(blastpath, blastcmd, query, db, gapopen=11, gapextend=1, nr_hits=200) + # FIXME: This method is meant to be used internally within GV. As such it + # can be guaranteed that parameters are of the right type. Type checking + # here is redundant. + raise TypeError unless blastcmd.is_a? String and query.is_a? String + + blastcmd = File.join(blastpath, blastcmd) unless blastpath.nil? + blastcmd = "#{blastcmd} -db #{db} -evalue #{EVALUE} -outfmt 5 -max_target_seqs #{nr_hits} -gapopen #{gapopen} -gapextend #{gapextend}" + cmd = "echo \"#{query}\" | #{blastcmd}" + output = %x[#{cmd} 2>/dev/null] + + # FIXME: + # Empty output doesn't necessarily indicate that BLAST+ binaries are not + # in $PATH. GV should guarantee the presence of BLAST+ binaries before + # this method is called. + raise ClasspathError if output.empty? + + output rescue TypeError => error $stderr.print "Type error at #{error.backtrace[0].scan(/\/([^\/]+:\d+):.*/)[0][0]}. "<< "Possible cause: one of the arguments of 'call_blast_from_stdin' method has not the proper type\n"
Refactoring - be more expressive. And add some FIXME annotations for later.
wurmlab_genevalidator
train
6c6110ef1d8063b88a40115cdd6ac7089a689200
diff --git a/botstory/ast/processor.py b/botstory/ast/processor.py index <HASH>..<HASH> 100644 --- a/botstory/ast/processor.py +++ b/botstory/ast/processor.py @@ -115,15 +115,16 @@ class StoryProcessor: # it seems we find stack item that matches our message compiled_story = self.library.get_story_by_topic(stack_tail['topic'], stack=stack[:-1]) - received_data = await self.process_next_part_of_story({ - 'step': stack[-1]['step'], - 'story': compiled_story, - 'stack': stack, - }, validation_result) + received_data = await self.process_next_part_of_story({ + 'step': stack[-1]['step'], + 'story': compiled_story, + 'stack': stack, + }, validation_result) + compiled_story = received_data['story'] waiting_for = await self.process_story( message=message, - compiled_story=received_data['story'], + compiled_story=compiled_story, ) if len(stack) == 0:
put process of next part of story for cases with non-empty stack
botstory_botstory
train
1fb3bc9de2500175f39fec4b126e3181d6c06006
diff --git a/firestore/google/cloud/firestore_v1/client.py b/firestore/google/cloud/firestore_v1/client.py index <HASH>..<HASH> 100644 --- a/firestore/google/cloud/firestore_v1/client.py +++ b/firestore/google/cloud/firestore_v1/client.py @@ -25,6 +25,7 @@ In the hierarchy of API concepts """ import os +import google.api_core.client_options from google.api_core.gapic_v1 import client_info from google.cloud.client import ClientWithProject @@ -79,6 +80,9 @@ class Client(ClientWithProject): requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own library or partner tool. + client_options (Union[dict, google.api_core.client_options.ClientOptions]): + Client options used to set user options on the client. API Endpoint + should be set through client_options. """ SCOPE = ( @@ -97,6 +101,7 @@ class Client(ClientWithProject): credentials=None, database=DEFAULT_DATABASE, client_info=_CLIENT_INFO, + client_options=None, ): # NOTE: This API has no use for the _http argument, but sending it # will have no impact since the _http() @property only lazily @@ -105,6 +110,13 @@ class Client(ClientWithProject): project=project, credentials=credentials, _http=None ) self._client_info = client_info + if client_options: + if type(client_options) == dict: + client_options = google.api_core.client_options.from_dict( + client_options + ) + self._client_options = client_options + self._database = database self._emulator_host = os.getenv(_FIRESTORE_EMULATOR_HOST) @@ -150,8 +162,10 @@ class Client(ClientWithProject): """ if self._emulator_host is not None: return self._emulator_host - - return firestore_client.FirestoreClient.SERVICE_ADDRESS + elif self._client_options and self._client_options.api_endpoint: + return self._client_options.api_endpoint + else: + return firestore_client.FirestoreClient.SERVICE_ADDRESS @property def _database_string(self): diff --git a/firestore/tests/unit/v1/test_client.py b/firestore/tests/unit/v1/test_client.py index <HASH>..<HASH> 100644 --- a/firestore/tests/unit/v1/test_client.py +++ b/firestore/tests/unit/v1/test_client.py @@ -64,16 +64,28 @@ class TestClient(unittest.TestCase): credentials = _make_credentials() database = "now-db" client_info = mock.Mock() + client_options = mock.Mock() client = self._make_one( project=self.PROJECT, credentials=credentials, database=database, client_info=client_info, + client_options=client_options, ) self.assertEqual(client.project, self.PROJECT) self.assertEqual(client._credentials, credentials) self.assertEqual(client._database, database) self.assertIs(client._client_info, client_info) + self.assertIs(client._client_options, client_options) + + def test_constructor_w_client_options(self): + credentials = _make_credentials() + client = self._make_one( + project=self.PROJECT, + credentials=credentials, + client_options={"api_endpoint": "foo-firestore.googleapis.com"}, + ) + self.assertEqual(client._target, "foo-firestore.googleapis.com") @mock.patch( "google.cloud.firestore_v1.gapic.firestore_client.FirestoreClient",
Firestore: Add client_options to v1. (#<I>)
googleapis_google-cloud-python
train
b27fae6db5206907819f7ebdebfb829ae94c7188
diff --git a/activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/signavio/SignavioConnector.java b/activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/signavio/SignavioConnector.java index <HASH>..<HASH> 100644 --- a/activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/signavio/SignavioConnector.java +++ b/activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/signavio/SignavioConnector.java @@ -359,7 +359,7 @@ public class SignavioConnector extends AbstractRepositoryConnector<SignavioConne Form createFolderForm = new Form(); createFolderForm.add("name", name); createFolderForm.add("description", ""); // TODO: what should we use here? - createFolderForm.add("parent", "/directory/" + parentFolderId); + createFolderForm.add("parent", "/directory" + parentFolderId); Representation createFolderRep = createFolderForm.getWebRepresentation(); Request jsonRequest = new Request(Method.POST, new Reference(getConfiguration().getDirectoryRootUrl()), createFolderRep); diff --git a/activiti-webapp-cycle/src/main/webapp/js/activiti-app.js b/activiti-webapp-cycle/src/main/webapp/js/activiti-app.js index <HASH>..<HASH> 100644 --- a/activiti-webapp-cycle/src/main/webapp/js/activiti-app.js +++ b/activiti-webapp-cycle/src/main/webapp/js/activiti-app.js @@ -556,7 +556,7 @@ onFailure: function CreateFolderDialog_onFailure(o) { // TODO: i18n - Activiti.widget.PopupManager.displayError("Connection Error", "Unable to create folder. Check your internet connection and make sure the Activiti server can be reached."); + // Activiti.widget.PopupManager.displayError("Connection Error", "Unable to create folder. Check your internet connection and make sure the Activiti server can be reached."); } });
fixed issue that caused an exception when creating a folder in activiti modeler
camunda_camunda-bpm-platform
train
5e358221feaa3bd4d75200977918facb5947d969
diff --git a/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPAChangeAttribute.java b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPAChangeAttribute.java index <HASH>..<HASH> 100755 --- a/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPAChangeAttribute.java +++ b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPAChangeAttribute.java @@ -36,6 +36,7 @@ public class LPAChangeAttribute implements ILayoutProcessingAction { } /** Apply the attribute change. */ + @Override public void perform() throws PortalException { // push the change into the PLF if (nodeId.startsWith(Constants.FRAGMENT_ID_USER_PREFIX)) {
docs: annotate LPAChangeAttribute perform() as @Override
Jasig_uPortal
train
664c9964c8ca147bfa4841f2055442ce6f4b490f
diff --git a/kmip/core/factories/payloads/request.py b/kmip/core/factories/payloads/request.py index <HASH>..<HASH> 100644 --- a/kmip/core/factories/payloads/request.py +++ b/kmip/core/factories/payloads/request.py @@ -40,6 +40,9 @@ class RequestPayloadFactory(PayloadFactory): def _create_locate_payload(self): return payloads.LocateRequestPayload() + def _create_check_payload(self): + return payloads.CheckRequestPayload() + def _create_get_payload(self): return payloads.GetRequestPayload() diff --git a/kmip/core/factories/payloads/response.py b/kmip/core/factories/payloads/response.py index <HASH>..<HASH> 100644 --- a/kmip/core/factories/payloads/response.py +++ b/kmip/core/factories/payloads/response.py @@ -40,6 +40,9 @@ class ResponsePayloadFactory(PayloadFactory): def _create_locate_payload(self): return payloads.LocateResponsePayload() + def _create_check_payload(self): + return payloads.CheckResponsePayload() + def _create_get_payload(self): return payloads.GetResponsePayload() diff --git a/kmip/tests/unit/core/factories/payloads/test_request.py b/kmip/tests/unit/core/factories/payloads/test_request.py index <HASH>..<HASH> 100644 --- a/kmip/tests/unit/core/factories/payloads/test_request.py +++ b/kmip/tests/unit/core/factories/payloads/test_request.py @@ -77,7 +77,8 @@ class TestRequestPayloadFactory(testtools.TestCase): self._test_payload_type(payload, payloads.LocateRequestPayload) def test_create_check_payload(self): - self._test_not_implemented(self.factory.create, enums.Operation.CHECK) + payload = self.factory.create(enums.Operation.CHECK) + self._test_payload_type(payload, payloads.CheckRequestPayload) def test_create_get_payload(self): payload = self.factory.create(enums.Operation.GET) diff --git a/kmip/tests/unit/core/factories/payloads/test_response.py b/kmip/tests/unit/core/factories/payloads/test_response.py index <HASH>..<HASH> 100644 --- a/kmip/tests/unit/core/factories/payloads/test_response.py +++ b/kmip/tests/unit/core/factories/payloads/test_response.py @@ -77,7 +77,8 @@ class TestResponsePayloadFactory(testtools.TestCase): self._test_payload_type(payload, payloads.LocateResponsePayload) def test_create_check_payload(self): - self._test_not_implemented(self.factory.create, enums.Operation.CHECK) + payload = self.factory.create(enums.Operation.CHECK) + self._test_payload_type(payload, payloads.CheckResponsePayload) def test_create_get_payload(self): payload = self.factory.create(enums.Operation.GET)
Add Check support to the payload factories This change adds Check payload support to the payload factories. Payload factory unit tests have been updated to account for the change.
OpenKMIP_PyKMIP
train
bad310a283d4d459464a2aff670fd596f5716fef
diff --git a/sip/execution_control/processing_controller/scheduler/scheduler.py b/sip/execution_control/processing_controller/scheduler/scheduler.py index <HASH>..<HASH> 100644 --- a/sip/execution_control/processing_controller/scheduler/scheduler.py +++ b/sip/execution_control/processing_controller/scheduler/scheduler.py @@ -25,6 +25,8 @@ APP = celery.Celery(broker=BROKER, backend=BACKEND) execution_task_name = 'sip_pbc.tasks.execute_processing_block' +if os.getenv('USE_DLG', None): + execution_task_name = 'dlg_pbc.tasks.execute_processing_block' class ProcessingBlockScheduler: # pylint: disable=too-few-public-methods
Use the daliuge-pbc PBC implementation on demand This could be implemented maybe as part of the ProcessingBlock object, but for the time being it's just another environment variable.
SKA-ScienceDataProcessor_integration-prototype
train
e765b43e2bf3d017f8ae8fd4d455d7bd60e11973
diff --git a/hugolib/page_output.go b/hugolib/page_output.go index <HASH>..<HASH> 100644 --- a/hugolib/page_output.go +++ b/hugolib/page_output.go @@ -83,6 +83,7 @@ func (p *PageOutput) copy() *PageOutput { if err != nil { panic(err) } + c.paginator = p.paginator return c }
hugolib: Avoid recreating the Paginator on copy See #<I>
gohugoio_hugo
train
2bbe25e4f4770595d36c34c36c5d2c2719e10fec
diff --git a/core/model/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/ExpressionOperation.java b/core/model/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/ExpressionOperation.java index <HASH>..<HASH> 100644 --- a/core/model/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/ExpressionOperation.java +++ b/core/model/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/ExpressionOperation.java @@ -44,18 +44,7 @@ public enum ExpressionOperation implements FunctionSymbol { HOURS("HOURS", TermTypeInferenceRules.PREDEFINED_INTEGER_RULE, XSD_DATETIME_DT, false), MINUTES("MINUTES", TermTypeInferenceRules.PREDEFINED_INTEGER_RULE, XSD_DATETIME_DT, false), SECONDS("SECONDS", TermTypeInferenceRules.PREDEFINED_DECIMAL_RULE, XSD_DATETIME_DT, false), - TZ("TZ", TermTypeInferenceRules.PREDEFINED_STRING_RULE, XSD_DATETIME_DT, false), - - /* - * Set functions (for aggregation) - * TODO: consider a non-atomic datatype - */ - - AVG("AVG", TermTypeInferenceRules.NON_INTEGER_NUMERIC_RULE, RDF_TERM_TYPE, false), - SUM("SUM", TermTypeInferenceRules.STANDARD_NUMERIC_RULE, RDF_TERM_TYPE, false), - MAX("MAX", TermTypeInferenceRules.STANDARD_NUMERIC_RULE, RDF_TERM_TYPE, false), - MIN("MIN", TermTypeInferenceRules.STANDARD_NUMERIC_RULE, RDF_TERM_TYPE, false), - COUNT("COUNT", TermTypeInferenceRules.PREDEFINED_INTEGER_RULE, RDF_TERM_TYPE, false); + TZ("TZ", TermTypeInferenceRules.PREDEFINED_STRING_RULE, XSD_DATETIME_DT, false); // 0-ary operations diff --git a/engine/reformulation/sql/src/main/java/it/unibz/inf/ontop/answering/reformulation/generation/impl/OneShotSQLGeneratorEngine.java b/engine/reformulation/sql/src/main/java/it/unibz/inf/ontop/answering/reformulation/generation/impl/OneShotSQLGeneratorEngine.java index <HASH>..<HASH> 100644 --- a/engine/reformulation/sql/src/main/java/it/unibz/inf/ontop/answering/reformulation/generation/impl/OneShotSQLGeneratorEngine.java +++ b/engine/reformulation/sql/src/main/java/it/unibz/inf/ontop/answering/reformulation/generation/impl/OneShotSQLGeneratorEngine.java @@ -1150,24 +1150,6 @@ public class OneShotSQLGeneratorEngine { String literal = getSQLString(function.getTerm(0), index, false); return sqladapter.dateTZ(literal); } - if (functionSymbol == ExpressionOperation.COUNT) { - if (function.getTerm(0).toString().equals("*")) { - return "COUNT(*)"; - } - String columnName = getSQLString(function.getTerm(0), index, false); - //havingCond = true; - return "COUNT(" + columnName + ")"; - } - if (functionSymbol == ExpressionOperation.AVG) { - String columnName = getSQLString(function.getTerm(0), index, false); - //havingCond = true; - return "AVG(" + columnName + ")"; - } - if (functionSymbol == ExpressionOperation.SUM) { - String columnName = getSQLString(function.getTerm(0), index, false); - //havingCond = true; - return "SUM(" + columnName + ")"; - } /* * New approach
Aggregation function symbols removed from ExpressionOperation.
ontop_ontop
train
9fd9c7a51fb37c0ebf5d5f0f69ca58832c775ec0
diff --git a/ocrmypdf/hocrtransform.py b/ocrmypdf/hocrtransform.py index <HASH>..<HASH> 100755 --- a/ocrmypdf/hocrtransform.py +++ b/ocrmypdf/hocrtransform.py @@ -196,14 +196,16 @@ class HocrTransform(): if len(elemtxt) == 0: continue + pxl_coords = self.element_coordinates(elem) + pt = self.pt_from_pixel(pxl_coords) + # if the advanced option `--interword-spaces` is true, append a space # to the end of each text element to allow simpler PDF viewers such # as PDF.js to better recognize words in search and copy and paste if interwordSpaces: elemtxt += ' ' - - pxl_coords = self.element_coordinates(elem) - pt = self.pt_from_pixel(pxl_coords) + pt = Rect._make((pt.x1, pt.y1, + pt.x2 + pdf.stringWidth(' ', fontname, pt.y2 - pt.y1), pt.y2)) # draw the bbox border if showBoundingboxes:
Scale BoundingBox and Text elements to account for additional space. Here we are manually scaling the pt width used for the BoundingBox and the Text element when manually adding whitespace to account for limitations of the PDF.js viewer. This fixes an initial regression noticed when selecting text elements in Chrome and PDFium. The width of the Text element and BoundBox had not been adjusted for the additional whitespace so the highlighting was offset slightly.
jbarlow83_OCRmyPDF
train
c616fdc94f38b76ebfd46b867b754b8d08805de3
diff --git a/can/interfaces/socketcan/socketcan_ctypes.py b/can/interfaces/socketcan/socketcan_ctypes.py index <HASH>..<HASH> 100644 --- a/can/interfaces/socketcan/socketcan_ctypes.py +++ b/can/interfaces/socketcan/socketcan_ctypes.py @@ -60,6 +60,10 @@ class SocketcanCtypes_Bus(BusABC): self.set_filters(kwargs['can_filters']) error = bindSocket(self.socket, channel) + if error < 0: + m = u'bindSocket failed for channel {} with error {}'.format( + channel, error) + raise can.CanError(m) if receive_own_messages: error1 = recv_own_msgs(self.socket) @@ -257,7 +261,10 @@ def bindSocket(socketID, channel_name): ifr.ifr_name = channel_name.encode('ascii') log.debug('calling ioctl SIOCGIFINDEX') # ifr.ifr_ifindex gets filled with that device's index - libc.ioctl(socketID, SIOCGIFINDEX, ctypes.byref(ifr)) + ret = libc.ioctl(socketID, SIOCGIFINDEX, ctypes.byref(ifr)) + if ret < 0: + m = u'Failure while getting "{}" interface index.'.format(channel_name) + raise can.CanError(m) log.info('ifr.ifr_ifindex: %d', ifr.ifr_ifindex) # select the CAN interface and bind the socket to it
[socketcan_ctypes] Raise CanError when socket binding fails
hardbyte_python-can
train
a5edea532c39144d430ac487baaed5a99aac020c
diff --git a/test/haml.js b/test/haml.js index <HASH>..<HASH> 100644 --- a/test/haml.js +++ b/test/haml.js @@ -1,3 +1,5 @@ +'use strict'; + const assert = require('assert'); const parse = require('@emmetio/abbreviation'); const Profile = require('@emmetio/output-profile'); diff --git a/test/html.js b/test/html.js index <HASH>..<HASH> 100644 --- a/test/html.js +++ b/test/html.js @@ -1,3 +1,5 @@ +'use strict'; + const assert = require('assert'); const parse = require('@emmetio/abbreviation'); const Profile = require('@emmetio/output-profile'); diff --git a/test/pug.js b/test/pug.js index <HASH>..<HASH> 100644 --- a/test/pug.js +++ b/test/pug.js @@ -1,3 +1,5 @@ +'use strict'; + const assert = require('assert'); const parse = require('@emmetio/abbreviation'); const Profile = require('@emmetio/output-profile'); diff --git a/test/slim.js b/test/slim.js index <HASH>..<HASH> 100644 --- a/test/slim.js +++ b/test/slim.js @@ -1,3 +1,5 @@ +'use strict'; + const assert = require('assert'); const parse = require('@emmetio/abbreviation'); const Profile = require('@emmetio/output-profile');
Fixed tests for Node < 6
emmetio_markup-formatters
train
33be42ff31d80f0a2cfd58bac69c55ca53f0a480
diff --git a/lxd/seccomp.go b/lxd/seccomp.go index <HASH>..<HASH> 100644 --- a/lxd/seccomp.go +++ b/lxd/seccomp.go @@ -58,6 +58,9 @@ struct seccomp_notify_proxy_msg { static int device_allowed(dev_t dev, mode_t mode) { + if ((dev == makedev(0, 0)) && (mode & S_IFCHR)) // whiteout + return 0; + if ((dev == makedev(5, 1)) && (mode & S_IFCHR)) // /dev/console return 0;
lxd/seccomp: Allow overlayfs whiteout
lxc_lxd
train
39f2f681e0356ae972e1ecae6a916d61094df88a
diff --git a/kconfiglib.py b/kconfiglib.py index <HASH>..<HASH> 100644 --- a/kconfiglib.py +++ b/kconfiglib.py @@ -451,8 +451,8 @@ class Config(object): if set_match: name, val = set_match.groups() - if val.startswith(('"', "'")): - if len(val) < 2 or val[-1] != val[0]: + if val[0] == '"': + if len(val) < 2 or val[-1] != '"': _parse_error(line, "malformed string literal", line_feeder.filename, line_feeder.linenr) # Strip quotes and remove escapings. The unescaping
Ignore '-style quotes in .config files. This is what the C implementation does, and it simplifies the code a bit.
ulfalizer_Kconfiglib
train
2e19ab3cc051f439592ce41fb80f859fa87c1d6c
diff --git a/spec/orm_adapter/example_app_shared.rb b/spec/orm_adapter/example_app_shared.rb index <HASH>..<HASH> 100644 --- a/spec/orm_adapter/example_app_shared.rb +++ b/spec/orm_adapter/example_app_shared.rb @@ -3,7 +3,7 @@ # # Then you can execute this shared spec as follows: # -# it_should_behave_like "execute app with orm_adapter" do +# it_should_behave_like "example app with orm_adapter" do # let(:user_class) { User } # let(:note_class) { Note } #
Minor comment change, but confused me when I saw it
ianwhite_orm_adapter
train
71a97d008f0bcb18bfb382e172215a608238d02d
diff --git a/server/index.js b/server/index.js index <HASH>..<HASH> 100644 --- a/server/index.js +++ b/server/index.js @@ -10,12 +10,12 @@ var corsHeaders = require('hapi-cors-headers') var hoodieServer = require('@hoodie/server').register var log = require('npmlog') var PouchDB = require('pouchdb-core') -var cloneDeep = require('lodash').cloneDeep +var _ = require('lodash') var registerPlugins = require('./plugins') function register (server, options, next) { - options = cloneDeep(options) + options = _.cloneDeep(options) if (!options.db) { options.db = {} }
style(server): require full lodash This is in accordance to `CODING_STYLE.md`.
hoodiehq_hoodie
train
5411867c89adcab5c35ea2cb773e2c4ca7f49e8d
diff --git a/server/helpers/launcher.js b/server/helpers/launcher.js index <HASH>..<HASH> 100644 --- a/server/helpers/launcher.js +++ b/server/helpers/launcher.js @@ -69,5 +69,5 @@ switch (process.argv[2]) { break; default: - console.log('Usage: [-f|start|stop|restart|status|reconfig|build [-c <config file>] [-p <pid file>]]'); + console.log('Usage: [-f|start|stop|restart|status|reconfig|build [-v] [-c <config file>] [-p <pid file>]]'); }
Added -v verbose flag into available commands list
prawnsalad_KiwiIRC
train
3730c4d3da8bbe8673694906616a4978e3dcb839
diff --git a/bam_test.go b/bam_test.go index <HASH>..<HASH> 100644 --- a/bam_test.go +++ b/bam_test.go @@ -187,7 +187,10 @@ func BenchmarkRoundtrip(b *testing.B) { if err != nil { break } - bw.Write(r) + err = bw.Write(r) + if err != nil { + b.Fatalf("Write failed: %v", err) + } } f.Close() } diff --git a/bgzf/bgzf.go b/bgzf/bgzf.go index <HASH>..<HASH> 100644 --- a/bgzf/bgzf.go +++ b/bgzf/bgzf.go @@ -284,7 +284,7 @@ func (bg *Writer) Next() (int, error) { if bg.closed { return 0, ErrClosed } - if err := bg.errState(); err != nil { + if err := bg.Err(); err != nil { return 0, err } @@ -298,14 +298,14 @@ func (bg *Writer) Write(b []byte) (int, error) { if bg.closed { return 0, ErrClosed } - err := bg.errState() + err := bg.Err() if err != nil { return 0, err } wk := <-bg.active var n int - for ; len(b) > 0 && err == nil; err = bg.errState() { + for ; len(b) > 0 && err == nil; err = bg.Err() { var _n int if wk.next == 0 || wk.next+len(b) <= len(wk.block) { _n = copy(wk.block[wk.next:], b) @@ -314,8 +314,8 @@ func (bg *Writer) Write(b []byte) (int, error) { } if wk.next == len(wk.block) || _n == 0 { - bg.queue <- wk n += wk.buf.Len() + bg.queue <- wk bg.qwg.Add(1) go wk.writeBlock() wk = <-bg.active @@ -323,14 +323,14 @@ func (bg *Writer) Write(b []byte) (int, error) { } bg.active <- wk - return n, bg.errState() + return n, bg.Err() } func (bg *Writer) Flush() error { if bg.closed { return ErrClosed } - if err := bg.errState(); err != nil { + if err := bg.Err(); err != nil { return err } @@ -344,18 +344,18 @@ func (bg *Writer) Flush() error { bg.qwg.Add(1) go wk.writeBlock() - return bg.errState() + return bg.Err() } func (bg *Writer) Wait() error { - if err := bg.errState(); err != nil { + if err := bg.Err(); err != nil { return err } bg.qwg.Wait() - return bg.errState() + return bg.Err() } -func (bg *Writer) errState() error { +func (bg *Writer) Err() error { bg.m.Lock() defer bg.m.Unlock() return bg.err diff --git a/writer.go b/writer.go index <HASH>..<HASH> 100644 --- a/writer.go +++ b/writer.go @@ -45,7 +45,7 @@ func NewWriterLevel(w io.Writer, h *Header, level, wc int) (*Writer, error) { func (bw *Writer) Write(r *Record) error { _ = r.marshal(&bw.rec) bw.rec.writeTo(bw.bg) - return nil + return bw.bg.Err() } func (bw *Writer) Close() error {
Expose bgzf Writer error state This allows us to return an error with the bam Writer without blocking.
biogo_hts
train
56afabd517c37398a9e8d79b8c4b724bdb222a75
diff --git a/kerncraft/cacheprediction.py b/kerncraft/cacheprediction.py index <HASH>..<HASH> 100755 --- a/kerncraft/cacheprediction.py +++ b/kerncraft/cacheprediction.py @@ -255,19 +255,13 @@ class CacheSimulationPredictor(CachePredictor): max_cache_size = max(map(lambda c: c.size(), csim.levels(with_mem=False))) max_array_size = max(self.kernel.array_sizes(in_bytes=True, subs_consts=True).values()) - offsets = [] - if max_array_size < max_cache_size: - # Full caching possible, go through all itreration before actual initialization - offsets = list(self.kernel.compile_global_offsets( - iteration=range(0, self.kernel.iteration_length()))) - # Regular Initialization warmup_indices = { symbol_pos_int(l['index']): ((l['stop']-l['start'])//l['increment'])//3 for l in self.kernel.get_loop_stack(subs_consts=True)} warmup_iteration_count = self.kernel.indices_to_global_iterator(warmup_indices) # Make sure we are not handeling gigabytes of data, but 1.5x the maximum cache size - while warmup_iteration_count*element_size > max_cache_size*1.5: + while warmup_iteration_count * element_size > max_cache_size*1.5: # Decreasing indices (starting from outer), until total size is small enough for l in self.kernel.get_loop_stack(): index = symbol_pos_int(l['index']) @@ -284,6 +278,12 @@ class CacheSimulationPredictor(CachePredictor): break warmup_iteration_count = self.kernel.indices_to_global_iterator(warmup_indices) + offsets = [] + if warmup_iteration_count*element_size < max_cache_size or max_array_size < max_cache_size: + # Full caching possible, go through all itreration before actual initialization + offsets = list(self.kernel.compile_global_offsets( + iteration=range(0, self.kernel.iteration_length()))) + # Align iteration count with cachelines # do this by aligning either writes (preferred) or reads # Assumption: writes (and reads) increase linearly diff --git a/kerncraft/kernel.py b/kerncraft/kernel.py index <HASH>..<HASH> 100755 --- a/kerncraft/kernel.py +++ b/kerncraft/kernel.py @@ -443,8 +443,14 @@ class Kernel(object): Inverse of global_iterator_to_indices(). """ - global_iterator = self.subs_consts(self.global_iterator()) - return global_iterator.subs(indices) + global_iterator = self.subs_consts(self.global_iterator().subs(indices)) + return global_iterator + + def max_global_iteration(self): + """Return global iterator with last iteration number""" + return self.indices_to_global_iterator({ + symbol_pos_int(var_name): end-1 for var_name, start, end, incr in self._loop_stack + }) def compile_global_offsets(self, iteration=0, spacing=0): """
another go at improving warm up iteration selection
RRZE-HPC_kerncraft
train
0781b33d503cd0f5443b9faaf2e53b547d181e7a
diff --git a/test/middleware_test.rb b/test/middleware_test.rb index <HASH>..<HASH> 100644 --- a/test/middleware_test.rb +++ b/test/middleware_test.rb @@ -18,7 +18,9 @@ class MiddlewareTest < Test::Unit::TestCase :root => '/some/root/path', :engine => Fewer::Engines::Css, :mount => '/css' - run lambda{|env| [200, {'Content-Type'=>'text/html'},'Hello World']} + run lambda { |env| + [200, { 'Content-Type' => 'text/html' }, ['Hello World']] + } end end
Rack expects to be able to call each on the body.
benpickles_fewer
train
d6370ba5f5d528fb2041c6a412721badd3fc8740
diff --git a/modules/server/src/main/java/org/jboss/wsf/stack/cxf/resolver/WebAppResolver.java b/modules/server/src/main/java/org/jboss/wsf/stack/cxf/resolver/WebAppResolver.java index <HASH>..<HASH> 100644 --- a/modules/server/src/main/java/org/jboss/wsf/stack/cxf/resolver/WebAppResolver.java +++ b/modules/server/src/main/java/org/jboss/wsf/stack/cxf/resolver/WebAppResolver.java @@ -23,6 +23,7 @@ package org.jboss.wsf.stack.cxf.resolver; import org.jboss.wsf.spi.management.EndpointResolver; import org.jboss.wsf.spi.deployment.Endpoint; +import org.jboss.wsf.spi.deployment.EndpointState; import javax.management.ObjectName; import java.util.Iterator; @@ -54,13 +55,15 @@ public class WebAppResolver implements EndpointResolver while(endpoints.hasNext()) { Endpoint auxEndpoint = endpoints.next(); - ObjectName sepId = auxEndpoint.getName(); - String propContext = sepId.getKeyProperty(Endpoint.SEPID_PROPERTY_CONTEXT); - String propEndpoint = sepId.getKeyProperty(Endpoint.SEPID_PROPERTY_ENDPOINT); - if (servletName.equals(propEndpoint) && contextPath.equals(propContext)) - { - endpoint = auxEndpoint; - break; + if (EndpointState.STARTED.equals(auxEndpoint.getState())) { + ObjectName sepId = auxEndpoint.getName(); + String propContext = sepId.getKeyProperty(Endpoint.SEPID_PROPERTY_CONTEXT); + String propEndpoint = sepId.getKeyProperty(Endpoint.SEPID_PROPERTY_ENDPOINT); + if (servletName.equals(propEndpoint) && contextPath.equals(propContext)) + { + endpoint = auxEndpoint; + break; + } } }
i[JBWS-<I>] Fixing EndpointResolver impl to check endpoint state
jbossws_jbossws-cxf
train
7e38db0ce5c3d5db87b8739de5d1473bba3c5714
diff --git a/src/Helper/WsHelper.php b/src/Helper/WsHelper.php index <HASH>..<HASH> 100644 --- a/src/Helper/WsHelper.php +++ b/src/Helper/WsHelper.php @@ -21,6 +21,7 @@ class WsHelper public const OPCODE_BINARY = 0x02; public const OPCODE_CLOSE = 0x08; public const OPCODE_PING = 0x09; + public const OPCODE_PONG = 0x10; /** * Generate WebSocket sign.(for server) diff --git a/src/WebSocketServer.php b/src/WebSocketServer.php index <HASH>..<HASH> 100644 --- a/src/WebSocketServer.php +++ b/src/WebSocketServer.php @@ -37,8 +37,8 @@ class WebSocketServer extends Server /** * Send data to client by frame object. - * * NOTICE: require swoole version >= 4.2.0 + * * @param Frame $frame * @return bool */
remove load Functions.php file from composer.json
swoft-cloud_swoft-websocket-server
train
b8bef524bcfd1ee5d0e134a574360f54f209f6e4
diff --git a/lib/omnibus/software.rb b/lib/omnibus/software.rb index <HASH>..<HASH> 100644 --- a/lib/omnibus/software.rb +++ b/lib/omnibus/software.rb @@ -353,6 +353,16 @@ module Omnibus expose :relative_path # + # The path where the extracted software lives. + # + # @return [String] + # + def project_dir + @project_dir ||= File.join(Config.source_dir, relative_path) + end + expose :project_dir + + # # The path where this software is installed on disk. # # @deprecated Use {#install_path} instead @@ -529,26 +539,7 @@ module Omnibus end # - # @!endgroup - # -------------------------------------------------- - - # - # Retieve the {#default_version} of the software. - # - # @deprecated Use {#default_version} instead. - # - # @return [String] - # - def given_version - log.deprecated(log_key) do - 'Software#given_version. Please use #default_version instead.' - end - - default_version - end - - # - # Retrieves the repo-level and project-level overrides for the software. + # The repo-level and project-level overrides for the software. # # @return [Hash] # @@ -561,18 +552,40 @@ module Omnibus @overrides[:version] = @repo_overrides[name] end end + @overrides end - # Was this software version overridden externally, relative to the + # + # Determine if this software version overridden externally, relative to the # version declared within the software DSL file? # - # @return [Boolean] + # @return [true, false] + # def overridden? - # note: using instance variables to bypass accessors that enforce overrides + # NOTE: using instance variables to bypass accessors that enforce overrides @overrides.key?(:version) && (@overrides[:version] != @version) end + # + # @!endgroup + # -------------------------------------------------- + + # + # Retieve the {#default_version} of the software. + # + # @deprecated Use {#default_version} instead. + # + # @return [String] + # + def given_version + log.deprecated(log_key) do + 'Software#given_version. Please use #default_version instead.' + end + + default_version + end + # @todo see comments on {Omnibus::Fetcher#without_caching_for} def version_guid Fetcher.for(self).version_guid @@ -641,14 +654,6 @@ module Omnibus "#{Config.cache_dir}/#{filename}" end - # @todo this would be simplified and clarified if @relative_path - # defaulted to @name... see the @todo tag for #relative_path - # @todo Move this up with the other *_dir methods for better - # logical grouping - def project_dir - @relative_path ? "#{Config.source_dir}/#{@relative_path}" : "#{Config.source_dir}/#{@name}" - end - # The name of the sentinel file that marks the most recent fetch # time of the software #
Make Software#project_dir a DSL method
chef_omnibus
train
34ab71b96c015563822a2701e7292b9432ecfe95
diff --git a/presto-main/src/main/java/com/facebook/presto/split/SplitManager.java b/presto-main/src/main/java/com/facebook/presto/split/SplitManager.java index <HASH>..<HASH> 100644 --- a/presto-main/src/main/java/com/facebook/presto/split/SplitManager.java +++ b/presto-main/src/main/java/com/facebook/presto/split/SplitManager.java @@ -30,6 +30,7 @@ import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -49,6 +50,7 @@ import static com.facebook.presto.util.IterableUtils.limit; import static com.facebook.presto.util.IterableUtils.shuffle; import static com.facebook.presto.util.RetryDriver.runWithRetryUnchecked; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.instanceOf; import static com.google.common.base.Predicates.or; @@ -226,13 +228,16 @@ public class SplitManager ImmutableList.Builder<PartitionInfo> builder = ImmutableList.builder(); for (PartitionInfo partition : partitions) { // translate assignments from column->value to symbol->value - Map<Symbol, String> assignments = new HashMap<>(); - for (Map.Entry<String, String> entry : partition.getKeyFields().entrySet()) { + // only bind partition keys that appear in the predicate + Map<String, String> relevantFields = Maps.filterKeys(partition.getKeyFields(), in(columnNameToSymbol.keySet())); + + ImmutableMap.Builder<Symbol, String> assignments = ImmutableMap.builder(); + for (Map.Entry<String, String> entry : relevantFields.entrySet()) { Symbol symbol = columnNameToSymbol.get(entry.getKey()); assignments.put(symbol, entry.getValue()); } - Expression optimized = new ExpressionOptimizer(assignments).optimize(predicate); + Expression optimized = new ExpressionOptimizer(assignments.build()).optimize(predicate); if (!optimized.equals(BooleanLiteral.FALSE_LITERAL) && !(optimized instanceof NullLiteral)) { builder.add(partition); }
Fix bug when partition key does not appear in predicate
prestodb_presto
train
63d98d468e59486da99721064f97373b722712d3
diff --git a/spec/models/alchemy/message_spec.rb b/spec/models/alchemy/message_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/alchemy/message_spec.rb +++ b/spec/models/alchemy/message_spec.rb @@ -2,54 +2,59 @@ require "rails_helper" -module Alchemy - Config.get(:mailer)["fields"].push("email_of_my_boss") - Config.get(:mailer)["validate_fields"].push("email_of_my_boss") +RSpec.describe "Alchemy::Message" do + let(:message) { Alchemy::Message.new } - describe Message do - let(:message) { Message.new } + describe ".config" do + it "should return the mailer config" do + expect(Alchemy::Message.config).to eq(Alchemy::Config.get(:mailer)) + end + end - describe ".config" do - it "should return the mailer config" do - expect(Config).to receive(:get).with(:mailer) - Message.config - end + it "has attributes writers and getters for all fields defined in mailer config" do + Alchemy::Config.get(:mailer)["fields"].each do |field| + expect(message).to respond_to(field) + expect(message).to respond_to("#{field}=") end + end - it "has attributes writers and getters for all fields defined in mailer config" do - Config.get(:mailer)["fields"].each do |field| - expect(message).to respond_to(field) - expect(message).to respond_to("#{field}=") + context "validation of" do + context "all fields defined in mailer config" do + it "adds errors on that fields" do + Alchemy::Config.get(:mailer)["validate_fields"].each do |field| + expect(message).to_not be_valid + expect(message.errors[field].size).to eq(1) + end end end - context "validation of" do - context "all fields defined in mailer config" do - it "adds errors on that fields" do - Config.get(:mailer)["validate_fields"].each do |field| - expect(message).to_not be_valid - expect(message.errors[field].size).to eq(1) - end - end + context "field containing email in its name" do + before do + stub_alchemy_config(:mailer, { + fields: %w[email_of_my_boss], + validate_fields: %w[email_of_my_boss], + }.with_indifferent_access) + Alchemy.send(:remove_const, :Message) + load Alchemy::Engine.root.join("app/models/alchemy/message.rb") end - context "field containing email in its name" do - context "when field has a value" do - before { message.email_of_my_boss = "wrong email format" } + context "when field has a value" do + let(:invalid_message) { Alchemy::Message.new } - it "adds error notice (is invalid) to the field" do - expect(message).to_not be_valid - expect(message.errors[:email_of_my_boss]).to include("is invalid") - end + before { invalid_message.email_of_my_boss = "wrong email format" } + + it "adds error notice (is invalid) to the field" do + expect(invalid_message).to_not be_valid + expect(invalid_message.errors[:email_of_my_boss]).to include("is invalid") end + end - context "when field is blank" do - before { message.email_of_my_boss = "" } + context "when field is blank" do + before { message.email_of_my_boss = "" } - it "adds error notice (can't be blank) to the field" do - expect(message).to_not be_valid - expect(message.errors[:email_of_my_boss]).to include("can't be blank") - end + it "adds error notice (can't be blank) to the field" do + expect(message).to_not be_valid + expect(message.errors[:email_of_my_boss]).to include("can't be blank") end end end
Refactor Message spec This spec needs to be adopted to latest Rails versions.
AlchemyCMS_alchemy_cms
train
a7981625bf69c317e49cac780a5dc9f221065d05
diff --git a/lib/core/jdl_application.js b/lib/core/jdl_application.js index <HASH>..<HASH> 100644 --- a/lib/core/jdl_application.js +++ b/lib/core/jdl_application.js @@ -41,7 +41,11 @@ module.exports = class JDLApplication { if (!optionName) { throw new Error('An option name has to be passed to get a value.'); } - return this.config.getOptionValue(optionName); + if (!this.config.hasOption(optionName)) { + return undefined; + } + const option = this.config.getOption(optionName); + return option.getValue(); } forEachOption(passedFunction) { diff --git a/lib/core/jdl_application_configuration.js b/lib/core/jdl_application_configuration.js index <HASH>..<HASH> 100644 --- a/lib/core/jdl_application_configuration.js +++ b/lib/core/jdl_application_configuration.js @@ -31,14 +31,14 @@ module.exports = class JDLApplicationConfiguration { return optionName in this.options; } - getOptionValue(optionName) { + getOption(optionName) { if (!optionName) { - throw new Error('An option name has to be passed to get a value.'); + throw new Error('An option name has to be passed to get the option.'); } if (!(optionName in this.options)) { return undefined; } - return this.options[optionName].getValue(); + return this.options[optionName]; } setOption(option) { diff --git a/test/spec/core/jdl_application_configuration.spec.js b/test/spec/core/jdl_application_configuration.spec.js index <HASH>..<HASH> 100644 --- a/test/spec/core/jdl_application_configuration.spec.js +++ b/test/spec/core/jdl_application_configuration.spec.js @@ -61,7 +61,7 @@ describe('JDLApplicationConfiguration', () => { }); }); }); - describe('getOptionValue', () => { + describe('getOption', () => { context('when not passing an option name', () => { let configuration; @@ -70,7 +70,7 @@ describe('JDLApplicationConfiguration', () => { }); it('should fail', () => { - expect(() => configuration.getOptionValue()).to.throw(/^An option name has to be passed to get a value\.$/); + expect(() => configuration.getOption()).to.throw(/^An option name has to be passed to get the option\.$/); }); }); context('when the configuration does not have the option', () => { @@ -81,7 +81,7 @@ describe('JDLApplicationConfiguration', () => { }); it('should return undefined', () => { - expect(configuration.getOptionValue(OptionNames.BASE_NAME)).to.be.undefined; + expect(configuration.getOption(OptionNames.BASE_NAME)).to.be.undefined; }); }); context('when the configuration has the option', () => { @@ -93,7 +93,9 @@ describe('JDLApplicationConfiguration', () => { }); it('should return its value', () => { - expect(configuration.getOptionValue(OptionNames.BASE_NAME)).to.equal('application'); + expect(configuration.getOption(OptionNames.BASE_NAME)).to.deep.equal( + new StringJDLApplicationConfigurationOption(OptionNames.BASE_NAME, 'application') + ); }); }); }); @@ -137,7 +139,7 @@ describe('JDLApplicationConfiguration', () => { }); it('should replace its value', () => { - expect(createdConfiguration.getOptionValue(OptionNames.BASE_NAME)).to.equal('application2'); + expect(createdConfiguration.getOption(OptionNames.BASE_NAME).getValue()).to.equal('application2'); }); }); });
Replaced the getOptionValue method by getOption in the JDLAppConfig Kept the getOptionValue in the JDLApp, and this class does the getValue call instead of the JDLAppConfig, that way the config doesn't handle values
jhipster_jhipster-core
train
c4c475d5f4ec40daa61f8274a3b54ff750ac3da5
diff --git a/src/create/cli.js b/src/create/cli.js index <HASH>..<HASH> 100755 --- a/src/create/cli.js +++ b/src/create/cli.js @@ -13,6 +13,10 @@ function flags(arc, raw, callback) { if (process.env.ARC_DANGERZONE) { console.log(chalk.grey(chalk.green.dim('✓'), `dangerzone: engaged\n`)) } + let local = process.argv[2] && process.argv[2] === '--local' || process.argv[2] === '-l' || process.argv[2] === 'local' + if (local) { + process.env.ARC_LOCAL = true + } callback(null, arc, raw, callback) } diff --git a/src/deploy/cli.js b/src/deploy/cli.js index <HASH>..<HASH> 100755 --- a/src/deploy/cli.js +++ b/src/deploy/cli.js @@ -6,14 +6,31 @@ var deployOne = require('./_deploy-one') var deployAll = require('./_deploy-all') var _progress = require('./_progress') +let flags = [ + 'production', + '--production', + '-p', + 'staging', + '--staging', + '-s' +] + init(function _init(err, arc) { + // npx deploy production (or --production, prod or -p) + let override = flags.includes(process.argv[2]) + if (override) { + let prod = process.argv[2].replace(/-/g, '').startsWith('p') + process.env.ARC_DEPLOY = prod? 'production' : 'staging' + } + // deploy to staging by default let env = (process.env.ARC_DEPLOY === 'production') ? 'production' : 'staging' let start = Date.now() - let isAll = process.argv.length === 2 + let isAll = process.argv.length === 2 || (process.argv.length === 3 && override) + if (process.env.PARALLEL_DEPLOYS_PER_SECOND) { console.log(chalk.grey(chalk.green.dim('✓'), `Parallel deploys per second: ${process.env.PARALLEL_DEPLOYS_PER_SECOND}\n`)) @@ -32,7 +49,7 @@ init(function _init(err, arc) { } else { // otherwise deploy whatever the last arg was (a src/path/to/lambda or public) - var pathToCode = process.argv[2] + var pathToCode = override? process.argv[3] : process.argv[2] var name = chalk.green.dim(`Deploying ${pathToCode}`) var total = 7 // magic number of steps in src var progress = _progress({name, total}) diff --git a/src/sandbox/env/_copy-arc.js b/src/sandbox/env/_copy-arc.js index <HASH>..<HASH> 100644 --- a/src/sandbox/env/_copy-arc.js +++ b/src/sandbox/env/_copy-arc.js @@ -44,6 +44,8 @@ module.exports = function _copyArc(callback) { } }) - console.log(chalk.dim(chalk.green.dim('✓'), '.arc copied to lambda node_modules/@architect/shared/.arc')) + let g = chalk.green.dim + let d = chalk.grey + console.log(g('✓'), d('.arc copied to lambda node_modules/@architect/shared/.arc')) callback() } diff --git a/src/sandbox/start.js b/src/sandbox/start.js index <HASH>..<HASH> 100644 --- a/src/sandbox/start.js +++ b/src/sandbox/start.js @@ -40,7 +40,7 @@ module.exports = function start(callback) { function _http(callback) { // vanilla af http server that mounts routes defined by .arc http.start(function() { - let start = chalk.grey('\n', chalk.green.dim('✓'), 'Started HTTP "server" @ ') + let start = chalk.grey('\n', 'Started HTTP "server" @ ') let end = chalk.cyan.underline(`http://localhost:${process.env.PORT}`) console.log(`${start} ${end}`) callback()
adds npx create local|--local|-l and npx deploy staging|production with likewise unix-y shortcut flags
architect_architect
train
1a09297986f33583b7619674e08152e6ea6370f8
diff --git a/lib/Agent.php b/lib/Agent.php index <HASH>..<HASH> 100644 --- a/lib/Agent.php +++ b/lib/Agent.php @@ -244,7 +244,7 @@ class Agent { $valid_metric = preg_match("/^([\d\w\-_]+\.)*[\d\w\-_]+$/i", $metric); $this->log->debug("valid_metric: $valid_metric"); - $valid_value = preg_match("/^-?\d+(\.\d+)?(e-\d+)?$/", print_r($value, TRUE)); + $valid_value = preg_match("/^-?\d+(\.\d+)?((e|E)-\d+)?$/", print_r($value, TRUE)); $this->log->debug("valid_value: $valid_value"); if($valid_metric && $valid_value) diff --git a/test/AgentTest.php b/test/AgentTest.php index <HASH>..<HASH> 100644 --- a/test/AgentTest.php +++ b/test/AgentTest.php @@ -161,18 +161,18 @@ class AgentTest extends \PHPUnit_Framework_TestCase { $I = $this->factoryAgent(); $I->setEnabled(FALSE); - $this->assertEquals(null, $I->increment("test")); - $this->assertEquals(null, $I->gauge("test", 1)); - $this->assertEquals(null, $I->notice("test")); + $this->assertEquals(null, $I->increment("test.disabled.increment")); + $this->assertEquals(null, $I->gauge("test.disabled.gauge", 1)); + $this->assertEquals(null, $I->notice("test disabled notice")); } public function testTimeAndTimeMsReturnBlockResultIfDisabled() { $I = $this->factoryAgent(); $I->setEnabled(FALSE); - $ret = $I->time("test", function() {return "time result";}); + $ret = $I->time("test.disabled.time", function() {return "time result";}); $this->assertEquals("time result", $ret); - $ret = $I->timeMs("test", function() {return "timeMs result";}); + $ret = $I->timeMs("test.disabled.timeMs", function() {return "timeMs result";}); $this->assertEquals("timeMs result", $ret); } @@ -319,6 +319,30 @@ class AgentTest extends \PHPUnit_Framework_TestCase $this->assertRegExp($expectedData, file_get_contents("test/server_commands_received")); } + public function testSendsIncrementCallsCorrectlyWithScientificNotation() + { + $I = $this->factoryAgent(); + $expectedData = + "/" . self::HELLO_REGEX . + "authenticate test\n" . + "increment php.increment 1.0E-11 [0-9]+ 1\n" . + "increment php.increment 1.2345E-5 [0-9]+ 1\n" . + "increment php.increment 0.3 [0-9]+ 1\n" . + "increment php.increment 4.0E-1 [0-9]+ 1\n/"; + + $ret = $I->increment('php.increment', 0.00000000001); + $this->assertEquals(0.00000000001, $ret); + $ret = $I->increment('php.increment', 12345.0E-9); + $this->assertEquals(12345.0E-9, $ret); + $ret = $I->increment('php.increment', 3.0E-1); + $this->assertEquals(3.0E-1, $ret); + $ret = $I->increment('php.increment', "4.0E-1"); + $this->assertEquals("4.0E-1", $ret); + sleep(2); + + $this->assertRegExp($expectedData, file_get_contents("test/server_commands_received")); + } + public function testSendsGaugeCallsCorrectly() { $I = $this->factoryAgent();
Fixed issue with PHP's scientific notation not matching ruby's, added test, updated some test metric names to make warnings more obvious.
Instrumental_instrumental_agent-php
train
a292be09ab6f6dcfb19ffccedb25e86205437889
diff --git a/src/main/java/org/primefaces/component/treetable/TreeTableRenderer.java b/src/main/java/org/primefaces/component/treetable/TreeTableRenderer.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/primefaces/component/treetable/TreeTableRenderer.java +++ b/src/main/java/org/primefaces/component/treetable/TreeTableRenderer.java @@ -264,7 +264,7 @@ public class TreeTableRenderer extends DataRenderer { boolean hasPaginator = tt.isPaginator(); if (!(root instanceof TreeNode)) { - throw new FacesException("treeTable's value must be an instance of org.primefaces.model.TreeNode"); + throw new FacesException("treeTable's value must be an instance of " + TreeNode.class.getName()); } if (hasPaginator) {
Fix #<I> - dynamically get the full-qualified name of TreeNode
primefaces_primefaces
train
00521d65d72fe66fa959c80faccd0a629672d445
diff --git a/tx-info.js b/tx-info.js index <HASH>..<HASH> 100644 --- a/tx-info.js +++ b/tx-info.js @@ -5,7 +5,7 @@ var TxData = require('./tx-data') var DATA_TYPES = TxData.types module.exports = function getTxInfo(tx, networkName, prefix) { - var txData = TxData.fromTx(tx, this.prefix) + var txData = TxData.fromTx(tx, prefix) if (!txData) return var addresses = {}
fix leftover 'this' from extraction from bitjoe-js
tradle_tx-data
train
df04e2e7a6d98dd6f1dbbf1cffd12e64d9d33d48
diff --git a/helper/schema/resource.go b/helper/schema/resource.go index <HASH>..<HASH> 100644 --- a/helper/schema/resource.go +++ b/helper/schema/resource.go @@ -155,6 +155,27 @@ type Resource struct { Timeouts *ResourceTimeout } +// ShimInstanceStateFromValue converts a cty.Value to a +// terraform.InstanceState. +func (r *Resource) ShimInstanceStateFromValue(state cty.Value) (*terraform.InstanceState, error) { + // Get the raw shimmed value. While this is correct, the set hashes don't + // match those from the Schema. + s := terraform.NewInstanceStateShimmedFromValue(state, r.SchemaVersion) + + // We now rebuild the state through the ResourceData, so that the set indexes + // match what helper/schema expects. + data, err := schemaMap(r.Schema).Data(s, nil) + if err != nil { + return nil, err + } + + s = data.State() + if s == nil { + s = &terraform.InstanceState{} + } + return s, nil +} + // See Resource documentation. type CreateFunc func(*ResourceData, interface{}) error @@ -550,8 +571,7 @@ func (r *Resource) upgradeState(s *terraform.InstanceState, meta interface{}) (* return nil, err } - s = InstanceStateFromStateValue(stateVal, r.SchemaVersion) - return s, nil + return r.ShimInstanceStateFromValue(stateVal) } // InternalValidate should be called to validate the structure diff --git a/helper/schema/shims.go b/helper/schema/shims.go index <HASH>..<HASH> 100644 --- a/helper/schema/shims.go +++ b/helper/schema/shims.go @@ -23,7 +23,7 @@ func DiffFromValues(prior, planned cty.Value, res *Resource) (*terraform.Instanc // only needs to be created for the apply operation, and any customizations // have already been done. func diffFromValues(prior, planned cty.Value, res *Resource, cust CustomizeDiffFunc) (*terraform.InstanceDiff, error) { - instanceState := InstanceStateFromStateValue(prior, res.SchemaVersion) + instanceState := terraform.NewInstanceStateShimmedFromValue(prior, res.SchemaVersion) configSchema := res.CoreConfigSchema() @@ -85,11 +85,3 @@ func JSONMapToStateValue(m map[string]interface{}, block *configschema.Block) (c func StateValueFromInstanceState(is *terraform.InstanceState, ty cty.Type) (cty.Value, error) { return is.AttrsAsObjectValue(ty) } - -// InstanceStateFromStateValue converts a cty.Value to a -// terraform.InstanceState. This function requires the schema version used by -// the provider, because the legacy providers used the private Meta data in the -// InstanceState to store the schema version. -func InstanceStateFromStateValue(state cty.Value, schemaVersion int) *terraform.InstanceState { - return terraform.NewInstanceStateShimmedFromValue(state, schemaVersion) -}
move InstanceState shim into schema.Resource This was the resource can rebuild the flatmapped state using the schema and ResourceData, providing us the the correct set key values.
hashicorp_terraform
train
3eeed4e4020cf1b4d6945a38e7020fd5045da66b
diff --git a/couchdb-audit/node.js b/couchdb-audit/node.js index <HASH>..<HASH> 100644 --- a/couchdb-audit/node.js +++ b/couchdb-audit/node.js @@ -18,10 +18,9 @@ module.exports = { * or a function to retrieve the name. * @api public */ - // withFelix: function(felix, felixAudit, name) { withFelix: function(felix, felixAudit, name) { if (arguments.length === 2) { - name = arguments[1]; + name = felixAudit; felixAudit = felix; } @@ -43,8 +42,8 @@ module.exports = { */ withNano: function(nano, dbName, auditDbName, designName, authorName) { if (arguments.length === 4) { - authorName = arguments[3]; - designName = arguments[2]; + authorName = designName; + designName = auditDbName; auditDbName = dbName; }
Removing commented out code, making reassignments clearer
medic_couchdb-audit
train
fad48dafe49fa69c9fe36cc688d805033afa165a
diff --git a/spec/factories.rb b/spec/factories.rb index <HASH>..<HASH> 100644 --- a/spec/factories.rb +++ b/spec/factories.rb @@ -118,9 +118,13 @@ FactoryGirl.define do end factory :none, :parent => :markdown do |m| - m.name "none" - m.description "None" - m.markup 'none' + name "none" + description "None" + markup 'none' + + after :stub do |filter| + TextFilter.stub(:find_by_name).with('') { nil } + end end factory :utf8article, :parent => :article do |u| diff --git a/spec/views/comments/html_sanitization_spec.rb b/spec/views/comments/html_sanitization_spec.rb index <HASH>..<HASH> 100644 --- a/spec/views/comments/html_sanitization_spec.rb +++ b/spec/views/comments/html_sanitization_spec.rb @@ -2,8 +2,8 @@ require 'spec_helper' shared_examples_for "CommentSanitization" do before do - @blog = FactoryGirl.create(:blog) - @article = mock_model(Article, :created_at => Time.now, :published_at => Time.now) + @blog = build_stubbed(:blog) + @article = build_stubbed(:article, :created_at => Time.now, :published_at => Time.now) Article.stub!(:find).and_return(@article) @blog.plugin_avatar = '' @blog.lang = 'en_US' @@ -22,6 +22,7 @@ shared_examples_for "CommentSanitization" do ['', 'markdown', 'textile', 'smartypants', 'markdown smartypants'].each do |value| it "Should sanitize content rendered with the #{value} textfilter" do @blog.comment_text_filter = value + build_stubbed(value.empty? ? 'none' : value) render :file => 'comments/show' rendered.should have_selector('.content')
Make sure text filters exist for comment clean up specs
publify_publify
train
90d758c1be7750bbba12654fa3985c944885eaea
diff --git a/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java b/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java index <HASH>..<HASH> 100644 --- a/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java +++ b/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java @@ -55,8 +55,6 @@ import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; -import static java.util.Collections.emptyList; -import static java.util.Collections.emptyMap; import static java.util.stream.Collectors.joining; /** @@ -122,7 +120,10 @@ public abstract class ProctorUtils { */ @Deprecated @SuppressWarnings("UnusedDeclaration") // TODO Remove? - public static void serializeTestDefinition(final Writer writer, final TestDefinition definition) throws IOException { + public static void serializeTestDefinition( + final Writer writer, + final TestDefinition definition + ) throws IOException { serializeObject(writer, definition); } @@ -420,15 +421,19 @@ public abstract class ProctorUtils { ) { final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder(); + final Set<String> testsToLoad = Sets.union(requiredTests.keySet(), dynamicTests); final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests(); - final Set<String> incompatibleTestNames = new HashSet<>(); - - for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) { - final String testName = entry.getKey(); + final Set<String> missingTests = new HashSet<>(); + final Set<String> incompatibleTests = new HashSet<>(); - if (requiredTests.containsKey(testName)) { - // required in specification + for (final String testName : testsToLoad) { + if (!definedTests.containsKey(testName)) { + // required by specification but missing in test matrix + resultBuilder.recordMissing(testName); + missingTests.add(testName); + } else if (requiredTests.containsKey(testName)) { + // required by specification try { verifyRequiredTest( testName, @@ -440,7 +445,7 @@ public abstract class ProctorUtils { ); } catch (final IncompatibleTestMatrixException e) { resultBuilder.recordError(testName, e); - incompatibleTestNames.add(testName); + incompatibleTests.add(testName); } } else if (dynamicTests.contains(testName)) { // resolved by dynamic filter @@ -454,16 +459,19 @@ public abstract class ProctorUtils { ); } catch (final IncompatibleTestMatrixException e) { resultBuilder.recordIncompatibleDynamicTest(testName, e); - incompatibleTestNames.add(testName); + incompatibleTests.add(testName); } } } - final Map<String, String> errorReasonsOfTestsWithInvalidDependency = + final Map<String, String> errorReasonsOfTestsByDependency = TestDependencies.validateDependenciesAndReturnReasons( - Maps.filterKeys(definedTests, key -> !incompatibleTestNames.contains(key))); + testsToLoad.stream() + .filter(testName -> !missingTests.contains(testName) && !incompatibleTests.contains(testName)) + .collect(Collectors.toMap(testName -> testName, definedTests::get)) + ); - errorReasonsOfTestsWithInvalidDependency.forEach((testName, errorReason) -> { + errorReasonsOfTestsByDependency.forEach((testName, errorReason) -> { final String message = "Invalid dependency field is detected: " + errorReason; if (requiredTests.containsKey(testName)) { resultBuilder.recordError(testName, new IncompatibleTestMatrixException(message)); @@ -472,8 +480,6 @@ public abstract class ProctorUtils { } }); - final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet()); - resultBuilder.recordAllMissing(missingTests); resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate()); return resultBuilder.build();
PROW-<I>: Optimize verify method for cases when #loaded test is small
indeedeng_proctor
train
a19d664dbaba1bd36b50fe9885a1531e2a825208
diff --git a/src/Fractal.php b/src/Fractal.php index <HASH>..<HASH> 100644 --- a/src/Fractal.php +++ b/src/Fractal.php @@ -243,17 +243,12 @@ class Fractal implements JsonSerializable /** * Specify the fieldsets to include in the response. * - * @param array|string $fieldsets array with key = resourceName (use NULL or empty - * string if you're not using a resource name) and value = fields to include + * @param array|string $fieldsets array with key = resourceName and value = fields to include * (array or comma separated string with field names) - * A string of field names can be used as a shortcut for ['' => $fields] * * @return $this */ public function parseFieldsets($fieldsets){ - if (is_string($fieldsets)) { - $fieldsets = ['' => $fieldsets]; - } foreach ($fieldsets as $key => $fields) { if (is_array($fields)) { $fieldsets[$key] = implode(',', $fields);
removed project-specific code that only worked with custom serializer
spatie_fractalistic
train
8d9a41af5569053313151dd72ce4cfe54b672713
diff --git a/python/ray/_private/runtime_env.py b/python/ray/_private/runtime_env.py index <HASH>..<HASH> 100644 --- a/python/ray/_private/runtime_env.py +++ b/python/ray/_private/runtime_env.py @@ -73,7 +73,7 @@ class RuntimeEnvDict: def __init__(self, runtime_env_json: dict): # Simple dictionary with all options validated. This will always # contain all supported keys; values will be set to None if - # unspecified. However, if all values are None this is set to {}. + # unspecified. However, if all values are None this is set to {}. self._dict = dict() if "working_dir" in runtime_env_json: @@ -119,11 +119,14 @@ class RuntimeEnvDict: raise NotImplementedError("The 'pip' field in runtime_env " "is not currently supported on " "Windows.") - if "conda" in runtime_env_json: + if ("conda" in runtime_env_json + and runtime_env_json["conda"] is not None): raise ValueError( "The 'pip' field and 'conda' field of " - "runtime_env cannot both be specified. To use " - "pip with conda, please only set the 'conda' " + "runtime_env cannot both be specified.\n" + f"specified pip field: {runtime_env_json['pip']}\n" + f"specified conda field: {runtime_env_json['conda']}\n" + "To use pip with conda, please only set the 'conda' " "field, and specify your pip dependencies " "within the conda YAML config dict: see " "https://conda.io/projects/conda/en/latest/" diff --git a/python/ray/_raylet.pyx b/python/ray/_raylet.pyx index <HASH>..<HASH> 100644 --- a/python/ray/_raylet.pyx +++ b/python/ray/_raylet.pyx @@ -1734,11 +1734,15 @@ cdef class CoreWorker: def get_current_runtime_env_dict(self): # This should never change, so we can safely cache it to avoid ser/de if self.current_runtime_env_dict is None: - self.current_runtime_env_dict = json.loads( - CCoreWorkerProcess.GetCoreWorker() - .GetWorkerContext() - .GetCurrentSerializedRuntimeEnv() - ) + if self.is_driver: + self.current_runtime_env_dict = \ + json.loads(self.get_job_config().serialized_runtime_env) + else: + self.current_runtime_env_dict = json.loads( + CCoreWorkerProcess.GetCoreWorker() + .GetWorkerContext() + .GetCurrentSerializedRuntimeEnv() + ) return self.current_runtime_env_dict def is_exiting(self): @@ -1798,30 +1802,28 @@ cdef class CoreWorker: return self.job_config def prepare_runtime_env(self, runtime_env_dict: dict) -> str: - """Update parent's runtime env with new env via a simple dict update. - - If the resulting runtime env is empty, fall back to the runtime env - set in the JobConfig. Returns the JSON-serialized runtime env. - """ + """Merge the given new runtime env with the current runtime env. - # Short-circuit in the common case. - if (runtime_env_dict == {} - and self.get_current_runtime_env_dict() == {}): - return self.get_job_config().serialized_runtime_env + If running in a driver, the current runtime env comes from the + JobConfig. Otherwise, we are running in a worker for an actor or + task, and the current runtime env comes from the current TaskSpec. + Args: + runtime_env_dict (dict): A runtime env for a child actor or task. + Returns: + The resulting merged JSON-serialized runtime env. + """ result_dict = copy.deepcopy(self.get_current_runtime_env_dict()) result_dict.update(runtime_env_dict) - # TODO(architkulkarni): remove once workers are cached by runtime env. + # NOTE(architkulkarni): This allows worker caching code in C++ to + # check if a runtime env is empty without deserializing it. if all(val is None for val in result_dict.values()): result_dict = {} - if result_dict == {}: - return self.get_job_config().serialized_runtime_env - else: - # TODO(architkulkarni): We should just use RuntimeEnvDict here - # so all the serialization and validation is done in one place - return json.dumps(result_dict, sort_keys=True) + # TODO(architkulkarni): We should just use RuntimeEnvDict here + # so all the serialization and validation is done in one place + return json.dumps(result_dict, sort_keys=True) cdef void async_callback(shared_ptr[CRayObject] obj, CObjectID object_ref, diff --git a/python/ray/tests/test_runtime_env_env_vars.py b/python/ray/tests/test_runtime_env_env_vars.py index <HASH>..<HASH> 100644 --- a/python/ray/tests/test_runtime_env_env_vars.py +++ b/python/ray/tests/test_runtime_env_env_vars.py @@ -236,7 +236,7 @@ def test_override_environment_variables_complex(shutdown_only, @pytest.mark.parametrize("use_runtime_env", [True, False]) def test_override_environment_variables_reuse(shutdown_only, use_runtime_env): - """Test that previously set env vars don't pollute newer calls.""" + """Test that new tasks don't incorrectly reuse previous environments.""" ray.init() env_var_name = "TEST123"
[Core] [runtime env] Merge actor/task's runtime env with JobConfig's runtime env (#<I>)
ray-project_ray
train
49edd3cf162e677ae856c1994b33ea72a186e4e7
diff --git a/skew/resources/__init__.py b/skew/resources/__init__.py index <HASH>..<HASH> 100644 --- a/skew/resources/__init__.py +++ b/skew/resources/__init__.py @@ -32,6 +32,7 @@ ResourceTypes = { 'aws.ec2.snapshot': 'aws.ec2.Snapshot', 'aws.ec2.volume': 'aws.ec2.Volume', 'aws.ec2.vpc': 'aws.ec2.Vpc', + 'aws.ec2.vpc-peering-connection': 'aws.ec2.VpcPeeringConnection', 'aws.ec2.subnet': 'aws.ec2.Subnet', 'aws.elb.loadbalancer': 'aws.elb.LoadBalancer', 'aws.iam.group': 'aws.iam.Group', diff --git a/skew/resources/aws/ec2.py b/skew/resources/aws/ec2.py index <HASH>..<HASH> 100644 --- a/skew/resources/aws/ec2.py +++ b/skew/resources/aws/ec2.py @@ -234,3 +234,19 @@ class NetworkAcl(AWSResource): name = 'NetworkAclId' date = None dimension = None + + +class VpcPeeringConnection(AWSResource): + + class Meta(object): + service = 'ec2' + type = 'vpc-peering-connection' + enum_spec = ('describe_vpc_peering_connection', + 'VpcPeeringConnection', None) + detail_spec = None + id = 'VpcPeeringConnectionId' + filter_name = 'VpcPeeringConnectionIds' + filter_type = 'list' + name = 'VpcPeeringConnectionId' + date = None + dimension = None
Adding support for VpcPeeringConnection resources.
scopely-devops_skew
train
f27256694ae69591015c90ccd150b2570d880768
diff --git a/src/Util/functions.php b/src/Util/functions.php index <HASH>..<HASH> 100644 --- a/src/Util/functions.php +++ b/src/Util/functions.php @@ -10,3 +10,14 @@ function every($items, callable $f) $f($item, $index); } } + +/** + * @param mixed $var + * @return string + */ +function typeof($var) +{ + return is_object($var) ? + get_class($var) : + gettype($var); +} diff --git a/tests/Unit/Suites/Util/FunctionsTest.php b/tests/Unit/Suites/Util/FunctionsTest.php index <HASH>..<HASH> 100644 --- a/tests/Unit/Suites/Util/FunctionsTest.php +++ b/tests/Unit/Suites/Util/FunctionsTest.php @@ -8,7 +8,7 @@ namespace LizardsAndPumpkins\Util; class FunctionsTest extends \PHPUnit_Framework_TestCase { private static $callbackArguments = []; - + /** * @param mixed $value * @param string|int $index @@ -18,25 +18,43 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase self::$callbackArguments[] = [$index, $value]; } + /** + * @return array[] + */ + private function getReceivedCallbackArguments() + { + return self::$callbackArguments; + } + protected function setUp() { self::$callbackArguments = []; } - public function testEveryItemIsPassedToTheCallback() + public function testEveryItemAndIndexIsPassedToTheCallback() { $sourceItems = [ new \stdClass(), new \stdClass(), ]; $receivedArguments = []; - every($sourceItems, function ($item, $key) use (&$receivedArguments) { - $receivedArguments[$key] = $item; + every($sourceItems, function ($item, $index) use (&$receivedArguments) { + $receivedArguments[$index] = $item; }); $this->assertSame($receivedArguments, $sourceItems); } - public function testEveryWorksWithTraversable() + public function testEveryWorksWithStringArrayIndexes() + { + $items = ['foo' => 'bar', 'baz' => 'qux']; + $receivedIndexes = []; + every($items, function ($item, $index) use (&$receivedIndexes) { + $receivedIndexes[] = $index; + }); + $this->assertSame(array_keys($items), $receivedIndexes); + } + + public function testEveryWorksWithTraversables() { $array = ['foo', 'bar', 'baz']; $items = new \ArrayIterator($array); @@ -47,28 +65,44 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase $this->assertSame($array, $receivedArguments); } - public function testEveryWorksWithStringArrayKeys() - { - $items = ['foo' => 'bar', 'baz' => 'qux']; - $receivedIndexes = []; - every($items, function ($item, $index) use (&$receivedIndexes) { - $receivedIndexes[] = $index; - }); - $this->assertSame(array_keys($items), $receivedIndexes); - } - public function testEveryWorksWithStringCallbacks() { $items = [111]; every($items, '\LizardsAndPumpkins\Util\callback_function'); - $this->assertSame([[0, 111]], self::$callbackArguments); + $this->assertSame([[0, 111]], $this->getReceivedCallbackArguments()); } public function testEveryWorksWithArrayCallbacks() { $items = [222]; every($items, [self::class, 'notifyCallback']); - $this->assertSame([[0, 222]], self::$callbackArguments); + $this->assertSame([[0, 222]], $this->getReceivedCallbackArguments()); + } + + /** + * @param mixed $value + * @param string $expected + * @dataProvider typeofDataProvider + */ + public function testTypeofReturnsExpectedStringRepresentationOfType($value, $expected) + { + $this->assertSame($expected, typeof($value)); + } + + /** + * @return array[] + */ + public function typeofDataProvider() + { + return [ + ['', 'string'], + [null, 'NULL'], + [1, 'integer'], + [.1, 'double'], + [[], 'array'], + [fopen(__FILE__, 'r'), 'resource'], + [$this, get_class($this)], + ]; } }
Issue #<I>: Add typeof() method as a better alternative to gettype()
lizards-and-pumpkins_catalog
train
8e3e179ee4d5661ee6d7641969f2b0e76867e903
diff --git a/src/Intervention/Image/Gd/Font.php b/src/Intervention/Image/Gd/Font.php index <HASH>..<HASH> 100644 --- a/src/Intervention/Image/Gd/Font.php +++ b/src/Intervention/Image/Gd/Font.php @@ -124,7 +124,7 @@ class Font extends \Intervention\Image\AbstractFont * * @return Array */ - protected function getBoxSize() + public function getBoxSize() { $box = array();
make getBoxSize() a public method
Intervention_image
train
d2c527f2fdccd91fb51949fc092fce2ff1cc418d
diff --git a/language/en_EN.interface.php b/language/en_EN.interface.php index <HASH>..<HASH> 100644 --- a/language/en_EN.interface.php +++ b/language/en_EN.interface.php @@ -342,6 +342,8 @@ return [ 'tr_meliscore_tool_platform_update_marketplace' => 'Allow updates from the marketplace', 'tr_meliscore_tool_platform_update_marketplace tooltip' => 'Check to allow updates from the marketplace or uncheck to disallow them', 'tr_meliscore_common_allow' => 'Allow', + 'tr_meliscore_tool_platform_invalid_platform_name' => 'The name of the platform can only contain letters and numbers, no spaces or special characters', + // Language Tool Translations 'tr_meliscore_tool_language' => 'Back-Office languages',
Missing enlish translation on platfrom validated added
melisplatform_melis-core
train
d0859bdbcce8fb939b5bf1e6f116fa5ec32cac4e
diff --git a/apiserver/controller/controller.go b/apiserver/controller/controller.go index <HASH>..<HASH> 100644 --- a/apiserver/controller/controller.go +++ b/apiserver/controller/controller.go @@ -20,7 +20,7 @@ import ( "github.com/juju/juju/apiserver/facade" "github.com/juju/juju/apiserver/params" "github.com/juju/juju/core/description" - "github.com/juju/juju/core/migration" + coremigration "github.com/juju/juju/core/migration" "github.com/juju/juju/state" "github.com/juju/juju/state/stateenvirons" ) @@ -387,47 +387,44 @@ func (c *ControllerAPI) initiateOneMigration(spec params.MigrationSpec) (string, return "", errors.Annotate(err, "unable to read model") } - // Get State for model. hostedState, err := c.state.ForModel(modelTag) if err != nil { return "", errors.Trace(err) } defer hostedState.Close() - // Start the migration. - targetInfo := spec.TargetInfo - - controllerTag, err := names.ParseModelTag(targetInfo.ControllerTag) + // Construct target info. + specTarget := spec.TargetInfo + controllerTag, err := names.ParseModelTag(specTarget.ControllerTag) if err != nil { return "", errors.Annotate(err, "controller tag") } - - authTag, err := names.ParseUserTag(targetInfo.AuthTag) + authTag, err := names.ParseUserTag(specTarget.AuthTag) if err != nil { return "", errors.Annotate(err, "auth tag") } - var mac *macaroon.Macaroon - if targetInfo.Macaroon != "" { + if specTarget.Macaroon != "" { mac = new(macaroon.Macaroon) - err := mac.UnmarshalJSON([]byte(targetInfo.Macaroon)) + err := mac.UnmarshalJSON([]byte(specTarget.Macaroon)) if err != nil { return "", errors.Annotate(err, "invalid macaroon") } } + targetInfo := coremigration.TargetInfo{ + ControllerTag: controllerTag, + Addrs: specTarget.Addrs, + CACert: specTarget.CACert, + AuthTag: authTag, + Password: specTarget.Password, + Macaroon: mac, + } - args := state.MigrationSpec{ + // Trigger the migration. + mig, err := hostedState.CreateMigration(state.MigrationSpec{ InitiatedBy: c.apiUser, - TargetInfo: migration.TargetInfo{ - ControllerTag: controllerTag, - Addrs: targetInfo.Addrs, - CACert: targetInfo.CACert, - AuthTag: authTag, - Password: targetInfo.Password, - Macaroon: mac, - }, - } - mig, err := hostedState.CreateMigration(args) + TargetInfo: targetInfo, + }) if err != nil { return "", errors.Trace(err) } diff --git a/apiserver/controller/controller_test.go b/apiserver/controller/controller_test.go index <HASH>..<HASH> 100644 --- a/apiserver/controller/controller_test.go +++ b/apiserver/controller/controller_test.go @@ -372,7 +372,7 @@ func (s *controllerSuite) TestInitiateMigration(c *gc.C) { } } -func (s *controllerSuite) TestInitiateMigrationValidationError(c *gc.C) { +func (s *controllerSuite) TestInitiateMigrationSpecError(c *gc.C) { // Create a hosted model to migrate. st := s.Factory.MakeModel(c, nil) defer st.Close()
apiserver/controller: Prepare for first prechecks Rearrange TargetInfo construction so it can be used for both the initial prechecks and the CreateMigration call.
juju_juju
train
5790971caa996ac46cb6987be05385707a9a4e50
diff --git a/dallinger/experiment_server/experiment_server.py b/dallinger/experiment_server/experiment_server.py index <HASH>..<HASH> 100644 --- a/dallinger/experiment_server/experiment_server.py +++ b/dallinger/experiment_server/experiment_server.py @@ -1326,20 +1326,23 @@ def check_for_duplicate_assignments(participant): def worker_complete(): """Complete worker.""" if not request.args.get('uniqueId'): - status = "bad request" - else: - participants = models.Participant.query.filter_by( - unique_id=request.args['uniqueId'], - ).all() - if not len(participants): - return error_response(error_type='UniqueId not found: {}'.format( - request.args['uniqueId'] - )) - participant = participants[0] - participant.end_time = datetime.now() - session.add(participant) - session.commit() - status = "success" + return error_response( + error_type="bad request", + error_text=u'uniqueId parameter is required' + ) + + participants = models.Participant.query.filter_by( + unique_id=request.args['uniqueId'], + ).all() + if not len(participants): + return error_response(error_type='UniqueId not found: {}'.format( + request.args['uniqueId'] + )) + participant = participants[0] + participant.end_time = datetime.now() + session.add(participant) + session.commit() + status = "success" if config.get('recruiter', 'mturk') == u'bots': # Trigger notification directly # Bot submissions skip all attention and bonus checks diff --git a/tests/test_experiment_server.py b/tests/test_experiment_server.py index <HASH>..<HASH> 100644 --- a/tests/test_experiment_server.py +++ b/tests/test_experiment_server.py @@ -5,6 +5,66 @@ from datetime import datetime from dallinger.config import get_config +@pytest.fixture +def app(db_session): + from dallinger.experiment_server import sockets + config = get_config() + if not config.ready: + config.load() + app = sockets.app + app.config['DEBUG'] = True + app.config['TESTING'] = True + client = app.test_client() + yield client + + +@pytest.mark.usefixtures('experiment_dir', 'active_config', 'db_session') +class TestWorkerComplete(object): + + def test_with_no_participant_id_returns_error(self, app): + resp = app.get('/worker_complete') + assert resp.status_code == 400 + assert 'uniqueId parameter is required' in resp.data + + def test_with_invalid_participant_id_returns_error(self, app): + resp = app.get('/worker_complete?uniqueId=nonsense') + assert resp.status_code == 400 + assert 'UniqueId not found: nonsense' in resp.data + + def test_with_valid_participant_id_returns_success(self, a, app): + participant = a.participant() + + resp = app.get('/worker_complete?uniqueId={}'.format( + participant.unique_id) + ) + assert resp.status_code == 200 + + def test_sets_end_time(self, a, app, db_session): + participant = a.participant() + app.get('/worker_complete?uniqueId={}'.format( + participant.unique_id) + ) + assert db_session.merge(participant).end_time is not None + + def test_records_notification_if_debug_mode(self, a, app, active_config): + from dallinger.models import Notification + active_config.extend({'mode': u'debug'}) + participant = a.participant() + app.get('/worker_complete?uniqueId={}'.format( + participant.unique_id) + ) + assert Notification.query.one().event_type == u'AssignmentSubmitted' + + def test_records_notification_if_bot_recruiter(self, a, app, active_config): + from dallinger.models import Notification + active_config.extend({'recruiter': u'bots'}) + participant = a.participant() + app.get('/worker_complete?uniqueId={}'.format( + participant.unique_id) + ) + assert Notification.query.one().event_type == u'BotAssignmentSubmitted' + + @pytest.mark.usefixtures('experiment_dir') class TestExperimentServer(object): worker_counter = 0
Tests and bug fix for /worker_complete route
Dallinger_Dallinger
train
a0ae56882866865da708fa0e5a662f7d87ea7bb8
diff --git a/lib/generamba/cli/template/template_list_command.rb b/lib/generamba/cli/template/template_list_command.rb index <HASH>..<HASH> 100644 --- a/lib/generamba/cli/template/template_list_command.rb +++ b/lib/generamba/cli/template/template_list_command.rb @@ -7,30 +7,11 @@ module Generamba::CLI desc 'list', 'Prints out the list of all templates available in the shared GitHub catalog' def list - does_rambafile_exist = Dir[RAMBAFILE_NAME].count > 0 - - if does_rambafile_exist - rambafile = YAML.load_file(RAMBAFILE_NAME) - catalogs = rambafile[CATALOGS_KEY] - end - - terminator = CatalogTerminator.new - terminator.remove_all_catalogs - downloader = CatalogDownloader.new - catalog_paths = [downloader.download_catalog(GENERAMBA_CATALOG_NAME, RAMBLER_CATALOG_REPO)] - - if catalogs != nil && catalogs.count > 0 - catalogs.each do |catalog_url| - catalog_name = catalog_url.split('://').last - catalog_name = catalog_name.gsub('/', '-'); - catalog_paths.push(downloader.download_catalog(catalog_name, catalog_url)) - end - end - catalog_template_list_helper = CatalogTemplateListHelper.new templates = [] + catalog_paths = downloader.update_all_catalogs_and_return_filepaths catalog_paths.each do |path| templates += catalog_template_list_helper.obtain_all_templates_from_a_catalog(path) templates = templates.uniq diff --git a/lib/generamba/cli/template/template_search_command.rb b/lib/generamba/cli/template/template_search_command.rb index <HASH>..<HASH> 100644 --- a/lib/generamba/cli/template/template_search_command.rb +++ b/lib/generamba/cli/template/template_search_command.rb @@ -8,10 +8,16 @@ module Generamba::CLI desc 'search [SEARCH_STRING]', 'Searches a template with a given name in the shared GitHub catalog' def search(term) downloader = CatalogDownloader.new - generamba_catalog_path = downloader.download_catalog(GENERAMBA_CATALOG_NAME, RAMBLER_CATALOG_REPO) - catalog_template_search_helper = CatalogTemplateSearchHelper.new - templates = catalog_template_search_helper.search_templates_in_a_catalog(generamba_catalog_path, term) + + catalog_paths = downloader.update_all_catalogs_and_return_filepaths + + templates = [] + catalog_paths.each do |path| + templates += catalog_template_search_helper.search_templates_in_a_catalog(path, term) + templates = templates.uniq + end + templates.map { |template_name| keywords = term.squeeze.strip.split(' ').compact.uniq matcher = Regexp.new('(' + keywords.join('|') + ')') diff --git a/lib/generamba/template/helpers/catalog_downloader.rb b/lib/generamba/template/helpers/catalog_downloader.rb index <HASH>..<HASH> 100644 --- a/lib/generamba/template/helpers/catalog_downloader.rb +++ b/lib/generamba/template/helpers/catalog_downloader.rb @@ -5,6 +5,33 @@ module Generamba # Provides the functionality to download template catalogs from the remote repository class CatalogDownloader + # Updates all of the template catalogs and returns their filepaths. + # If there is a Rambafile in the current directory, it also updates all of the catalogs specified there. + # + # @return [Array] An array of filepaths to downloaded catalogs + def update_all_catalogs_and_return_filepaths + does_rambafile_exist = Dir[RAMBAFILE_NAME].count > 0 + + if does_rambafile_exist + rambafile = YAML.load_file(RAMBAFILE_NAME) + catalogs = rambafile[CATALOGS_KEY] + end + + terminator = CatalogTerminator.new + terminator.remove_all_catalogs + + catalog_paths = [download_catalog(GENERAMBA_CATALOG_NAME, RAMBLER_CATALOG_REPO)] + + if catalogs != nil && catalogs.count > 0 + catalogs.each do |catalog_url| + catalog_name = catalog_url.split('://').last + catalog_name = catalog_name.gsub('/', '-'); + catalog_paths.push(download_catalog(catalog_name, catalog_url)) + end + end + return catalog_paths + end + # Clones a template catalog from a remote repository # # @param name [String] The name of the template catalog
Added the ability to search templates in multiple catalogs (#<I>)
strongself_Generamba
train
94a0c56442fb5b78996cca586488d2d9343115e3
diff --git a/src/CloudApi/Connector.php b/src/CloudApi/Connector.php index <HASH>..<HASH> 100644 --- a/src/CloudApi/Connector.php +++ b/src/CloudApi/Connector.php @@ -110,8 +110,12 @@ class Connector implements ConnectorInterface if (property_exists($object, '_embedded') && property_exists($object->_embedded, 'items')) { $return = $object->_embedded->items; } elseif (property_exists($object, 'error')) { - foreach ($object->message as $message) { - $output .= $message; + if (is_object($object->message)) { + foreach ($object->message as $message) { + $output .= $message; + } + } else { + $output = $object->message; } throw new \Exception($output); } else {
Caters to errors both in objects and out.
typhonius_acquia-php-sdk-v2
train
9ba22744a473c847d0ef2ef5529915dc12b48664
diff --git a/lib/components/resource-editing/resource-form/RadioButtons.js b/lib/components/resource-editing/resource-form/RadioButtons.js index <HASH>..<HASH> 100644 --- a/lib/components/resource-editing/resource-form/RadioButtons.js +++ b/lib/components/resource-editing/resource-form/RadioButtons.js @@ -16,11 +16,11 @@ var FormUtility = require('./FormUtilityMixin'); * @class RadioButton * @type {ReactComponent} * - * @prop {!String} fieldKey The key for the property on the object getting edited. - * @prop {String} label - * @prop {String} identifier - * @prop {String} labelAttribute - * @prop {Array} options Possible options that will become the radio-button. + * @prop {!String} fieldKey The key for the property on the object getting edited. + * @prop {String} label The label for entire component. Displayed above the radio buttons + * @prop {String} valueKey If the bound resource doesn't save data to `value` you can define your own value key here. + * @prop {String} labelAttribute The attribute on the bound resource to display as the option next to the radio button. + * @prop {Array} options Possible options that will become the radio-button. * * @memberOf FormComponents * @see {@link FormComponents} @@ -29,7 +29,7 @@ var RadioButton = React.createClass({ propTypes: { fieldKey: React.PropTypes.string.isRequired, label: React.PropTypes.string, - identifier: React.PropTypes.string, + valueKey: React.PropTypes.string, labelAttribute: React.PropTypes.string, helpText: React.PropTypes.string, options: React.PropTypes.array @@ -78,13 +78,15 @@ var RadioButton = React.createClass({ var index = event.target.dataset.index; // Find first match (like laravel's queryBuilder->first()) - var selectedOption = this.props.options[index]; + var selectedOption = this.props.options[index], + valueKey = this.props.valueKey || 'value'; this.setState({ - fieldValue: selectedOption.value + fieldValue: selectedOption[valueKey] }, function () { this.props.changeCallback(this.props.fieldKey, this.state.fieldValue, this); }); + }, /** @@ -98,24 +100,22 @@ var RadioButton = React.createClass({ var fieldValue = this.state.fieldValue || {}; return this.props.options.map(function (option, index) { + var value = this.props.valueKey ? option[this.props.valueKey] : option.value; + return ( <div key={index} className="radio radio-success"> <label> <input - type = "radio" - name = {option.name || ('option' + index)} - value = {option.value} - onChange = {this.handleChange} - data-index = {index} - checked = {_.isEqual(this.state.fieldValue, option.value)} - disabled = {this.props.disabled || false} /> - + type="radio" name={option.name || ('option' + index)} value={value} + onChange={this.handleChange} + data-index={index} + checked={_.isEqual(this.state.fieldValue, value)} /> <span className="circle"></span> <span className="check"></span> <div>{this.props.labelAttribute ? option[this.props.labelAttribute] : option.label}</div> </label> </div> - ); + ) }.bind(this)); },
Adding the ability to define a radio button's value key
MortarJS_Mortar-JS
train
7efdb916410059f40db338e544942c05583c01e6
diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java index <HASH>..<HASH> 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java @@ -86,6 +86,7 @@ import org.springframework.util.StringUtils; * @author Eddú Meléndez * @author Quinten De Swaef * @author Venil Noronha + * @author Aurélien Leboulanger */ @ConfigurationProperties(prefix = "server", ignoreUnknownFields = true) public class ServerProperties @@ -656,6 +657,19 @@ public class ServerProperties */ private Charset uriEncoding; + /** + * Maximum amount of connections accept and process. + * <p>Once the limit has been reached, + * the operating system may still accept connections based on the @link{acceptCount} setting.</p> + */ + private int maxConnections = 0; + + /** + * Maximum queue length for incoming connection requests when all possible request processing threads are in use. + * Any requests received when the queue is full will be refused. + */ + private int acceptCount = 0; + public int getMaxThreads() { return this.maxThreads; } @@ -748,6 +762,22 @@ public class ServerProperties this.uriEncoding = uriEncoding; } + public int getMaxConnections() { + return this.maxConnections; + } + + public void setMaxConnections(int maxConnections) { + this.maxConnections = maxConnections; + } + + public int getAcceptCount() { + return this.acceptCount; + } + + public void setAcceptCount(int acceptCount) { + this.acceptCount = acceptCount; + } + void customizeTomcat(ServerProperties serverProperties, TomcatEmbeddedServletContainerFactory factory) { if (getBasedir() != null) { @@ -782,6 +812,40 @@ public class ServerProperties if (this.redirectContextRoot != null) { customizeRedirectContextRoot(factory, this.redirectContextRoot); } + if (this.maxConnections > 0) { + customizeMaxConnections(factory); + } + if (this.acceptCount > 0) { + customizeAcceptCount(factory); + } + } + + private void customizeAcceptCount(TomcatEmbeddedServletContainerFactory factory) { + factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { + + @Override + public void customize(Connector connector) { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setBacklog(Tomcat.this.acceptCount); + } + } + }); + } + + private void customizeMaxConnections(TomcatEmbeddedServletContainerFactory factory) { + factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { + + @Override + public void customize(Connector connector) { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setMaxConnections(Tomcat.this.maxConnections); + } + } + }); } private void customizeConnectionTimeout( diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index <HASH>..<HASH> 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -325,6 +325,22 @@ public class ServerPropertiesTests { } @Test + public void testCustomizeTomcatAcceptCount() throws Exception { + Map<String, String> map = new HashMap<String, String>(); + map.put("server.tomcat.accept-count", "10"); + bindProperties(map); + assertThat(this.properties.getTomcat().getAcceptCount()).isEqualTo(10); + } + + @Test + public void testCustomizeTomcatMaxConnections() throws Exception { + Map<String, String> map = new HashMap<String, String>(); + map.put("server.tomcat.max-connections", "5"); + bindProperties(map); + assertThat(this.properties.getTomcat().getMaxConnections()).isEqualTo(5); + } + + @Test public void customizeTomcatDisplayName() throws Exception { Map<String, String> map = new HashMap<String, String>(); map.put("server.display-name", "MyBootApp");
Manage Tomcat queued connections Adding two tomcat server properties: - server.tomcat.accept-count - server.tomcat.max-connections Closes gh-<I>
spring-projects_spring-boot
train
343a8a3e0341986c955cdbe2518b913a39726ad0
diff --git a/django_th/management/commands/publish.py b/django_th/management/commands/publish.py index <HASH>..<HASH> 100644 --- a/django_th/management/commands/publish.py +++ b/django_th/management/commands/publish.py @@ -28,8 +28,8 @@ class Command(BaseCommand): connection.close() failed_tries = settings.DJANGO_TH.get('failed_tries', 10) trigger = TriggerService.objects.filter( - Q(provider_failed__gte=failed_tries) | - Q(consumer_failed__gte=failed_tries), + Q(provider_failed__lte=failed_tries) | + Q(consumer_failed__lte=failed_tries), status=True, user__is_active=True, provider__name__status=True, diff --git a/django_th/management/commands/read.py b/django_th/management/commands/read.py index <HASH>..<HASH> 100644 --- a/django_th/management/commands/read.py +++ b/django_th/management/commands/read.py @@ -28,8 +28,8 @@ class Command(BaseCommand): connection.close() failed_tries = settings.DJANGO_TH.get('failed_tries', 10) trigger = TriggerService.objects.filter( - Q(provider_failed__gte=failed_tries) | - Q(consumer_failed__gte=failed_tries), + Q(provider_failed__lte=failed_tries) | + Q(consumer_failed__lte=failed_tries), status=True, user__is_active=True, provider__name__status=True, diff --git a/django_th/tools.py b/django_th/tools.py index <HASH>..<HASH> 100644 --- a/django_th/tools.py +++ b/django_th/tools.py @@ -5,7 +5,7 @@ import datetime import time from django.conf import settings -from django.core.mail import send_mass_mail +from django.core.mail import send_mail, mail_admins """ @@ -89,10 +89,7 @@ def to_datetime(data): def warn_user_and_admin(consumer_provider, service): - from_mail = settings.ADMINS if len(settings.ADMINS) > 0 else '' - from_mail = settings.MANAGERS if len(settings.MANAGERS) > 0 else '' - if len(from_mail) == 0: - from_mail = settings.DEFAULT_FROM_EMAIL + from_mail = settings.DEFAULT_FROM_EMAIL if consumer_provider == 'provider': service_name = service.provider.name.name.split('Service')[1] @@ -100,20 +97,20 @@ def warn_user_and_admin(consumer_provider, service): service_name = service.consumer.name.name.split('Service')[1] title = 'Trigger "{}" disabled'.format(service.description) + body = 'The trigger "{}" has been disabled due to an issue with "{}". ' \ 'Try to renew it to refresh the token to try to fix the issue'. \ format(service.description, service_name) # for enduser - message1 = (title, - body, - from_mail, - [service.user.email]) - # for admin - - message2 = (title, + send_mail(title, + body, + from_mail, + [service.user.email], + fail_silently=False) + # for admins + body = 'The trigger "{}" has been disabled due to an issue with "{}". ' \ + 'User {}\'s trigger'.format(service.description, service_name, + service.user.email) + mail_admins(title, body, - from_mail, - [from_mail]) - # send the two mails - - send_mass_mail((message1, message2), fail_silently=False) + fail_silently=False)
fix #<I> Mistake in a test
push-things_django-th
train
d65cfc0c59701295dfddbad7152acec1a08e9940
diff --git a/tests/Unit/Suites/Product/Block/FilterNavigationBlockTest.php b/tests/Unit/Suites/Product/Block/FilterNavigationBlockTest.php index <HASH>..<HASH> 100644 --- a/tests/Unit/Suites/Product/Block/FilterNavigationBlockTest.php +++ b/tests/Unit/Suites/Product/Block/FilterNavigationBlockTest.php @@ -46,10 +46,11 @@ class FilterNavigationBlockTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->stubBlockRenderer = $this->getMock(BlockRenderer::class, [], [], '', false); + $blockName = 'foo'; $this->stubFilterCollection = $this->getMock(FilterNavigationFilterCollection::class, [], [], '', false); $stubDataObject = $this->stubFilterCollection; - $this->block = new FilterNavigationBlock($this->stubBlockRenderer, 'foo.phtml', 'foo', $stubDataObject); + $this->block = new FilterNavigationBlock($this->stubBlockRenderer, 'foo.phtml', $blockName, $stubDataObject); } public function testBlockClassIsExtended()
Issue #<I>: Refactor FilterNavigationBlockTest
lizards-and-pumpkins_catalog
train
a8ce290e9e3244a2c1df52eadf074dbbbe2deccb
diff --git a/test/specs/modules/Dropdown/Dropdown-test.js b/test/specs/modules/Dropdown/Dropdown-test.js index <HASH>..<HASH> 100644 --- a/test/specs/modules/Dropdown/Dropdown-test.js +++ b/test/specs/modules/Dropdown/Dropdown-test.js @@ -21,11 +21,11 @@ const wrapperMount = (node, opts) => { attachTo = document.createElement('div') document.body.appendChild(attachTo) - wrapper = global.mount(node, { ...opts, attachTo }) + wrapper = mount(node, { ...opts, attachTo }) return wrapper } -const wrapperShallow = (...args) => (wrapper = global.shallow(...args)) -const wrapperRender = (...args) => (wrapper = global.render(...args)) +const wrapperShallow = (...args) => (wrapper = shallow(...args)) +const wrapperRender = (...args) => (wrapper = render(...args)) // ---------------------------------------- // Options @@ -52,9 +52,6 @@ const dropdownMenuIsOpen = () => { menu.should.have.className('visible') } -options = getOptions() -defaultProps = { options } - describe('Dropdown Component', () => { beforeEach(() => { attachTo = undefined @@ -720,12 +717,15 @@ describe('Dropdown Component', () => { }) it('still allows moving selection after blur/focus', () => { + // open, first item is selected const search = wrapperMount(<Dropdown {...defaultProps} search />) .find('input.search') + .simulate('focus') + + domEvent.keyDown(document, { key: 'ArrowDown' }) + dropdownMenuIsOpen() - // open, first item is selected const items = wrapper - .simulate('click') .find('DropdownItem') items
test(Dropdown): fix search selection test
Semantic-Org_Semantic-UI-React
train
796e79c276063b137efb80de39d31a4e5ccf6cbf
diff --git a/test/integration/src/test/java/io/pravega/test/integration/ReadWriteTest.java b/test/integration/src/test/java/io/pravega/test/integration/ReadWriteTest.java index <HASH>..<HASH> 100644 --- a/test/integration/src/test/java/io/pravega/test/integration/ReadWriteTest.java +++ b/test/integration/src/test/java/io/pravega/test/integration/ReadWriteTest.java @@ -67,8 +67,8 @@ public class ReadWriteTest { private static final String STREAM_NAME = "testMultiReaderWriterStream" + RandomFactory.create().nextInt(Integer.MAX_VALUE); private static final int NUM_WRITERS = 20; private static final int NUM_READERS = 20; - private static final long TOTAL_NUM_EVENTS = 20000; - private static final int NUM_EVENTS_BY_WRITER = 1000; + private static final int NUM_EVENTS_BY_WRITER = 500; + private static final long TOTAL_NUM_EVENTS = NUM_WRITERS * NUM_EVENTS_BY_WRITER; private AtomicLong eventData; private AtomicLong eventReadCount; private AtomicBoolean stopReadFlag; @@ -242,7 +242,7 @@ public class ReadWriteTest { EventWriterConfig.builder().build()); for (int i = 0; i < NUM_EVENTS_BY_WRITER; i++) { long value = data.incrementAndGet(); - log.info("Writing event {}", value); + log.debug("Writing event {}", value); writer.writeEvent(String.valueOf(value), value); writer.flush(); } @@ -263,7 +263,7 @@ public class ReadWriteTest { ReaderConfig.builder().build()); while (!(exitFlag.get() && readCount.get() == writeCount.get())) { final Long longEvent = reader.readNextEvent(SECONDS.toMillis(2)).getEvent(); - log.info("Reading event {}", longEvent); + log.debug("Reading event {}", longEvent); if (longEvent != null) { //update if event read is not null. readResult.add(longEvent);
Issue <I>: Sporadic test failure in ReadWriteTest.readWriteTest (#<I>) Reduced the number of events written and read in the test, as well as do not log per-event messages.
pravega_pravega
train
8c49af9013808a44d124d4c6700906f94078b1f1
diff --git a/flusher.go b/flusher.go index <HASH>..<HASH> 100644 --- a/flusher.go +++ b/flusher.go @@ -41,6 +41,7 @@ func (s *Server) Flush(interval time.Duration, metricLimit int) { totalLocalSets int totalLocalTimers int ) + gatherStart := time.Now() for i, w := range s.Workers { s.logger.WithField("worker", i).Debug("Flushing") wm := w.Flush() @@ -56,6 +57,7 @@ func (s *Server) Flush(interval time.Duration, metricLimit int) { totalLocalSets += len(wm.localSets) totalLocalTimers += len(wm.localTimers) } + s.statsd.TimeInMilliseconds("flush.total_duration_ns", float64(time.Now().Sub(gatherStart).Nanoseconds()), []string{"part:gather"}, 1.0) totalLength := totalCounters + totalGauges + (totalTimers+totalHistograms)*(HistogramLocalLength+len(percentiles)) + // local-only histograms will be flushed with percentiles, so we intentionally @@ -64,6 +66,8 @@ func (s *Server) Flush(interval time.Duration, metricLimit int) { if s.ForwardAddr == "" { totalLength += totalSets } + + combineStart := time.Now() finalMetrics := make([]DDMetric, 0, totalLength) for _, wm := range tempMetrics { for _, c := range wm.counters { @@ -107,6 +111,7 @@ func (s *Server) Flush(interval time.Duration, metricLimit int) { finalMetrics[i].Hostname = s.Hostname finalMetrics[i].Tags = append(finalMetrics[i].Tags, s.Tags...) } + s.statsd.TimeInMilliseconds("flush.total_duration_ns", float64(time.Now().Sub(combineStart).Nanoseconds()), []string{"part:combine"}, 1.0) s.statsd.Count("worker.metrics_flushed_total", int64(totalCounters), []string{"metric_type:counter"}, 1.0) s.statsd.Count("worker.metrics_flushed_total", int64(totalGauges), []string{"metric_type:gauge"}, 1.0) @@ -156,7 +161,7 @@ func (s *Server) Flush(interval time.Duration, metricLimit int) { go s.flushPart(chunk, &wg) } wg.Wait() - s.statsd.TimeInMilliseconds("flush.total_duration_ns", float64(time.Now().Sub(flushStart).Nanoseconds()), nil, 1.0) + s.statsd.TimeInMilliseconds("flush.total_duration_ns", float64(time.Now().Sub(flushStart).Nanoseconds()), []string{"part:post"}, 1.0) s.logger.WithField("metrics", len(finalMetrics)).Info("Completed flush to Datadog") } @@ -177,6 +182,7 @@ func (s *Server) flushForward(wms []WorkerMetrics) { } jsonMetrics := make([]JSONMetric, 0, jmLength) + exportStart := time.Now() for _, wm := range wms { for _, histo := range wm.histograms { jm, err := histo.Export() @@ -217,6 +223,7 @@ func (s *Server) flushForward(wms []WorkerMetrics) { jsonMetrics = append(jsonMetrics, jm) } } + s.statsd.TimeInMilliseconds("forward.duration_ns", float64(time.Now().Sub(exportStart).Nanoseconds()), []string{"part:export"}, 1.0) s.statsd.Gauge("forward.post_metrics_total", float64(len(jsonMetrics)), nil, 1.0) if len(jsonMetrics) == 0 { @@ -225,6 +232,7 @@ func (s *Server) flushForward(wms []WorkerMetrics) { } // always re-resolve the host to avoid dns caching + dnsStart := time.Now() endpoint, err := resolveEndpoint(fmt.Sprintf("%s/import", s.ForwardAddr)) if err != nil { // not a fatal error if we fail @@ -232,6 +240,7 @@ func (s *Server) flushForward(wms []WorkerMetrics) { s.statsd.Count("forward.error_total", 1, []string{"cause:dns"}, 1.0) s.logger.WithError(err).Warn("Could not re-resolve host for forward") } + s.statsd.TimeInMilliseconds("forward.duration_ns", float64(time.Now().Sub(dnsStart).Nanoseconds()), []string{"part:dns"}, 1.0) // the error has already been logged (if there was one), so we only care // about the success case
Time even more parts of flushing/forwarding
stripe_veneur
train
a4747abad9b0abed0a8953070e4ac7da97bf4d96
diff --git a/tests/unit/commands/validate_test.py b/tests/unit/commands/validate_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/commands/validate_test.py +++ b/tests/unit/commands/validate_test.py @@ -1,21 +1,21 @@ from unittest import TestCase - from schemer import ValidationException +from ..utils import get_app_dusty_schema, get_lib_dusty_schema from dusty.commands.validate import (_validate_app_references, _validate_cycle_free) from dusty import constants class ValidatorTest(TestCase): def test_validate_app_with_bad_service(self): specs = {'apps': { - 'app1': { + 'app1': get_app_dusty_schema({ 'depends': { 'services': [ 'service1', 'service2' ] } - } + }) }, 'services': { 'service1': {} @@ -26,14 +26,14 @@ class ValidatorTest(TestCase): def test_validate_app_with_bad_app(self): specs = {'apps': { - 'app1': { + 'app1': get_app_dusty_schema({ 'depends': { 'apps': [ 'app3', ] } - }, - 'app2': {} + }), + 'app2': get_app_dusty_schema({}) } } with self.assertRaises(AssertionError): @@ -41,16 +41,16 @@ class ValidatorTest(TestCase): def test_validate_app_with_bad_lib(self): specs = {'apps': { - 'app1': { + 'app1': get_app_dusty_schema({ 'depends': { 'libs': [ 'lib2', ] } - } + }) }, 'libs': { - 'lib1': {} + 'lib1': get_lib_dusty_schema({}) } } with self.assertRaises(AssertionError): @@ -58,41 +58,43 @@ class ValidatorTest(TestCase): def test_app_cycle_detection(self): specs = {'apps': { - 'app1': { + 'app1': get_app_dusty_schema({ 'depends': { 'apps': [ 'app1', ] } - } + }) } } with self.assertRaises(ValidationException): _validate_cycle_free(specs) def test_lib_cycle_detection(self): - specs = {'libs': { - 'lib1': { + specs = { + 'apps': {}, + 'libs': { + 'lib1': get_lib_dusty_schema({ 'depends': { 'libs': [ 'lib2', ] } - }, - 'lib2': { + }), + 'lib2': get_lib_dusty_schema({ 'depends': { 'libs': [ 'lib3', ] } - }, - 'lib3': { + }), + 'lib3': get_lib_dusty_schema({ 'depends': { 'libs': [ 'lib1', ] } - } + }) } } with self.assertRaises(ValidationException):
actuall fixed all the tests (sheepish)
gamechanger_dusty
train
11a7782ba7d4ef91782e4cac26b33638ef6d15d2
diff --git a/packages/ringcentral-widgets/components/MessageItem/index.js b/packages/ringcentral-widgets/components/MessageItem/index.js index <HASH>..<HASH> 100644 --- a/packages/ringcentral-widgets/components/MessageItem/index.js +++ b/packages/ringcentral-widgets/components/MessageItem/index.js @@ -520,7 +520,7 @@ export default class MessageItem extends Component { className={styles.actionMenuList} currentLocale={currentLocale} onLog={ - isVoicemail || isFax || extraButton ? + isVoicemail || isFax || renderExtraButton ? undefined : (onLogConversation && this.logConversation) } onViewEntity={onViewContact && this.viewSelectedContact}
Fixbug/extra log icon of group message (#<I>) modify judge condition from extraButton to renderExtraButton
ringcentral_ringcentral-js-widgets
train
39f938bec5e8d903eb5abde1d87b67492b1b4dcb
diff --git a/addon/services/csv.js b/addon/services/csv.js index <HASH>..<HASH> 100644 --- a/addon/services/csv.js +++ b/addon/services/csv.js @@ -74,7 +74,7 @@ export default Ember.Service.extend({ var csv = JSON2CSV(data); - saveAs(new Blob([csv],{type:"data:text/csv;charset=utf-8"}), fileName); + saveAs(new Blob([csv],{type:"data:text/csv;charset=utf-8"}), options.fileName); }
fixed filename for csv
roofstock_ember-cli-data-export
train
0afe79d1cbdf29121634efc922cc430b3227634a
diff --git a/test/test_related_posts.rb b/test/test_related_posts.rb index <HASH>..<HASH> 100644 --- a/test/test_related_posts.rb +++ b/test/test_related_posts.rb @@ -29,6 +29,7 @@ class TestRelatedPosts < Test::Unit::TestCase 'destination' => dest_dir, 'lsi' => true}) end + any_instance_of(Jekyll::RelatedPosts, :display => nil) @site = Site.new(Jekyll.configuration) end
mute LSI output in tests
jekyll_jekyll
train
181b0ed4be5becd3e184a62a54235b03ce89f1cc
diff --git a/NebulaPythonSDK/sdk.py b/NebulaPythonSDK/sdk.py index <HASH>..<HASH> 100644 --- a/NebulaPythonSDK/sdk.py +++ b/NebulaPythonSDK/sdk.py @@ -23,49 +23,49 @@ class Nebula: url = self.host + "/api/apps/" + app payload = json.dumps(config) headers = self.headers - response = requests.request("POST", url, data=payload, headers=headers) + response = requests.request("POST", url, data=payload, headers=headers, timeout=300) return response # delete an existing nebula app, no confirmation required in SDK so be careful def delete_app(self, app): url = self.host + "/api/apps/" + app headers = self.headers - response = requests.request("DELETE", url, headers=headers) + response = requests.request("DELETE", url, headers=headers, timeout=300) return response # list all of the apps managed by nebula def list_apps(self): url = self.host + "/api/apps" headers = self.headers - response = requests.request("GET", url, headers=headers) + response = requests.request("GET", url, headers=headers, timeout=300) return response # list the config of a nebula app, only requires the app name def list_app_info(self, app): url = self.host + "/api/apps/" + app headers = self.headers - response = requests.request("GET", url, headers=headers) + response = requests.request("GET", url, headers=headers, timeout=300) return response # stop a nebula app, only requires the app name def stop_app(self, app): url = self.host + "/api/apps/" + app + "/stop" headers = self.headers - response = requests.request("POST", url, headers=headers) + response = requests.request("POST", url, headers=headers, timeout=300) return response # start a nebula app, only requires the app name def start_app(self, app): url = self.host + "/api/apps/" + app + "/start" headers = self.headers - response = requests.request("POST", url, headers=headers) + response = requests.request("POST", url, headers=headers, timeout=300) return response # restart a nebula app, only requires the app name def restart_app(self, app): url = self.host + "/api/apps/" + app + "/restart" headers = self.headers - response = requests.request("POST", url, headers=headers) + response = requests.request("POST", url, headers=headers, timeout=300) return response # update a nebula app, requires the app name and a dict of the config values you want to change, any combination of @@ -74,19 +74,19 @@ class Nebula: url = self.host + "/api/apps/" + app + "/update" payload = json.dumps(config) headers = self.headers - response = requests.request("PUT", url, data=payload, headers=headers) + response = requests.request("PUT", url, data=payload, headers=headers, timeout=300) return response # rolling restart an app, only requires the app name def roll_app(self, app): url = self.host + "/api/apps/" + app + "/roll" headers = self.headers - response = requests.request("POST", url, headers=headers) + response = requests.request("POST", url, headers=headers, timeout=300) return response # check that the contacted api is responding as expected def check_api(self): url = self.host + "/api/status" headers = self.headers - response = requests.request("GET", url, headers=headers) + response = requests.request("GET", url, headers=headers, timeout=300) return response
adding timeout to all requests sent from the SDK
nebula-orchestrator_nebula-python-sdk
train
bee6ced5c2590dad9f5e0827e8a8972ce14bf7f8
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -130,6 +130,7 @@ class Generate(Command): if len(argv) > 1 and argv[1] in ["bdist_wheel", "install"]: error_compiler.start() api_compiler.start() + docs_compiler.start() setup( name="Pyrogram",
Fix Telegram API missing on readthedocs
pyrogram_pyrogram
train
a4dbb5c3042363805c780132da48e052a172b2ec
diff --git a/template/www/cordova.js b/template/www/cordova.js index <HASH>..<HASH> 100644 --- a/template/www/cordova.js +++ b/template/www/cordova.js @@ -1,5 +1,5 @@ // Platform: windows -// 533e1bfdbc57d54106ca39a02b21a1909f84fda7 +// 2fd4bcb84048415922d13d80d35b8d1668e8e150 /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file @@ -817,7 +817,7 @@ module.exports = channel; }); -// file: d:/coho/cordova-windows/cordova-js-src/exec.js +// file: d:/cordova/cordova-windows/cordova-js-src/exec.js define("cordova/exec", function(require, exports, module) { /*jslint sloppy:true, plusplus:true*/ @@ -1394,7 +1394,7 @@ exports.reset(); }); -// file: d:/coho/cordova-windows/cordova-js-src/platform.js +// file: d:/cordova/cordova-windows/cordova-js-src/platform.js define("cordova/platform", function(require, exports, module) { module.exports = {
CB-<I> Update JS snapshot to version <I>-dev (via coho)
apache_cordova-windows
train
e65b5c5fdb3710a9fb864d53434190bdaad3a6ea
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - Add user last_online field - Add support for inline formsets - Add rest API support +- Add option to add extra buttons to header #### Changed - Set fallback for user profile name and avatar diff --git a/app/testblog/apps.py b/app/testblog/apps.py index <HASH>..<HASH> 100644 --- a/app/testblog/apps.py +++ b/app/testblog/apps.py @@ -16,6 +16,16 @@ class BlogConfig(BaseConfig): search_description = '{publish_date} {title} {price}' list_default_fields = ['id', 'publish_date', 'title'] + view_header_buttons = [ + { + 'label': 'Publish', # string or function + 'url': 'trionyx:model-edit', # string or function + 'type': 'default', # string or function + 'show': lambda obj, alias: True, # Function that gives True or False if button must be displayed + 'modal': True, + } + ] + class Category: verbose_name = '{name}' diff --git a/trionyx/config.py b/trionyx/config.py index <HASH>..<HASH> 100644 --- a/trionyx/config.py +++ b/trionyx/config.py @@ -120,6 +120,24 @@ class ModelConfig: - model_name: Class name of model """ + view_header_buttons = None + """ + List with button configurations to be displayed in view header bar + + .. code-block:: python + + view_header_buttons = [ + { + 'label': 'Send email', # string or function + 'url': lambda obj : reverse('blog.post', kwargs={'pk': obj.id}), # string or function + 'type': 'default', + 'show': lambda obj, alias : True, # Function that gives True or False if button must be displayed + 'modal': True, + } + ] + + """ + disable_add = False """Disable add for this model""" diff --git a/trionyx/trionyx/templates/trionyx/core/model_view.html b/trionyx/trionyx/templates/trionyx/core/model_view.html index <HASH>..<HASH> 100644 --- a/trionyx/trionyx/templates/trionyx/core/model_view.html +++ b/trionyx/trionyx/templates/trionyx/core/model_view.html @@ -8,12 +8,24 @@ {% if back_url %} <a href="{{ back_url }}" class="btn btn-default">Back</a> {% endif %} + + {% for button in view_header_buttons %} + <a + href="{% if button.modal %}#{% else %}{{ button.url }}{% endif %}" + {% if button.modal %}onClick="openDialog('{{ button.url }}')"{% endif %} + class="btn btn-{{ button.type }}" + > + {{ button.label }} + </a> + {% endfor %} + {% if delete_url and delete_permission %} <a href="{{ delete_url }}" class="btn btn-default">Delete</a> {% endif %} {% if edit_url and change_permission %} <a href="{{ edit_url }}" class="btn btn-default">Edit</a> {% endif %} + {% endblock %} {% block content_before_messages %} diff --git a/trionyx/views/models.py b/trionyx/views/models.py index <HASH>..<HASH> 100644 --- a/trionyx/views/models.py +++ b/trionyx/views/models.py @@ -410,6 +410,7 @@ class DetailTabView(ModelPermissionMixin, DetailView, ModelClassMixin): 'model_name': self.get_model_name(), 'model_alias': self.get_model_alias(), 'model_verbose_name': self.object._meta.verbose_name.title(), + 'view_header_buttons': list(self.view_header_buttons()), 'back_url': self.get_back_url(), 'edit_url': self.get_edit_url(), 'delete_url': self.get_delete_url(), @@ -448,6 +449,27 @@ class DetailTabView(ModelPermissionMixin, DetailView, ModelClassMixin): 'pk': self.object.id }) + def view_header_buttons(self): + if self.get_model_config().view_header_buttons: + for config in self.get_model_config().view_header_buttons: + if 'show' in config and not config['show'](self.object, self.get_model_alias()): + continue + + button_type = config.get('type', 'default') + yield { + 'label': config['label'](self.object, self.get_model_alias()) if callable(config['label']) else config['label'], + 'type':button_type(self.object, self.get_model_alias()) if callable(button_type) else button_type, + 'url': config['url'](self.object, self.get_model_alias()) if callable(config['url']) else reverse( + config['url'], + kwargs={ + 'app': self.get_app_label(), + 'model': self.get_model_name(), + 'pk': self.object.id + } + ), + 'modal': config.get('modal', True) + } + def get_model_alias(self): """Get model alias""" if self.model_alias:
[FEATURE] Add option to add extra buttons to header
krukas_Trionyx
train
79b28e00cdf0d701ad891cbd850e4ad5b60a62cd
diff --git a/fsm.go b/fsm.go index <HASH>..<HASH> 100644 --- a/fsm.go +++ b/fsm.go @@ -867,6 +867,11 @@ func (f *FSMContext) ActivityInfo(h HistoryEvent) *ActivityInfo { return f.pendingActivities.ActivityType(h) } +// ActivitiesInfo will return a map of activityId -> ActivityInfo for all in-flight activities in the workflow. +func (f *FSMContext) ActivitiesInfo() map[string]*ActivityInfo{ + return f.pendingActivities.Activities +} + // Serialize will use the current fsm's Serializer to serialize the given struct. It will panic on errors, which is ok in the context of a Decider. // If you want to handle errors, use Serializer().Serialize(...) instead. func (f *FSMContext) Serialize(data interface{}) string {
add a way to get all the activities for a workflow
sclasen_swf4go
train
54b8b9c4e65bd9462ed6229e919ce7fa4e3672f6
diff --git a/src/active-expressions.js b/src/active-expressions.js index <HASH>..<HASH> 100644 --- a/src/active-expressions.js +++ b/src/active-expressions.js @@ -1,6 +1,7 @@ import Interpreter from './babelsberg/jsinterpreter/interpreter.js'; import { Stack } from './utils.js'; import { Listener } from './listener.js'; +import { BaseActiveExpression } from './base/base-active-expressions.js'; export { ConstraintInterpreter } from './constraint-interpreter.js'; @@ -12,44 +13,19 @@ class Handler { } } -class ActiveExpression { +class ActiveExpression extends BaseActiveExpression { constructor(func, scope) { - console.log(func); - this.func = func; - this.lastValue = this.getCurrentValue(); + super(func); this.scope = scope; - this.callbacks = []; this.propertyAccessors = new Set(); this.installListeners(); } - getCurrentValue() { - return this.func(); - } - + // TODO: remove indirection propertyAssigned() { - let currentValue = this.getCurrentValue(); - if(this.lastValue === currentValue) { return; } - - this.lastValue = currentValue; - this.callbacks.forEach(callback => callback()); - } - - onChange(callback) { - this.callbacks.push(callback); - - return this; - } - - /** - * TODO - * like a bind for AExpr - * @param items - */ - applyOn(...items) { - throw new Error('Not yet implemented'); + this.checkAndNotify(); } revoke() { diff --git a/src/base/base-active-expressions.js b/src/base/base-active-expressions.js index <HASH>..<HASH> 100644 --- a/src/base/base-active-expressions.js +++ b/src/base/base-active-expressions.js @@ -4,13 +4,20 @@ export class BaseActiveExpression { * * @param func (Function) the expression to be observed */ - constructor(func) {} + constructor(func) { + // console.log(func); + this.func = func; + this.lastValue = this.getCurrentValue(); + this.callbacks = []; + } /** * aliases with 'now' * @returns {*} the current value of the expression */ - getCurrentValue() {} + getCurrentValue() { + return this.func(); + } onChange(callback) { this.callbacks.push(callback); @@ -18,6 +25,19 @@ export class BaseActiveExpression { return this; } + checkAndNotify() { + let currentValue = this.getCurrentValue(); + if(this.lastValue === currentValue) { return; } + + this.lastValue = currentValue; + this.notify(); + + } + + notify() { + this.callbacks.forEach(callback => callback()); + } + /** * TODO * like a bind for AExpr @@ -26,10 +46,6 @@ export class BaseActiveExpression { applyOn(...items) { throw new Error('Not yet implemented'); } - - revoke() { - this.removeListeners(); - } } export default BaseActiveExpression; diff --git a/src/ticking/ticking-active-expressions.js b/src/ticking/ticking-active-expressions.js index <HASH>..<HASH> 100644 --- a/src/ticking/ticking-active-expressions.js +++ b/src/ticking/ticking-active-expressions.js @@ -1,3 +1,21 @@ -export function aexpr(func, __scope__) { - // TODO: continue here +import { BaseActiveExpression } from './../base/base-active-expressions.js'; + +const TICKING_INSTANCES = new Set(); + +class TickingActiveExpression extends BaseActiveExpression { + + constructor(func) { + super(func); + TICKING_INSTANCES.add(this); + } + + revoke() { + this.removeListeners(); + } +} + +export function aexpr(func, scope) { return new TickingActiveExpression(func, scope); } + +export function check(group = TICKING_INSTANCES) { + group.forEach(aexpr => aexpr.checkAndNotify()); } diff --git a/tests/ticking/tickingActiveExpressionTests.js b/tests/ticking/tickingActiveExpressionTests.js index <HASH>..<HASH> 100644 --- a/tests/ticking/tickingActiveExpressionTests.js +++ b/tests/ticking/tickingActiveExpressionTests.js @@ -1,21 +1,25 @@ 'use strict'; -import { aexpr } from '../../src/ticking/ticking-active-expressions.js'; +import { aexpr, check } from './../../src/ticking/ticking-active-expressions.js'; - -describe('Ticking Active Expressions', function() { +describe('Ticking Active Expressions', () => { it("runs a basic aexpr", () => { var obj = {a: 2, b: 3}; let spy = sinon.spy(); aexpr(function() { return obj.a; - }, {obj}).onChange(spy); + }).onChange(spy); + check(); expect(spy.called).to.be.false; obj.a = 42; + check(); expect(spy.calledOnce).to.be.true; }); + + it("recognize changes to local variables", () => {}); + });
extracted duplicate functionality of implementation strategies into shared superclass
active-expressions_active-expressions
train
fbd52f864d106694107888e55bdc085c5a77dbdd
diff --git a/scripts/gh-pages.js b/scripts/gh-pages.js index <HASH>..<HASH> 100644 --- a/scripts/gh-pages.js +++ b/scripts/gh-pages.js @@ -8,13 +8,13 @@ * ------------ * * % node ./scripts/gh-pages - * gh-pages -d dist -r git@github.com:MozVR/vr-components.git + * gh-pages -d dist -r git@github.com:MozVR/aframe.git * * % node ./scripts/gh-pages cvan - * gh-pages -d dist -r git@github.com:cvan/vr-components.git + * gh-pages -d dist -r git@github.com:cvan/aframe.git * - * % node ./scripts/gh-pages git@github.com:dmarcos/vr-components.git - * gh-pages -d dist -r git@github.com:dmarcos/vr-components.git + * % node ./scripts/gh-pages git@github.com:dmarcos/aframe.git + * gh-pages -d dist -r git@github.com:dmarcos/aframe.git * */ @@ -25,7 +25,7 @@ var path = require('path'); var repo = { username: 'MozVR', - name: 'vr-components' + name: 'aframe' }; var arg = process.argv[2];
deploy to `aframe` GitHub Pages since remote name changed (issue #<I>)
aframevr_aframe
train
73ad6502ccbbff516ce18ed31694b17e1bbc481b
diff --git a/api/graphite.go b/api/graphite.go index <HASH>..<HASH> 100644 --- a/api/graphite.go +++ b/api/graphite.go @@ -145,7 +145,10 @@ MainLoop: case <-ctx.Done(): //request canceled return nil, nil - case err := <-errorChan: + case err, ok := <-errorChan: + if !ok { + break MainLoop + } return nil, err case r, ok := <-responseChan: if !ok {
fix: don't treat errorChan close as an error
grafana_metrictank
train
e060601bc1a38b85126d1035f2f5dea7ef0a2c73
diff --git a/lib/bashcov.rb b/lib/bashcov.rb index <HASH>..<HASH> 100644 --- a/lib/bashcov.rb +++ b/lib/bashcov.rb @@ -48,6 +48,7 @@ module Bashcov @options.root_directory = Dir.getwd @options.skip_uncovered = false + @options.bash_path = "/bin/bash" @options.mute = false end diff --git a/lib/bashcov/bash_info.rb b/lib/bashcov/bash_info.rb index <HASH>..<HASH> 100644 --- a/lib/bashcov/bash_info.rb +++ b/lib/bashcov/bash_info.rb @@ -2,6 +2,7 @@ module Bashcov # Module exposing information concerning the installed Bash version # @note methods do not cache results because {bash_path} can change at # runtime + # @note receiver is expected to implement +bash_path+ module BashInfo # @return [Array<String>] An array representing the components of # +BASH_VERSINFO+ @@ -14,17 +15,16 @@ module Bashcov bash_versinfo[0..1].join.to_i >= 41 end - # @return [Boolean] Whether Bash supports a +PS4+ of greater than 128 bytes + # @param [Integer] bytes The number of bytes to test; default 128 + # @return [Boolean] Whether Bash supports a +PS4+ of at least a given + # number of bytes # @see https://tiswww.case.edu/php/chet/bash/CHANGES # @note Item +i.+ under the +bash-4.2-release+ to +bash-4.3-alpha+ change # list notes that version 4.2 truncates +PS4+ if it is greater than 128 # bytes. - def truncated_ps4? - bash_versinfo[0..1].join.to_i <= 42 - end - - def bash_path - "/bin/bash" + def truncated_ps4?(length = 128) + ps4 = SecureRandom.base64(length) + !`PS4=#{ps4} #{bash_path} 2>&1 1>&- -xc 'echo hello'`.start_with?(ps4) end end end
Added default @options.bash_path and made .truncated_ps4? more intelligent by checking whether Bash does in fact truncated PS4
infertux_bashcov
train
72945619b1f6b5a047248f6d41315d996c053e02
diff --git a/lib/auth.strategies/janrain.js b/lib/auth.strategies/janrain.js index <HASH>..<HASH> 100644 --- a/lib/auth.strategies/janrain.js +++ b/lib/auth.strategies/janrain.js @@ -4,12 +4,12 @@ */ var OAuth= require("oauth").OAuth2, connect = require("connect"), - http = require('http'); + https = require('https'); /* * Provides basic support for Janrain / RPX SSO * Would work best when using a dedicated authentication-app page - * + * * Please note this strategy requires there to be a bodyDecoder module * in the connect stack prior to it. */ @@ -18,70 +18,74 @@ Janrain= module.exports= function(options, server) { var that= {}; var my= {}; that.name = options.name || "janrain"; - + // Todo: connect-auth should really have a global auth failure app associated with it. my.failedLoginPath= options.failedLoginPath || '/'; my.appDomain= options.appDomain; my.callback= options.callback; my.signInUrl= "https://"+ my.appDomain+".rpxnow.com/openid/v2/signin?token_url="+ escape(my.callback) my.apiKey= options.apiKey; - - // Build the authentication routes required + + // Build the authentication routes required that.setupRoutes= function(server) { server.use('/', connect.router(function routes(app){ - app.post('/auth/janrain_callback', function(req, res){ - if( req.body && req.body.token ) { - req.authenticate([that.name], function(error, authenticated) { - if( error ) { console.log(error) } - else { - if( authenticated ) { - //todo: support an optional passed argument, when using embedded urls. - var redirectTo= req.session.auth.janrain_redirect_url || '/'; - res.writeHead(303, { 'Location': redirectTo }); - res.end(''); - } - else { - //TODO: connect-auth should have a notion of failed apps. - res.writeHead(303, { 'Location': my.failedLoginPath }); - res.end(''); - } - } - }); - } - else { - res.writeHead(303, { 'Location': my.failedLoginPath }); - res.end(''); - } - }); - })); + function handleJanrainCallback(req,res) { + if( req.method == 'GET' ) req.getAuthDetails().janrain_came_back_with_get= true; // If we get a GET to this url it suggests a login failure. + req.authenticate([that.name], function(error, authenticated) { + res.writeHead(303, { 'Location': req.getAuthDetails().janrain_redirect_url }); + res.end(''); + }) + } + app.get('/auth/janrain_callback', handleJanrainCallback); + app.post('/auth/janrain_callback', handleJanrainCallback); + })); } // Declare the method that actually does the authentication that.authenticate= function(req, res, callback) { - var self= this; - if( req.body && req.body.token ) { // Phase 2 - var google = http.createClient(443, 'rpxnow.com', true); - var request = google.request('GET', '/api/v2/auth_info?apiKey=' + my.apiKey + '&token=' + req.body.token, {'host': 'rpxnow.com'}); - var result= ""; - request.addListener('response', function (response) { + var self= this; + + this._janrain_fail= function() { + req.getAuthDetails().janrain_login_attempt_failed= true; + this.fail(callback); + } + if( req.getAuthDetails().janrain_login_attempt_failed === true ) { // Phase 3 [Fail scenario where an immediaet re-test occurs in the consumer code] + delete req.getAuthDetails().janrain_login_attempt_failed; + self.fail( callback ); + } + else if( req.getAuthDetails().janrain_came_back_with_get === true ) { // Phase 2 (Fail) + delete req.getAuthDetails().janrain_came_back_with_get; + self._janrain_fail( callback ); + } + else if( req.body && req.body.token ) { // Phase 2 (Succeed) + var options = { + host: 'rpxnow.com', + port: 443, + path:'/api/v2/auth_info?apiKey=' + my.apiKey + '&token=' + req.body.token, + method: 'GET', + headers: {'host' : 'rpxnow.com'} + }; + + var request = https.request(options, function (response) { + var result= ""; response.setEncoding('utf8'); response.addListener('data', function (chunk) { result += chunk; }); response.addListener('end', function () { if( response.statusCode != 200 ) { - self.fail(callback); + self._janrain_fail( callback ); } else { var data= JSON.parse(result); self.success(data.profile, callback) - } + } }); }); request.end(); } else { // Phase 1 - req.session.auth['janrain_redirect_url']= req.url; + req.getAuthDetails()['janrain_redirect_url']= req.url; self.redirect(res, my.signInUrl, callback); } - } + } return that; }; \ No newline at end of file
Update Janrain strategy to work with the now fairly ubiquitous failure callback model
ciaranj_connect-auth
train
7e9ee957dea90669ce06f67109271dbeed0a1c52
diff --git a/openquake/job/params.py b/openquake/job/params.py index <HASH>..<HASH> 100644 --- a/openquake/job/params.py +++ b/openquake/job/params.py @@ -33,6 +33,7 @@ CALCULATION_MODE = { 'Classical': 'classical', 'Deterministic': 'deterministic', 'Event Based': 'event_based', + 'Disaggregation': 'disaggregation', } ENUM_MAP = {
added missing calculation mode to job params Former-commit-id: 1ad<I>b<I>dd9ba8d<I>d6ba<I>e3bc4d<I>
gem_oq-engine
train
7cb4cb4d1defd0ec6f398e05f1831e238592ebc3
diff --git a/src/sap.ui.ux3/src/sap/ui/ux3/DataSetSimpleView.js b/src/sap.ui.ux3/src/sap/ui/ux3/DataSetSimpleView.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.ux3/src/sap/ui/ux3/DataSetSimpleView.js +++ b/src/sap.ui.ux3/src/sap/ui/ux3/DataSetSimpleView.js @@ -213,6 +213,10 @@ sap.ui.define(['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/core/ResizeHa * @protected */ DataSetSimpleView.prototype.updateView = function(aDiff) { + //if view is not rendered no Dom update is necessary + if (!this.getDomRef()) { + return; + } var rm = sap.ui.getCore().createRenderManager(), iLastLength = this.items.length;
[FIX] ux3.DataSetSimpleView: suppress view update if not rendered If the DatSet items are changed an update for an not rendered view will throw an exception (no DOM exists). So we need to suppress the update in this case. Change-Id: I<I>dc8fb9dc1b<I>e4fb7a<I>d3bda<I>f BCP: <I> <I> <I>
SAP_openui5
train
e6216775f82a7ae5796cba1b76fa9211f631a00f
diff --git a/src/CodeStore.php b/src/CodeStore.php index <HASH>..<HASH> 100644 --- a/src/CodeStore.php +++ b/src/CodeStore.php @@ -42,6 +42,16 @@ abstract class CodeStore const C_INDENT_DECREMENT_AFTER = 8; /** + * String for separating parts of the generated code. In most cases a comment with one character repeated many times. + * + * @var string + * + * @since 1.0.0 + * @api + */ + protected $separator; + + /** * The number of spaces per indentation level. * * @var int @@ -55,19 +65,28 @@ abstract class CodeStore */ private $lines; + /** + * The maximum width of the generated code (in chars). + * + * @var int + */ + private $width; + //-------------------------------------------------------------------------------------------------------------------- /** * Object constructor. * * @param int $indentation The number of spaces per indentation level. + * @param int $width The maximum width of the generated code (in chars). * * @since 1.0.0 * @api */ - public function __construct($indentation = 2) + public function __construct($indentation = 2, $width = 120) { $this->indentation = $indentation; $this->lines = []; + $this->width = $width; } //-------------------------------------------------------------------------------------------------------------------- @@ -105,6 +124,18 @@ abstract class CodeStore //-------------------------------------------------------------------------------------------------------------------- /** + * Appends the separator to the generated code. + * + * @since 1.0.0 + * @api + */ + public function appendSeparator() + { + $this->append($this->separator, false); + } + + //-------------------------------------------------------------------------------------------------------------------- + /** * Appends a part of code to the last line of code. * * @param string $part The part of code to be to the last line. @@ -155,6 +186,12 @@ abstract class CodeStore $indentLevel = max(0, $indentLevel - 1); } + // If the line is a separator shorten the separator. + if ($this->separator!==null && $line==$this->separator) + { + $line = $this->shortenSeparator($this->width - $this->indentation * $indentLevel); + } + // Append the line with indentation. $lines[] = $this->addIndentation($line, $indentLevel); @@ -179,6 +216,20 @@ abstract class CodeStore //-------------------------------------------------------------------------------------------------------------------- /** + * Returns the code as an array of strings (without indentation). + * + * @return string[] + * + * @since 1.0.0 + * @api + */ + public function getLines() + { + return $this->lines; + } + + //-------------------------------------------------------------------------------------------------------------------- + /** * Returns the indentation mode based on a line of code. * * The indentation mode can be any combination of the following flags (combined with the | bitwise operator). @@ -200,6 +251,19 @@ abstract class CodeStore //-------------------------------------------------------------------------------------------------------------------- /** + * Returns the separator to a required length. + * + * @param int $length The required length of the separator. + * + * @return string + */ + protected function shortenSeparator($length) + { + return substr($this->separator, 0, $length); + } + + //-------------------------------------------------------------------------------------------------------------------- + /** * Returns a line of code with the proper amount of indentationMode. * * @param string $line The line of code. @@ -209,7 +273,7 @@ abstract class CodeStore */ private function addIndentation($line, $indentLevel) { - return str_repeat(' ', $this->indentation * $indentLevel).$line; + return ($line==='') ? '' : str_repeat(' ', $this->indentation * $indentLevel).$line; } //--------------------------------------------------------------------------------------------------------------------
Added support for separators.
SetBased_php-helper-code-store
train
a19eaa1178c384881c1744d669998c28bceb5d0e
diff --git a/libargos/repo/filesytemrti.py b/libargos/repo/filesytemrti.py index <HASH>..<HASH> 100644 --- a/libargos/repo/filesytemrti.py +++ b/libargos/repo/filesytemrti.py @@ -98,15 +98,17 @@ def autodetectedFileTreeItem(fileName): except KeyError: cls = UnknownFileRti - try: - rti = cls.createFromFileName(fileName) - except Exception as ex: - if DEBUGGING: - raise - logger.error("Unable open {} as {}".format(fileName, cls)) - logger.error("Reason: {}".format(ex)) - rti = UnableToOpenFileRti.createFromFileName(fileName) - - return rti + return cls.createFromFileName(fileName) + +# try: +# rti = cls.createFromFileName(fileName) +# except Exception as ex: +# if DEBUGGING: +# raise +# logger.error("Unable open {} as {}".format(fileName, cls)) +# logger.error("Reason: {}".format(ex)) +# rti = UnableToOpenFileRti.createFromFileName(fileName) +# +# return rti diff --git a/libargos/repo/repository.py b/libargos/repo/repository.py index <HASH>..<HASH> 100644 --- a/libargos/repo/repository.py +++ b/libargos/repo/repository.py @@ -19,7 +19,6 @@ """ import logging from libargos.qt.editabletreemodel import BaseTreeModel -#from libargos.repo.filesytemrti import UnableToOpenFileRti from libargos.info import DEBUGGING from libargos.utils.cls import type_name diff --git a/libargos/repo/treeitems.py b/libargos/repo/treeitems.py index <HASH>..<HASH> 100644 --- a/libargos/repo/treeitems.py +++ b/libargos/repo/treeitems.py @@ -57,7 +57,7 @@ class BaseRti(AbstractLazyLoadTreeItem): check_class(fileName, StringType, allow_none=True) if fileName: fileName = os.path.realpath(fileName) - assert os.path.exists(fileName), "File not found: {}".format(fileName) + #assert os.path.exists(fileName), "File not found: {}".format(fileName) self._fileName = fileName @@ -107,6 +107,7 @@ class BaseRti(AbstractLazyLoadTreeItem): """ logger.debug("Closing {}".format(self)) if self._isOpen: + #self._forgetException() self._closeResources() self._isOpen = False diff --git a/libargos/widgets/mainwindow.py b/libargos/widgets/mainwindow.py index <HASH>..<HASH> 100644 --- a/libargos/widgets/mainwindow.py +++ b/libargos/widgets/mainwindow.py @@ -99,10 +99,10 @@ class MainWindow(QtGui.QMainWindow): self.deleteItemAction.setShortcut("Ctrl+D") self.openFileAction = QtGui.QAction("Open Item", self) - self.openFileAction.setShortcut("Ctrl+O") + self.openFileAction.setShortcut("Ctrl+K") # TODO: remove shortcut self.closeFileAction = QtGui.QAction("Close Item", self) - self.closeFileAction.setShortcut("Ctrl+P") # TODO: remove shortcut + self.closeFileAction.setShortcut("Ctrl+L") # TODO: remove shortcut def __setupMenu(self): diff --git a/libargos/widgets/repotree.py b/libargos/widgets/repotree.py index <HASH>..<HASH> 100644 --- a/libargos/widgets/repotree.py +++ b/libargos/widgets/repotree.py @@ -88,20 +88,26 @@ class RepoTreeView(ToggleColumnTreeView): selectedItem = self.model().getItem(selectedIndex) return selectedItem, selectedIndex - def openSelectedItem(self): - """ Opens the selected file in the repository. The file must be closed beforehand. + """ Opens the selected item in the repository. """ - selectedItem, _selectedIndex = self._getSelectedItem() + logger.debug("openSelectedItem") + selectedItem, selectedIndex = self._getSelectedItem() selectedItem.open() + self.expand(selectedIndex) # to visit the children and thus show the 'open' icons def closeSelectedItem(self): - """ Closes the selected file in the repository. The file must be closed beforehand. + """ Closes the selected item in the repository. + All its children will be unfetched and closed. """ - _selectedItem, selectedIndex = self._getSelectedItem() + logger.debug("closeSelectedItem") + selectedItem, selectedIndex = self._getSelectedItem() + + # First we remove all the children, this will close them as well. self.model().removeAllChildrenAtIndex(selectedIndex) + selectedItem.close() self.collapse(selectedIndex) # otherwise the children will be fetched immediately
Fixed bug: Item was not cloesd, only its children.
titusjan_argos
train
185e169033d743678e426e60c60ee64fba03dd3c
diff --git a/tests/test_errors.py b/tests/test_errors.py index <HASH>..<HASH> 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -283,6 +283,18 @@ class TestErrors(unittest.TestCase): assert len(str(context.exception)) < 1000 assert ' ... ' in str(context.exception) + def test_no_error_tuple_info(self): + + class RaisesError(properties.HasProperties): + + @properties.validator + def raise_error(self): + raise properties.ValidationError('') + + errorer = RaisesError() + with self.assertRaises(properties.ValidationError): + errorer.validate() + if __name__ == '__main__': unittest.main()
Add test where obvious validation error is ignored
seequent_properties
train
cb422bb5dd81c625382d1cd4d4494083aa4be6fb
diff --git a/src/test/java/picocli/I18nCommand.java b/src/test/java/picocli/I18nCommand.java index <HASH>..<HASH> 100644 --- a/src/test/java/picocli/I18nCommand.java +++ b/src/test/java/picocli/I18nCommand.java @@ -32,4 +32,9 @@ public class I18nCommand { @Parameters(index = "1", description = "top param1 description") String param1; + + @Override + public String toString() { + return getClass().getName(); + } }
[#<I>] fix broken test
remkop_picocli
train
8fb08a5a76b39ce81ce5d47a2919c0a391c5a9df
diff --git a/src/Foundation/Console/OptimizeCommand.php b/src/Foundation/Console/OptimizeCommand.php index <HASH>..<HASH> 100644 --- a/src/Foundation/Console/OptimizeCommand.php +++ b/src/Foundation/Console/OptimizeCommand.php @@ -78,7 +78,7 @@ class OptimizeCommand extends Command */ protected function compileClasses() { - $outputPath = $this->framework['path.base'] .Ds .'Boot' .DS .'Compiled.php'; + $outputPath = $this->framework['path.base'] .DS .'Boot' .DS .'Compiled.php'; // $preloader = (new Factory)->create(['skip' => true]); @@ -105,7 +105,7 @@ class OptimizeCommand extends Command { $app = $this->framework; - $core = require __DIR__.DS .'Optimize'.DS.'config.php'; + $core = require __DIR__.DS .'Optimize' .DS .'config.php'; return array_merge($core, $this->framework['config']['compile']); }
Improve Nova\Console\OptimizeCommand
nova-framework_system
train
261eb9517d836cc35501fed2b70534958fc8228d
diff --git a/src/test/java/org/hobsoft/hamcrest/compose/ConjunctionMatcherTest.java b/src/test/java/org/hobsoft/hamcrest/compose/ConjunctionMatcherTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/hobsoft/hamcrest/compose/ConjunctionMatcherTest.java +++ b/src/test/java/org/hobsoft/hamcrest/compose/ConjunctionMatcherTest.java @@ -38,6 +38,22 @@ public class ConjunctionMatcherTest // tests // ---------------------------------------------------------------------------------------------------------------- + @Test + public void constructorWithMatcherReturnsCompositeMatcher() + { + ConjunctionMatcher<Object> actual = new ConjunctionMatcher<>(asList(anything("x"))); + + assertThat(asString(actual), is("x")); + } + + @Test + public void constructorWithMatchersReturnsCompositeMatcher() + { + ConjunctionMatcher<Object> actual = new ConjunctionMatcher<>(asList(anything("x"), anything("y"))); + + assertThat(asString(actual), is("x and y")); + } + @Test(expected = NullPointerException.class) public void constructorWithNullMatchersThrowsException() {
Added ConjunctionMatcher constructor tests
markhobson_hamcrest-compose
train
32fe558ebe6253fa4132c76ed4a29735f04bb7b3
diff --git a/webapps/ui/cockpit/tests/specs/process-instance-spec.js b/webapps/ui/cockpit/tests/specs/process-instance-spec.js index <HASH>..<HASH> 100644 --- a/webapps/ui/cockpit/tests/specs/process-instance-spec.js +++ b/webapps/ui/cockpit/tests/specs/process-instance-spec.js @@ -11,7 +11,7 @@ var definitionPage = require('../pages/process-definition'); var instancePage = require('../pages/process-instance'); -describe('Cockpit Process Instance Spec', function() { +describe.skip('Cockpit Process Instance Spec', function() { describe('page navigation', function() { diff --git a/webapps/ui/cockpit/tests/specs/repository-spec.js b/webapps/ui/cockpit/tests/specs/repository-spec.js index <HASH>..<HASH> 100644 --- a/webapps/ui/cockpit/tests/specs/repository-spec.js +++ b/webapps/ui/cockpit/tests/specs/repository-spec.js @@ -77,7 +77,7 @@ describe('Repository Spec', function() { }); - describe('deployments search', function() { + describe.skip('deployments search', function() { before(function() { return testHelper(setupFile.setup1, function() { diff --git a/webapps/ui/common/tests/develop.conf.js b/webapps/ui/common/tests/develop.conf.js index <HASH>..<HASH> 100644 --- a/webapps/ui/common/tests/develop.conf.js +++ b/webapps/ui/common/tests/develop.conf.js @@ -27,7 +27,7 @@ exports.config = { capabilities: { 'browserName': 'chrome', 'chromeOptions': { - 'args': ['incognito', 'disable-extensions', 'start-maximized', 'enable-crash-reporter-for-testing'] + 'args': ['start-maximized', 'enable-crash-reporter-for-testing'] }, 'loggingPrefs': { 'browser': 'ALL' diff --git a/webapps/ui/tasklist/tests/specs/create-task-spec.js b/webapps/ui/tasklist/tests/specs/create-task-spec.js index <HASH>..<HASH> 100644 --- a/webapps/ui/tasklist/tests/specs/create-task-spec.js +++ b/webapps/ui/tasklist/tests/specs/create-task-spec.js @@ -10,7 +10,7 @@ var dashboardPage = require('../pages/dashboard'); var createTaskDialogPage = dashboardPage.createTask; -describe('Tasklist Create Task Spec', function () { +describe.skip('Tasklist Create Task Spec', function () { describe('create task without tenant', function() { diff --git a/webapps/ui/tasklist/tests/specs/filter-basic-spec.js b/webapps/ui/tasklist/tests/specs/filter-basic-spec.js index <HASH>..<HASH> 100644 --- a/webapps/ui/tasklist/tests/specs/filter-basic-spec.js +++ b/webapps/ui/tasklist/tests/specs/filter-basic-spec.js @@ -7,7 +7,7 @@ var dashboardPage = require('../pages/dashboard'); var editModalPage = dashboardPage.taskFilters.editFilterPage; -describe('Tasklist Filter Basic Spec', function() { +describe.skip('Tasklist Filter Basic Spec', function() { describe('initial validation', function() { diff --git a/webapps/ui/tasklist/tests/specs/process-start-spec.js b/webapps/ui/tasklist/tests/specs/process-start-spec.js index <HASH>..<HASH> 100644 --- a/webapps/ui/tasklist/tests/specs/process-start-spec.js +++ b/webapps/ui/tasklist/tests/specs/process-start-spec.js @@ -10,7 +10,7 @@ var dashboardPage = require('../pages/dashboard'); var startDialogPage = dashboardPage.startProcess; -describe('Tasklist Start Spec', function () { +describe.skip('Tasklist Start Spec', function () { describe('start process dialog', function() { diff --git a/webapps/ui/tasklist/tests/specs/task-claiming-spec.js b/webapps/ui/tasklist/tests/specs/task-claiming-spec.js index <HASH>..<HASH> 100644 --- a/webapps/ui/tasklist/tests/specs/task-claiming-spec.js +++ b/webapps/ui/tasklist/tests/specs/task-claiming-spec.js @@ -6,7 +6,7 @@ var setupFile = require('./task-claiming-setup'); var dashboardPage = require('../pages/dashboard'); -describe('Task Claiming Spec', function() { +describe.skip('Task Claiming Spec', function() { describe('claim and unclaim', function() { diff --git a/webapps/ui/tasklist/tests/specs/task-dates-spec.js b/webapps/ui/tasklist/tests/specs/task-dates-spec.js index <HASH>..<HASH> 100644 --- a/webapps/ui/tasklist/tests/specs/task-dates-spec.js +++ b/webapps/ui/tasklist/tests/specs/task-dates-spec.js @@ -8,7 +8,7 @@ var taskViewPage = dashboardPage.currentTask; var taskListPage = dashboardPage.taskList; -describe('Task Dates Spec', function() { +describe.skip('Task Dates Spec', function() { describe('follow-up dates', function() {
chore: disable failing test cases related to CAM-<I>
camunda_camunda-bpm-platform
train
60adeb8a53d52c3c567cd1577fbdb378702e9b49
diff --git a/lib/vanity/metric/active_record.rb b/lib/vanity/metric/active_record.rb index <HASH>..<HASH> 100644 --- a/lib/vanity/metric/active_record.rb +++ b/lib/vanity/metric/active_record.rb @@ -57,7 +57,7 @@ module Vanity def values(sdate, edate) query = { :conditions=>{ @ar_timestamp=>(sdate.to_time...(edate + 1).to_time) }, :group=>"date(#{@ar_scoped.connection.quote_column_name @ar_timestamp})" } - grouped = @ar_column ? @ar_scoped.calculate(@ar_aggregate, @ar_column, query) : @ar_scoped.count(query) + grouped = @ar_column ? @ar_scoped.send(@ar_aggregate, @ar_column, query) : @ar_scoped.count(query) (sdate..edate).inject([]) { |ordered, date| ordered << (grouped[date.to_s] || 0) } end diff --git a/test/metric/active_record_test.rb b/test/metric/active_record_test.rb index <HASH>..<HASH> 100644 --- a/test/metric/active_record_test.rb +++ b/test/metric/active_record_test.rb @@ -42,7 +42,6 @@ context "ActiveRecord Metric" do end test "record average" do - Sky.aggregates File.open "tmp/experiments/metrics/sky_is_limit.rb", "w" do |f| f.write <<-RUBY metric "Sky is limit" do @@ -51,13 +50,12 @@ context "ActiveRecord Metric" do RUBY end Vanity.playground.metrics - Sky.create! :height=>4 + Sky.create! :height=>8 Sky.create! :height=>2 - assert_equal 3, Vanity::Metric.data(metric(:sky_is_limit)).last.last + assert_equal 5, Vanity::Metric.data(metric(:sky_is_limit)).last.last end test "record minimum" do - Sky.aggregates File.open "tmp/experiments/metrics/sky_is_limit.rb", "w" do |f| f.write <<-RUBY metric "Sky is limit" do @@ -72,7 +70,6 @@ context "ActiveRecord Metric" do end test "record maximum" do - Sky.aggregates File.open "tmp/experiments/metrics/sky_is_limit.rb", "w" do |f| f.write <<-RUBY metric "Sky is limit" do @@ -108,7 +105,6 @@ context "ActiveRecord Metric" do end test "with scope" do - Sky.aggregates File.open "tmp/experiments/metrics/sky_is_limit.rb", "w" do |f| f.write <<-RUBY metric "Sky is limit" do diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -84,7 +84,7 @@ class Test::Unit::TestCase Vanity.playground.collecting = false Vanity.playground.stubs(:connection).returns(stub(:flushdb=>nil)) end - + def teardown Vanity.context = nil FileUtils.rm_rf "tmp" @@ -101,32 +101,6 @@ end ActiveRecord::Base.logger = $logger ActiveRecord::Base.establish_connection :adapter=>"sqlite3", :database=>File.expand_path("database.sqlite") -# Call this to define aggregate functions not available in SQlite. -class ActiveRecord::Base - def self.aggregates - connection.raw_connection.create_aggregate("minimum", 1) do - step do |func, value| - func[:minimum] = value.to_i unless func[:minimum] && func[:minimum].to_i < value.to_i - end - finalize { |func| func.result = func[:minimum] } - end - - connection.raw_connection.create_aggregate("maximum", 1) do - step do |func, value| - func[:maximum] = value.to_i unless func[:maximum] && func[:maximum].to_i > value.to_i - end - finalize { |func| func.result = func[:maximum] } - end - - connection.raw_connection.create_aggregate("average", 1) do - step do |func, value| - func[:total] = func[:total].to_i + value.to_i - func[:count] = func[:count].to_i + 1 - end - finalize { |func| func.result = func[:total].to_i / func[:count].to_i } - end - end -end class Array @@ -134,7 +108,7 @@ class Array unless method_defined?(:shuffle) def shuffle copy = clone - Array.new(size) { copy.delete_at(Kernel.rand(copy.size)) } + Array.new(size) { copy.delete_at(Kernel.rand(copy.size)) } end end end @@ -145,7 +119,7 @@ def context(*args, &block) return super unless (name = args.first) && block parent = Class === self ? self : (defined?(ActiveSupport::TestCase) ? ActiveSupport::TestCase : Test::Unit::TestCase) klass = Class.new(parent) do - def self.test(name, &block) + def self.test(name, &block) define_method("test_#{name.gsub(/\W/,'_')}", &block) if block end def self.xtest(*args) end
Calling calculate with aggregate operations 'minimum', 'maximum', and 'average' is not valid for some (any?) adapters (including, at least, sqlite and postgres). Safer to call the appropriate matching aggregate method rather than calculate.
assaf_vanity
train
cff71166ec65cee1a070f04ac5c4d10fe3b009d9
diff --git a/odb.go b/odb.go index <HASH>..<HASH> 100644 --- a/odb.go +++ b/odb.go @@ -182,17 +182,21 @@ func (v *Odb) Hash(data []byte, otype ObjectType) (oid *Oid, err error) { // contents of the object. func (v *Odb) NewReadStream(id *Oid) (*OdbReadStream, error) { stream := new(OdbReadStream) + var ctype C.git_otype + var csize C.size_t runtime.LockOSThread() defer runtime.UnlockOSThread() - ret := C.git_odb_open_rstream(&stream.ptr, v.ptr, id.toC()) + ret := C.git_odb_open_rstream(&stream.ptr, &csize, &ctype, v.ptr, id.toC()) runtime.KeepAlive(v) runtime.KeepAlive(id) if ret < 0 { return nil, MakeGitError(ret) } + stream.Size = uint64(csize) + stream.Type = ObjectType(ctype) runtime.SetFinalizer(stream, (*OdbReadStream).Free) return stream, nil } @@ -264,7 +268,9 @@ func (object *OdbObject) Data() (data []byte) { } type OdbReadStream struct { - ptr *C.git_odb_stream + ptr *C.git_odb_stream + Size uint64 + Type ObjectType } // Read reads from the stream
Adjust to the change in the git_odb_open_rstream signature
libgit2_git2go
train
97b8c0678e356a06adaed4c3826f793d97cc444c
diff --git a/messaging/src/main/java/org/cloudiator/messaging/services/ProcessService.java b/messaging/src/main/java/org/cloudiator/messaging/services/ProcessService.java index <HASH>..<HASH> 100644 --- a/messaging/src/main/java/org/cloudiator/messaging/services/ProcessService.java +++ b/messaging/src/main/java/org/cloudiator/messaging/services/ProcessService.java @@ -1,15 +1,14 @@ package org.cloudiator.messaging.services; -import org.cloudiator.messages.Process; -import org.cloudiator.messages.Process.CreateLanceProcessRequest; import org.cloudiator.messages.Process.CreateFaasProcessRequest; -import org.cloudiator.messages.Process.FaasProcessCreatedResponse; +import org.cloudiator.messages.Process.CreateLanceProcessRequest; import org.cloudiator.messages.Process.CreateProcessRequest; import org.cloudiator.messages.Process.CreateScheduleRequest; import org.cloudiator.messages.Process.CreateSparkProcessRequest; import org.cloudiator.messages.Process.DeleteLanceProcessRequest; import org.cloudiator.messages.Process.DeleteProcessRequest; import org.cloudiator.messages.Process.DeleteScheduleRequest; +import org.cloudiator.messages.Process.FaasProcessCreatedResponse; import org.cloudiator.messages.Process.LanceProcessCreatedResponse; import org.cloudiator.messages.Process.LanceProcessDeletedResponse; import org.cloudiator.messages.Process.ProcessCreatedResponse; @@ -101,4 +100,6 @@ public interface ProcessService { ProcessGroupQueryResponse queryProcessGroups(ProcessGroupQueryMessage processGroupQueryMessage) throws ResponseException; + + void subscribeProcessGroupQueryRequest(MessageCallback<ProcessGroupQueryMessage> callback); } diff --git a/messaging/src/main/java/org/cloudiator/messaging/services/ProcessServiceImpl.java b/messaging/src/main/java/org/cloudiator/messaging/services/ProcessServiceImpl.java index <HASH>..<HASH> 100644 --- a/messaging/src/main/java/org/cloudiator/messaging/services/ProcessServiceImpl.java +++ b/messaging/src/main/java/org/cloudiator/messaging/services/ProcessServiceImpl.java @@ -1,9 +1,9 @@ package org.cloudiator.messaging.services; import com.google.inject.Inject; -import org.cloudiator.messages.Process; -import org.cloudiator.messages.Process.*; import javax.inject.Named; +import org.cloudiator.messages.Process; +import org.cloudiator.messages.Process.CreateFaasProcessRequest; import org.cloudiator.messages.Process.CreateLanceProcessRequest; import org.cloudiator.messages.Process.CreateProcessRequest; import org.cloudiator.messages.Process.CreateScheduleRequest; @@ -11,6 +11,7 @@ import org.cloudiator.messages.Process.CreateSparkProcessRequest; import org.cloudiator.messages.Process.DeleteLanceProcessRequest; import org.cloudiator.messages.Process.DeleteProcessRequest; import org.cloudiator.messages.Process.DeleteScheduleRequest; +import org.cloudiator.messages.Process.FaasProcessCreatedResponse; import org.cloudiator.messages.Process.LanceProcessCreatedResponse; import org.cloudiator.messages.Process.LanceProcessDeletedResponse; import org.cloudiator.messages.Process.ProcessCreatedResponse; @@ -29,8 +30,6 @@ import org.cloudiator.messaging.MessageInterface; import org.cloudiator.messaging.ResponseCallback; import org.cloudiator.messaging.ResponseException; -import javax.inject.Named; - public class ProcessServiceImpl implements ProcessService { private final MessageInterface messageInterface; @@ -210,4 +209,10 @@ public class ProcessServiceImpl implements ProcessService { return messageInterface.call(processGroupQueryMessage, ProcessGroupQueryResponse.class, timeout); } + @Override + public void subscribeProcessGroupQueryRequest(MessageCallback<ProcessGroupQueryMessage> callback) { + messageInterface.subscribe(ProcessGroupQueryMessage.class, ProcessGroupQueryMessage.parser(), callback); + } + + }
added missing logic for querying ProcessGroups
cloudiator_common
train
267792666ee423dff30ec6fad42db6cbe074f1ad
diff --git a/retext.py b/retext.py index <HASH>..<HASH> 100755 --- a/retext.py +++ b/retext.py @@ -319,7 +319,7 @@ class ReTextWindow(QMainWindow): self.connect(self.actionSaveGDocs, SIGNAL('triggered()'), self.saveGDocs) self.connect(self.actionAboutQt, SIGNAL('triggered()'), qApp, SLOT('aboutQt()')) self.usefulTags = ('center', 's', 'span', 'table', 'td', 'tr', 'u') - self.usefulChars = ('hellip', 'laquo', 'minus', 'mdash', 'nbsp', 'ndash', 'raquo') + self.usefulChars = ('deg', 'hellip', 'laquo', 'larr', 'mdash', 'middot', 'minus', 'nbsp', 'ndash', 'raquo', 'rarr', 'times') self.tagsBox = QComboBox(self.editBar) self.tagsBox.addItem(self.tr('Tags')) self.tagsBox.addItems(self.usefulTags)
Stable release <I> * More useful symbols
retext-project_retext
train