hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
7643d87cdd030cf92c3d35194089f3157e32af79
diff --git a/src/main/java/org/odlabs/wiquery/core/commons/WiQueryCoreHeaderContributor.java b/src/main/java/org/odlabs/wiquery/core/commons/WiQueryCoreHeaderContributor.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/odlabs/wiquery/core/commons/WiQueryCoreHeaderContributor.java +++ b/src/main/java/org/odlabs/wiquery/core/commons/WiQueryCoreHeaderContributor.java @@ -178,11 +178,11 @@ public class WiQueryCoreHeaderContributor implements Serializable, for (WiQueryPluginRenderingListener listener : pluginRenderingListeners) { listener.onRender(plugin, manager, headerResponse); } - + plugin.contribute(manager); } - initializeResourceManager( headerResponse, manager ); + initializeResourceManager(headerResponse, manager); mergeResources(response, settings, wiQueryHeaderResponse); @@ -193,8 +193,8 @@ public class WiQueryCoreHeaderContributor implements Serializable, } private void initializeResourceManager( IHeaderResponse headerResponse, WiQueryResourceManager manager ) { - if(WiQuerySettings.get().isEnableWiqueryResourceManagement()){ - manager.initialize(headerResponse); + if(WiQuerySettings.get().isEnableWiqueryResourceManagement()) { + manager.initialize(headerResponse); } } @@ -225,8 +225,8 @@ public class WiQueryCoreHeaderContributor implements Serializable, } } } - - initializeResourceManager( wiQueryHeaderResponse, manager ); + + initializeResourceManager(headerResponse, manager); mergeResources(response, settings, wiQueryHeaderResponse); }
fix on r<I>. the wrong variable was used, this breaks all ajax requests targets. svn path=/trunk/; revision=<I>
WiQuery_wiquery
train
18b96068b13ab2c7b296194ad55734f654197449
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -184,10 +184,11 @@ about.) For more on Alan Kay, go to youtube and vimeo. His 30+ min lectures are heavenly. + The End ------- -... for now. +... for now. (Todo: async and css). diff --git a/lib/json_applet.js b/lib/json_applet.js index <HASH>..<HASH> 100644 --- a/lib/json_applet.js +++ b/lib/json_applet.js @@ -183,7 +183,7 @@ Applet.prototype.run = function (source) { func_meta = me.funcs[token]; if (!func_meta) - return me.save_error( new Error("Func not found: " + token) ); + return me.save_error( new Error("Function not found: " + token) ); curr = { prev: prev, diff --git a/lib/sanitize.js b/lib/sanitize.js index <HASH>..<HASH> 100644 --- a/lib/sanitize.js +++ b/lib/sanitize.js @@ -84,8 +84,9 @@ E.string_in_array = function (unk, name) { var temp = null; E.attr_funcs = []; for (temp in E) { - if (_.isFunction(E[temp])) + if (_.isFunction(E[temp])) { E.attr_funcs.push(temp); + } } E.opt = function (func, name) { @@ -94,7 +95,11 @@ E.opt = function (func, name) { return null; return func(v, name); }; -} +}; + +_.each(E.attr_funcs, function (name, i) { + E["opt_" + name] = E.opt(E[name], name); +}); // **************************************************************** // ****************** End of Sanitize Attr Checkers *************** diff --git a/lib/www_applet.js b/lib/www_applet.js index <HASH>..<HASH> 100644 --- a/lib/www_applet.js +++ b/lib/www_applet.js @@ -43,7 +43,29 @@ OK.new = function (source, multi_def) { return app; }; -OK.tag_run = function () { +OK.tag_run = function (run, args, content) { + var tag_meta = run.app.data.tags[run.name]; + + // Unknown attrs. + var unk = _.compact(_.map(args, function (v, k) { + if (!tag_meta.args[k]) + return k; + return null; + })); + + if (unk.length) + return run.error(new Error('Unknown attributes: ' + unk.join(', '))); + + // Sanitize attrs. + var clean_attrs = {}; + for (var name in tag_meta.args) { + var valid = tag_meta.args[name](args[name]); + if (valid && valid.message) + return run.error(valid); + clean_attrs[name] = valid; + } + + // conso.log(clean_attrs[id].toString()) NOT_READY(); return OK.Element.new(tag, args, content); }; @@ -80,7 +102,7 @@ OK.tags = { ] , 'a' : [ - {hre: S.href}, + {id: S.opt_id, href: S.href}, S.string, function (meta, attrs, content) { return element('a', [args, 'href', {ok_type:'link'}], content); diff --git a/test/www_applet_html.js b/test/www_applet_html.js index <HASH>..<HASH> 100644 --- a/test/www_applet_html.js +++ b/test/www_applet_html.js @@ -32,7 +32,7 @@ describe( 'ok_slang', function () { 'a', {id: 'my name'}, [ "enter wrong name" ] ]; - assert.equal(run(html).error.message, "Invalid chars in text_input id: my name"); + assert.equal(run(html).error.message, "id: invalid characters: \"my name\""); }); it( 'returns error if unknown element', function () { @@ -40,7 +40,7 @@ describe( 'ok_slang', function () { 'text_inputy', {}, ["enter name"] ]; - assert.equal(run(slang).error.message, "Unknown element: text_inputy"); + assert.equal(run(slang).error.message, "Function not found: text_inputy"); }); }); // === end desc
Implemented: attrs are run through sanitizer.
da99_www_app
train
23143bb7d132c0b67a70029af66abe643d664f5e
diff --git a/acceptancetests/jujupy/exceptions.py b/acceptancetests/jujupy/exceptions.py index <HASH>..<HASH> 100644 --- a/acceptancetests/jujupy/exceptions.py +++ b/acceptancetests/jujupy/exceptions.py @@ -28,9 +28,6 @@ class StatusTimeout(Exception): class ControllersTimeout(Exception): """Raised when 'juju show-controller' timed out.""" -class BackupTimeout(Exception): - """Raised when 'juju create-backup' timed out.""" - class SoftDeadlineExceeded(Exception): """Raised when an overall client operation takes too long."""
Remove BackupTimeout as it's no longer required
juju_juju
train
57f576bbf1e1ec85520b3b1a5d981cf166554e6a
diff --git a/rpcserver.go b/rpcserver.go index <HASH>..<HASH> 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -951,6 +951,8 @@ func (r *rpcServer) PendingChannels(ctx context.Context, }, ) + resp.TotalLimboBalance += channel.LocalBalance + // If the channel was force closed, then we'll need to query // the utxoNursery for additional information. case channeldb.ForceClose:
rpc: include pending close channels in total limbo balance
lightningnetwork_lnd
train
483308b165313541541e8436c0460d22e437fb3b
diff --git a/skorch/helper.py b/skorch/helper.py index <HASH>..<HASH> 100644 --- a/skorch/helper.py +++ b/skorch/helper.py @@ -5,6 +5,7 @@ They should not be used in skorch directly. """ from functools import partial from skorch.utils import _make_split +from skorch.utils import _make_optimizer class SliceDict(dict): @@ -112,8 +113,7 @@ def filtered_optimizer(optimizer, filter_fn): it to ``optimizer``. """ - from skorch.utils import make_optimizer - return partial(make_optimizer, optimizer=optimizer, filter_fn=filter_fn) + return partial(_make_optimizer, optimizer=optimizer, filter_fn=filter_fn) def predefined_split(dataset): diff --git a/skorch/utils.py b/skorch/utils.py index <HASH>..<HASH> 100644 --- a/skorch/utils.py +++ b/skorch/utils.py @@ -417,7 +417,7 @@ class FirstStepAccumulator: return self.step -def make_optimizer(pgroups, optimizer, filter_fn, **kwargs): +def _make_optimizer(pgroups, optimizer, filter_fn, **kwargs): """Used by ``skorch.helper.filtered_optimizer`` to allow for pickling""" return optimizer(filter_fn(pgroups), **kwargs)
RFC: Converts make_optimizer to a private func (#<I>)
skorch-dev_skorch
train
07e3b9315c3d87205ef5ac890767c277f29d9068
diff --git a/core/src/main/java/io/undertow/util/DateUtils.java b/core/src/main/java/io/undertow/util/DateUtils.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/undertow/util/DateUtils.java +++ b/core/src/main/java/io/undertow/util/DateUtils.java @@ -23,6 +23,7 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; +import java.util.concurrent.TimeUnit; import io.undertow.UndertowOptions; import io.undertow.server.HttpServerExchange; @@ -41,7 +42,6 @@ public class DateUtils { private static final String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z"; private static volatile String cachedDateString; - private static volatile long nextUpdateTime = -1; /** * Thread local cache of this date format. This is technically a small memory leak, however @@ -58,6 +58,16 @@ public class DateUtils { } }; + /** + * Invalidates the current date + */ + private static final Runnable INVALIDATE_TASK = new Runnable() { + @Override + public void run() { + cachedDateString = null; + } + }; + private static final String RFC1036_PATTERN = "EEEEEEEEE, dd-MMM-yy HH:mm:ss z"; private static final String ASCITIME_PATTERN = "EEE MMM d HH:mm:ss yyyyy"; @@ -238,14 +248,19 @@ public class DateUtils { public static void addDateHeaderIfRequired(HttpServerExchange exchange) { HeaderMap responseHeaders = exchange.getResponseHeaders(); if(exchange.getConnection().getUndertowOptions().get(UndertowOptions.ALWAYS_SET_DATE, true) && !responseHeaders.contains(Headers.DATE)) { - long time = System.nanoTime(); - if(time < nextUpdateTime) { - responseHeaders.put(Headers.DATE, cachedDateString); + String dateString = cachedDateString; + if(dateString != null) { + responseHeaders.put(Headers.DATE, dateString); } else { + //set the time and register a timer to invalidate it + //note that this is racey, it does not matter if multiple threads do this + //the perf cost of synchronizing would be more than the perf cost of multiple threads running it long realTime = System.currentTimeMillis(); - String dateString = DateUtils.toDateString(new Date(realTime)); + long mod = realTime % 1000; + long toGo = 1000 - mod; + dateString = DateUtils.toDateString(new Date(realTime)); cachedDateString = dateString; - nextUpdateTime = time + 1000000000; + exchange.getConnection().getIoThread().executeAfter(INVALIDATE_TASK, toGo, TimeUnit.MILLISECONDS); responseHeaders.put(Headers.DATE, dateString); } } @@ -254,4 +269,5 @@ public class DateUtils { private DateUtils() { } + }
Change to using a timer to invalidate the date rather than calling nanoTime each request
undertow-io_undertow
train
426f30a9620f3a3a3f75f9e3f663c3348218ce85
diff --git a/lib/query.js b/lib/query.js index <HASH>..<HASH> 100644 --- a/lib/query.js +++ b/lib/query.js @@ -12,6 +12,9 @@ var Query = function(config) { //set or used until a rowDescription message comes in this.rowDescription = null; this.callback = config.callback; + this._fieldNames = []; + this._fieldConverters = []; + this._result = new Result(); EventEmitter.call(this); }; @@ -27,41 +30,69 @@ var noParse = function(val) { return val; }; -//creates datarow metatdata from the supplied -//data row information -var buildDataRowMetadata = function(msg, converters, names) { +//associates row metadata from the supplied +//message with this query object +//metadata used when parsing row results +p.handleRowDescription = function(msg) { + this._fieldNames = []; + this._fieldConverters = []; var len = msg.fields.length; for(var i = 0; i < len; i++) { var field = msg.fields[i]; var dataTypeId = field.dataTypeID; - names[i] = field.name; + this._fieldNames[i] = field.name; switch(dataTypeId) { case 20: case 21: case 23: case 26: - converters[i] = parseInt; + this._fieldConverters[i] = parseInt; break; case 1700: case 700: case 701: - converters[i] = parseFloat; + this._fieldConverters[i] = parseFloat; break; case 16: - converters[i] = function(val) { + this._fieldConverters[i] = function(val) { return val === 't'; }; break; case 1114: case 1184: - converters[i] = dateParser; + this._fieldConverters[i] = dateParser; break; default: - converters[i] = dataTypeParsers[dataTypeId] || noParse; + this._fieldConverters[i] = dataTypeParsers[dataTypeId] || noParse; break; } }; -} +}; + +p.handleDataRow = function(msg) { + var self = this; + var row = {}; + for(var i = 0; i < msg.fields.length; i++) { + var rawValue = msg.fields[i]; + if(rawValue === null) { + //leave null values alone + row[self._fieldNames[i]] = null; + } else { + //convert value to javascript + row[self._fieldNames[i]] = self._fieldConverters[i](rawValue); + } + } + self.emit('row', row); + + //if there is a callback collect rows + if(self.callback) { + self._result.addRow(row); + } +}; + +p.handleCommandComplete = function(msg) { + this._result.addCommandComplete(msg); +}; p.submit = function(connection) { var self = this; @@ -71,30 +102,12 @@ p.submit = function(connection) { connection.query(this.text); } - var converters = []; - var names = []; - var handleRowDescription = function(msg) { - buildDataRowMetadata(msg, converters, names); - }; - - var result = new Result(); - - var handleDatarow = function(msg) { - var row = {}; - for(var i = 0; i < msg.fields.length; i++) { - var rawValue = msg.fields[i]; - row[names[i]] = rawValue === null ? null : converters[i](rawValue); - } - self.emit('row', row); - - //if there is a callback collect rows + var onReadyForQuery = function() { + removeListeners(); if(self.callback) { - result.addRow(row); + self.callback(null, self._result); } - }; - - var onCommandComplete = function(msg) { - result.addCommandComplete(msg); + self.emit('end', self._result); }; var onError = function(err) { @@ -108,25 +121,21 @@ p.submit = function(connection) { self.emit('end'); }; - var onReadyForQuery = function() { - removeListeners(); - if(self.callback) { - self.callback(null, result); - } - self.emit('end', result); - }; + var onRowDescription = this.handleRowDescription.bind(this); + var onDataRow = this.handleDataRow.bind(this); + var onCommandComplete = this.handleCommandComplete.bind(this); var removeListeners = function() { //remove all listeners - connection.removeListener('rowDescription', handleRowDescription); - connection.removeListener('dataRow', handleDatarow); + connection.removeListener('rowDescription', onRowDescription); + connection.removeListener('dataRow', onDataRow); connection.removeListener('readyForQuery', onReadyForQuery); connection.removeListener('commandComplete', onCommandComplete); connection.removeListener('error', onError); }; - connection.on('rowDescription', handleRowDescription); - connection.on('dataRow', handleDatarow); + connection.on('rowDescription', onRowDescription); + connection.on('dataRow', onDataRow); connection.on('readyForQuery', onReadyForQuery); connection.on('commandComplete', onCommandComplete); connection.on('error', onError); @@ -185,7 +194,6 @@ p.prepare = function(connection) { }; connection.on('portalSuspended', getRows); - connection.on('commandComplete', onCommandComplete); connection.on('error', onCommandComplete); };
started making listeners non-closure based
brianc_node-postgres
train
340017153e4ebea134bba5bd7cfb33600617e924
diff --git a/keanu-python/tests/test_gradient_optimization.py b/keanu-python/tests/test_gradient_optimization.py index <HASH>..<HASH> 100644 --- a/keanu-python/tests/test_gradient_optimization.py +++ b/keanu-python/tests/test_gradient_optimization.py @@ -22,7 +22,7 @@ def test_gradient_op_bayes_net(model): def test_gradient_op_vertex(model): gradient_optimizer = kn.GradientOptimizer(model.temperature) - assert len(gradient_optimizer.net.getLatentVertices()) == 1 + assert gradient_optimizer.net.getLatentVertices().size() == 1 def test_gradient_op_throws_with_invalid_net_param(): @@ -56,4 +56,4 @@ def test_thermometers_max_likelihood_gradient(model): assert logProb < 0. temperature = model.temperature.getValue().scalar() - assert 20.995 < temperature < 21.005 \ No newline at end of file + assert 20.995 < temperature < 21.005 diff --git a/keanu-python/tests/test_non_gradient_optimization.py b/keanu-python/tests/test_non_gradient_optimization.py index <HASH>..<HASH> 100644 --- a/keanu-python/tests/test_non_gradient_optimization.py +++ b/keanu-python/tests/test_non_gradient_optimization.py @@ -24,7 +24,7 @@ def test_non_gradient_op_bayes_net(model): def test_non_gradient_op_vertex(model): non_gradient_optimizer = kn.NonGradientOptimizer(model.a) - assert len(non_gradient_optimizer.net.getLatentVertices()) == 2 + assert non_gradient_optimizer.net.getLatentVertices().size() == 2 def test_non_gradient_op_throws_with_invalid_net_param():
Use size instead of len on Java lists.
improbable-research_keanu
train
7d8e12dfb3d92049c496c6388972326425b34dec
diff --git a/test/vector-test.js b/test/vector-test.js index <HASH>..<HASH> 100644 --- a/test/vector-test.js +++ b/test/vector-test.js @@ -605,6 +605,24 @@ describe("vector", function () { [(7*4)+(8*5)+(9*6)]]); assertVectorsExactlyEqual(r, expected); }); + it("should multiply [m,n] * [n,1] with m > n", function () { + let v1 = new Vector( + [[1,2,3], + [4,5,6], + [7,8,9], + [1,2,3]]); + let v2 = new Vector([4,5,6]).transpose(); + let r = doBoth( + () => Vector.matrixMultiply(v1, v2), + () => v1.matrixMultiply(v2), + assertVectorsExactlyEqual); + let expected = new Vector( + [[(1*4)+(2*5)+(3*6)], + [(4*4)+(5*5)+(6*6)], + [(7*4)+(8*5)+(9*6)], + [(1*4)+(2*5)+(3*6)]]); + assertVectorsExactlyEqual(r, expected); + }); it("should multiply [n,n] * [n,n]", function () { let v1 = new Vector( [[1,2,3], diff --git a/vector.js b/vector.js index <HASH>..<HASH> 100644 --- a/vector.js +++ b/vector.js @@ -288,12 +288,12 @@ function checkMatrixMultiplyDimensions(s1, s2){ //a=b=c=n, d=1 //b=c=n, a=d=1 //a=d=n, b=c=1 + // + // [4,3]*[3,1] this is OK! + // a=4, b=3, c=3, d=1 let a = s1[0];let b = s1[1];let c = s2[0];let d = s2[1]; // Fail if a != d (unless d is 1 and a = b) or b != c if(b !== c) throw new Error(`Matrix size mismatch: ${s1} * ${s2}`); - if(a !== d){ - if(a !== b || d !== 1) throw new Error(`Matrix size mismatch: ${s1} * ${s2}`); - } } function getStringRec(v1){
Fix size check for matrix multiplication.
benmosheron_ben-loves-vectors
train
b30fe7de05afcb8a3675c79314bb2fabf4d7782c
diff --git a/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeComparator.java b/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeComparator.java index <HASH>..<HASH> 100644 --- a/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeComparator.java +++ b/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeComparator.java @@ -22,6 +22,7 @@ */ package org.arakhne.afc.attrs.attr; +import java.io.Serializable; import java.util.Comparator; @@ -34,9 +35,11 @@ import java.util.Comparator; * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ -public class AttributeComparator implements Comparator<Attribute> { +public class AttributeComparator implements Comparator<Attribute>, Serializable { - /** + private static final long serialVersionUID = -5930539797174658160L; + + /** * Compares its two arguments for order. Returns a negative integer, * zero, or a positive integer as the first argument is less than, equal * to, or greater than the second.<p> diff --git a/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeNameComparator.java b/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeNameComparator.java index <HASH>..<HASH> 100644 --- a/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeNameComparator.java +++ b/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeNameComparator.java @@ -22,6 +22,7 @@ */ package org.arakhne.afc.attrs.attr; +import java.io.Serializable; import java.util.Comparator; @@ -34,7 +35,9 @@ import java.util.Comparator; * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ -public class AttributeNameComparator implements Comparator<Attribute> { +public class AttributeNameComparator implements Comparator<Attribute>, Serializable { + + private static final long serialVersionUID = -2416416144079568908L; /** {@inheritDoc} */ diff --git a/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeValueComparator.java b/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeValueComparator.java index <HASH>..<HASH> 100644 --- a/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeValueComparator.java +++ b/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeValueComparator.java @@ -22,6 +22,7 @@ */ package org.arakhne.afc.attrs.attr; +import java.io.Serializable; import java.util.Comparator; @@ -34,9 +35,11 @@ import java.util.Comparator; * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ -public class AttributeValueComparator implements Comparator<AttributeValue> { +public class AttributeValueComparator implements Comparator<AttributeValue>, Serializable { - /** + private static final long serialVersionUID = 3633022581453456195L; + + /** * Compares its two arguments for order. Returns a negative integer, * zero, or a positive integer as the first argument is less than, equal * to, or greater than the second.<p>
Add the missed dependencies in the maven tool module.
gallandarakhneorg_afc
train
1ac0f18a91bfccff7b809c23cf64ab2520d59d8f
diff --git a/languagetool-core/src/main/java/org/languagetool/tagging/disambiguation/rules/DisambiguationPatternRuleReplacer.java b/languagetool-core/src/main/java/org/languagetool/tagging/disambiguation/rules/DisambiguationPatternRuleReplacer.java index <HASH>..<HASH> 100644 --- a/languagetool-core/src/main/java/org/languagetool/tagging/disambiguation/rules/DisambiguationPatternRuleReplacer.java +++ b/languagetool-core/src/main/java/org/languagetool/tagging/disambiguation/rules/DisambiguationPatternRuleReplacer.java @@ -202,7 +202,7 @@ class DisambiguationPatternRuleReplacer extends AbstractPatternRulePerformer { null, Match.CaseConversion.NONE, false, false, Match.IncludeRange.NONE); - MatchState matchState = tmpMatchToken.createState(rule.getLanguage().getSynthesizer(), whTokens[fromPos]); + MatchState matchState = tmpMatchToken.createState(rule.getLanguage().getSynthesizer(), whTokens[position]); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position] .getHistoricalAnnotations();
corrected the token that is passed when creating a new MatchState
languagetool-org_languagetool
train
9e5f12f8b4cdb7e1b0c39f0f9e6fc5678454cbf7
diff --git a/command/helpers_test.go b/command/helpers_test.go index <HASH>..<HASH> 100644 --- a/command/helpers_test.go +++ b/command/helpers_test.go @@ -312,8 +312,9 @@ func TestPrettyTimeDiff(t *testing.T) { {-20460 * time.Hour, "2y4mo ago"}, } for _, tc := range test_cases { - t2 := time.Now().Add(tc.d) - out := prettyTimeDiff(t2, time.Now()) + now := time.Now() + t2 := now.Add(tc.d) + out := prettyTimeDiff(t2, now) if out != tc.exp { t.Fatalf("expected :%v but got :%v", tc.exp, out) }
Declare time.Now once to prevent flakiness
hashicorp_nomad
train
c3130ce81159d227ea13b56c7db23fb9bbd41cbf
diff --git a/core/common/src/main/java/alluxio/cli/CommandUtils.java b/core/common/src/main/java/alluxio/cli/CommandUtils.java index <HASH>..<HASH> 100644 --- a/core/common/src/main/java/alluxio/cli/CommandUtils.java +++ b/core/common/src/main/java/alluxio/cli/CommandUtils.java @@ -13,7 +13,6 @@ package alluxio.cli; import alluxio.util.CommonUtils; -import com.google.common.base.Throwables; import org.reflections.Reflections; import java.lang.reflect.Modifier; @@ -50,7 +49,7 @@ public final class CommandUtils { try { cmd = CommonUtils.createNewClassInstance(cls, classArgs, objectArgs); } catch (Exception e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } commandsMap.put(cmd.getCommandName(), cmd); }
Deprecate Throwables.propagate with RuntimeException in CommandUtils.java
Alluxio_alluxio
train
ad234f225f7ccd79114cba997bc2d318b1f0b90c
diff --git a/moto/batch/models.py b/moto/batch/models.py index <HASH>..<HASH> 100644 --- a/moto/batch/models.py +++ b/moto/batch/models.py @@ -815,8 +815,10 @@ class BatchBackend(BaseBackend): raise InvalidParameterValueException( "computeResources must contain {0}".format(param) ) - - if self.iam_backend.get_role_by_arn(cr["instanceRole"]) is None: + for profile in self.iam_backend.get_instance_profiles(): + if profile.arn == cr["instanceRole"]: + break + else: raise InvalidParameterValueException( "could not find instanceRole {0}".format(cr["instanceRole"]) )
Batch: computeResources.instanceRole is an instance profile It's not an IAM role (the API parameter name in Batch is a misnomer). Validation by matching against known role ARNs will always fail. Scan the known instance profile ARNs instead.
spulec_moto
train
3fdc01e477bf61480ef07ec4639a87eb3c827e44
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboards_controller.rb b/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboards_controller.rb index <HASH>..<HASH> 100644 --- a/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboards_controller.rb +++ b/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboards_controller.rb @@ -76,7 +76,7 @@ class DashboardsController < ApplicationController if @dashboard.editable_by?(current_user) render :partial => 'edit_form', :resource => params[:resource] else - redirect_to :action => 'index', :resource => params[:resource] + redirect_to :action => 'index', :resource => params[:resource], :status => 401 end end @@ -91,8 +91,7 @@ class DashboardsController < ApplicationController render :partial => 'dashboards/edit_form', :status => 400, :resource => params[:resource] end else - # TODO - notify error ? - render :text => @dashboard.id.to_s, :resource => params[:resource], :status => 200 + render :text => @dashboard.id.to_s, :resource => params[:resource], :status => 401 end end
SONAR-<I> Return proper response codes on unauthorized operation
SonarSource_sonarqube
train
f63bfc6b51ac5ae2eb0eda200d22d8181e875733
diff --git a/service_configuration_lib/__init__.py b/service_configuration_lib/__init__.py index <HASH>..<HASH> 100644 --- a/service_configuration_lib/__init__.py +++ b/service_configuration_lib/__init__.py @@ -141,12 +141,19 @@ def services_deployed_on(hostname, service_configuration=None): running_services = services_that_run_on(hostname, service_configuration) # Deployed services are a superset of running ones deployed_services = running_services + for service in service_configuration: - if 'deployed_to' in service_configuration[service] and \ - service_configuration[service]['deployed_to'] and \ - hostname in service_configuration[service]['deployed_to'] and \ - service not in running_services : + if ( + 'deployed_to' in service_configuration[service] and + service_configuration[service]['deployed_to'] and + ( + service_configuration[service]['deployed_to'] is True or + hostname in service_configuration[service]['deployed_to'] + ) and + service not in running_services + ): deployed_services.append(service) + return deployed_services def services_needing_puppet_help_here(): diff --git a/tests/test_service_configuration_lib.py b/tests/test_service_configuration_lib.py index <HASH>..<HASH> 100755 --- a/tests/test_service_configuration_lib.py +++ b/tests/test_service_configuration_lib.py @@ -39,7 +39,16 @@ class ServiceConfigurationLibTestCase(T.TestCase): }, 'needs_puppet_help': True, 'ssl': True, - 'vip': 'fakevip3'} + 'vip': 'fakevip3', + }, + 'fake_service4': { 'deployed_to': True, + 'runs_on': [], + 'needs_puppet_help': True, + }, + 'fake_service5': { 'deployed_to': [], + 'runs_on': [], + 'needs_puppet_help': True, + }, } def test_generate_service_info_should_have_all_keys(self): @@ -98,14 +107,14 @@ class ServiceConfigurationLibTestCase(T.TestCase): T.assert_equal(expected, actual) def test_services_deployed_to_should_return_deployed_and_running_services(self): - expected = ['fake_service1', 'fake_service2', 'fake_service3'] + expected = ['fake_service1', 'fake_service2', 'fake_service3', 'fake_service4'] fake_hostname = 'fake_hostname3' fake_service_configuration = self.fake_service_configuration actual = service_configuration_lib.services_deployed_on(fake_hostname, fake_service_configuration) T.assert_equal(expected, actual) def test_services_needing_puppet_help_on_should_properly_read_configuration(self): - expected = [ 'fake_service3' ] + expected = [ 'fake_service3', 'fake_service4' ] fake_hostname = 'fake_hostname4' fake_service_configuration = self.fake_service_configuration actual = service_configuration_lib.services_needing_puppet_help_on(fake_hostname, fake_service_configuration)
Make it so that deployed_to: True causes a service to be deployed everywhere
Yelp_service_configuration_lib
train
634f4479ff12654870dc3416c872dd092d449a20
diff --git a/karma.saucelabs.conf.js b/karma.saucelabs.conf.js index <HASH>..<HASH> 100644 --- a/karma.saucelabs.conf.js +++ b/karma.saucelabs.conf.js @@ -1,6 +1,16 @@ 'use strict' var customLaunchers = { + win10chrome: { + base: 'SauceLabs', + browserName: 'chrome', + platform: 'Windows 10' + }, + win10firefox: { + base: 'SauceLabs', + browserName: 'firefox', + platform: 'Windows 10' + }, osxSafari: { base: 'SauceLabs', browserName: 'safari', @@ -10,6 +20,16 @@ var customLaunchers = { base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 12.1.4' + }, + win10edge: { + base: 'SauceLabs', + browserName: 'MicrosoftEdge', + platform: 'Windows 10' + }, + win10ie11: { + base: 'SauceLabs', + browserName: 'internet explorer', + platform: 'Windows 10' } } diff --git a/karma.saucelabs.ie.conf.js b/karma.saucelabs.ie.conf.js index <HASH>..<HASH> 100644 --- a/karma.saucelabs.ie.conf.js +++ b/karma.saucelabs.ie.conf.js @@ -1,17 +1,11 @@ 'use strict' var customLaunchers = { - win7ie8: { + win10ie11: { base: 'SauceLabs', browserName: 'internet explorer', - platform: 'Windows XP', - version: '8.0' - }, - win7ie7: { - base: 'SauceLabs', - browserName: 'internet explorer', - platform: 'Windows XP', - version: '7.0' + platform: 'Windows 10', + version: '11.0' } }
Moving to available browsers in saucelabs
holidayextras_barometer
train
0130e9c194735be7514f1d420e7fdba595e21d4d
diff --git a/lib/utils/format_utils.js b/lib/utils/format_utils.js index <HASH>..<HASH> 100644 --- a/lib/utils/format_utils.js +++ b/lib/utils/format_utils.js @@ -19,7 +19,13 @@ function formatComment(comment) { return parts[0]; } return parts.reduce(function(previousValue, currentValue) { - return previousValue.concat(currentValue.trim().replace(/[*]*\s*/, '')); + // newlines in the middle of the comment should stay to achieve: + // multiline comments entered by user drive unchanged from JDL studio to generated domain class + var delimiter = ''; + if (previousValue !== '') { + delimiter = '\n'; + } + return previousValue.concat(delimiter, currentValue.trim().replace(/[*]*\s*/, '')); }, ''); } diff --git a/test/spec/parser/entity_parser_test.js b/test/spec/parser/entity_parser_test.js index <HASH>..<HASH> 100644 --- a/test/spec/parser/entity_parser_test.js +++ b/test/spec/parser/entity_parser_test.js @@ -56,7 +56,7 @@ describe('::convert', function () { expect(content.Department.relationships[1].javadoc).to.eq('A relationship'); expect(content.Department.fields.length).to.eq(2); expect(content.Department.entityTableName).to.eq('department'); - expect(content.Employee.javadoc).to.eq('The Employee entity.'); + expect(content.Employee.javadoc).to.eq('The Employee entity.\nSecond line in javadoc.'); expect(content.Employee.pagination).to.eq('infinite-scroll'); expect(content.Employee.relationships[3].javadoc).to.eq('Another side of the same relationship'); expect(content.Job.relationships[0].otherEntityRelationshipName).to.eq('job'); diff --git a/test/spec/utils/format_utils_test.js b/test/spec/utils/format_utils_test.js index <HASH>..<HASH> 100644 --- a/test/spec/utils/format_utils_test.js +++ b/test/spec/utils/format_utils_test.js @@ -47,9 +47,9 @@ describe('FormatUtils', function() { var multiLineComment1 = '\n* <p>first line of comment</p><br/>\n*<p>second line</p>\n'; var multiLineComment2 = '*** <p>first line of comment</p><br/>\n* *<p>second line</p>\n\n'; var multiLineComment3 = '\n * abcde\n * fghij\n * nothing\n'; - var expectedResult1 = '<p>first line of comment</p><br/><p>second line</p>'; - var expectedResult2 = '<p>first line of comment</p><br/>*<p>second line</p>'; - var expectedResult3 = 'abcdefghijnothing'; + var expectedResult1 = '<p>first line of comment</p><br/>\n<p>second line</p>'; + var expectedResult2 = '<p>first line of comment</p><br/>\n*<p>second line</p>'; + var expectedResult3 = 'abcde\nfghij\nnothing'; describe(buildTestTitle(multiLineComment1), function() { it('returns ' + buildTestTitle(expectedResult1), function() { diff --git a/test/test_files/complex_jdl.jdl b/test/test_files/complex_jdl.jdl index <HASH>..<HASH> 100644 --- a/test/test_files/complex_jdl.jdl +++ b/test/test_files/complex_jdl.jdl @@ -30,6 +30,7 @@ entity Job { /** * The Employee entity. + * Second line in javadoc. */ entity Employee { employeeId Long,
drive multiline javadoc unchanged from JDL Studio to generated domain class this change is tested with PR jhipster/generator-jhipster#<I> advisable is merge this PR after jhipster/generator-jhipster#<I> is merged fix jhipster/jhipster-core#<I>
jhipster_jhipster-core
train
56b2e1ae7ae2335f7292d740a3004901fae7293f
diff --git a/src/Composer/Installer.php b/src/Composer/Installer.php index <HASH>..<HASH> 100644 --- a/src/Composer/Installer.php +++ b/src/Composer/Installer.php @@ -35,6 +35,7 @@ use Composer\Installer\NoopInstaller; use Composer\Installer\SuggestedPackagesReporter; use Composer\IO\IOInterface; use Composer\Package\AliasPackage; +use Composer\Package\RootAliasPackage; use Composer\Package\BasePackage; use Composer\Package\CompletePackage; use Composer\Package\Link; @@ -779,6 +780,9 @@ class Installer $request = new Request($lockedRepository); $request->fixPackage($rootPackage, false); + if ($rootPackage instanceof RootAliasPackage) { + $request->fixPackage($rootPackage->getAliasOf(), false); + } $fixedPackages = $platformRepo->getPackages(); if ($this->additionalFixedRepository) {
Allow installing an aliased root package
composer_composer
train
3bbc312ec1cd35b5c8c00d78353cc0fdfe8bddfd
diff --git a/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/Util.java b/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/Util.java index <HASH>..<HASH> 100644 --- a/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/Util.java +++ b/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/Util.java @@ -62,7 +62,7 @@ public final class Util { public static String translateClassification(final NerClassification nerClas, final NerClassification previous) { if (nerClas == null) return NOTHING; - // If there is a previous classificationfrom a different phrase of the same type, then indicate a new + // If there is a previous classification from a different phrase of the same type, then indicate a new // classification using 'B-' prefix, otherwise it is the same phrase and we use the regular 'I-' prefix. final String prefix = previous != null && previous.phraseStartIndex != nerClas.phraseStartIndex @@ -79,7 +79,7 @@ public final class Util { case UNKNOWN: return prefix + "MISC"; - // DATE and anything else new we do should return nothing found, since CoNLL only do the 4 types above + // DATE and any other new classes we add should return nothing found, since CoNLL only do the 4 types above case DATE: default: return NOTHING; diff --git a/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/cmdline/Main.java b/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/cmdline/Main.java index <HASH>..<HASH> 100644 --- a/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/cmdline/Main.java +++ b/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/cmdline/Main.java @@ -43,6 +43,12 @@ public final class Main { private Main() {} + /** + * Parse the CoNLL 2003 test data into sentences, use NICTA t3as NER to analyse the text, and print out the results + * so that they can be checked by the 'conlleval' tool. See here for more info: + * + * http://www.cnts.ua.ac.be/conll2003/ner/ + */ @SuppressWarnings("MethodNamesDifferingOnlyByCase") public static void main(final String[] args) throws IOException { final Options opts = getOptions(args); @@ -51,22 +57,26 @@ public final class Main { try (final ConllReader r = new ConllReader(opts.file.get(0))) { while (r.hasNext()) { - System.out.println("-DOCSTART- -X- O O O"); - System.out.println(); + // each section in the test results data starts with a DOCSTART + System.out.println("-DOCSTART- -X- O O O\n"); final Collection<Sentence> sentences = r.next(); + for (final Sentence conllSentence : sentences) { final NerResultSet nerResultSet = nea.process(conllSentence.sentence); final Map<Integer, NerClassification> phraseMap = Util.positionClassificationMap(nerResultSet); + ConllToken previousToken = null; - for (int i = 0; i < conllSentence.tokens.size(); i++) { - final ConllToken conllToken = conllSentence.tokens.get(i); + for (final ConllToken conllToken : conllSentence.tokens) { final NerClassification nerClas = phraseMap.get(conllToken.startIndex); final NerClassification previousClas = previousToken == null ? null : phraseMap.get(previousToken.startIndex); final String clas = Util.translateClassification(nerClas, previousClas); + + // print out the token, the test annotations, and our classification of the token System.out.printf("%s %s %s\n", conllToken.token, conllToken.classifiers, clas); previousToken = conllToken; } + // finish each sentence with a newline System.out.println(); } }
Added some comments to the code.
NICTA_nicta-ner
train
fbe27e61d41a145226dd246b9bcc0b7d8be7f3cb
diff --git a/commands/system/download.js b/commands/system/download.js index <HASH>..<HASH> 100644 --- a/commands/system/download.js +++ b/commands/system/download.js @@ -1,57 +1,76 @@ const request = require("superagent"); const vm = require("vm"); -var fs = require("fs"); +var fs = require("fs-extra"); exports.run = (client, msg, [url]) => { request.get(url, (err, res) => { if (err) console.log(err); + // Load Command Data + var mod = { + exports: {} + }; + try { + vm.runInNewContext(res.text, { module: mod, exports: mod.exports }, {timeout: 500}); + } catch (e) { + msg.reply(`URL command not valid: ${e}`); + return; + } + + let name = mod.exports.help.name; + let description = mod.exports.help.description; + + if (client.commands.has(name)) { + msg.reply(`The command \`${name}\` already exists in the bot!`); + return; + } + + msg.channel.sendMessage(`Are you sure you want to load the following command into your bot? +\`\`\`asciidoc +=== NAME === +${name} + +=== DESCRIPTION === +${description} +\`\`\``); + const collector = msg.channel.createCollector(m => m.author === msg.author, { - time: 10000 - }); - msg.channel.sendMessage("Are you sure you want to add the following command to your bot?").then(() => { - msg.channel.sendCode("js", res.text); + time: 5000 }); + collector.on("message", m => { - if (m.content === "no") collector.stop("aborted"); - if (m.content === "yes") collector.stop("success"); + if (m.content.toLowerCase() === "no") collector.stop("aborted"); + if (m.content.toLowerCase() === "yes") collector.stop("success"); }); + collector.on("end", (collected, reason) => { - if (reason === "time") return msg.channel.sendMessage("Timed out: Maybe you should review the code before trying to add it?"); - if (reason === "aborted") return msg.channel.sendMessage("Canceled: The script **has not** been added."); + if (reason === "time") return msg.channel.sendMessage(":timer: 5s timeout. Can you read a bit faster?"); + if (reason === "aborted") return msg.channel.sendMessage(":no_mobile_phones: Load Aborted. Command not installed."); if (reason === "success") { - msg.channel.sendMessage("Adding to Commands...") - .then((m) => { - var mod = { - exports: {} - }; - try { - vm.runInNewContext(res.text, { module: mod, exports: mod.exports }, {}); - } catch (e) { - m.edit(`Command not valid: ${e}`); - return; - } - let name = mod.exports.help.name; - let description = mod.exports.help.description; - let dir = client.clientBaseDir + "commands/downloaded/"; - client.funcs.log(`New Command: ${name} / ${description}`); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir); + msg.channel.sendMessage(":inbox_tray: `Loading Command...`").then(m => { + let category = mod.exports.help.category ? mod.exports.help.category : "Downloaded"; + let dir = require("path").resolve(`${client.clientBaseDir}/commands/${category}/`); + client.funcs.log(dir); + m.edit(`:inbox_tray: \`Loading Command into ${dir}/${name}.js...\``); + + fs.ensureDir(dir, err => { + if (err) { + fs.mkDirSync(dir); } - fs.writeFile(`${dir}${name}.js`, res.text, (err) => { + fs.writeFile(`${dir}/${name}.js`, res.text, (err) => { if(err) console.error(err); - client.funcs.loadNewCommand(client, client.clientBaseDir + "commands/downloaded/" + `${name}.js`) + let relativePath = require("path").relative(client.clientBasePath, dir); + client.funcs.loadNewCommand(client, `${relativePath}/${name}.js`) .then(() => { - m.edit(`Successfully Loaded: ${name}`); + m.edit(`:inbox_tray: Successfully Loaded: ${name}`); }) .catch(e => { - m.edit(`Command load failed: ${name}\n\`\`\`${e.stack}\`\`\``); + m.edit(`:no_mobile_phones: Command load failed: ${name}\n\`\`\`${e.stack}\`\`\``); + fs.unlink(`${dir}/${name}.js`); }); }); - }) - .catch(e => { - console.error(e); }); + }); } }); });
Fix Download Command Using new paths. Downloaded commands go in client.
dirigeants_komada
train
3fdc481a5eba4a8059d2dd7945d4e9e1d5b1d1c2
diff --git a/lib/codemirror.js b/lib/codemirror.js index <HASH>..<HASH> 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -4767,11 +4767,11 @@ window.CodeMirror = (function() { if (extend) extendSelection(this, pos); else setSelection(this, pos, pos); }), - setSelection: docOperation(function(anchor, head) { - setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor)); + setSelection: docOperation(function(anchor, head, bias) { + setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), bias); }), - extendSelection: docOperation(function(from, to) { - extendSelection(this, clipPos(this, from), to && clipPos(this, to)); + extendSelection: docOperation(function(from, to, bias) { + extendSelection(this, clipPos(this, from), to && clipPos(this, to), bias); }), getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);},
Add (undocumented, not yet final) extra argument to setSelection and extendSelection Issue #<I>
codemirror_CodeMirror
train
7c81513dac23aa65f723ced72f266b234922c3a9
diff --git a/validator/file.php b/validator/file.php index <HASH>..<HASH> 100644 --- a/validator/file.php +++ b/validator/file.php @@ -210,6 +210,7 @@ class file } else { + // @todo: stylesheet.css have yet to be fixed for 3.1 $this->messages->push('debug', $this->user->lang('FILE_NOT_VALIDATED', $origin_file)); } } diff --git a/validator/key.php b/validator/key.php index <HASH>..<HASH> 100644 --- a/validator/key.php +++ b/validator/key.php @@ -174,36 +174,34 @@ class key { $this->validate_dateformats($file, $key, $against_language, $validate_language); } - else if ($key === 'datetime') + else if ( + $key === 'datetime' || + $key === 'timezones' || + $key === 'tokens' || + $key === 'report_reasons' || + $key === 'PM_ACTION' || + $key === 'PM_CHECK' || + $key === 'PM_RULE' + ) { - #$this->validate_dateformats($file, $key, $against_language, $validate_language); - } - else if ($key === 'timezones') - { - #$this->validate_dateformats($file, $key, $against_language, $validate_language); - } - else if ($key === 'tokens') - { - #$this->validate_array_key($file, $key, $against_language, $validate_language); - } - else if ($key === 'report_reasons') - { - #$this->validate_array_key($file, $key, $against_language, $validate_language); - } - else if ($key === 'PM_ACTION') - { - #$this->validate_array_key($file, $key, $against_language, $validate_language); + $this->validate_array_key($file, $key, $against_language, $validate_language); } - else if ($key === 'PM_CHECK') + // ACL array in 3.0, removed in 3.1 + else if ($this->phpbb_version === '3.0' && strpos($key, 'acl_') === 0) { - #$this->validate_array_key($file, $key, $against_language, $validate_language); + $this->validate_acl($file, $key, $against_language, $validate_language); } - else if ($key === 'PM_RULE') + // Some special arrays in 3.0, removed in 3.1 + else if ($this->phpbb_version === '3.0' && ( + $key === 'permission_cat' || + $key === 'permission_type' || + $key === 'tz' || + $key === 'tz_zones')) { - #$this->validate_array_key($file, $key, $against_language, $validate_language); + $this->validate_array_key($file, $key, $against_language, $validate_language); } - // Fix for 3.1 - Plurals are normal there... - else if ($key === 'NUM_POSTS_IN_QUEUE' || $key === 'USER_LAST_REMINDED') + // Some special plurals in 3.0 + else if ($this->phpbb_version === '3.0' && ($key === 'NUM_POSTS_IN_QUEUE' || $key === 'USER_LAST_REMINDED')) { $this->validate_array_key($file, $key, $against_language, $validate_language); } @@ -227,13 +225,24 @@ class key { $this->validate_array_key($file, $key, $against_language, $validate_language); } - else if (isset($key_types['integer'])) + else if ($this->phpbb_version !== '3.0' && isset($key_types['integer'])) { - // Plurals?! + // @todo: Plurals have yet to be fixed for 3.1 $this->messages->push('debug', $this->user->lang('LANG_ARRAY_UNSUPPORTED', $file, $key)); $this->validate_array_key($file, $key, $against_language, $validate_language); return; } + else if ($this->phpbb_version === '3.0' && isset($key_types['integer'])) + { + // For 3.0 this should not happen + $this->messages->push('debug', $this->user->lang('LANG_ARRAY_UNSUPPORTED', $file, $key)); + return; + } + else + { + $this->messages->push('debug', $this->user->lang('LANG_ARRAY_MIXED', $file, $key, implode(', ', array_keys($key_types)))); + return; + } } else {
Add validation of <I> into <I>
phpbb_phpbb-translation-validator
train
587f013159eaa31ebd70dc52a990081231c2af59
diff --git a/public/js/omega.js b/public/js/omega.js index <HASH>..<HASH> 100644 --- a/public/js/omega.js +++ b/public/js/omega.js @@ -139,7 +139,8 @@ var OmegaIssueTracker = {}; }); this.socket.on('issue prioritized', function (updater, id, props) { - that.handleMessage(updater + ' marked ' + id + ' as critical.'); + var maybeNot = props.critical ? '' : ' not'; + that.handleMessage(updater + ' marked ' + id + ' as' + maybeNot + ' critical.'); that.refreshIssue(id, props); }); }; diff --git a/server.js b/server.js index <HASH>..<HASH> 100644 --- a/server.js +++ b/server.js @@ -84,9 +84,9 @@ io.sockets.on('connection', function(socket) { }); socket.on('prioritize issue', function(id) { - issues[id-1].critical = true; + issues[id-1].critical = !issues[id-1].critical; issueDb.write(issues); - io.sockets.emit('issue prioritized', socket.nickname, id, {critical: true}); + io.sockets.emit('issue prioritized', socket.nickname, id, {critical: issues[id-1].critical}); }); socket.on('reset issues', function() { diff --git a/tests/omega-spec.js b/tests/omega-spec.js index <HASH>..<HASH> 100644 --- a/tests/omega-spec.js +++ b/tests/omega-spec.js @@ -1,3 +1,18 @@ +var sock = { + on: function () {}, + emit: function () {} +}; +var messages = {}; +var name = {}; +var message = {}; +var form = { + submit: function () {} +}; + +var tracker = new OmegaIssueTracker.Tracker(messages, name, message, form, sock); +tracker.user("elbow"); +tracker.loggedIn(true); + describe("omega", function () { describe("displays html links", function () { @@ -31,26 +46,20 @@ describe("omega", function () { }); }); - describe("parses arguments", function () { + describe("prioritizes issues", function () { + it ("can prioritize", function () { + message.val = function () { return ":star 5"; }; - it("can assign multi-digit issues", function () { - var sock = { - on: function () {}, - emit: function () {} - }, - messages = {}, - name = {}, - message = { - val: function () { return ":assign 50"; } - }, - form = { - submit: function () {} - }; + spyOn(tracker, 'prioritizeIssue'); + tracker.handleInput(); + expect(tracker.prioritizeIssue).toHaveBeenCalledWith(5); + }); + }); - var tracker = new OmegaIssueTracker.Tracker(messages, name, message, form, sock); - tracker.user("elbow"); - tracker.loggedIn(true); - + describe("parses arguments", function () { + it("can assign multi-digit issues", function () { + message.val = function () { return ":assign 50"; }; + spyOn(tracker, 'assignIssue'); tracker.handleInput(); expect(tracker.assignIssue).toHaveBeenCalledWith(50, undefined);
Can now toggle issues as critical. Added a quick test... need node tests.
wachunga_omega
train
f5f4e316b81016ca005f74af4c25e52850171013
diff --git a/test/helpers/utils.go b/test/helpers/utils.go index <HASH>..<HASH> 100644 --- a/test/helpers/utils.go +++ b/test/helpers/utils.go @@ -338,3 +338,21 @@ func ManifestGet(manifestFilename string) string { } return filepath.Join(BasePath, "k8sT", "manifests", manifestFilename) } + +// WriteOrAppendToFile writes data to a file named by filename. +// If the file does not exist, WriteFile creates it with permissions perm; +// otherwise WriteFile appends the data to the file +func WriteOrAppendToFile(filename string, data []byte, perm os.FileMode) error { + f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, perm) + if err != nil { + return err + } + n, err := f.Write(data) + if err == nil && n < len(data) { + err = io.ErrShortWrite + } + if err1 := f.Close(); err == nil { + err = err1 + } + return err +}
Test: added WriteOrAppendToFile helper function Added `WriteOrAppendToFile` helper function to be able to append data to any other file.
cilium_cilium
train
3be1b53532d234122009b07ef570828a746c3c40
diff --git a/src/species/toucher.js b/src/species/toucher.js index <HASH>..<HASH> 100644 --- a/src/species/toucher.js +++ b/src/species/toucher.js @@ -190,21 +190,25 @@ define(function(require) { event = document.createEvent('Event'); event.initEvent('touch' + type, true, true); - // just like the mobile browsers, on touchend we dont include a touchlist - if(type != 'end') { - touches.forEach(function(touch, i) { - touchlist.push({ - pageX: touch.x, - pageY: touch.y, - clientX: touch.x, - clientY: touch.y, - target: element, - identifier: i - }) - }); - } + touchlist.identifiedTouch = touchlist.item = function(index) { + return this[index] || {} + }; + + touches.forEach(function(touch, i) { + touchlist.push({ + pageX: touch.x, + pageY: touch.y, + clientX: touch.x, + clientY: touch.y, + screenX: touch.x, + screenY: touch.y, + target: element, + identifier: i + }) + }); - event.touches = touchlist; + event.touches = (type == 'end') ? [] : touchlist; + event.targetTouches = (type == 'end') ? [] : touchlist; event.changedTouches = touchlist; element.dispatchEvent(event);
added touch methods/properies, as described by w3c
marmelab_gremlins.js
train
8c8ec7d516128bdabc5ec7891b9a4154af77bb6d
diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index <HASH>..<HASH> 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -2,6 +2,7 @@ * Fixed error where default session class does not exist. * Fixed human_name for the model to use its own human name and not delegate to the associated model. Translation should be under authlogic.models.user_session (or whatever the name of your session is). +* Fixed human_attribute_name to use Authlogic keys for translation instead of ActiveRecord: authlogic.attributes.user_session.login. == 2.0.2 released 2009-3-24 diff --git a/lib/authlogic/i18n.rb b/lib/authlogic/i18n.rb index <HASH>..<HASH> 100644 --- a/lib/authlogic/i18n.rb +++ b/lib/authlogic/i18n.rb @@ -39,6 +39,14 @@ module Authlogic # not_confirmed: Your account is not confirmed # not_approved: Your account is not approved # no_authentication_details: You did not provide any details for authentication. + # models: + # user_session: UserSession (or whatever name you are using) + # attributes: + # user_session: (or whatever name you are using) + # login: login + # email: email + # passwword: password + # remember_me: remember me class I18n class << self # All message translation is passed to this method. The first argument is the key for the message. The second is options, see the rails I18n library for a list of options used. @@ -49,6 +57,7 @@ module Authlogic options[:default] end end + alias_method :translate, :t end end end \ No newline at end of file diff --git a/lib/authlogic/session/active_record_trickery.rb b/lib/authlogic/session/active_record_trickery.rb index <HASH>..<HASH> 100644 --- a/lib/authlogic/session/active_record_trickery.rb +++ b/lib/authlogic/session/active_record_trickery.rb @@ -11,8 +11,10 @@ module Authlogic end module ClassMethods - def human_attribute_name(*args) - klass.human_attribute_name(*args) + def human_attribute_name(attribute_key_name, options = {}) + options[:count] ||= 1 + options[:default] ||= attribute_key_name.humanize + I18n.t("attributes.#{name.underscore}.#{attribute_key_name}", options) end def human_name(*args)
Fixed human_attribute_name to use Authlogic keys for translation instead of ActiveRecord
binarylogic_authlogic
train
7d2bbb6ca4d5c3edd576def3f042e6c39549bb57
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -102,12 +102,12 @@ class TestController < ActionController::Base end def conditional_hello_with_expires_in_with_public_with_more_keys - expires_in 1.minute, :public => true, 'max-stale' => 5.hours + expires_in 1.minute, :public => true, 's-maxage' => 5.hours render :action => 'hello_world' end def conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax - expires_in 1.minute, :public => true, :private => nil, 'max-stale' => 5.hours + expires_in 1.minute, :public => true, :private => nil, 's-maxage' => 5.hours render :action => 'hello_world' end @@ -1421,12 +1421,12 @@ class ExpiresInRenderTest < ActionController::TestCase def test_expires_in_header_with_additional_headers get :conditional_hello_with_expires_in_with_public_with_more_keys - assert_equal "max-age=60, public, max-stale=18000", @response.headers["Cache-Control"] + assert_equal "max-age=60, public, s-maxage=18000", @response.headers["Cache-Control"] end def test_expires_in_old_syntax get :conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax - assert_equal "max-age=60, public, max-stale=18000", @response.headers["Cache-Control"] + assert_equal "max-age=60, public, s-maxage=18000", @response.headers["Cache-Control"] end def test_expires_now
Removed max-stale from the tests since it's a request cache-control directive, just for clarity sake.
rails_rails
train
5e827318a1dd6a55969709b9e9609513905d450d
diff --git a/archive.go b/archive.go index <HASH>..<HASH> 100644 --- a/archive.go +++ b/archive.go @@ -226,8 +226,16 @@ func (v *volume) nextVolName() { func (v *volume) next() (*fileBlockHeader, error) { for { + var atEOF bool + h, err := v.fileBlockReader.next() - if err != errArchiveContinues { + switch err { + case errArchiveContinues: + case io.EOF: + // Read all of volume without finding an end block. The only way + // to tell if the archive continues is to try to open the next volume. + atEOF = true + default: return h, err } @@ -235,6 +243,10 @@ func (v *volume) next() (*fileBlockHeader, error) { v.nextVolName() v.f, err = os.Open(v.dir + v.file) // Open next volume file if err != nil { + if atEOF && os.IsNotExist(err) { + // volume not found so assume that the archive has ended + return nil, io.EOF + } return nil, err } v.num++
Allow multi volume files to not have end blocks. Some older multi volume files may not have end blocks. If there is no end block, just try and open the next volume. If it doesnt exist, assume the archive ends. If the next volume file is invalid and the archive really should have ended there will be errors.
nwaples_rardecode
train
df91466adc1c4a2bf01533b40a022a4bc0249c42
diff --git a/pypet/tests/unittests/utils_test.py b/pypet/tests/unittests/utils_test.py index <HASH>..<HASH> 100644 --- a/pypet/tests/unittests/utils_test.py +++ b/pypet/tests/unittests/utils_test.py @@ -3,7 +3,10 @@ __author__ = 'Robert Meyer' import time import sys import pickle -from collections import Set, Sequence, Mapping +try: + from collections import Set, Sequence, Mapping +except ImportError: + from collections.abc import Set, Sequence, Mapping import pandas as pd import numpy as np diff --git a/pypet/utils/comparisons.py b/pypet/utils/comparisons.py index <HASH>..<HASH> 100644 --- a/pypet/utils/comparisons.py +++ b/pypet/utils/comparisons.py @@ -2,7 +2,10 @@ __author__ = 'Robert Meyer' -from collections import Sequence, Mapping +try: + from collections import Sequence, Mapping +except ImportError: + from collections.abc import Sequence, Mapping import numpy as np import pandas as pd
fix(py<I>): correct collections related imports
SmokinCaterpillar_pypet
train
c48b7648a7ad7790a2dfc42a8b59a7f3cdeceb45
diff --git a/code/pages/ExtensibleSearchPage.php b/code/pages/ExtensibleSearchPage.php index <HASH>..<HASH> 100644 --- a/code/pages/ExtensibleSearchPage.php +++ b/code/pages/ExtensibleSearchPage.php @@ -687,7 +687,7 @@ class ExtensibleSearchPage_Controller extends Page_Controller { // Determine whether the search parameters have been passed through. if(!isset($data['Search'])) { - $data['Search'] = null; + $data['Search'] = ''; } if(!isset($data['SortBy'])) { $data['SortBy'] = $page->SortBy; @@ -695,8 +695,9 @@ class ExtensibleSearchPage_Controller extends Page_Controller { if(!isset($data['SortDirection'])) { $data['SortDirection'] = $page->SortDirection; } + $request = $this->getRequest(); if(!isset($form)) { - $this->getForm($this->getRequest()); + $this->getForm($request); } // Instantiate some default templates. @@ -755,7 +756,7 @@ class ExtensibleSearchPage_Controller extends Page_Controller { // The paginated list needs to be manipulated, as sorting and filtering is not possible otherwise. - $start = isset($_GET['start']) ? (int)$_GET['start'] : 0; + $start = $request->getVar('start') ? (int)$request->getVar('start') : 0; $_GET['start'] = 0; // Determine the full-text search results.
Cleaning up the extensible search page results definition.
nglasl_silverstripe-extensible-search
train
aa2c1dcee06b3aa5cbbf87574a0940c5a1cfbf2f
diff --git a/tests/test_ipuz.py b/tests/test_ipuz.py index <HASH>..<HASH> 100644 --- a/tests/test_ipuz.py +++ b/tests/test_ipuz.py @@ -456,7 +456,7 @@ class IPUZWriteTestCase(IPUZBaseTestCase): class IPUZRoundTripTestCase(IPUZBaseTestCase): - def test_first_ipuz_file(self): + def test_first_ipuz_file_with_json(self): with open("fixtures/first.ipuz") as f: data = f.read() @@ -464,3 +464,12 @@ class IPUZRoundTripTestCase(IPUZBaseTestCase): output_string = ipuz.write(output, json_only=True) second_output = ipuz.read(output_string) self.assertEqual(output, second_output) + + def test_first_ipuz_file_with_jsonp(self): + with open("fixtures/first.ipuz") as f: + data = f.read() + + output = ipuz.read(data) + output_string = ipuz.write(output) + second_output = ipuz.read(output_string) + self.assertEqual(output, second_output)
Added test case for JSONP round trip
svisser_ipuz
train
72c7bd2311594a896386b9a7789f709748e9d1cc
diff --git a/src/Properties/HigherOrderCollectionProxyPropertyExtension.php b/src/Properties/HigherOrderCollectionProxyPropertyExtension.php index <HASH>..<HASH> 100644 --- a/src/Properties/HigherOrderCollectionProxyPropertyExtension.php +++ b/src/Properties/HigherOrderCollectionProxyPropertyExtension.php @@ -12,7 +12,7 @@ use PHPStan\Reflection\PropertyReflection; use PHPStan\TrinaryLogic; use PHPStan\Type; -class HigherOrderCollectionProxyPropertyExtension implements PropertiesClassReflectionExtension +final class HigherOrderCollectionProxyPropertyExtension implements PropertiesClassReflectionExtension { public function hasProperty(ClassReflection $classReflection, string $propertyName): bool { @@ -35,23 +35,22 @@ class HigherOrderCollectionProxyPropertyExtension implements PropertiesClassRefl $returnType = HigherOrderCollectionProxyHelper::determineReturnType($methodType->getValue(), $modelType, $propertyType); - return new class($modelType, $returnType) implements PropertyReflection { - /** @var Type\ObjectType */ - private $modelType; + return new class($classReflection, $returnType) implements PropertyReflection { + /** @var ClassReflection */ + private $classReflection; /** @var Type\Type */ private $returnType; - public function __construct(Type\ObjectType $modelType, Type\Type $returnType) + public function __construct(ClassReflection $classReflection, Type\Type $returnType) { - $this->modelType = $modelType; + $this->classReflection = $classReflection; $this->returnType = $returnType; } public function getDeclaringClass(): \PHPStan\Reflection\ClassReflection { - /** @phpstan-ignore-next-line */ - return $this->modelType->getClassReflection(); + return $this->classReflection; } public function isStatic(): bool
fix: use original class reflection to avoid type issues
nunomaduro_larastan
train
5a5baec719ea1fc55da62779dd19e1e9a749e033
diff --git a/insteonplm/plm.py b/insteonplm/plm.py index <HASH>..<HASH> 100644 --- a/insteonplm/plm.py +++ b/insteonplm/plm.py @@ -58,6 +58,7 @@ class PLM(asyncio.Protocol, DeviceBase): self._write_transport_lock = asyncio.Lock(loop=self._loop) self._message_callbacks = MessageCallback() self._saved_device_info = [] + self._cb_load_all_link_db_done = [] self._address = None self._cat = None @@ -163,6 +164,12 @@ class PLM(asyncio.Protocol, DeviceBase): """Register a callback for when a matching new device is seen.""" self.devices.add_device_callback(callback) + def add_all_link_done_callback(self, callback): + """Register a callback to be invoked when a all link database is done.""" + self.log.debug('Added new callback %s ', + callback) + self._cb_load_all_link_db_done.append(callback) + def poll_devices(self): """Request status updates from each device.""" for addr in self.devices: @@ -376,7 +383,10 @@ class PLM(asyncio.Protocol, DeviceBase): self._handle_get_next_all_link_record_nak, None) else: - self._save_device_info() + self._save_device_info() + while len(self._cb_load_all_link_db_done) > 0: + callback = self._cb_load_all_link_db_done.pop() + callback() self._loop.call_soon(self.poll_devices) self.log.debug('Ending _handle_get_next_all_link_record_nak')
Update for all-link complete callback
nugget_python-insteonplm
train
219aaa06eb16a77de61d1e675761aa6b0a0e95b7
diff --git a/lib/cuporter/node/html.rb b/lib/cuporter/node/html.rb index <HASH>..<HASH> 100644 --- a/lib/cuporter/node/html.rb +++ b/lib/cuporter/node/html.rb @@ -6,7 +6,7 @@ module Cuporter class Parent < NodeBase def build - super('div') + super(node_name) self << ul end @@ -15,7 +15,7 @@ module Cuporter end def add_child(node) - if node['class'] == 'name' + if node['class'] == 'cuke_name' super(node) else ul << node @@ -48,7 +48,16 @@ module Cuporter end def file_name - file.split(/\//).last + path = delete('file').value.split(File::SEPARATOR) + name = html_node(:span) + name.content = "/#{path.pop}" + parent = html_node(:em) + parent.content = "/#{path.pop}" + div = html_node('div', :class => 'file') + div.children = path.join('/') + div << parent + div << name + div end # sort on: file path, name, substring of name after any ':' @@ -67,6 +76,13 @@ module Cuporter super(other) end + def build + super do + self << file_name + self << ul + end + end + end # The set of examples in a scenario outline @@ -75,10 +91,11 @@ module Cuporter HTML_TAG = :li def build - super('div') - table << thead - table << tbody - self << table + super('div') do + table << thead + table << tbody + self << table + end end def table @@ -127,6 +144,7 @@ module Cuporter HTML_TAG = :li include Leaf include Tagged + end class Example < NodeBase diff --git a/lib/cuporter/node/node_base.rb b/lib/cuporter/node/node_base.rb index <HASH>..<HASH> 100644 --- a/lib/cuporter/node/node_base.rb +++ b/lib/cuporter/node/node_base.rb @@ -121,15 +121,30 @@ module Cuporter NodeBase = Nokogiri::XML::Node module Html + def html_node(node_name, attributes = {}) + n = NodeBase.new(node_name.to_s, document) + attributes.each do |attr, value| + value = value.is_a?(Array) ? value.join(",") : value.to_s.strip + n[attr.to_s] = value unless value.empty? + end + n + end + + def cuke_name + unless @cuke_name + if self['cuke_name'] + @cuke_name = html_node('div', 'class' => 'cuke_name') + @cuke_name.children = delete('cuke_name').value + @cuke_name['alt'] = delete('tags').value if self['tags'] + end + end + @cuke_name + end + # this gets mixed in to NodeBase/Nokogiri::XML::Node def build(node_name = 'span') - #self.content = parse("<div class='cuke_name'>#{delete('cuke_name').value}</div>") if self['cuke_name'] - if self['cuke_name'] - cuke_name = NodeBase.new(node_name, document) - cuke_name['class'] = 'name' - cuke_name.children = delete('cuke_name').value - self.children = cuke_name - end + self.children = cuke_name if cuke_name + yield if block_given? end end end @@ -144,9 +159,9 @@ module Cuporter end def copy_attrs(node, attributes) - attributes.each do | attr, value | + attributes.each do |attr, value| value = value.is_a?(Array) ? value.join(",") : value.to_s.strip - node[attr.to_s] = value unless value.empty? + node[attr.to_s] = value unless value.empty? end node end
pretty doc structure for feature view, tag view broken
twcamper_cuporter
train
5b36e4f908ed1f39773777ed5e22447f5d65029c
diff --git a/lib/collection/property.js b/lib/collection/property.js index <HASH>..<HASH> 100644 --- a/lib/collection/property.js +++ b/lib/collection/property.js @@ -103,13 +103,14 @@ _.extend(Property.prototype, /** @lends Property.prototype */ { * @private * @draft * - * @param {VariableList=} [variables] - One can specifically provide a VariableList for doing the substitution. In + * @param {?VariableList=} [variables] - One can specifically provide a VariableList for doing the substitution. In * the event one is not provided, the variables are taken from this object or one from the parent tree. + * @param {Array<Object>} overrides - additional objects to lookup for variable values * @returns {Object|undefined} * * @throws {Error} If `variables` cannot be resolved up the parent chain. */ - toObjectResolved: function (variables) { + toObjectResolved: function (variables, overrides) { var variableSourceObj = this; // We see if variables can be found in this object itself. @@ -124,7 +125,7 @@ _.extend(Property.prototype, /** @lends Property.prototype */ { throw Error('Unable to resolve variables. Require a List type property for variable auto resolution.'); } - return variables ? variables.substitute(this.toJSON()) : undefined; + return variables ? variables.substitute(this.toJSON(), overrides) : undefined; } });
Updated Property.toObjectResolved to accept and forward an additional `overrides` parameter to the substitution function of variable replacement
postmanlabs_postman-collection
train
b5f7ab4c6ab48eeeecd01640a057bb092597c0bb
diff --git a/gocode.go b/gocode.go index <HASH>..<HASH> 100644 --- a/gocode.go +++ b/gocode.go @@ -16,6 +16,7 @@ var ( server = flag.Bool("s", false, "run a server instead of a client") format = flag.String("f", "nice", "output format (vim | emacs | nice)") input = flag.String("in", "", "use this file instead of stdin input") + debug = flag.Bool("debug", false, "turn on additional debug messages") ) type Formatter interface { @@ -140,6 +141,9 @@ func serverFunc() int { rpcremote := new(RPCRemote) rpc.Register(rpcremote) + if *debug { + daemon.ctx.debuglog = os.Stdout + } daemon.acr.Loop() return 0 } diff --git a/gocodelib.go b/gocodelib.go index <HASH>..<HASH> 100644 --- a/gocodelib.go +++ b/gocodelib.go @@ -508,9 +508,7 @@ func (self *AutoCompleteContext) processPackageData(filename, uniquename, pkgnam file.addPackageAlias(pkgname, uniquename) } - if self.debuglog != nil { - fmt.Fprintf(self.debuglog, "parsing package '%s'...\n", pkgname) - } + self.debugLog("parsing package '%s'...\n", pkgname) s = s[i+1:] internalPackages := make(map[string]*bytes.Buffer) @@ -550,15 +548,15 @@ func (self *AutoCompleteContext) processPackageData(filename, uniquename, pkgnam if err != nil { panic(fmt.Sprintf("failure in:\n%s\n%s\n", value, err.String())) } else { - if self.debuglog != nil { - fmt.Fprintf(self.debuglog, "\t%s: OK (ndecls: %d)\n", key, len(decls)) - } f := new(ast.File) // fake file f.Decls = decls ast.FileExports(f) localname := "" if key == uniquename { localname = self.genForeignPackageAlias(pkgname, uniquename) + self.debugLog("\t!%s: OK (ndecls: %d)\n", key, len(decls)) + } else { + self.debugLog("\t%s: OK (ndecls: %d)\n", key, len(decls)) } self.addToPackage(key, localname, f.Decls) } @@ -1221,6 +1219,12 @@ func NewAutoCompleteContext() *AutoCompleteContext { return self } +func (self *AutoCompleteContext) debugLog(f string, a ...interface{}) { + if self.debuglog != nil { + fmt.Fprintf(self.debuglog, f, a) + } +} + func (self *AutoCompleteContext) addToPackage(globalname, localname string, decls []ast.Decl) { if self.m[globalname] == nil { self.m[globalname] = NewDecl(localname, DECL_MODULE, self.current)
Reorganize debug output mechanism.
nsf_gocode
train
11af585101a2af98891b47101c045a457f2ac1dc
diff --git a/core/core.js b/core/core.js index <HASH>..<HASH> 100644 --- a/core/core.js +++ b/core/core.js @@ -1698,7 +1698,7 @@ exports._bootstrap = function(self, name) { break; case 'core.Image': self.element.remove(); - self.element = $('<img/>'); + self.element = $('<div/>'); self.parent.element.append(self.element); self.element.on('load', self._onLoad.bind(self)); self.element.on('error', self._onError.bind(self));
Image is not img anymore (fix annoying image borders).
pureqml_qmlcore
train
aa8c33270b7304fb1a5310d205c22ad9fdd88645
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,14 @@ Have a look at the [examples](example/). ### Basic Authentication Flow ```php -$provider = new \Alcohol\OAuth2\Client\Provider\EveOnline([ +$provider = new Alcohol\OAuth2\Client\Provider\EveOnline([ 'clientId' => '{client-id}', 'clientSecret' => '{client-secret}', 'redirectUri' => 'https://example.com/callback-url', + // the following are optional and displayed here with their default values + 'urlAuthorize' => 'https://login.eveonline.com/oauth/authorize', + 'urlAccessToken' => 'https://login.eveonline.com/oauth/token', + 'urlResourceOwnerDetails' => 'https://login.eveonline.com/oauth/verify', ]); // If we don't have an authorization code then get one @@ -68,7 +72,7 @@ if (!isset($_GET['code'])) { var_export($resourceOwner->toArray()); - } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { + } catch (League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { // Failed to get the access token or user details. exit($e->getMessage()); @@ -88,7 +92,7 @@ $request = $provider->getAuthenticatedRequest( $accessToken ); -$client = new \GuzzleHttp\Client(); +$client = new GuzzleHttp\Client(); $response = $client->send($request); print $response->getBody(); @@ -112,7 +116,7 @@ if ($existingAccessToken->hasExpired()) { ## Testing -> Sorry, I got lazy. Just don't break the example. +> Sorry, I got lazy. Just don't break the examples. ## Contributing diff --git a/example/basic.php b/example/basic.php index <HASH>..<HASH> 100644 --- a/example/basic.php +++ b/example/basic.php @@ -15,6 +15,10 @@ $provider = new Alcohol\OAuth2\Client\Provider\EveOnline([ 'clientId' => '{client-id}', 'clientSecret' => '{client-secret}', 'redirectUri' => 'https://example.com/callback-url', + // the following are optional and displayed here with their default values + 'urlAuthorize' => 'https://login.eveonline.com/oauth/authorize', + 'urlAccessToken' => 'https://login.eveonline.com/oauth/token', + 'urlResourceOwnerDetails' => 'https://login.eveonline.com/oauth/verify', ]); // If we don't have an authorization code then get one diff --git a/example/scoped.php b/example/scoped.php index <HASH>..<HASH> 100644 --- a/example/scoped.php +++ b/example/scoped.php @@ -15,6 +15,10 @@ $provider = new Alcohol\OAuth2\Client\Provider\EveOnline([ 'clientId' => '{client-id}', 'clientSecret' => '{client-secret}', 'redirectUri' => 'https://example.com/callback-url', + // the following are optional and displayed here with their default values + 'urlAuthorize' => 'https://login.eveonline.com/oauth/authorize', + 'urlAccessToken' => 'https://login.eveonline.com/oauth/token', + 'urlResourceOwnerDetails' => 'https://login.eveonline.com/oauth/verify', ]); // If we don't have an authorization code then get one diff --git a/src/EveOnline.php b/src/EveOnline.php index <HASH>..<HASH> 100644 --- a/src/EveOnline.php +++ b/src/EveOnline.php @@ -20,11 +20,25 @@ class EveOnline extends AbstractProvider use BearerAuthorizationTrait; /** - * Whether or not to issue calls against the test server (Sisi). + * The base URL for authorizing a client. * - * @var bool + * @var string */ - protected $useSisi = false; + protected $urlAuthorize = 'https://login.eveonline.com/oauth/authorize'; + + /** + * The base URL for requesting an access token. + * + * @var string + */ + protected $urlAccessToken = 'https://login.eveonline.com/oauth/token'; + + /** + * The URL for requesting the resource owner's details. + * + * @var string + */ + protected $urlResourceOwnerDetails = 'https://login.eveonline.com/oauth/verify'; /** * Get authorization url to begin OAuth flow. @@ -35,7 +49,7 @@ class EveOnline extends AbstractProvider */ public function getBaseAuthorizationUrl(): string { - return sprintf('%s/oauth/authorize', $this->getDomain()); + return $this->urlAuthorize; } /** @@ -49,7 +63,7 @@ class EveOnline extends AbstractProvider */ public function getBaseAccessTokenUrl(array $params): string { - return sprintf('%s/oauth/token', $this->getDomain()); + return $this->urlAccessToken; } /** @@ -63,21 +77,7 @@ class EveOnline extends AbstractProvider */ public function getResourceOwnerDetailsUrl(AccessToken $token): string { - return sprintf('%s/oauth/verify', $this->getDomain()); - } - - /** - * Get the base domain to use in each request (test or production). - * - * @return string - */ - protected function getDomain(): string - { - if ($this->useSisi) { - return 'https://sisilogin.testeveonline.com'; - } - - return 'https://login.eveonline.com'; + return $this->urlResourceOwnerDetails; } /**
adjust readme, examples and configuration of provider
alcohol_oauth2-eveonline
train
d23c4ab462930f410ebdd4a4dfa007b1fbe36944
diff --git a/source/application/controllers/admin/article_stock.php b/source/application/controllers/admin/article_stock.php index <HASH>..<HASH> 100644 --- a/source/application/controllers/admin/article_stock.php +++ b/source/application/controllers/admin/article_stock.php @@ -16,7 +16,7 @@ * along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com - * @copyright (C) OXID eSales AG 2003-2015 + * @copyright (C) OXID eSales AG 2003-2016 * @version OXID eShop CE */ @@ -62,6 +62,10 @@ class Article_Stock extends oxAdminDetails $this->_aViewData["otherlang"][$id] = clone $oLang; } + if ($oArticle->isDerived()) { + $this->_aViewData['readonly'] = true; + } + // variant handling if ($oArticle->oxarticles__oxparentid->value) { $oParentArticle = oxNew("oxArticle"); @@ -99,10 +103,6 @@ class Article_Stock extends oxAdminDetails $soxId = $this->getEditObjectId(); $aParams = oxRegistry::getConfig()->getRequestParameter("editval"); - // shopid - $sShopID = oxRegistry::getSession()->getVariable("actshop"); - $aParams['oxarticles__oxshopid'] = $sShopID; - $oArticle = oxNew("oxArticle"); $oArticle->loadInLang($this->_iEditLang, $soxId); @@ -141,8 +141,7 @@ class Article_Stock extends oxAdminDetails $this->resetContentCache(); $sOxArtId = $this->getEditObjectId(); - - + $this->onArticleAmountPriceChange($sOxArtId); $aParams = oxRegistry::getConfig()->getRequestParameter("editval"); @@ -215,13 +214,15 @@ class Article_Stock extends oxAdminDetails */ public function updateprices() { - $aParams = oxRegistry::getConfig()->getRequestParameter("updateval"); if (is_array($aParams)) { foreach ($aParams as $soxId => $aStockParams) { $this->addprice($soxId, $aStockParams); } } + + $sOxArtId = $this->getEditObjectId(); + $this->onArticleAmountPriceChange($sOxArtId); } @@ -234,7 +235,19 @@ class Article_Stock extends oxAdminDetails $oDb = oxDb::getDb(); $sPriceId = $oDb->quote(oxRegistry::getConfig()->getRequestParameter("priceid")); - $sId = $oDb->quote($this->getEditObjectId()); + $articleId = $this->getEditObjectId(); + $sId = $oDb->quote($articleId); $oDb->execute("delete from oxprice2article where oxid = {$sPriceId} and oxartid = {$sId}"); + + $this->onArticleAmountPriceChange($articleId); + } + + /** + * Method is used to bind to article amount price change. + * + * @param string $articleId + */ + protected function onArticleAmountPriceChange($articleId) + { } } diff --git a/tests/unit/admin/articlestockTest.php b/tests/unit/admin/articlestockTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/admin/articlestockTest.php +++ b/tests/unit/admin/articlestockTest.php @@ -16,7 +16,7 @@ * along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com - * @copyright (C) OXID eSales AG 2003-2015 + * @copyright (C) OXID eSales AG 2003-2016 * @version OXID eShop CE */ @@ -246,7 +246,7 @@ class Unit_Admin_ArticleStockTest extends OxidTestCase $sOXID = "_testId"; //expected shop id - $sShopId = "oxbaseshop"; + $sShopId = $this->getTestConfig()->getShopEdition() == 'EE' ? '2' : 'oxbaseshop'; $oConfig = $this->getMock("oxConfig", array("getShopId")); $oConfig->expects($this->any())->method('getShopId')->will($this->returnValue($sShopId));
ESDEV-<I> Remove edition based code from article_stock
OXID-eSales_oxideshop_ce
train
1c26fe427df0422467dfa8de73929feb1eba2890
diff --git a/core/src/main/java/org/infinispan/notifications/cachelistener/CacheNotifierImpl.java b/core/src/main/java/org/infinispan/notifications/cachelistener/CacheNotifierImpl.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/infinispan/notifications/cachelistener/CacheNotifierImpl.java +++ b/core/src/main/java/org/infinispan/notifications/cachelistener/CacheNotifierImpl.java @@ -68,7 +68,6 @@ import org.infinispan.filter.CacheFilters; import org.infinispan.filter.KeyFilter; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.locking.ClusteringDependentLogic; -import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; @@ -835,10 +834,15 @@ public final class CacheNotifierImpl<K, V> extends AbstractListenerImpl<Event<K, throw new UnsupportedOperationException("Cluster listeners cannot be used with Invalidation Caches!"); } else if (cacheMode.isDistributed() || cacheMode.isScattered()) { clusterListenerIDs.put(listener, generatedId); - EmbeddedCacheManager manager = cache.getCacheManager(); - Address ourAddress = manager.getAddress(); + RpcManager rpcManager = cache.getAdvancedCache().getRpcManager(); + Address ourAddress = null; + List<Address> members = null; + + if (rpcManager != null) { + ourAddress = rpcManager.getAddress(); + members = rpcManager.getMembers(); + } - List<Address> members = manager.getMembers(); // If we are the only member don't even worry about sending listeners if (members != null && members.size() > 1) { DistributedExecutionCompletionService decs = new DistributedExecutionCompletionService(distExecutorService); @@ -874,7 +878,7 @@ public final class CacheNotifierImpl<K, V> extends AbstractListenerImpl<Event<K, int extraCount = 0; // If anyone else joined since we sent these we have to send the listeners again, since they may have queried // before the other nodes got the new listener - List<Address> membersAfter = manager.getMembers(); + List<Address> membersAfter = rpcManager.getMembers(); //at this point, the rpcManager is never null. for (Address member : membersAfter) { if (!members.contains(member) && !member.equals(ourAddress)) { if (trace) {
ISPN-<I> CacheNotifier should use the cache member and not the view members
infinispan_infinispan
train
2bb3199da718be4e3150b5555bbf12364c3987be
diff --git a/src/core/vdom/patch.js b/src/core/vdom/patch.js index <HASH>..<HASH> 100644 --- a/src/core/vdom/patch.js +++ b/src/core/vdom/patch.js @@ -550,6 +550,9 @@ export function createPatchFunction (backend) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly) } else if (isDef(ch)) { + if (process.env.NODE_ENV !== 'production') { + checkDuplicateKeys(ch) + } if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '') addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue) } else if (isDef(oldCh)) { diff --git a/test/unit/modules/vdom/patch/children.spec.js b/test/unit/modules/vdom/patch/children.spec.js index <HASH>..<HASH> 100644 --- a/test/unit/modules/vdom/patch/children.spec.js +++ b/test/unit/modules/vdom/patch/children.spec.js @@ -530,4 +530,16 @@ describe('vdom patch: children', () => { patch(vnode2, vnode3) expect(`Duplicate keys detected: 'b'`).toHaveBeenWarned() }) + + it('should warn with duplicate keys: patchVnode with empty oldVnode', () => { + function makeNode (key) { + return new VNode('li', { key: key }) + } + + const vnode1 = new VNode('div') + const vnode2 = new VNode('div', undefined, ['1', '2', '3', '4', '4'].map(makeNode)) + + patch(vnode1, vnode2) + expect(`Duplicate keys detected: '4'`).toHaveBeenWarned() + }) })
polish: warn duplicate keys when patching children into empty node (#<I>) close #<I>
kaola-fed_megalo
train
ff4e72d20e901d0ae9e011328c0bae137d309f7e
diff --git a/azure-storage-blob/azure/storage/blob/_upload_chunking.py b/azure-storage-blob/azure/storage/blob/_upload_chunking.py index <HASH>..<HASH> 100644 --- a/azure-storage-blob/azure/storage/blob/_upload_chunking.py +++ b/azure-storage-blob/azure/storage/blob/_upload_chunking.py @@ -290,17 +290,12 @@ class _BlockBlobChunkUploader(_BlobChunkUploader): class _PageBlobChunkUploader(_BlobChunkUploader): - EMPTY_PAGE = bytearray(512) - def _is_chunk_empty(self, chunk_data): - # read until non-zero data is encountered + # read until non-zero byte is encountered # if reached the end without returning, then chunk_data is all 0's - data = BytesIO(chunk_data) - page = data.read(512) - while page != b'': - if page != self.EMPTY_PAGE: + for each_byte in chunk_data: + if each_byte != 0: return False - page = data.read(512) return True def _upload_chunk(self, chunk_start, chunk_data):
Minor improvement to page blob upload optimization
Azure_azure-storage-python
train
4f7cd5b8e4a7a585bef2f991de8c31ae2459daf3
diff --git a/libtelemetry/src/main/java/com/mapbox/android/telemetry/ChinaCertificatePins.java b/libtelemetry/src/main/java/com/mapbox/android/telemetry/ChinaCertificatePins.java index <HASH>..<HASH> 100644 --- a/libtelemetry/src/main/java/com/mapbox/android/telemetry/ChinaCertificatePins.java +++ b/libtelemetry/src/main/java/com/mapbox/android/telemetry/ChinaCertificatePins.java @@ -12,9 +12,20 @@ class ChinaCertificatePins { { put("events.mapbox.cn", new ArrayList<String>() { { + //old certificates add("sha256/gakY+fylqW6kp6piqnaQNLZFzT8HlhzP5lsGJk5WguE="); add("sha256/5kJvNEMw0KjrCAu7eXY5HZdvyCS13BbA0VJG1RSP91w="); add("sha256/r/mIkG3eEpVdm+u/ko/cwxzOMo1bk4TyHIlByibiA5E="); + + //new digicert certificates + add("sha256/3coVlMAEAYhOEJHgXwloiPDGaF+ZfxHZbVoK8AYYWVg="); + add("sha256/5kJvNEMw0KjrCAu7eXY5HZdvyCS13BbA0VJG1RSP91w="); + add("sha256/r/mIkG3eEpVdm+u/ko/cwxzOMo1bk4TyHIlByibiA5E="); + + //new GeoTrust Certs + add("sha256/+O+QJCmvoB/FkTd0/5FvmMSvFbMqjYU+Txrw1lyGkUQ="); + add("sha256/zUIraRNo+4JoAYA7ROeWjARtIoN4rIEbCpfCRQT6N6A="); + add("sha256/r/mIkG3eEpVdm+u/ko/cwxzOMo1bk4TyHIlByibiA5E="); } }); }
Add new China Certificate Hashes (#<I>) * New Digicert Hashes - generated new digicerts hashes * Geotrust certs - added new geotrust hashes
mapbox_mapbox-events-android
train
50cdbe7f917a06004120b0568ed1ab06737684dd
diff --git a/vendor/assets/javascripts/perspectives.js b/vendor/assets/javascripts/perspectives.js index <HASH>..<HASH> 100644 --- a/vendor/assets/javascripts/perspectives.js +++ b/vendor/assets/javascripts/perspectives.js @@ -42,21 +42,21 @@ }).attr('content') } - var renderPerspectivesResponse = function(href, container, json, status, xhr) { - var $container = $(container) + var renderPerspectivesResponse = function(options) { + var $container = $(options.container) console.time('perspectives rendering') var version = perspectivesVersion() || '' if (version.length && version !== xhr.getResponseHeader('X-Perspectives-Version')) { - locationReplace(href) + locationReplace(options.href) return false } - var $rendered = $(renderTemplateData(json)) + var $rendered = $(renderTemplateData(options.json)) $container.html($rendered) - $(document).trigger('perspectives:load', xhr) + $(document).trigger('perspectives:load', options.xhr) console.timeEnd('perspectives rendering') } @@ -68,20 +68,34 @@ var replaceContainer = $this.attr('data-perspectives-replace') ? $this.attr('data-perspectives-replace') : container $.getJSON(fetchHref, function(json, status, xhr) { - var args = Array.prototype.slice.call(arguments) - args.unshift(href, replaceContainer) + $this.trigger('perspectives:response', [renderPerspectivesResponse, { + json: json, + status: status, + xhr: xhr, + href: href, + container: replaceContainer + }]) - renderPerspectivesResponse.apply(this, args) window.history.pushState({container: container}, href, href) }) return false } + $(document).on('perspectives:response', function(e, defaultRender, options) { defaultRender(options) }) + $(window).on('popstate.perspectives', function(event) { var originalEvent = event.originalEvent if(originalEvent && originalEvent.state && originalEvent.state.container) { - $.getJSON(window.location.href, renderPerspectivesResponse.bind(null, window.location.href, originalEvent.state.container)) + $.getJSON(window.location.href, function(json, status, xhr) { + renderPerspectivesResponse({ + json: json, + status: status, + xhr: xhr, + href: window.location.href, + container: originalEvent.state.container + }) + }) } })
Prefer event delegation - Allow users to listen to response events on a link they want to listen to, and do whatever they want with the response data
Genius_perspectives
train
8c651d59a7cf9a335cb5afb44ee7b564be934b4d
diff --git a/docs/source/conf.py b/docs/source/conf.py index <HASH>..<HASH> 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -31,6 +31,9 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. +# namingpath = r'B:\write\code\git\naming' +# import sys +# sys.path.append(namingpath) extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', diff --git a/naming/base.py b/naming/base.py index <HASH>..<HASH> 100644 --- a/naming/base.py +++ b/naming/base.py @@ -18,6 +18,8 @@ def _field_property(field_name: str) -> property: return self._values.get(field_name) def setter(self, value): + if value and str(value) == self._values.get(field_name): + return new_name = self.get_name(**{field_name: value}) self.set_name(new_name) return property(getter, setter) @@ -124,6 +126,7 @@ class _BaseName(metaclass=_ABCName): :param name: The name to be set on this object. :raises NameError: If an invalid string is provided. + :returns: Reference to self. """ match = self.__regex.match(name) if not match: @@ -132,6 +135,7 @@ class _BaseName(metaclass=_ABCName): raise NameError(msg) self.__set_name(name) self.__values.update(match.groupdict()) + return self @property def _values(self) -> typing.Dict[str, str]: diff --git a/naming/tests/__init__.py b/naming/tests/__init__.py index <HASH>..<HASH> 100644 --- a/naming/tests/__init__.py +++ b/naming/tests/__init__.py @@ -29,6 +29,8 @@ class TestName(unittest.TestCase): n = Name() n.set_name('setname') self.assertEqual('setname', n.get_name()) + self.assertEqual(n, n.set_name('setname')) + self.assertTrue(isinstance(n.set_name('setname'), n.__class__)) class TestEasyName(unittest.TestCase): @@ -52,6 +54,8 @@ class TestEasyName(unittest.TestCase): pf = ProjectFile('this_is_my_base_name_2017_christianl_constant_iamlast.base.17.abc') self.assertEqual('this_is_my_base_name_2017_christianl_constant_iamlast', pf.nice_name) self.assertEqual('this_is_my_base_name_2017_christianl_constant_iamlast.base.17', pf.pipe_name) + # setting same fields should be returning early + pf.year = 2017 self.assertEqual('2017', pf.year) self.assertEqual('iamlast', pf.lastfield) self.assertEqual('abc', pf.extension) diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -12,5 +12,5 @@ setup( url='https://github.com/chrizzFTD/naming', download_url='https://github.com/chrizzFTD/naming/releases/tag/0.1.3', classifiers=['Programming Language :: Python :: 3.6'], - extras_require={'docs': ['sphinx_autodoc_typehints']} + extras_require={'docs': ['sphinx_autodoc_typehints', 'sphinx_rtd_theme']} )
dev - Set Name Optimized (#8) Added setting values optimisation, returning self reference on set_name method.
chrizzFTD_naming
train
e7451c455da449d023360d6dd9977f2697ffc3c9
diff --git a/src/Column/ResolvedColumnType.php b/src/Column/ResolvedColumnType.php index <HASH>..<HASH> 100644 --- a/src/Column/ResolvedColumnType.php +++ b/src/Column/ResolvedColumnType.php @@ -229,7 +229,7 @@ class ResolvedColumnType implements ResolvedColumnTypeInterface $values = []; - foreach ($column->getOption('field_mapping') as $field) { + foreach ($column->getOption('field_mapping') as $mappingName => $field) { // Ignore null and boolean as these fields-names are always illegal // CompoundColumnType sometimes has one key with a boolean value @@ -237,7 +237,7 @@ class ResolvedColumnType implements ResolvedColumnTypeInterface continue; } - $values[$field] = $dataMapper->getData($field, $object); + $values[is_int($mappingName) ? $field : $mappingName] = $dataMapper->getData($field, $object); } if ($useTransformers) { diff --git a/tests/Extension/Core/ColumnType/BaseTypeTest.php b/tests/Extension/Core/ColumnType/BaseTypeTest.php index <HASH>..<HASH> 100644 --- a/tests/Extension/Core/ColumnType/BaseTypeTest.php +++ b/tests/Extension/Core/ColumnType/BaseTypeTest.php @@ -17,7 +17,7 @@ abstract class BaseTypeTest extends ColumnTypeTestCase { public function testPassLabelToView() { - $column = $this->factory->createColumn('id', $this->getTestedType(), $this->datagrid, ['label' => 'My label', 'field_mapping' => ['key']]); + $column = $this->factory->createColumn('id', $this->getTestedType(), $this->datagrid, ['label' => 'My label', 'field_mapping' => ['id' => 'key']]); $object = new \stdClass(); $object->key = ' foo '; diff --git a/tests/Extension/Core/ColumnType/TextTypeTest.php b/tests/Extension/Core/ColumnType/TextTypeTest.php index <HASH>..<HASH> 100644 --- a/tests/Extension/Core/ColumnType/TextTypeTest.php +++ b/tests/Extension/Core/ColumnType/TextTypeTest.php @@ -41,7 +41,7 @@ class TextTypeTest extends BaseTypeTest $data = [1 => $object]; $options = [ - 'field_mapping' => ['key', 'key2'], + 'field_mapping' => ['foo' => 'key', 'key2'], 'value_format' => ' - %s - ', 'value_glue' => ',', ];
provide field_mapping values as assoc array
rollerworks-graveyard_datagrid
train
a7fce6d9176cf3662d153af54270f345eb0bec8d
diff --git a/examples/run_squad.py b/examples/run_squad.py index <HASH>..<HASH> 100644 --- a/examples/run_squad.py +++ b/examples/run_squad.py @@ -241,7 +241,10 @@ def evaluate(args, model, tokenizer, prefix=""): # Compute predictions output_prediction_file = os.path.join(args.output_dir, "predictions_{}.json".format(prefix)) output_nbest_file = os.path.join(args.output_dir, "nbest_predictions_{}.json".format(prefix)) - output_null_log_odds_file = os.path.join(args.output_dir, "null_odds_{}.json".format(prefix)) + if args.version_2_with_negative: + output_null_log_odds_file = os.path.join(args.output_dir, "null_odds_{}.json".format(prefix)) + else: + output_null_log_odds_file = None if args.model_type in ['xlnet', 'xlm']: # XLNet uses a more complex post-processing procedure
fix squad v1 error (na_prob_file should be None)
huggingface_pytorch-pretrained-BERT
train
4cb2e1e07be7ca308d624f459f96774e00493519
diff --git a/routing/dht/dht_test.go b/routing/dht/dht_test.go index <HASH>..<HASH> 100644 --- a/routing/dht/dht_test.go +++ b/routing/dht/dht_test.go @@ -208,7 +208,7 @@ func TestProvides(t *testing.T) { func TestLayeredGet(t *testing.T) { u.Debug = false - addrs,_,dhts := setupDHTS(4, t) + addrs, _, dhts := setupDHTS(4, t) _, err := dhts[0].Connect(addrs[1]) if err != nil { @@ -254,7 +254,7 @@ func TestLayeredGet(t *testing.T) { func TestFindPeer(t *testing.T) { u.Debug = false - addrs,peers,dhts := setupDHTS(4, t) + addrs, peers, dhts := setupDHTS(4, t) _, err := dhts[0].Connect(addrs[1]) if err != nil { diff --git a/routing/dht/ext_test.go b/routing/dht/ext_test.go index <HASH>..<HASH> 100644 --- a/routing/dht/ext_test.go +++ b/routing/dht/ext_test.go @@ -3,12 +3,13 @@ package dht import ( "testing" + "code.google.com/p/goprotobuf/proto" + peer "github.com/jbenet/go-ipfs/peer" - u "github.com/jbenet/go-ipfs/util" swarm "github.com/jbenet/go-ipfs/swarm" - //ma "github.com/jbenet/go-multiaddr" + u "github.com/jbenet/go-ipfs/util" + ma "github.com/jbenet/go-multiaddr" - "fmt" "time" ) @@ -36,7 +37,7 @@ func (f *fauxNet) Listen() error { for { select { case in := <-f.Chan.Outgoing: - for _,h := range f.handlers { + for _, h := range f.handlers { reply := h(in) if reply != nil { f.Chan.Incoming <- reply @@ -54,24 +55,69 @@ func (f *fauxNet) AddHandler(fn func(*swarm.Message) *swarm.Message) { } func (f *fauxNet) Send(mes *swarm.Message) { + f.Chan.Outgoing <- mes +} +func (f *fauxNet) GetChan() *swarm.Chan { + return f.Chan } -func TestGetFailure(t *testing.T) { +func (f *fauxNet) Connect(addr *ma.Multiaddr) (*peer.Peer, error) { + return nil, nil +} + +func TestGetFailures(t *testing.T) { fn := newFauxNet() fn.Listen() local := new(peer.Peer) - local.ID = peer.ID([]byte("test_peer")) + local.ID = peer.ID("test_peer") d := NewDHT(local, fn) + other := &peer.Peer{ID: peer.ID("other_peer")} + d.Start() - b, err := d.GetValue(u.Key("test"), time.Second) + d.Update(other) + + // This one should time out + _, err := d.GetValue(u.Key("test"), time.Millisecond*5) if err != nil { - t.Fatal(err) + nerr, ok := err.(*u.IpfsError) + if !ok { + t.Fatal("Got different error than we expected.") + } + if nerr.Inner != u.ErrTimeout { + t.Fatal("Got different error than we expected.") + } + } else { + t.Fatal("Did not get expected error!") } - fmt.Println(b) + fn.AddHandler(func(mes *swarm.Message) *swarm.Message { + pmes := new(PBDHTMessage) + err := proto.Unmarshal(mes.Data, pmes) + if err != nil { + t.Fatal(err) + } + + resp := DHTMessage{ + Type: pmes.GetType(), + Id: pmes.GetId(), + Response: true, + Success: false, + } + return swarm.NewMessage(mes.Peer, resp.ToProtobuf()) + }) + + // This one should fail with NotFound + _, err = d.GetValue(u.Key("test"), time.Millisecond*5) + if err != nil { + if err != u.ErrNotFound { + t.Fatal("Expected ErrNotFound, got: %s", err) + } + } else { + t.Fatal("expected error, got none.") + } }
add fauxNet to stand in for Swarm in tests to reproduce various network conditions
ipfs_go-ipfs
train
8a545a3534f1ac6ab335a9726058bc75811cd232
diff --git a/config/routes.rb b/config/routes.rb index <HASH>..<HASH> 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,7 +1,3 @@ Rails.application.routes.draw do - namespace :outpost do - resources :sessions, only: [:create, :destroy] - get 'login' => "sessions#new", as: :login - get 'logout' => "sessions#destroy", as: :logout - end + end diff --git a/spec/internal/config/routes.rb b/spec/internal/config/routes.rb index <HASH>..<HASH> 100644 --- a/spec/internal/config/routes.rb +++ b/spec/internal/config/routes.rb @@ -3,5 +3,8 @@ Rails.application.routes.draw do namespace :outpost do root to: 'home#index' + resources :sessions, only: [:create, :destroy] + get 'login' => "sessions#new", as: :login + get 'logout' => "sessions#destroy", as: :logout end end
Move routes out of outpost for now
SCPR_outpost
train
cb7198523333a7abf80babed78dfcbc929babf49
diff --git a/examples/simple.js b/examples/simple.js index <HASH>..<HASH> 100644 --- a/examples/simple.js +++ b/examples/simple.js @@ -3,8 +3,8 @@ var rna = require("drawrnajs"); var app = rna.vis; //initalize input boxes with example structure -document.getElementById('SEQ_BOX').value = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCARACAGCACGACACUAGCAGUCAGUGUCAGACUGCARACAGCACGACACUAGCAGUCAGUGUCAGACUGCARA"; -document.getElementById('DOTBR_BOX').value = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...))))).."; +document.getElementById('SEQ_BOX').value = "CGCUUCAUAUAAUCCUAAUGAUAUGGUUUGGGAGUUUCUACCAAGAGCCUUAAACUCUUGAUUAUGAAGUG"; +document.getElementById('DOTBR_BOX').value = "(((((((((...((((((.........))))))........((((((.......))))))..)))))))))"; //init colors $("#acolor").spectrum({ color: "#64F73F" }); $("#ccolor").spectrum({ color: "#FFB340" }); @@ -25,11 +25,11 @@ app({graph: struct, el: cy, doc: document, win: window}); var runButton = document.getElementById('PERFORM_VIS'); runButton.readOnly = true; -runButton.addEventListener('click', function(){ +runButton.addEventListener('click', function(){ document.getElementById('ALERT').value = ""; var input = rna.io.getInputSequences(); if(rna.io.checkConditions(input)){ struct = rna.t.transformDotBracket(input[0], input[1]); app({graph: struct, el: cy, doc: document, win: window}); } -}, false); \ No newline at end of file +}, false);
fixed bug in .getCoordinates
bene200_drawrnajs
train
a99f845c45d6702da4d3c0af61df2e52080c9257
diff --git a/internal/pkg/platform/platform_matcher_test.go b/internal/pkg/platform/platform_matcher_test.go index <HASH>..<HASH> 100644 --- a/internal/pkg/platform/platform_matcher_test.go +++ b/internal/pkg/platform/platform_matcher_test.go @@ -1,6 +1,7 @@ package platform import ( + "fmt" "testing" "github.com/containers/image/v5/types" @@ -8,29 +9,28 @@ import ( "github.com/stretchr/testify/assert" ) -func TestWantedPlatformsCompatibility(t *testing.T) { - ctx := &types.SystemContext{ - ArchitectureChoice: "arm", - OSChoice: "linux", - VariantChoice: "v6", +func TestWantedPlatforms(t *testing.T) { + for _, c := range []struct { + ctx types.SystemContext + expected []imgspecv1.Platform + }{ + { // ARM + types.SystemContext{ArchitectureChoice: "arm", OSChoice: "linux", VariantChoice: "v6"}, + []imgspecv1.Platform{ + {OS: "linux", Architecture: "arm", Variant: "v6"}, + {OS: "linux", Architecture: "arm", Variant: "v5"}, + }, + }, + { // Custom (completely unrecognized data) + types.SystemContext{ArchitectureChoice: "armel", OSChoice: "freeBSD", VariantChoice: "custom"}, + []imgspecv1.Platform{ + {OS: "freeBSD", Architecture: "armel", Variant: "custom"}, + }, + }, + } { + testName := fmt.Sprintf("%q/%q/%q", c.ctx.ArchitectureChoice, c.ctx.OSChoice, c.ctx.VariantChoice) + platforms, err := WantedPlatforms(&c.ctx) + assert.Nil(t, err, testName) + assert.Equal(t, c.expected, platforms, testName) } - platforms, err := WantedPlatforms(ctx) - assert.Nil(t, err) - assert.Equal(t, []imgspecv1.Platform{ - {OS: ctx.OSChoice, Architecture: ctx.ArchitectureChoice, Variant: "v6"}, - {OS: ctx.OSChoice, Architecture: ctx.ArchitectureChoice, Variant: "v5"}, - }, platforms) -} - -func TestWantedPlatformsCustom(t *testing.T) { - ctx := &types.SystemContext{ - ArchitectureChoice: "armel", - OSChoice: "freeBSD", - VariantChoice: "custom", - } - platforms, err := WantedPlatforms(ctx) - assert.Nil(t, err) - assert.Equal(t, []imgspecv1.Platform{ - {OS: ctx.OSChoice, Architecture: ctx.ArchitectureChoice, Variant: ctx.VariantChoice}, - }, platforms) }
Combine the two TestWantedPlatforms* tests ... and make them table-driven. Does not change the test contents.
containers_image
train
fba679410bd85b64313a3e93aec68992342876b1
diff --git a/test_reporter.py b/test_reporter.py index <HASH>..<HASH> 100644 --- a/test_reporter.py +++ b/test_reporter.py @@ -1,8 +1,14 @@ +import sys from mock import patch import moban.reporter as reporter -from StringIO import StringIO from nose.tools import eq_ +PY2 = sys.info[0] == 2 +if PY2: + from StringIO import StringIO +else: + from io import StringIO + def test_partial_run(): patcher = patch('sys.stdout', new_callable=StringIO)
:bug: fix python 3 problem with stringio
moremoban_moban-handlebars
train
1b4113843f328171e4884ca9dfbffebe04078246
diff --git a/meshcut.py b/meshcut.py index <HASH>..<HASH> 100644 --- a/meshcut.py +++ b/meshcut.py @@ -322,7 +322,6 @@ def merge_close_vertices(verts, faces, close_epsilon=1e-5): # Compute a mapping from old to new : for each input vert, store the index # of the new vert it will be merged into - close_epsilon = 1e-5 old2new = np.zeros(D.shape[0], dtype=np.int) # A mask indicating if a vertex has already been merged into another merged_verts = np.zeros(D.shape[0], dtype=np.bool)
Removed redefined close_epsilon
julienr_meshcut
train
1ef60fae643fddd4712c1db21aac135bcee0a75f
diff --git a/extensions/featured-header.php b/extensions/featured-header.php index <HASH>..<HASH> 100644 --- a/extensions/featured-header.php +++ b/extensions/featured-header.php @@ -16,7 +16,7 @@ * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * @package FeaturedHeader - * @version 0.1.0 - Alpha + * @version 0.1.0 * @author Justin Tadlock <[email protected]> * @copyright Copyright (c) 2012, Justin Tadlock * @link http://justintadlock.com
Featured Header <I>.
justintadlock_hybrid-core
train
2026dbc635c461daf62da09a3c588f61f3db2f5f
diff --git a/src/serve.js b/src/serve.js index <HASH>..<HASH> 100644 --- a/src/serve.js +++ b/src/serve.js @@ -13,7 +13,7 @@ program function serve(inputPath, options) { const Server = require('./services/Server'); - let server = new Server({watch: options.watch}); + let server = new Server({watch: options.watch, cwd: process.cwd()}); if (options.logging) { server.on('request', (req, err) => { if (err) { diff --git a/src/services/Server.js b/src/services/Server.js index <HASH>..<HASH> 100644 --- a/src/services/Server.js +++ b/src/services/Server.js @@ -1,5 +1,5 @@ const os = require('os'); -const {basename, join} = require('path'); +const {relative, join} = require('path'); const EventEmitter = require('events'); const {readJsonSync, existsSync, lstat} = require('fs-extra'); const ecstatic = require('ecstatic'); @@ -12,9 +12,10 @@ const MAX_PORT = 65535; module.exports = class Server extends EventEmitter { - constructor({watch = false} = {}) { + constructor({cwd, watch = false}) { super(); this._watch = watch; + this._cwd = cwd; } static get externalAddresses() { @@ -64,11 +65,11 @@ module.exports = class Server extends EventEmitter { _serveFile(appPath) { let servePackageJson = (req, res, next) => { if (req.url === '/package.json') { - return res.json({main: basename(appPath)}); + return res.json({main: relative(this._cwd, appPath)}); } next(); }; - return this._startServer(join(appPath, '..'), [servePackageJson]); + return this._startServer(this._cwd, [servePackageJson]); } _startServer(appPath, middlewares = []) { diff --git a/test/Server.test.js b/test/Server.test.js index <HASH>..<HASH> 100644 --- a/test/Server.test.js +++ b/test/Server.test.js @@ -1,4 +1,4 @@ -const {join, basename} = require('path'); +const {join, relative, basename} = require('path'); const {writeFileSync} = require('fs-extra'); const temp = require('temp').track(); const portscanner = require('portscanner'); @@ -13,8 +13,8 @@ describe('Server', function() { let server, path; beforeEach(function() { - server = new Server(); path = temp.mkdirSync('foo'); + server = new Server({cwd: path}); stub(proc, 'execSync'); stub(proc, 'exec'); }); @@ -82,7 +82,7 @@ describe('Server', function() { }); it('runs watch script when watch option given', function() { - server = new Server({watch: true}); + server = new Server({cwd: path, watch: true}); writeFileSync(join(path, 'package.json'), '{"main": "foo.js"}'); return server.serve(path) .then(() => { @@ -102,7 +102,7 @@ describe('Server', function() { it('uses next unused port', function() { writeFileSync(join(path, 'package.json'), '{"main": "foo.js"}'); - let server2 = new Server(); + let server2 = new Server({cwd: path}); return server.serve(path).then(() => { return server2.serve(path).then(() => { expect(server.port).to.be.ok; @@ -126,6 +126,7 @@ describe('Server', function() { it('delivers a synthetic package.json for a file', function() { let file = join(path, 'foo.js'); writeFileSync(file, 'content'); + server = new Server({cwd: path}); return server.serve(file) .then(() => fetch(`http://127.0.0.1:${server.port}/package.json`)) .then(response => response.json()) @@ -134,6 +135,18 @@ describe('Server', function() { }); }); + it('delivers a synthetic package.json for a file relative to given directory', function() { + let file = join(path, 'foo.js'); + writeFileSync(file, 'content'); + server = new Server({cwd: join(path, '..')}); + return server.serve(file) + .then(() => fetch(`http://127.0.0.1:${server.port}/package.json`)) + .then(response => response.json()) + .then(json => { + expect(json.main).to.equal(relative(join(path, '..'), file)); + }); + }); + }); });
Fix serving snippets from subdirectories of the cwd Previously, only serving snippets from the current working directory of the serve command was supported. Support serving a snippet, which is in a directory descendant of the current working directory. In this case, files in the current working directory will be served along. Change-Id: I4b7a<I>e7c<I>c3f<I>f1b<I>d<I>f<I>a<I>caa
eclipsesource_tabris-js-cli
train
1e47457f7d80eb586be83ee3d46547656d179d99
diff --git a/metpy/plots/tests/test_skewt.py b/metpy/plots/tests/test_skewt.py index <HASH>..<HASH> 100644 --- a/metpy/plots/tests/test_skewt.py +++ b/metpy/plots/tests/test_skewt.py @@ -3,6 +3,7 @@ # SPDX-License-Identifier: BSD-3-Clause """Tests for the `skewt` module.""" +import matplotlib from matplotlib.gridspec import GridSpec import matplotlib.pyplot as plt import numpy as np @@ -13,6 +14,8 @@ from metpy.plots import Hodograph, SkewT from metpy.testing import patch_round, set_agg_backend # noqa: F401 from metpy.units import units +MPL_VERSION = matplotlib.__version__[:3] + @pytest.mark.mpl_image_compare(tolerance=0.021, remove_text=True) def test_skewt_api(): @@ -66,7 +69,7 @@ def test_profile(): return np.linspace(1000, 100, 10), np.linspace(20, -20, 10), np.linspace(25, -30, 10) [email protected]_image_compare(tolerance=0, remove_text=True) [email protected]_image_compare(tolerance={'1.4': 1.71}.get(MPL_VERSION, 0.), remove_text=True) def test_skewt_shade_cape_cin(test_profile): """Test shading CAPE and CIN on a SkewT plot.""" p, t, tp = test_profile @@ -79,7 +82,7 @@ def test_skewt_shade_cape_cin(test_profile): return fig [email protected]_image_compare(tolerance=0, remove_text=True) [email protected]_image_compare(tolerance={'1.4': 1.70}.get(MPL_VERSION, 0.), remove_text=True) def test_skewt_shade_area(test_profile): """Test shading areas on a SkewT plot.""" p, t, tp = test_profile @@ -102,7 +105,7 @@ def test_skewt_shade_area_invalid(test_profile): skew.shade_area(p, t, tp, which='positve') [email protected]_image_compare(tolerance=0, remove_text=True) [email protected]_image_compare(tolerance={'1.4': 1.75}.get(MPL_VERSION, 0.), remove_text=True) def test_skewt_shade_area_kwargs(test_profile): """Test shading areas on a SkewT plot with kwargs.""" p, t, tp = test_profile
MNT: Increase threshold for new tests on matplotlib <I> These pass fine on <I> without it, so I'm just going to blame <I> cruftiness.
Unidata_MetPy
train
476fb565cecb483f7506f4dceb438d506464194d
diff --git a/consensus/clique/clique.go b/consensus/clique/clique.go index <HASH>..<HASH> 100644 --- a/consensus/clique/clique.go +++ b/consensus/clique/clique.go @@ -600,8 +600,7 @@ func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, res } // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing) if c.config.Period == 0 && len(block.Transactions()) == 0 { - log.Info("Sealing paused, waiting for transactions") - return nil + return errors.New("sealing paused while waiting for transactions") } // Don't hold the signer fields for the entire sealing procedure c.lock.RLock() @@ -621,8 +620,7 @@ func (c *Clique) Seal(chain consensus.ChainHeaderReader, block *types.Block, res if recent == signer { // Signer is among recents, only wait if the current block doesn't shift it out if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit { - log.Info("Signed recently, must wait for others") - return nil + return errors.New("signed recently, must wait for others") } } } diff --git a/miner/worker.go b/miner/worker.go index <HASH>..<HASH> 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -593,6 +593,9 @@ func (w *worker) taskLoop() { if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil { log.Warn("Block sealing failed", "err", err) + w.pendingMu.Lock() + delete(w.pendingTasks, sealHash) + w.pendingMu.Unlock() } case <-w.exitCh: interrupt()
miner, consensus/clique: avoid memory leak during block stasis (#<I>) This PR fixes a problem which arises on clique networks when there is a network stall. Previously, the worker packages were tracked, even if the sealing engine decided not to seal the block (due to clique rules about recent signing). These tracked-but-not-sealed blocks kept building up in memory. This PR changes the situation so the sealing engine instead returns an error, and the worker can thus un-track the package.
ethereum_go-ethereum
train
aed3ff36311d997690666134a3dcf6188ef72289
diff --git a/build.py b/build.py index <HASH>..<HASH> 100644 --- a/build.py +++ b/build.py @@ -11,6 +11,8 @@ import sys import os import re import hashlib +import urllib2 +import shutil try: import __builtin__ as builtin @@ -636,16 +638,46 @@ def preprocess(xidl, target): # Where it all begins... # ########################################################### -XIDL = """\ -http://www.virtualbox.org/svn/vbox/trunk/src/VBox/Main/idl/VirtualBox.xidl""" -def main(virtualbox_xidl): +def download_master(): + "Download the master xidl" + xidl = "http://www.virtualbox.org/svn/vbox/trunk/src/VBox/Main/idl/VirtualBox.xidl" + if 0 != os.system('wget %s' % xidl): + assert 0 == os.system('curl %s > VirtualBox.xidl' % xidl) + +def download_stable(): + "Download latest tarball for stable release then unpack xidl" + url = urllib2.urlopen('https://www.virtualbox.org/wiki/Downloads') + page = url.read() + match = re.search("http://download.virtualbox.org/virtualbox/" + "([0-9\.]+)/VirtualBox-([0-9\.]+).tar.bz2" + , page) + if not match: + raise Exception("Failed to find source tarball url") + sourceurl = page[match.start():match.end()] + bzname = sourceurl.split('/')[-1] + tarname = os.path.splitext(bzname)[0] + if not os.path.exists(tarname): + print("Download stable code %s > %s" % (sourceurl, bzname) ) + if 0 != os.system('wget %s' % sourceurl): + assert 0 == os.system('curl -L %s > %s' % (sourceurl, bzname) ) + assert os.path.exists(bzname), "failed to download %s" % sourceurl + assert 0 == os.system('bunzip2 %s' % bzname), "failed to bunzip2 %s" % bzname + assert os.path.exists(tarname), "failed bunzip %s" % tarname + assert 0 == os.system('tar xf %s' % tarname), "failed to tar xf %s" % tarname + source_dir = os.path.splitext(tarname)[0] + path = './%s/src/VBox/Main/idl/VirtualBox.xidl' % source_dir + assert os.path.exists(path), "VirtualBox.xidl was not at %s" % path + shutil.copy(path, 'VirtualBox.xidl') + +def main(virtualbox_xidl, use_master=False): if not os.path.exists(virtualbox_xidl): - if 0 != os.system('wget %s' % XIDL): - assert 0 == os.system('curl %s > VirtualBox.xidl' % XIDL) + if use_master: + download_master() + else: + download_stable() virtualbox_xidl = 'VirtualBox.xidl' - assert os.path.exists(virtualbox_xidl), "failed to download %s" % XIDL - + assert os.path.exists(virtualbox_xidl) print("Create new virtualbox/library.py") xidl = open(virtualbox_xidl, 'rb').read()
Now using the stable release VirtualBox.xidl in the library.py build process
sethmlarson_virtualbox-python
train
7a9f53a0b2fb9a006322d376c7dca841b598ed56
diff --git a/packages/widget-message-meet/Gruntfile.js b/packages/widget-message-meet/Gruntfile.js index <HASH>..<HASH> 100644 --- a/packages/widget-message-meet/Gruntfile.js +++ b/packages/widget-message-meet/Gruntfile.js @@ -10,16 +10,15 @@ var path = require('path'); module.exports = function configGrunt(grunt) { - grunt.config('webpack', + grunt.config('shell', { - options: require('./webpack/webpack.prod'), + options: { + execOptions: { + cwd: __dirname + } + }, build: { - hot: false, - inline: false, - keepalive: false, - progress: false, - watch: false, - debug: false + command: 'npm run build' } }); grunt.config('webpack-dev-server', @@ -38,11 +37,11 @@ module.exports = function configGrunt(grunt) { grunt.registerTask('build', [ 'clean:dist', - 'webpack:build' + 'shell:build' ]); grunt.registerTask('test', ['jest']); grunt.registerTask('test-clean', ['clean:snapshots', 'jest']); - grunt.registerTask('start', ['webpack-dev-server:start']); - grunt.registerTask('default', ['start']); + grunt.registerTask('serve', ['webpack-dev-server:start']); + grunt.registerTask('default', ['server']); }; diff --git a/packages/widget-message-meet/package.json b/packages/widget-message-meet/package.json index <HASH>..<HASH> 100644 --- a/packages/widget-message-meet/package.json +++ b/packages/widget-message-meet/package.json @@ -11,6 +11,7 @@ "start": "webpack-dev-server --history-api-fallback --hot --inline --port 8000 --colors", "test": "jest", "build": "NODE_ENV=production webpack --config webpack/webpack.prod.js", + "build:dev": "NODE_ENV=development webpack --config webpack/webpack.dev.js", "storybook": "start-storybook -p 6006", "build-storybook": "build-storybook" }, diff --git a/packages/widget-message-meet/webpack/webpack.dev.js b/packages/widget-message-meet/webpack/webpack.dev.js index <HASH>..<HASH> 100644 --- a/packages/widget-message-meet/webpack/webpack.dev.js +++ b/packages/widget-message-meet/webpack/webpack.dev.js @@ -16,7 +16,7 @@ module.exports = require(`./webpack.base`)({ chunkFilename: `[name].chunk.js` }, plugins, - devtools: `eval`, + devtools: `cheap-module-eval-source-map`, postcss: [postcssReporter], debug: true });
refactor(widget-message-meet): Switch to grunt-shell to bypass grunt-webpack bug
webex_spark-js-sdk
train
1e91f997cbc571d45b7c3e88a55936fa56eb3036
diff --git a/findschemes.py b/findschemes.py index <HASH>..<HASH> 100755 --- a/findschemes.py +++ b/findschemes.py @@ -146,9 +146,8 @@ def e_unnorm_post(t_table, words, stanzas, schemes, rprobs): scheme_indices = schemes.get_schemes_for_len(len(stanza)) for scheme_index in scheme_indices: scheme = schemes.scheme_list[scheme_index] - # TODO Multiply with rprobs column-wise - posterior_prob = rprobs[scheme_index] * post_prob_scheme(t_table, words, stanza, scheme) - probs[i, scheme_index] = posterior_prob + probs[i, scheme_index] = post_prob_scheme(t_table, words, stanza, scheme) + probs = numpy.dot(probs, numpy.diag(rprobs)) return probs
Multiply probs with rprobs column-wise
jvamvas_rhymediscovery
train
fcbcab7be1f9241f9e56edbdff4ee92261f4f204
diff --git a/src/com/google/javascript/jscomp/Es6RewriteModules.java b/src/com/google/javascript/jscomp/Es6RewriteModules.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/Es6RewriteModules.java +++ b/src/com/google/javascript/jscomp/Es6RewriteModules.java @@ -146,11 +146,12 @@ public final class Es6RewriteModules extends AbstractPostOrderCallback */ public Es6RewriteModules( AbstractCompiler compiler, + ModuleMetadataMap moduleMetadataMap, @Nullable PreprocessorSymbolTable preprocessorSymbolTable) { + checkNotNull(moduleMetadataMap); this.compiler = compiler; + this.moduleMetadataMap = moduleMetadataMap; this.preprocessorSymbolTable = preprocessorSymbolTable; - this.moduleMetadataMap = compiler.getModuleMetadataMap(); - checkNotNull(this.moduleMetadataMap); } /** diff --git a/src/com/google/javascript/jscomp/TranspilationPasses.java b/src/com/google/javascript/jscomp/TranspilationPasses.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/TranspilationPasses.java +++ b/src/com/google/javascript/jscomp/TranspilationPasses.java @@ -48,6 +48,7 @@ public class TranspilationPasses { preprocessorTableFactory.maybeInitialize(compiler); return new Es6RewriteModules( compiler, + compiler.getModuleMetadataMap(), preprocessorTableFactory.getInstanceOrNull()); } diff --git a/test/com/google/javascript/jscomp/Es6RewriteModulesTest.java b/test/com/google/javascript/jscomp/Es6RewriteModulesTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/Es6RewriteModulesTest.java +++ b/test/com/google/javascript/jscomp/Es6RewriteModulesTest.java @@ -61,7 +61,9 @@ public final class Es6RewriteModulesTest extends CompilerTestCase { new GatherModuleMetadata( compiler, /* processCommonJsModules= */ false, ResolutionMode.BROWSER) .process(externs, root); - new Es6RewriteModules(compiler, /* preprocessorSymbolTable= */ null).process(externs, root); + new Es6RewriteModules( + compiler, compiler.getModuleMetadataMap(), /* preprocessorSymbolTable= */ null) + .process(externs, root); }; } diff --git a/test/com/google/javascript/jscomp/Es6RewriteModulesWithGoogInteropTest.java b/test/com/google/javascript/jscomp/Es6RewriteModulesWithGoogInteropTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/Es6RewriteModulesWithGoogInteropTest.java +++ b/test/com/google/javascript/jscomp/Es6RewriteModulesWithGoogInteropTest.java @@ -70,9 +70,11 @@ public final class Es6RewriteModulesWithGoogInteropTest extends CompilerTestCase protected CompilerPass getProcessor(Compiler compiler) { return (externs, root) -> { new GatherModuleMetadata( - compiler, /* processCommonJsModules= */ false, ResolutionMode.BROWSER) + compiler, /* processCommonJsModules= */ false, ResolutionMode.BROWSER) + .process(externs, root); + new Es6RewriteModules( + compiler, compiler.getModuleMetadataMap(), /* preprocessorSymbolTable= */ null) .process(externs, root); - new Es6RewriteModules(compiler, /* preprocessorSymbolTable= */ null).process(externs, root); }; }
Inject Es6RewriteModules with a ModuleMetadataMap to make the dependency clearer. ------------- Created by MOE: <URL>
google_closure-compiler
train
9d89cb04ac330c8600949a3df9411533b1f6a1de
diff --git a/vine-core/src/main/java/com/blankstyle/vine/eventbus/root/RootVerticle.java b/vine-core/src/main/java/com/blankstyle/vine/eventbus/root/RootVerticle.java index <HASH>..<HASH> 100644 --- a/vine-core/src/main/java/com/blankstyle/vine/eventbus/root/RootVerticle.java +++ b/vine-core/src/main/java/com/blankstyle/vine/eventbus/root/RootVerticle.java @@ -162,7 +162,7 @@ public class RootVerticle extends BusModBase implements Handler<Message<JsonObje } }); registerStem(stemContext); - message.reply(heartbeatAddress); + message.reply(new JsonObject().putString("address", heartbeatAddress)); } /**
Refactor stem verticle to use heartbeats if a root address is provided.
kuujo_vertigo
train
ea109c8d04109f02bc8a202f991dd7330bc8a947
diff --git a/pywws/WeatherStation.py b/pywws/WeatherStation.py index <HASH>..<HASH> 100755 --- a/pywws/WeatherStation.py +++ b/pywws/WeatherStation.py @@ -382,21 +382,26 @@ class weather_station: self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, 9, [0xA1, buf_1, buf_2, 0x20, 0xA1, buf_1, buf_2, 0x20], value=0x200, timeout=1000) - new_block = self.devh.interruptRead(0x81, 0x20, 1000) - if len(new_block) == 0x20: - if new_block == old_block: - break - if old_block != None: - self.logger.debug('_read_block changing %06x', ptr) - old_block = new_block + try: + new_block = self.devh.interruptRead(0x81, 0x20, 1000) + if len(new_block) == 0x20: + if new_block == old_block: + break + if old_block != None: + self.logger.debug('_read_block changing %06x', ptr) + old_block = new_block + except usb.USBError, ex: + if ex.args != ('No error',): + raise return new_block def _read_fixed_block(self, hi=0x0100): result = [] for mempos in range(0x0000, hi, 0x0020): result += self._read_block(mempos) # check 'magic number' - if result[0:2] not in ([0x55, 0xAA], [0xFF, 0xFF]): - raise IOError("Invalid data from weather station") + if result[:2] not in ([0x55, 0xAA], [0xFF, 0xFF], [0x55, 0x55]): + raise IOError( + "Unrecognised 'magic number' %02x %02x", result[0], result[1]) return result def _write_byte(self, ptr, value): buf_1 = (ptr / 256) & 0xFF @@ -404,16 +409,32 @@ class weather_station: self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, 9, [0xA2, buf_1, buf_2, 0x20, 0xA2, value, 0, 0x20], value=0x200, timeout=1000) - result = self.devh.interruptRead(0x81, 0x08, 1000) - for byte in result: - if byte != 0xA5: - raise IOError('_write_byte failed') + while True: + try: + result = self.devh.interruptRead(0x81, 0x08, 1000) + for byte in result: + if byte != 0xA5: + raise IOError('_write_byte failed') + break + except usb.USBError, ex: + if ex.args != ('No error',): + raise def write_data(self, data): """Write a set of single bytes to the weather station. Data must be an array of (ptr, value) pairs.""" + # send data for ptr, value in data: self._write_byte(ptr, value) - self._write_byte(0x1A, 0xAA) + # set 'data changed' + self._write_byte(self.fixed_format['data_changed'][0], 0xAA) + # wait for station to clear 'data changed' + while True: + ack = _decode( + self._read_fixed_block(0x0020), self.fixed_format['data_changed']) + if ack == 0: + break + self.logger.debug('write_data waiting for ack') + time.sleep(6) # Tables of "meanings" for raw weather station data. Each key # specifies an (offset, type, multiplier) tuple that is understood # by _decode. @@ -442,6 +463,7 @@ class weather_station: fixed_format = { 'read_period' : (16, 'ub', None), 'timezone' : (24, 'sb', None), + 'data_changed' : (26, 'ub', None), 'data_count' : (27, 'us', None), 'current_pos' : (30, 'us', None), 'rel_pressure' : (32, 'us', 0.1),
Improved reliability of reading & writing weather station data. Added new 'magic number' to list of recognised ones.
jim-easterbrook_pywws
train
6ac204d625c70fe01b59c13cfd2d1f55f3051a4f
diff --git a/spec/support/mock_spec_helper.rb b/spec/support/mock_spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/support/mock_spec_helper.rb +++ b/spec/support/mock_spec_helper.rb @@ -1,12 +1,12 @@ - module MockSpecHelper def mock_rest_client @api_version = RightApi::Client::API_VERSION + @test_account_id = '1' @rest_client = RestClient::Resource.new(RightApi::Client::DEFAULT_API_URL) flexmock(RestClient::Resource).should_receive(:new).and_return(@rest_client) @session = flexmock(:cookies => {}) - @header = {'X_API_VERSION' => @api_version, :cookies => {}, :accept => :json} + @header = {'X_API_VERSION' => @api_version, 'X_ACCOUNT' => @test_account_id, :cookies => {}, :accept => :json} end def given_user_facing_client @@ -15,7 +15,7 @@ module MockSpecHelper {'email' => 'email', 'password' => 'password', 'account_href' => '/api/accounts/1'}, {'X_API_VERSION' => @api_version}, Proc).and_return(@session) flexmock(@rest_client).should_receive(:get).with(@header, Proc).and_return(['', '{}']) - @client = RightApi::Client.new(:email => 'email', :password => 'password', :account_id => '1') + @client = RightApi::Client.new(:email => 'email', :password => 'password', :account_id => @test_account_id) end def given_instance_facing_client @@ -28,7 +28,7 @@ module MockSpecHelper "href": "/api/clouds/1/instances/1", "rel": "self" }]}']) - @client = RightApi::Client.new(:instance_token => 'instance_token', :account_id => '1') + @client = RightApi::Client.new(:instance_token => 'instance_token', :account_id => @test_account_id) end end
acu<I> Fixing broken stubs to get specs green
rightscale_right_api_client
train
f49052837799bb6826271d028e2e8a681ef4d9e1
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index <HASH>..<HASH> 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3395,7 +3395,7 @@ class DataFrame(NDFrame): Parameters ---------- - other : DataFrame + other : DataFrame, or object coercible into a DataFrame join : {'left', 'right', 'outer', 'inner'}, default 'left' overwrite : boolean, default True If True then overwrite values for common keys in the calling frame @@ -3409,7 +3409,11 @@ class DataFrame(NDFrame): if join != 'left': raise NotImplementedError + if not isinstance(other, DataFrame): + other = DataFrame(other) + other = other.reindex_like(self) + for col in self.columns: this = self[col].values that = other[col].values diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index <HASH>..<HASH> 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -5784,6 +5784,11 @@ class TestDataFrame(unittest.TestCase, CheckIndexing, [1.5, nan, 7.]]) assert_frame_equal(df, expected) + + + + + def test_update_nooverwrite(self): df = DataFrame([[1.5, nan, 3.], [1.5, nan, 3.], @@ -5830,6 +5835,27 @@ class TestDataFrame(unittest.TestCase, CheckIndexing, np.testing.assert_raises(Exception, df.update, *(other,), **{'raise_conflict' : True}) + def test_update_from_non_df(self): + d = {'a': Series([1, 2, 3, 4]), 'b': Series([5, 6, 7, 8])} + df = DataFrame(d) + + d['a'] = Series([5, 6, 7, 8]) + df.update(d) + + expected = DataFrame(d) + + assert_frame_equal(df, expected) + + d = {'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]} + df = DataFrame(d) + + d['a'] = [5, 6, 7, 8] + df.update(d) + + expected = DataFrame(d) + + assert_frame_equal(df, expected) + def test_combineAdd(self): # trivial comb = self.frame.combineAdd(self.frame)
Allow DataFrame.update to accept non DataFrame object and attempt to coerce.
pandas-dev_pandas
train
3718c74fe17f67d9f8bdfa56b9e1bf612a2b9b3b
diff --git a/openquake/calculators/base.py b/openquake/calculators/base.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/base.py +++ b/openquake/calculators/base.py @@ -903,11 +903,10 @@ def save_gmfs(calculator): oq = calculator.oqparam logging.info('Reading gmfs from file') if oq.inputs['gmfs'].endswith('.csv'): - # TODO: check if import_gmfs can be removed eids = import_gmfs( dstore, oq.inputs['gmfs'], calculator.sitecol.complete.sids) else: # XML - eids, gmfs = readinput.eids, readinput.gmfs + raise NotImplementedError('Cannot import %s' % oq.inputs['gmfs']) E = len(eids) events = numpy.zeros(E, rupture.events_dt) events['id'] = eids @@ -919,10 +918,9 @@ def save_gmfs(calculator): (oq.number_of_ground_motion_fields, E)) else: # set the number of GMFs from the file oq.number_of_ground_motion_fields = E - # NB: save_gmfs redefine oq.sites in case of GMFs from XML or CSV - if oq.inputs['gmfs'].endswith('.xml'): + # NB: save_gmfs redefine oq.sites in case of GMFs from XML + if oq.inputs['gmfs'].endswith('.csv'): haz_sitecol = readinput.get_site_collection(oq) - N, E, M = gmfs.shape save_gmf_data(dstore, haz_sitecol, gmfs[haz_sitecol.sids], oq.imtls, events)
Worked on the GMFs importer [skip hazardlib]
gem_oq-engine
train
df987b98782f527d023437343b41a3f0478177ea
diff --git a/grails-web-common/src/main/groovy/org/codehaus/groovy/grails/web/servlet/DefaultGrailsApplicationAttributes.java b/grails-web-common/src/main/groovy/org/codehaus/groovy/grails/web/servlet/DefaultGrailsApplicationAttributes.java index <HASH>..<HASH> 100644 --- a/grails-web-common/src/main/groovy/org/codehaus/groovy/grails/web/servlet/DefaultGrailsApplicationAttributes.java +++ b/grails-web-common/src/main/groovy/org/codehaus/groovy/grails/web/servlet/DefaultGrailsApplicationAttributes.java @@ -74,33 +74,30 @@ public class DefaultGrailsApplicationAttributes implements GrailsApplicationAttr if (context != null) { appContext = (ApplicationContext)context.getAttribute(APPLICATION_CONTEXT); } - initBeans(); } public ApplicationContext getApplicationContext() { return appContext; } - private void initBeans() { - if (appContext != null) { - pagesTemplateEngine = fetchBeanFromAppCtx(ResourceAwareTemplateEngine.BEAN_ID); + private GrailsPluginManager getPluginManager() { + if(pluginManager==null) { pluginManager = fetchBeanFromAppCtx(GrailsPluginManager.BEAN_NAME); - grailsApplication = fetchBeanFromAppCtx(GrailsApplication.APPLICATION_ID); - groovyPagesUriService = fetchBeanFromAppCtx(GroovyPagesUriService.BEAN_ID); - messageSource = fetchBeanFromAppCtx("messageSource"); - } - else { - LOG.warn("ApplicationContext not found in " + APPLICATION_CONTEXT + " attribute of servlet context."); - } - if (groovyPagesUriService == null) { - groovyPagesUriService = new DefaultGroovyPagesUriService(); } + return pluginManager; } @SuppressWarnings("unchecked") private <T> T fetchBeanFromAppCtx(String name) { + if(appContext==null) { + return null; + } try { - return (T)appContext.getBean(name); + if(appContext.containsBean(name)) { + return (T)appContext.getBean(name); + } else { + return null; + } } catch(BeansException e) { LOG.warn("Bean named '" + name + "' is missing."); @@ -110,8 +107,8 @@ public class DefaultGrailsApplicationAttributes implements GrailsApplicationAttr public String getPluginContextPath(HttpServletRequest request) { GroovyObject controller = getController(request); - if (controller != null) { - String path = pluginManager.getPluginPathForInstance(controller); + if (controller != null && getPluginManager() != null) { + String path = getPluginManager().getPluginPathForInstance(controller); return path == null ? "" : path; } @@ -191,12 +188,12 @@ public class DefaultGrailsApplicationAttributes implements GrailsApplicationAttr public String getTemplateUri(CharSequence templateName, ServletRequest request) { Assert.notNull(templateName, "Argument [template] cannot be null"); - return groovyPagesUriService.getTemplateURI(getControllerName(request), templateName.toString()); + return getGroovyPagesUriService().getTemplateURI(getControllerName(request), templateName.toString()); } public String getViewUri(String viewName, HttpServletRequest request) { Assert.notNull(viewName, "Argument [view] cannot be null"); - return groovyPagesUriService.getDeployedViewURI(getControllerName(request), viewName); + return getGroovyPagesUriService().getDeployedViewURI(getControllerName(request), viewName); } public String getControllerActionUri(ServletRequest request) { @@ -209,16 +206,19 @@ public class DefaultGrailsApplicationAttributes implements GrailsApplicationAttr } public ResourceAwareTemplateEngine getPagesTemplateEngine() { - if (pagesTemplateEngine != null) { - return pagesTemplateEngine; + if (pagesTemplateEngine == null) { + pagesTemplateEngine = fetchBeanFromAppCtx(ResourceAwareTemplateEngine.BEAN_ID); } - if (LOG.isWarnEnabled()) { + if (pagesTemplateEngine == null && LOG.isWarnEnabled()) { LOG.warn("No bean named [" + ResourceAwareTemplateEngine.BEAN_ID + "] defined in Spring application context!"); } - return null; + return pagesTemplateEngine; } public GrailsApplication getGrailsApplication() { + if(grailsApplication==null) { + grailsApplication = fetchBeanFromAppCtx(GrailsApplication.APPLICATION_ID); + } return grailsApplication; } @@ -248,18 +248,27 @@ public class DefaultGrailsApplicationAttributes implements GrailsApplicationAttr } public String getNoSuffixViewURI(GroovyObject controller, String viewName) { - return groovyPagesUriService.getNoSuffixViewURI(controller, viewName); + return getGroovyPagesUriService().getNoSuffixViewURI(controller, viewName); } public String getTemplateURI(GroovyObject controller, String templateName) { - return groovyPagesUriService.getTemplateURI(controller, templateName); + return getGroovyPagesUriService().getTemplateURI(controller, templateName); } public GroovyPagesUriService getGroovyPagesUriService() { + if (groovyPagesUriService == null) { + groovyPagesUriService = fetchBeanFromAppCtx(GroovyPagesUriService.BEAN_ID); + if (groovyPagesUriService == null) { + groovyPagesUriService = new DefaultGroovyPagesUriService(); + } + } return groovyPagesUriService; } public MessageSource getMessageSource() { + if(messageSource==null) { + messageSource = fetchBeanFromAppCtx("messageSource"); + } return messageSource; } }
resolve beans lazily in DefaultGrailsApplicationAttributes
grails_grails-core
train
717d1f8b5c0ce050ddb97224c8f01c6ca6029669
diff --git a/plugins/rate_limit.js b/plugins/rate_limit.js index <HASH>..<HASH> 100644 --- a/plugins/rate_limit.js +++ b/plugins/rate_limit.js @@ -186,7 +186,13 @@ exports.rate_limit = function (connection, key, value, cb) { plugin.db.setex(key, ttl, 1, check_limits); } else { // old key - plugin.db.incr(key, check_limits); + plugin.db.incr(key, function (err3, result) { + if (result === 1) { + plugin.db.expire(key, ttl); + } + check_limits(err3, result); + } + ); } }); };
Updated logic to address case where Redis deletes record between get and incr. If incr creates a new record, make sure it also has a TTL. (#<I>)
haraka_Haraka
train
fc589e4e83e6fb176aca5e42a5b338d0be23fc39
diff --git a/.toys/ci.rb b/.toys/ci.rb index <HASH>..<HASH> 100644 --- a/.toys/ci.rb +++ b/.toys/ci.rb @@ -265,7 +265,14 @@ def find_changed_directories files dirs = Set.new files.each do |file| if file =~ %r{^([^/]+)/.+$} - dirs << Regexp.last_match[1] + dir = Regexp.last_match[1] + dirs << dir + if dir =~ %r{^(.+)-v\d[^-]*$} + wrapper_dir = Regexp.last_match[1] + if Dir.exists? wrapper_dir + dirs << wrapper_dir + end + end end end filter_gem_dirs dirs.to_a
chore: run tests for wrappers when child directories have changed
googleapis_google-cloud-ruby
train
d92beeee3dad366352379fc95dc40f387dd4cb9f
diff --git a/docs/sources/http_api/snapshot.md b/docs/sources/http_api/snapshot.md index <HASH>..<HASH> 100644 --- a/docs/sources/http_api/snapshot.md +++ b/docs/sources/http_api/snapshot.md @@ -68,7 +68,8 @@ JSON Body schema: "deleteKey":"XXXXXXX", "deleteUrl":"myurl/api/snapshots-delete/XXXXXXX", "key":"YYYYYYY", - "url":"myurl/dashboard/snapshot/YYYYYYY" + "url":"myurl/dashboard/snapshot/YYYYYYY", + "id": 1, } ``` @@ -192,7 +193,7 @@ Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk HTTP/1.1 200 Content-Type: application/json -{"message":"Snapshot deleted. It might take an hour before it's cleared from any CDN caches."} +{"message":"Snapshot deleted. It might take an hour before it's cleared from any CDN caches.", "id": 1} ``` ## Delete Snapshot by deleteKey @@ -214,5 +215,5 @@ Accept: application/json HTTP/1.1 200 Content-Type: application/json -{"message":"Snapshot deleted. It might take an hour before it's cleared from any CDN caches."} -``` \ No newline at end of file +{"message":"Snapshot deleted. It might take an hour before it's cleared from any CDN caches.", "id": 1} +``` diff --git a/pkg/api/dashboard_snapshot.go b/pkg/api/dashboard_snapshot.go index <HASH>..<HASH> 100644 --- a/pkg/api/dashboard_snapshot.go +++ b/pkg/api/dashboard_snapshot.go @@ -132,6 +132,7 @@ func CreateDashboardSnapshot(c *models.ReqContext, cmd models.CreateDashboardSna "deleteKey": cmd.DeleteKey, "url": url, "deleteUrl": setting.ToAbsUrl("api/snapshots-delete/" + cmd.DeleteKey), + "id": cmd.Result.Id, }) } @@ -223,7 +224,10 @@ func DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) Response { return Error(500, "Failed to delete dashboard snapshot", err) } - return JSON(200, util.DynMap{"message": "Snapshot deleted. It might take an hour before it's cleared from any CDN caches."}) + return JSON(200, util.DynMap{ + "message": "Snapshot deleted. It might take an hour before it's cleared from any CDN caches.", + "id": query.Result.Id, + }) } // DELETE /api/snapshots/:key @@ -269,7 +273,10 @@ func DeleteDashboardSnapshot(c *models.ReqContext) Response { return Error(500, "Failed to delete dashboard snapshot", err) } - return JSON(200, util.DynMap{"message": "Snapshot deleted. It might take an hour before it's cleared from any CDN caches."}) + return JSON(200, util.DynMap{ + "message": "Snapshot deleted. It might take an hour before it's cleared from any CDN caches.", + "id": query.Result.Id, + }) } // GET /api/dashboard/snapshots diff --git a/pkg/api/dashboard_snapshot_test.go b/pkg/api/dashboard_snapshot_test.go index <HASH>..<HASH> 100644 --- a/pkg/api/dashboard_snapshot_test.go +++ b/pkg/api/dashboard_snapshot_test.go @@ -109,6 +109,7 @@ func TestDashboardSnapshotAPIEndpoint_singleSnapshot(t *testing.T) { require.NoError(t, err) assert.True(t, strings.HasPrefix(respJSON.Get("message").MustString(), "Snapshot deleted")) + assert.Equal(t, 1, respJSON.Get("id").MustInt()) assert.Equal(t, http.MethodGet, externalRequest.Method) assert.Equal(t, ts.URL, fmt.Sprintf("http://%s", externalRequest.Host)) @@ -141,6 +142,7 @@ func TestDashboardSnapshotAPIEndpoint_singleSnapshot(t *testing.T) { require.NoError(t, err) assert.True(t, strings.HasPrefix(respJSON.Get("message").MustString(), "Snapshot deleted")) + assert.Equal(t, 1, respJSON.Get("id").MustInt()) assert.Equal(t, ts.URL, fmt.Sprintf("http://%s", externalRequest.Host)) assert.Equal(t, "/", externalRequest.URL.EscapedPath()) }) @@ -163,6 +165,7 @@ func TestDashboardSnapshotAPIEndpoint_singleSnapshot(t *testing.T) { require.NoError(t, err) assert.True(t, strings.HasPrefix(respJSON.Get("message").MustString(), "Snapshot deleted")) + assert.Equal(t, 1, respJSON.Get("id").MustInt()) }) }) @@ -186,6 +189,11 @@ func TestDashboardSnapshotAPIEndpoint_singleSnapshot(t *testing.T) { require.NoError(t, writeErr) assert.Equal(t, 200, sc.resp.Code) + respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes()) + require.NoError(t, err) + + assert.True(t, strings.HasPrefix(respJSON.Get("message").MustString(), "Snapshot deleted")) + assert.Equal(t, 1, respJSON.Get("id").MustInt()) }) loggedInUserScenarioWithRole(t,
API: add ID to snapshot API responses (#<I>) * API: add ID to snapshot API responses * API: update snapshot tests
grafana_grafana
train
667882fa81b647a5d060ef03ee8656302d945f28
diff --git a/penaltymodel_core/penaltymodel/core/classes/specification.py b/penaltymodel_core/penaltymodel/core/classes/specification.py index <HASH>..<HASH> 100644 --- a/penaltymodel_core/penaltymodel/core/classes/specification.py +++ b/penaltymodel_core/penaltymodel/core/classes/specification.py @@ -117,6 +117,9 @@ class Specification(object): u and v are variables in the desired penalty model and u, v have an interaction - there is an edge between nodes u, v in `graph`. + min_classical_gap (float): The minimum energy gap between the highest feasible state and + the lowest infeasible state. Default value is 2. + """ @dimod.decorators.vartype_argument('vartype') def __init__(self, graph, decision_variables, feasible_configurations, vartype, diff --git a/penaltymodel_lp/penaltymodel/lp/generation.py b/penaltymodel_lp/penaltymodel/lp/generation.py index <HASH>..<HASH> 100644 --- a/penaltymodel_lp/penaltymodel/lp/generation.py +++ b/penaltymodel_lp/penaltymodel/lp/generation.py @@ -75,7 +75,19 @@ def _get_lp_matrix(spin_states, nodes, edges, offset_weight, gap_weight): #TODO: Check if len(table.keys()[0]) == len(decision_variables) def generate_bqm(graph, table, decision_variables, linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=2): - + """ + Args: + graph: A networkx.Graph + table: An iterable of valid spin configurations. Each configuration is a tuple of + variable assignments ordered by `decision`. + decision_variables: An ordered iterable of the variables in the binary quadratic model. + linear_energy_ranges: Dictionary of the form {v: (min, max), ...} where min and + max are the range of values allowed to v. The default range is [-2, 2]. + quadratic_energy_ranges: Dict of the form {(u, v): (min, max), ...} where min and max are + the range of values allowed to (u, v). The default range is [-1, 1]. + min_classical_gap: A float. The minimum energy gap between the highest feasible state and + the lowest infeasible state. + """ # Check for auxiliary variables in the graph if len(graph) != len(decision_variables): raise ValueError('Penaltymodel-lp does not handle problems with auxiliary variables') diff --git a/penaltymodel_maxgap/penaltymodel/maxgap/generation.py b/penaltymodel_maxgap/penaltymodel/maxgap/generation.py index <HASH>..<HASH> 100644 --- a/penaltymodel_maxgap/penaltymodel/maxgap/generation.py +++ b/penaltymodel_maxgap/penaltymodel/maxgap/generation.py @@ -36,6 +36,8 @@ def generate_ising(graph, feasible_configurations, decision_variables, quadratic_energy_ranges (dict): A dict of the form {(u, v): (min, max), ...} where min and max are the range of values allowed to (u, v). + min_classical_gap (float): The minimum energy gap between the highest feasible state and the + lowest infeasible state. smt_solver_name (str/None): The name of the smt solver. Must be a solver available to pysmt. If None, uses the pysmt default. diff --git a/penaltymodel_mip/penaltymodel/mip/generation.py b/penaltymodel_mip/penaltymodel/mip/generation.py index <HASH>..<HASH> 100644 --- a/penaltymodel_mip/penaltymodel/mip/generation.py +++ b/penaltymodel_mip/penaltymodel/mip/generation.py @@ -36,6 +36,10 @@ def generate_bqm(graph, table, decision, Dict of the form {(u, v): (min, max), ...} where min and max are the range of values allowed to (u, v). The default range is [-1, 1]. + min_classical_gap (float): + The minimum energy gap between the highest feasible state and the lowest infeasible + state. + precision (int, optional, default=7): Values returned by the optimization solver are rounded to `precision` digits of precision.
Add min_classical_gap to docstrings
dwavesystems_penaltymodel
train
921904c726e70527721dfe59b16fcb2900bb5d9d
diff --git a/pymatgen/analysis/substrate_analyzer.py b/pymatgen/analysis/substrate_analyzer.py index <HASH>..<HASH> 100644 --- a/pymatgen/analysis/substrate_analyzer.py +++ b/pymatgen/analysis/substrate_analyzer.py @@ -317,12 +317,16 @@ class SubstrateAnalyzer: if elasticity_tensor is None: return 9999 + # Get the appropriate surface structure + struc = SlabGenerator(self.film, match['film_miller'], 20, 15, + primitive=False).get_slab().oriented_unit_cell + # Generate 3D lattice vectors for film super lattice film_matrix = list(match['film_sl_vecs']) film_matrix.append(np.cross(film_matrix[0], film_matrix[1])) # Generate 3D lattice vectors for substrate super lattice - # Out of place substrate super lattice has to be same length as + # Out of plane substrate super lattice has to be same length as # Film out of plane vector to ensure no extra deformation in that # direction substrate_matrix = list(match['sub_sl_vecs']) @@ -335,7 +339,7 @@ class SubstrateAnalyzer: dfm = Deformation(transform_matrix) - strain = dfm.green_lagrange_strain.von_mises_strain + strain = dfm.green_lagrange_strain.von_mises_strain.convert_to_ieee(struc,initial_fit=False) energy_density = elasticity_tensor.energy_density( dfm.green_lagrange_strain)
Convert strain to IEEE to match with elastic tensor
materialsproject_pymatgen
train
bda08da60249cd9278d5354fd22e097d0b3d635f
diff --git a/pub/js/lib/swiping_container.js b/pub/js/lib/swiping_container.js index <HASH>..<HASH> 100644 --- a/pub/js/lib/swiping_container.js +++ b/pub/js/lib/swiping_container.js @@ -28,6 +28,10 @@ define(['lib/bind'], function (bind) { scrollPosition = outerContainer.scrollLeft, innerContainer = outerContainer.querySelector(innerContainerSelector); + if (null === innerContainer) { + return; + } + bind(outerContainer, 'scroll', function () { toggleSwipingArrows(outerContainerSelector, 'ul'); }); @@ -36,4 +40,4 @@ define(['lib/bind'], function (bind) { nextArr.style.opacity = innerContainer.offsetWidth - document.body.clientWidth > scrollPosition ? 1 : 0; }); } -}); \ No newline at end of file +});
Issue #<I>: Fix empty swiping blocks rendering
lizards-and-pumpkins_catalog
train
212b9f2e67b203d428cda70940112bdb6c290d86
diff --git a/lib/alias.js b/lib/alias.js index <HASH>..<HASH> 100644 --- a/lib/alias.js +++ b/lib/alias.js @@ -1,7 +1,9 @@ import retry from 'async-retry'; import Now from '../lib'; +import toHost from './to-host'; export default class Alias extends Now { + async ls () { return retry(async (bail) => { const res = await this._fetch('/now/aliases'); @@ -34,25 +36,27 @@ export default class Alias extends Now { })); } - async set (url, aliases) { - console.log('set', url, aliases); - const deploymentId = url; // TODO get from API - return retry(async (bail) => { - const res = await this._fetch(`/now/aliases/${deploymentId}/`, { - method: 'POST', - body: { - aliases: aliases - } - }); + async set (deployment, alias) { + const list = await this.list(); + let key, val; - if (200 !== res.status && (400 <= res.status || 500 > res.status)) { - if (this._debug) console.log('> [debug] bailing on creating due to %s', res.status); - return bail(responseError(res)); - } + if (~deployment.indexOf('.')) { + val = toHost(deployment); + key = 'url'; + } else { + val = deployment; + key = 'uid'; + } - return await res.json(); - }, { retries: 3, minTimeout: 2500, onRetry: this._onRetry }); + const id = list.find((d) => d[key] === val); + + if (!id) { + const err = new Error(`Deployment not found by ${key} "${deployment}"`); + err.userError = true; + throw err; + } } + } function responseError (res) {
alias: implement uid / host search
zeit_now-cli
train
c675d781f89f2057c8e5e0e53896adf468cfbac1
diff --git a/setuptools/command/build.py b/setuptools/command/build.py index <HASH>..<HASH> 100644 --- a/setuptools/command/build.py +++ b/setuptools/command/build.py @@ -65,6 +65,11 @@ class SubCommand(Protocol): of ``get_output_mapping()``. Alternatively, ``setuptools`` **MAY** attempt to use :doc:`import hooks <python:reference/import>` to redirect any attempt to import to the directory with the original source code and other files built in place. + + Please note that custom sub-commands **SHOULD NOT** rely on ``run()`` being + executed (or not) to provide correct return values for ``get_outputs()``, + ``get_output_mapping()`` or ``get_source_files()``. The ``get_*`` methods should + work independently of ``run()``. """ editable_mode: bool = False @@ -106,6 +111,17 @@ class SubCommand(Protocol): def run(self): """(Required by the original :class:`setuptools.Command` interface)""" + def get_source_files(self) -> List[str]: + """ + Return a list of all files that are used by the command to create the expected + outputs. + For example, if your build command transpiles Java files into Python, you should + list here all the Java files. + The primary purpose of this function is to help populating the ``sdist`` + with all the files necessary to build the distribution. + All files should be strings relative to the project root directory. + """ + def get_outputs(self) -> List[str]: """ Return a list of files intended for distribution as they would have been diff --git a/setuptools/command/sdist.py b/setuptools/command/sdist.py index <HASH>..<HASH> 100644 --- a/setuptools/command/sdist.py +++ b/setuptools/command/sdist.py @@ -4,10 +4,12 @@ import os import sys import io import contextlib +from itertools import chain from .py36compat import sdist_add_defaults from .._importlib import metadata +from .build import _ORIGINAL_SUBCOMMANDS _default_revctrl = list @@ -100,6 +102,10 @@ class sdist(sdist_add_defaults, orig.sdist): if orig_val is not NoValue: setattr(os, 'link', orig_val) + def add_defaults(self): + super().add_defaults() + self._add_defaults_build_sub_commands() + def _add_defaults_optional(self): super()._add_defaults_optional() if os.path.isfile('pyproject.toml'): @@ -112,6 +118,14 @@ class sdist(sdist_add_defaults, orig.sdist): self.filelist.extend(build_py.get_source_files()) self._add_data_files(self._safe_data_files(build_py)) + def _add_defaults_build_sub_commands(self): + build = self.get_finalized_command("build") + missing_cmds = set(build.get_sub_commands()) - _ORIGINAL_SUBCOMMANDS + # ^-- the original built-in sub-commands are already handled by default. + cmds = (self.get_finalized_command(c) for c in missing_cmds) + files = (c.get_source_files() for c in cmds if hasattr(c, "get_source_files")) + self.filelist.extend(chain.from_iterable(files)) + def _safe_data_files(self, build_py): """ Since the ``sdist`` class is also used to compute the MANIFEST diff --git a/setuptools/tests/test_sdist.py b/setuptools/tests/test_sdist.py index <HASH>..<HASH> 100644 --- a/setuptools/tests/test_sdist.py +++ b/setuptools/tests/test_sdist.py @@ -10,6 +10,7 @@ from unittest import mock import pytest +from setuptools import Command from setuptools._importlib import metadata from setuptools import SetuptoolsDeprecationWarning from setuptools.command.sdist import sdist @@ -517,6 +518,46 @@ class TestSdistTest: manifest = cmd.filelist.files assert 'pyproject.toml' not in manifest + def test_build_subcommand_source_files(self, tmpdir): + touch(tmpdir / '.myfile~') + + # Sanity check: without custom commands file list should not be affected + dist = Distribution({**SETUP_ATTRS, "script_name": "setup.py"}) + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert '.myfile~' not in manifest + + # Test: custom command should be able to augment file list + dist = Distribution({**SETUP_ATTRS, "script_name": "setup.py"}) + build = dist.get_command_obj("build") + build.sub_commands = [*build.sub_commands, ("build_custom", None)] + + class build_custom(Command): + def initialize_options(self): + ... + + def finalize_options(self): + ... + + def run(self): + ... + + def get_source_files(self): + return ['.myfile~'] + + dist.cmdclass.update(build_custom=build_custom) + + cmd = sdist(dist) + cmd.use_defaults = True + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert '.myfile~' in manifest + def test_default_revctrl(): """
sdist: Add files from build subcommands (get_source_files)
pypa_setuptools
train
c254f4bfa8615b3191462bc386474d58996c20bf
diff --git a/src/main/resources/META-INF/resources/primefaces/menu/menu.js b/src/main/resources/META-INF/resources/primefaces/menu/menu.js index <HASH>..<HASH> 100644 --- a/src/main/resources/META-INF/resources/primefaces/menu/menu.js +++ b/src/main/resources/META-INF/resources/primefaces/menu/menu.js @@ -686,12 +686,12 @@ PrimeFaces.widget.ContextMenu = PrimeFaces.widget.TieredMenu.extend({ }, bindTree: function() { - var rowSelector = this.jqTargetId + ' ' + (this.cfg.nodeType ? 'li.' + this.cfg.nodeType + ' .ui-tree-selectable-node': '.ui-tree-selectable-node'), + var nodeSelector = this.jqTargetId + ' ' + (this.cfg.nodeType ? 'li.' + this.cfg.nodeType + ' .ui-tree-selectable': '.ui-tree-selectable'), event = this.cfg.event + '.tree', _self = this; - $(document).off(event, rowSelector) - .on(event, rowSelector, null, function(e) { + $(document).off(event, nodeSelector) + .on(event, nodeSelector, null, function(e) { window[_self.cfg.targetWidgetVar].nodeClick(e, $(this)); _self.show(e); e.preventDefault();
Restored contextmenu support for new tree widget
primefaces_primefaces
train
97c61370a1843588e460feff72a5bb34ebbad51d
diff --git a/pymatgen/io/qchem/inputs.py b/pymatgen/io/qchem/inputs.py index <HASH>..<HASH> 100644 --- a/pymatgen/io/qchem/inputs.py +++ b/pymatgen/io/qchem/inputs.py @@ -496,7 +496,7 @@ class QCInput(MSONable): Returns: List of sections. """ - patterns = {"sections": r"^\s*?\$([a-z]+)", "multiple_jobs": r"(@@@)"} + patterns = {"sections": r"^\s*?\$([a-z_]+)", "multiple_jobs": r"(@@@)"} matches = read_pattern(string, patterns) # list of the sections present sections = [val[0] for val in matches["sections"]] @@ -509,6 +509,7 @@ class QCInput(MSONable): raise ValueError("Output file does not contain a molecule section") if "rem" not in sections: raise ValueError("Output file does not contain a rem section") + print(sections) return sections @staticmethod @@ -666,10 +667,11 @@ class QCInput(MSONable): print("No valid vdW inputs found. Note that there should be no '=' chracters in vdW input lines.") return "", {} - if vdw_table[0][0][0] == 1: - mode = "atomic" - elif vdw_table[0][0][0] == 2: + if vdw_table[0][0][0] == 2: mode = "sequential" + else: + mode = "atomic" + return mode, dict(vdw_table[0][1:])
bugfix to detect underscore in van_der_waals
materialsproject_pymatgen
train
6379fed5d25b1e15a229df5896b306babdaf3ee2
diff --git a/workflows/recipe/__init__.py b/workflows/recipe/__init__.py index <HASH>..<HASH> 100644 --- a/workflows/recipe/__init__.py +++ b/workflows/recipe/__init__.py @@ -25,6 +25,7 @@ def _wrap_subscription(transport_layer, subscription_call, channel, callback, to connect all messages originating from the same recipe, then the information will be passed to this function, which must be a context manager factory. + :return: Return value of call to subscription_call. ''' allow_non_recipe_messages = kwargs.pop('allow_non_recipe_messages', False) @@ -53,7 +54,7 @@ def _wrap_subscription(transport_layer, subscription_call, channel, callback, # str(header)[:1000], str(message)[:1000]) transport_layer.nack(header) - subscription_call(channel, unwrap_recipe, *args, **kwargs) + return subscription_call(channel, unwrap_recipe, *args, **kwargs) def wrap_subscribe(transport_layer, channel, callback, *args, **kwargs): '''Listen to a queue on the transport layer, similar to the subscribe call in @@ -66,10 +67,11 @@ def wrap_subscribe(transport_layer, channel, callback, *args, **kwargs): The callback will pass three arguments, a RecipeWrapper object (details below), the header as a dictionary structure, and the message. + :return: A unique subscription ID ''' - _wrap_subscription(transport_layer, transport_layer.subscribe, - channel, callback, *args, **kwargs) + return _wrap_subscription(transport_layer, transport_layer.subscribe, + channel, callback, *args, **kwargs) def wrap_subscribe_broadcast(transport_layer, channel, callback, *args, **kwargs): '''Listen to a topic on the transport layer, similar to the @@ -82,7 +84,13 @@ def wrap_subscribe_broadcast(transport_layer, channel, callback, *args, **kwargs The callback will pass three arguments, a RecipeWrapper object (details below), the header as a dictionary structure, and the message. + :return: A unique subscription ID ''' - _wrap_subscription(transport_layer, transport_layer.subscribe_broadcast, - channel, callback, *args, **kwargs) + return _wrap_subscription( + transport_layer, + transport_layer.subscribe_broadcast, + channel, + callback, + *args, **kwargs + ) diff --git a/workflows/recipe/test_wrap_subscription.py b/workflows/recipe/test_wrap_subscription.py index <HASH>..<HASH> 100644 --- a/workflows/recipe/test_wrap_subscription.py +++ b/workflows/recipe/test_wrap_subscription.py @@ -60,7 +60,7 @@ def test_wrapping_a_subscription(rw_mock): '''Test queue subscription with recipe wrapper.''' transport, recipient = mock.Mock(), mock.Mock() - workflows.recipe.wrap_subscribe(transport, mock.sentinel.channel, recipient, + sid = workflows.recipe.wrap_subscribe(transport, mock.sentinel.channel, recipient, mock.sentinel.irrelevant_extra_arg, keyword=mock.sentinel.keyword_arg) # Channel and any extra arguments must be passed on to transport layer. @@ -69,6 +69,7 @@ def test_wrapping_a_subscription(rw_mock): mock.sentinel.irrelevant_extra_arg, keyword=mock.sentinel.keyword_arg) callback = transport.subscribe.call_args[0][1] assert callback != recipient + assert sid == transport.subscribe.return_value # Part II: Message handling via unwrapper check_message_handling_via_unwrapper(callback, recipient, transport, rw_mock, False) @@ -78,12 +79,13 @@ def test_wrapping_a_subscription_allowing_non_recipe_messages(rw_mock): '''Test queue subscription with recipe wrapper allowing non-recipe messages to pass through.''' transport, recipient = mock.Mock(), mock.Mock() - workflows.recipe.wrap_subscribe(transport, mock.sentinel.channel, recipient, + sid = workflows.recipe.wrap_subscribe(transport, mock.sentinel.channel, recipient, mock.sentinel.irrelevant_extra_arg, keyword=mock.sentinel.keyword_arg, allow_non_recipe_messages=True) transport.subscribe.assert_called_once() callback = transport.subscribe.call_args[0][1] + assert sid == transport.subscribe.return_value # Part II: Message handling via unwrapper check_message_handling_via_unwrapper(callback, recipient, transport, rw_mock, True) @@ -93,7 +95,7 @@ def test_wrapping_a_broadcast_subscription(rw_mock): '''Test topic subscription with recipe wrapper.''' transport, recipient = mock.Mock(), mock.Mock() - workflows.recipe.wrap_subscribe_broadcast(transport, mock.sentinel.channel, recipient, + sid = workflows.recipe.wrap_subscribe_broadcast(transport, mock.sentinel.channel, recipient, mock.sentinel.irrelevant_extra_arg, keyword=mock.sentinel.keyword_arg) # Channel and any extra arguments must be passed on to transport layer. @@ -102,6 +104,7 @@ def test_wrapping_a_broadcast_subscription(rw_mock): mock.sentinel.irrelevant_extra_arg, keyword=mock.sentinel.keyword_arg) callback = transport.subscribe_broadcast.call_args[0][1] assert callback != recipient + assert sid == transport.subscribe_broadcast.return_value # Part II: Message handling via unwrapper check_message_handling_via_unwrapper(callback, recipient, transport, rw_mock, False) @@ -124,7 +127,7 @@ def test_wrapping_a_subscription_with_log_extension(): lext.exit.assert_not_called() lext.recipient() - workflows.recipe.wrap_subscribe(transport, mock.sentinel.channel, recipient, + sid = workflows.recipe.wrap_subscribe(transport, mock.sentinel.channel, recipient, log_extender=lext) # Channel and any extra arguments must be passed on to transport layer. @@ -132,6 +135,7 @@ def test_wrapping_a_subscription_with_log_extension(): transport.subscribe.assert_called_once_with(mock.sentinel.channel, mock.ANY) callback = transport.subscribe.call_args[0][1] assert callback != recipient + assert sid == transport.subscribe.return_value # Part II: Message handling
Return subscription IDs for wrapped subscriptions That way subscriptions created via the recipe wrapper can be unsubscribed again. Fixes #<I>.
DiamondLightSource_python-workflows
train
4b625ced123e3ee8b8d8adba61603ac13f6207a2
diff --git a/lib/provider.js b/lib/provider.js index <HASH>..<HASH> 100644 --- a/lib/provider.js +++ b/lib/provider.js @@ -26,7 +26,7 @@ function Provider(options) { this.options = Object.assign({}, defaultOptions, options); - var gethApiDouble = new GethApiDouble(Object.assign({}, options, { _provider: self })); + var gethApiDouble = new GethApiDouble(Object.assign({}, this.options, { _provider: self })); this.engine = new ProviderEngine({ blockTracker: new BlockTracker({ blockchain: gethApiDouble.state.blockchain })
Revert bug which causes us to log by default
trufflesuite_ganache-core
train
98b96ab1e6ef94f283377b40efe71c4abfe7e5ea
diff --git a/test/codemirror.spec.js b/test/codemirror.spec.js index <HASH>..<HASH> 100644 --- a/test/codemirror.spec.js +++ b/test/codemirror.spec.js @@ -71,7 +71,7 @@ describe('uiCodemirror', function () { $compile('<div ui-codemirror></div>')(scope); expect(CodeMirror.callCount).toEqual(1); - expect(CodeMirror).toHaveBeenCalledWith(jasmine.any(Function)); + expect(CodeMirror).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Object)); expect(codemirror).toBeDefined(); }); diff --git a/ui-codemirror.js b/ui-codemirror.js index <HASH>..<HASH> 100644 --- a/ui-codemirror.js +++ b/ui-codemirror.js @@ -18,6 +18,7 @@ angular.module('ui.codemirror', []) // Create a codemirror instance with // - the function that will to place the editor into the document. + // - the initial content of the editor. // see http://codemirror.net/doc/manual.html#api_constructor var value = tElement.text(); var codeMirror = new CodeMirror(function (cm_el) { @@ -36,7 +37,7 @@ angular.module('ui.codemirror', []) } tElement.replaceWith(cm_el); - }); + }, {value: value}); return function postLink(scope, iElement, iAttrs, ngModel) {
chore: Initialise the editor value with the element content
angular-ui_ui-codemirror
train
bcb0a1ad505fc52afd800d829f363de8e76336c0
diff --git a/core/roboconf-messaging-rabbitmq/src/main/java/net/roboconf/messaging/rabbitmq/internal/RabbitMqClientAgent.java b/core/roboconf-messaging-rabbitmq/src/main/java/net/roboconf/messaging/rabbitmq/internal/RabbitMqClientAgent.java index <HASH>..<HASH> 100644 --- a/core/roboconf-messaging-rabbitmq/src/main/java/net/roboconf/messaging/rabbitmq/internal/RabbitMqClientAgent.java +++ b/core/roboconf-messaging-rabbitmq/src/main/java/net/roboconf/messaging/rabbitmq/internal/RabbitMqClientAgent.java @@ -28,18 +28,19 @@ package net.roboconf.messaging.rabbitmq.internal; import java.io.IOException; import java.util.HashMap; import java.util.Map; +import java.util.Set; import net.roboconf.core.model.beans.Instance; import net.roboconf.core.model.helpers.InstanceHelpers; import net.roboconf.core.model.helpers.VariableHelpers; import net.roboconf.core.utils.Utils; import net.roboconf.messaging.api.client.IAgentClient; -import net.roboconf.messaging.api.reconfigurables.ReconfigurableClientAgent; -import net.roboconf.messaging.api.utils.SerializationUtils; import net.roboconf.messaging.api.messages.Message; import net.roboconf.messaging.api.messages.from_agent_to_agent.MsgCmdAddImport; import net.roboconf.messaging.api.messages.from_agent_to_agent.MsgCmdRemoveImport; import net.roboconf.messaging.api.messages.from_agent_to_agent.MsgCmdRequestImport; +import net.roboconf.messaging.api.reconfigurables.ReconfigurableClientAgent; +import net.roboconf.messaging.api.utils.SerializationUtils; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; @@ -158,12 +159,16 @@ public class RabbitMqClientAgent extends RabbitMqClient implements IAgentClient */ @Override public void publishExports( Instance instance ) throws IOException { - this.logger.fine( "Agent '" + getAgentId() + "' is publishing its exports." ); // For all the exported variables... // ... find the component or facet name... - for( String facetOrComponentName : VariableHelpers.findPrefixesForExportedVariables( instance )) + Set<String> names = VariableHelpers.findPrefixesForExportedVariables( instance ); + if( names.isEmpty()) + this.logger.fine( "Agent '" + getAgentId() + "' is publishing its exports." ); + + else for( String facetOrComponentName : names ) { publishExports( instance, facetOrComponentName ); + } } @@ -211,6 +216,9 @@ public class RabbitMqClientAgent extends RabbitMqClient implements IAgentClient // ... find the component or facet name... for( String facetOrComponentName : VariableHelpers.findPrefixesForExportedVariables( instance )) { + // Log here, for debug + this.logger.fine( "Agent '" + getAgentId() + "' is un-publishing its exports (" + facetOrComponentName + ")." ); + // Publish them MsgCmdRemoveImport message = new MsgCmdRemoveImport( facetOrComponentName, @@ -243,11 +251,11 @@ public class RabbitMqClientAgent extends RabbitMqClient implements IAgentClient String exchangeName = RabbitMqUtils.buildExchangeName( this.applicationName, false ); if( command == ListenerCommand.START ) { - this.logger.fine( "Agent '" + getAgentId() + "' starts listening requests from other agents." ); + this.logger.fine( "Agent '" + getAgentId() + "' starts listening requests from other agents (" + facetOrComponentName + ")." ); this.channel.queueBind( queueName, exchangeName, routingKey ); } else { - this.logger.fine( "Agent '" + getAgentId() + "' stops listening requests from other agents." ); + this.logger.fine( "Agent '" + getAgentId() + "' stops listening requests from other agents (" + facetOrComponentName + ")." ); this.channel.queueUnbind( queueName, exchangeName, routingKey ); } } @@ -266,6 +274,9 @@ public class RabbitMqClientAgent extends RabbitMqClient implements IAgentClient // ... find the component or facet name... for( String facetOrComponentName : VariableHelpers.findPrefixesForImportedVariables( instance )) { + // Log here, for debug + this.logger.fine( "Agent '" + getAgentId() + "' is requesting exports from other agents (" + facetOrComponentName + ")." ); + // ... and ask to publish them. // Grouping variable requests by prefix reduces the number of messages. MsgCmdRequestImport message = new MsgCmdRequestImport( facetOrComponentName ); @@ -295,11 +306,11 @@ public class RabbitMqClientAgent extends RabbitMqClient implements IAgentClient String exchangeName = RabbitMqUtils.buildExchangeName( this.applicationName, false ); if( command == ListenerCommand.START ) { - this.logger.fine( "Agent '" + getAgentId() + "' starts listening exports from other agents." ); + this.logger.fine( "Agent '" + getAgentId() + "' starts listening exports from other agents (" + facetOrComponentName + ")." ); this.channel.queueBind( queueName, exchangeName, routingKey ); } else { - this.logger.fine( "Agent '" + getAgentId() + "' stops listening exports from other agents." ); + this.logger.fine( "Agent '" + getAgentId() + "' stops listening exports from other agents (" + facetOrComponentName + ")." ); this.channel.queueUnbind( queueName, exchangeName, routingKey ); } }
#<I> Improve log messages in the agent's messaging (RabbitMQ)
roboconf_roboconf-platform
train
d487f05d51f611e35286205f523a588cfbfa87d9
diff --git a/spyderlib/widgets/editor.py b/spyderlib/widgets/editor.py index <HASH>..<HASH> 100644 --- a/spyderlib/widgets/editor.py +++ b/spyderlib/widgets/editor.py @@ -1380,7 +1380,8 @@ class EditorStack(QWidget): if self.inspector is not None and self.inspector.dockwidget.isVisible(): # ObjectInspector widget exists and is visible self.inspector.set_object_text(qstr) - self.setFocus() + editor = self.get_current_editor() + editor.setFocus() def new(self, filename, encoding, text): """
Fixed Issue <I>: after calling object inspector automatically (with 'object inspector link' feature), the editor was loosing focus
spyder-ide_spyder
train
534395e7ea23109495aff3b0e63762af6d332378
diff --git a/src/Translation/TranslationFile.php b/src/Translation/TranslationFile.php index <HASH>..<HASH> 100644 --- a/src/Translation/TranslationFile.php +++ b/src/Translation/TranslationFile.php @@ -139,7 +139,6 @@ class TranslationFile ->name('*.php') ->notName('*~') ->exclude(['cache', 'config', 'database', 'resources', 'tests']) - ->in($this->app['resources']->getPath('apppath')) ->in(__DIR__ . DIRECTORY_SEPARATOR . '..'); foreach ($finder as $file) {
There are no php files (with translatable strings) in app folder.
bolt_bolt
train
6c12fcb62428b82291412633f2466989b74fe7e3
diff --git a/components/lib/datatable/BodyCell.js b/components/lib/datatable/BodyCell.js index <HASH>..<HASH> 100644 --- a/components/lib/datatable/BodyCell.js +++ b/components/lib/datatable/BodyCell.js @@ -511,7 +511,7 @@ export class BodyCell extends Component { const align = this.getColumnProp('align'); const value = this.resolveFieldData(); const cellClassName = ObjectUtils.getPropValue(this.props.cellClassName, value, { props: this.props.tableProps, rowData: this.props.rowData, column: this.props.column }); - const className = classNames(this.getColumnProp('bodyClassName'), this.getColumnProp('class'), cellClassName, { + const className = classNames(this.getColumnProp('bodyClassName'), this.getColumnProp('className'), cellClassName, { 'p-selection-column': selectionMode !== null, 'p-editable-column': editor, 'p-cell-editing': editor && this.state.editing,
Fixed #<I> - Body cell is not assigned with the className property of Column
primefaces_primereact
train
68753db53f3c80f8dbf5cbf3f9163c31778dafcc
diff --git a/ChangeLog.md b/ChangeLog.md index <HASH>..<HASH> 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,5 +1,10 @@ # Changelog +## v2.4.3 + +- Corrected unneded config in DependencyInjection (04/03/2020) +- Removed sitch function to reduce Cyclomatic complexity (05/03/2020) + ## v2.4.2 - Cosmetic changes dur to Codacy review (04/03/2020) @@ -109,7 +114,6 @@ - Created branch 1.x (30/08/2018) - Modified files to use own sytem of key-value for config (30/08/2018) - ## v1.x ## v1.2.2 diff --git a/DependencyInjection/c975LConfigExtension.php b/DependencyInjection/c975LConfigExtension.php index <HASH>..<HASH> 100644 --- a/DependencyInjection/c975LConfigExtension.php +++ b/DependencyInjection/c975LConfigExtension.php @@ -31,8 +31,5 @@ class c975LConfigExtension extends Extension new FileLocator(__DIR__.'/../Resources/config') ); $loader->load('services.yml'); - - $configuration = new Configuration(); - $processedConfig = $this->processConfiguration($configuration, $configs); } } diff --git a/Form/ConfigType.php b/Form/ConfigType.php index <HASH>..<HASH> 100644 --- a/Form/ConfigType.php +++ b/Form/ConfigType.php @@ -27,25 +27,16 @@ class ConfigType extends AbstractType { foreach ($options['data'] as $key => $value) { if ('configDataReserved' !== $key && is_array($value)) { - switch ($value['type']) { - case 'bool': - $classType = 'CheckboxType'; - break; - case 'date': - $classType = 'DateType'; - break; - case 'int': - $classType = 'IntegerType'; - break; - case 'float': - $classType = 'NumberType'; - break; - case 'array': - case 'string': - default: - $classType = 'TextType'; - break; - } + $classesTypes = array( + 'bool' => 'CheckboxType', + 'date' => 'DateType', + 'int' => 'IntegerType', + 'float' => 'NumberType', + 'array' => 'TextType', + 'string' => 'TextType', + ); + + $classType = isset($classesTypes[$value['type']]) ? $classesTypes[$value['type']] : 'TextType'; //Defines field options $fieldOptions = array( diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,6 @@ ConfigBundle does the following: ## Bundle installation - ### Step 1: Download the Bundle Use [Composer](https://getcomposer.org) to install the library diff --git a/Service/ConfigService.php b/Service/ConfigService.php index <HASH>..<HASH> 100644 --- a/Service/ConfigService.php +++ b/Service/ConfigService.php @@ -231,9 +231,9 @@ class ConfigService implements ConfigServiceInterface */ public function getConfigFolder() { - $rootFolder = $this->container->getParameter('kernel.root_dir'); + $root = $this->container->getParameter('kernel.root_dir'); - return '4' === substr(Kernel::VERSION, 0, 1) ? $rootFolder . '/../config/' : $rootFolder . '/../app/config/'; + return '3' === substr(Kernel::VERSION, 0, 1) ? $root . '/../app/config/' : $root . '/../config/'; } /**
- Corrected unneded config in DependencyInjection (<I>/<I>/<I>) - Removed sitch function to reduce Cyclomatic complexity (<I>/<I>/<I>)
975L_ConfigBundle
train
931fb3d8ddab068d79a7bf7c66b1f989ffdda200
diff --git a/lib/policies/oauth2-introspect/oauth2-introspect.js b/lib/policies/oauth2-introspect/oauth2-introspect.js index <HASH>..<HASH> 100644 --- a/lib/policies/oauth2-introspect/oauth2-introspect.js +++ b/lib/policies/oauth2-introspect/oauth2-introspect.js @@ -13,7 +13,8 @@ module.exports = function (actionParams) { const requestedScopes = req.egContext.apiEndpoint.scopes; const scopeCheck = (tokenData, done) => { - const avaiableScopes = tokenData.scopes ? tokenData.scopes.split(' ') : []; + const tokenDataScopes = tokenData.scope || tokenData.scopes; + const avaiableScopes = tokenDataScopes ? tokenDataScopes.split(' ') : []; if (requestedScopes.every(scope => avaiableScopes.includes(scope))) { return done(null, tokenData);
Fixed: OAuth2 introspection cannot identify 'scope' claim token implementation Now OAuth2 introspection can read 'scope' and 'scopes' claims from different OAuth2 Token scopes implementations
ExpressGateway_express-gateway
train
3c6926cddc59e634d8eaa1c22cba9bf9d6dc0f7d
diff --git a/manager-bundle/src/Composer/ScriptHandler.php b/manager-bundle/src/Composer/ScriptHandler.php index <HASH>..<HASH> 100644 --- a/manager-bundle/src/Composer/ScriptHandler.php +++ b/manager-bundle/src/Composer/ScriptHandler.php @@ -50,27 +50,25 @@ class ScriptHandler $fs->ensureDirectoryExists($binDir); $fs->ensureDirectoryExists($varDir); - $consoleInstalled = static::installContaoConsole( + static::installContaoConsole( static::findContaoConsole($composer), $binDir . '/console', $fs->findShortestPath($binDir, $vendorDir, true), $fs->findShortestPath($binDir, $varDir, true) ); - if ($consoleInstalled) { - $event->getIO()->write(' Added the console entry point.', false); - - self::executeCommand( - sprintf( - '%s/console contao:generate-entry-points --ansi --web-dir=%s --var-dir=%s --vendor-dir=%s --force', - escapeshellarg($extra['symfony-bin-dir']), - escapeshellarg($extra['symfony-web-dir']), - escapeshellarg($extra['symfony-var-dir']), - escapeshellarg($fs->findShortestPath(getcwd(), $vendorDir, true)) - ), - $event - ); - } + $event->getIO()->write(' Added the console entry point.', false); + + self::executeCommand( + sprintf( + '%s/console contao:install-web-dir --ansi --web-dir=%s --var-dir=%s --vendor-dir=%s --force', + escapeshellarg($extra['symfony-bin-dir']), + escapeshellarg($extra['symfony-web-dir']), + escapeshellarg($extra['symfony-var-dir']), + escapeshellarg($fs->findShortestPath(getcwd(), $vendorDir, true)) + ), + $event + ); } private static function installContaoConsole($filePath, $installTo, $vendorDir, $kernelRootDir) @@ -86,12 +84,11 @@ class ScriptHandler ); if (file_put_contents($installTo, $content) > 0) { - chmod($installTo, 0755); - - return true; + @chmod($installTo, 0755); + return; } - return false; + throw new \UnderflowException('Contao console script could not be installed.'); } private static function findContaoConsole(Composer $composer) @@ -102,7 +99,7 @@ class ScriptHandler } } - throw new \UnderflowException('Contao console script could not be installed'); + throw new \UnderflowException('Contao console script was not found.'); } /**
[Manager] Adjust composer script handler to use new command and throw exceptions on errors
contao_contao
train
8e01c93577be5ac7cb2545f2292b573434313f77
diff --git a/lib/api_client_base/request.rb b/lib/api_client_base/request.rb index <HASH>..<HASH> 100644 --- a/lib/api_client_base/request.rb +++ b/lib/api_client_base/request.rb @@ -59,8 +59,12 @@ module APIClientBase end def default_uri - uri = URI(host) - uri.path = api_client_base_path if !api_client_base_path.nil? + uri = if !api_client_base_path.nil? + URI.join(host, api_client_base_path) + else + URI(host) + end + uri.to_s end
Use URI.join to support appending a path to hosts that already have a path
bloom-solutions_api_client_base-ruby
train
df18be74a34afca43accfa98322d53eb27e5ac04
diff --git a/test/integration/rtpbroadcast.js b/test/integration/rtpbroadcast.js index <HASH>..<HASH> 100644 --- a/test/integration/rtpbroadcast.js +++ b/test/integration/rtpbroadcast.js @@ -66,8 +66,10 @@ describe('Rtpbroadcast tests', function() { }) .then(function(response) { var list = response.getData('list'); - assert.equal(list.length, 1); - assert.equal(list[0]['id'], mountpointId); + var createdMountpoint = jQuery.grep(list, function(mountpoint) { + return mountpoint.id == mountpointId; + }); + assert.equal(createdMountpoint.length, 1); return rtpbroadcastPlugin.destroy(mountpointId); }) .then(function(response) {
Fix rtpbroadcast integration test
cargomedia_janus-gateway-js
train
8eaf3303c2486a3edc067d81aa34a9645f316c34
diff --git a/spec/public/lawnchair-spec.js b/spec/public/lawnchair-spec.js index <HASH>..<HASH> 100644 --- a/spec/public/lawnchair-spec.js +++ b/spec/public/lawnchair-spec.js @@ -145,6 +145,14 @@ context('Lawnchair', function(){ }); }); + should( 'get 10 items in a page.', function() { + store.nuke(); + for (var i = 0; i < 300; i++) { + store.save({key: i, value: "test" + i}); + } + store.paged(1,'equals(r.length, 10); start();'); + }); + // --- }); diff --git a/src/Lawnchair.js b/src/Lawnchair.js index <HASH>..<HASH> 100644 --- a/src/Lawnchair.js +++ b/src/Lawnchair.js @@ -22,6 +22,7 @@ Lawnchair.prototype = { 'blackberry':window.BlackBerryPersistentStorageAdaptor }; this.adaptor = opts.adaptor ? new adaptors[opts.adaptor](opts) : new WebkitSQLiteAdaptor(opts); + // Check for native JSON functions. if (!JSON || !JSON.stringify) throw "Native JSON functions unavailable - please include http://www.json.org/json2.js or run on a decent browser :P"; }, @@ -44,6 +45,9 @@ Lawnchair.prototype = { // Removes all documents from a store and returns self. nuke:function(callback) {this.adaptor.nuke(callback);return this}, + // Returns a page of results based on offset provided by user and perPage option + paged:function(page, callback) {this.adaptor.paged(page, callback)}, + /** * Iterator that accepts two paramters (methods or eval strings): * diff --git a/src/adaptors/WebkitSQLiteAdaptor.js b/src/adaptors/WebkitSQLiteAdaptor.js index <HASH>..<HASH> 100644 --- a/src/adaptors/WebkitSQLiteAdaptor.js +++ b/src/adaptors/WebkitSQLiteAdaptor.js @@ -25,6 +25,7 @@ WebkitSQLiteAdaptor.prototype = { this.display = merge('shed', opts.display ); this.max = merge(65536, opts.max ); this.db = merge(null, opts.db ); + this.perPage = merge(10, opts.perPage ); // default sqlite callbacks this.onError = function(){}; @@ -141,6 +142,29 @@ WebkitSQLiteAdaptor.prototype = { that.onError); }); }, + paged:function(page, callback) { + var cb = this.terseToVerboseCallback(callback); + var that = this; + this.db.transaction(function(t) { + var offset = that.perPage * (page - 1); // a little offset math magic so users don't have to be 0-based + var sql = "SELECT * FROM " + that.table + " ORDER BY timestamp ASC LIMIT ? OFFSET ?"; + t.executeSql(sql, [that.perPage, offset], function(tx, results) { + if (results.rows.length == 0 ) { + cb([]); + } else { + var r = []; + for (var i = 0, l = results.rows.length; i < l; i++) { + var raw = results.rows.item(i).value; + var obj = that.deserialize(raw); + obj.key = results.rows.item(i).id; + r.push(obj); + } + cb(r); + } + }, + that.onError); + }); + }, remove:function(keyOrObj, callback) { var that = this; if (callback)
Add paging to Lawnchair, at least for Webkit. The default page size is <I> records but can be modified via options when initializing the Lawnchair.
brianleroux_lawnchair
train
7e73d16f0efc904af6ee7cd978f7cc8993d598a9
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -20,8 +20,8 @@ __requires__ = 'setuptools >= 3.0.0' try: from setuptools import setup, Extension, find_packages, __version__ as stools_ver except: - print "Looks like your version of setuptools is too old. You should use " \ - "provided ez_setup.py to upgrade your installation." + print "Looks like your version (%s) of setuptools is too old. You should use " \ + "provided ez_setup.py to upgrade your installation." % stools_ver sys.exit(1) """
[setup] print version, if required version is not found.
markovmodel_PyEMMA
train
42eb640ac73253c869b0eac8707500ff95429e0c
diff --git a/dist/pptxgen.js b/dist/pptxgen.js index <HASH>..<HASH> 100644 --- a/dist/pptxgen.js +++ b/dist/pptxgen.js @@ -52,6 +52,7 @@ Number.isInteger = Number.isInteger || function(value) { // Detect Node.js (NODEJS is ultimately used to determine how to save: either `fs` or web-based, so using fs-detection is perfect) var NODEJS = false; +var APPJS = false; { // NOTE: `NODEJS` determines which network library to use, so using fs-detection is apropos. if ( typeof module !== 'undefined' && module.exports && typeof require === 'function' && typeof window === 'undefined' ) { @@ -63,11 +64,13 @@ var NODEJS = false; NODEJS = false; } } + else if ( typeof module !== 'undefined' && module.exports && typeof require === 'function' && typeof window !== 'undefined') { + APPJS = true; + } } -// [Node.js] <script> includes -// TODO: Issue #137 (move these to very bottom where other require()s are) -if ( NODEJS ) { +// Require [include] colors/shapes for Node/Angular/React, etc. +if ( NODEJS || APPJS ) { var gObjPptxColors = require('../dist/pptxgen.colors.js'); var gObjPptxShapes = require('../dist/pptxgen.shapes.js'); } @@ -75,7 +78,7 @@ if ( NODEJS ) { var PptxGenJS = function(){ // APP var APP_VER = "2.5.0-beta"; - var APP_BLD = "20190126"; + var APP_BLD = "20190204"; // CONSTANTS var MASTER_OBJECTS = { @@ -161,7 +164,7 @@ var PptxGenJS = function(){ // A: Create internal pptx object var gObjPptx = {}; - // B: Set Presentation Property Defaults + // B: Set Presentation property defaults { // Presentation props/metadata gObjPptx.author = 'PptxGenJS'; @@ -5592,7 +5595,7 @@ function getUuid(uuidFormat) { }); } -// [Node.js] support +// NodeJS support if ( NODEJS ) { var jQuery = null; var fs = null; @@ -5612,17 +5615,17 @@ if ( NODEJS ) { try { JSZip = require("jszip"); } catch(ex){ console.error("Unable to load `jszip`"); throw 'LIB-MISSING-JSZIP'; } try { sizeOf = require("image-size"); } catch(ex){ console.error("Unable to load `image-size`"); throw 'LIB-MISSING-IMGSIZE'; } - // C: Export module + // LAST: Export module module.exports = PptxGenJS; } -// Angular support -else if ( typeof module !== 'undefined' && module.exports && typeof require === 'function' && typeof window !== 'undefined') { +// Angular/React/etc support +else if ( APPJS ) { // A: jQuery dependency try { jQuery = require("jquery"); } catch(ex){ console.error("Unable to load `jquery`!\n"+ex); throw 'LIB-MISSING-JQUERY'; } // B: Other dependencies try { JSZip = require("jszip"); } catch(ex){ console.error("Unable to load `jszip`"); throw 'LIB-MISSING-JSZIP'; } - // C: Export module + // LAST: Export module module.exports = PptxGenJS; } diff --git a/examples/nodejs-demo.js b/examples/nodejs-demo.js index <HASH>..<HASH> 100644 --- a/examples/nodejs-demo.js +++ b/examples/nodejs-demo.js @@ -1,7 +1,7 @@ /* * NAME: nodejs-demo.js * AUTH: Brent Ely (https://github.com/gitbrent/) - * DATE: 20181023 + * DATE: 20190204 * DESC: PptxGenJS feature demos for Node.js * REQS: npm 4.x + `npm install pptxgenjs` * @@ -92,6 +92,8 @@ else { var pptx = new PptxGenJS(); var slide = pptx.addNewSlide(); slide.addText( 'New Node Presentation', {x:1.5, y:1.5, w:6, h:2, margin:0.1, fill:'FFFCCC'} ); + // Test that `pptxgen.shapes.js` was loaded/is available + slide.addShape(pptx.shapes.OVAL_CALLOUT, { x:6, y:2, w:3, h:2, fill:'00FF00', line:'000000', lineSize:1 }); // **NOTE**: Only uncomment one EXAMPLE at a time
made shapes and colors libraries available to front end apps (Issue #<I>)
gitbrent_PptxGenJS
train
0b3980a0c18fb3a99f6e8f9a79a0060bf8a19d4d
diff --git a/tests/conftest.py b/tests/conftest.py index <HASH>..<HASH> 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -47,7 +47,8 @@ def UnboundUser(engine): age = bloop.Column(bloop.Integer) name = bloop.Column(bloop.String) email = bloop.Column(bloop.String) - joined = bloop.Column(bloop.DateTime) + # Field with dynamo_name != model_name + joined = bloop.Column(bloop.DateTime, name="j") by_email = bloop.GlobalSecondaryIndex(hash_key="email", projection="all") diff --git a/tests/test_filter.py b/tests/test_filter.py index <HASH>..<HASH> 100644 --- a/tests/test_filter.py +++ b/tests/test_filter.py @@ -181,7 +181,7 @@ def test_select_specific(engine, User): result = q.select([User.email, User.joined]).all() expected = {"Select": "SPECIFIC_ATTRIBUTES", - "ExpressionAttributeNames": {"#n0": "email", "#n1": "joined", + "ExpressionAttributeNames": {"#n0": "email", "#n1": "j", "#n2": "id"}, "ScanIndexForward": True, "ExpressionAttributeValues": {":v3": {"S": str(user_id)}}, diff --git a/tests/test_model.py b/tests/test_model.py index <HASH>..<HASH> 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -1,3 +1,4 @@ +import arrow import uuid import bloop.column import bloop.index @@ -12,7 +13,7 @@ def test_default_model_init(User): """ Missing attributes are set to `None` """ user = User(id=uuid.uuid4(), email="[email protected]") assert user.email == "[email protected]" - assert user.name is None + assert not hasattr(user, "name") def test_load_default_init(engine, local_bind): @@ -56,12 +57,15 @@ def test_load_dump(User): """ _load and _dump should be symmetric """ user_id = uuid.uuid4() - user = User(id=user_id, name="name", email="[email protected]", age=25) + now = arrow.now() + user = User(id=user_id, name="name", email="[email protected]", age=25, + joined=now) serialized_user = { "id": {"S": str(user_id)}, "age": {"N": "25"}, "name": {"S": "name"}, - "email": {"S": "[email protected]"} + "email": {"S": "[email protected]"}, + "j": {"S": now.to("utc").isoformat()} } assert User._load(serialized_user) == user
Add field with different dynamo_name to test User
numberoverzero_bloop
train
ac6c25f7629011c9a51692e684b1e1db3422585d
diff --git a/spacy/_ml.py b/spacy/_ml.py index <HASH>..<HASH> 100644 --- a/spacy/_ml.py +++ b/spacy/_ml.py @@ -381,7 +381,8 @@ def fine_tune(embedding, combine=None): flat_grad = model.ops.flatten(d_output) model.d_mix[1] += flat_tokvecs.dot(flat_grad.T).sum() model.d_mix[0] += flat_vecs.dot(flat_grad.T).sum() - sgd(model._mem.weights, model._mem.gradient, key=model.id) + if sgd is not None: + sgd(model._mem.weights, model._mem.gradient, key=model.id) return d_output return output, fine_tune_bwd model = wrap(fine_tune_fwd, embedding)
Check SGD is not None in update
explosion_spaCy
train
3a773d6fd2e5a4c60ae093c16eedfdc6518ec46c
diff --git a/tests/HigherOrderInput.test.js b/tests/HigherOrderInput.test.js index <HASH>..<HASH> 100644 --- a/tests/HigherOrderInput.test.js +++ b/tests/HigherOrderInput.test.js @@ -64,9 +64,7 @@ describe('ListInput', () => { const wrapper = mount( <ListInput ofType={GraphQLString} onChange={() => {}} /> ); - wrapper.find('input[type="button"]').simulate('click'); - - expect(wrapper.find('input[type="text"]').length).toEqual(2); + expect(wrapper.find('input[type="button"]').prop('value')).toEqual('+'); }); it('displays nested button to add item for nested lists', async () => { @@ -74,11 +72,43 @@ describe('ListInput', () => { <ListInput ofType={new GraphQLList(GraphQLString)} onChange={() => {}} /> ); wrapper.find('input[type="button"]').forEach(w => w.simulate('click')); - expect(wrapper.find('input[type="text"]').length).toEqual(3); }); - // TODO test add + it('does not display remove button for list with one item', () => { + const wrapper = mount( + <ListInput ofType={GraphQLString} onChange={() => {}} /> + ); + expect(wrapper.find('input[type="text"]').length).toEqual(1); + }); + + it('displays remove button for list with more than one item', () => { + const wrapper = mount( + <ListInput ofType={GraphQLString} onChange={() => {}} /> + ); + wrapper.find('input[type="button"]').simulate('click'); + expect(wrapper.find('input[type="button"]').length).toEqual(3); + }); + + it('clicking remove button removes item from list', () => { + const wrapper = mount( + <ListInput ofType={GraphQLString} onChange={() => {}} /> + ); + wrapper.find('input[type="button"]').simulate('click'); // add + wrapper + .find('input[type="button"]') + .first() + .simulate('click'); // remove + expect(wrapper.find('input[type="text"]').length).toEqual(1); + }); + + it('clicking add button adds new item to list', () => { + const wrapper = mount( + <ListInput ofType={GraphQLString} onChange={() => {}} /> + ); + wrapper.find('input[type="button"]').simulate('click'); + expect(wrapper.find('input[type="text"]').length).toEqual(2); + }); }); const setInput = 0; diff --git a/tests/HigherOrderOutput.test.js b/tests/HigherOrderOutput.test.js index <HASH>..<HASH> 100644 --- a/tests/HigherOrderOutput.test.js +++ b/tests/HigherOrderOutput.test.js @@ -158,4 +158,12 @@ describe('ObjectOutput', () => { )); expect(value.x.selected).toNotExist(); }); + + it('field arguments are displayed', () => { + const fields = { + data: { args: [{ name: 'x', type: GraphQLInt }], type: GraphQLString } + }; + const wrapper = wrap({ name: '', fields }); + expect(wrapper.find('input[type="number"]').exists()).toExist(); + }); });
test(args): Add tests for removing items from lists and displaying arguments
pi-cubed_typed-ui
train
9d6351fd5a79ea708802279555957e0053930d71
diff --git a/wffweb/src/main/java/com/webfirmframework/wffweb/css/UrlCss3Value.java b/wffweb/src/main/java/com/webfirmframework/wffweb/css/UrlCss3Value.java index <HASH>..<HASH> 100644 --- a/wffweb/src/main/java/com/webfirmframework/wffweb/css/UrlCss3Value.java +++ b/wffweb/src/main/java/com/webfirmframework/wffweb/css/UrlCss3Value.java @@ -58,10 +58,13 @@ public class UrlCss3Value extends AbstractBean<UrlCss3Value> { * @since 1.0.0 * @author WFF */ - private void extractAndAssign(String urlString) { - urlString = urlString.trim(); - if (urlString.startsWith("url(") && urlString.contains(")")) { - final String[] urlStringParts = urlString.split("[)]"); + private void extractAndAssign(final String urlString) { + + final String urlStringTrimmed = urlString.trim(); + + if (urlStringTrimmed.startsWith("url(") + && urlStringTrimmed.contains(")")) { + final String[] urlStringParts = urlStringTrimmed.split("[)]"); String extractedUrl = urlStringParts[0] .substring(urlStringParts[0].indexOf('(')); @@ -85,7 +88,7 @@ public class UrlCss3Value extends AbstractBean<UrlCss3Value> { } } } else { - throw new InvalidValueException(urlString + throw new InvalidValueException(urlStringTrimmed + " is not a valid url string. It should be in the format of url(\"Test.png\")75 158 or url(\"Testing.png\")"); } }
Code improvement Avoided reassigning parameters such as 'urlString'
webfirmframework_wff
train
bc975100698ed0b1a63efc2f2a9699bb8a738226
diff --git a/src/Socket.php b/src/Socket.php index <HASH>..<HASH> 100644 --- a/src/Socket.php +++ b/src/Socket.php @@ -479,7 +479,7 @@ class Socket implements Stringable $return = @socket_import_stream($stream); if ($return === false || is_null($return)) { - throw new SocketException($stream); + throw new SocketException($stream instanceof Socketresource ? $stream : null); } return new self($return); @@ -802,6 +802,7 @@ class Socket implements Stringable public function setBlocking(bool $bool): void { $this->checkInvalidResourceState(); + if ($bool) { @socket_set_block($this->resource); } else {
Don't pass non-socket resource to SocketException
navarr_Sockets
train
621b3f70382d283bdd3f40bc845848f5c39d2a2a
diff --git a/lib/networking/voicetransports/VoiceTransportBase.js b/lib/networking/voicetransports/VoiceTransportBase.js index <HASH>..<HASH> 100644 --- a/lib/networking/voicetransports/VoiceTransportBase.js +++ b/lib/networking/voicetransports/VoiceTransportBase.js @@ -139,7 +139,7 @@ class VoiceTransportBase { const decryptedPacket = new Buffer(packet.length - 16); header.copy(decryptedPacket); - for (let i = 0; i < decrypted.length; i++) { + for (var i = 0, len = decrypted.length; i < len; i++) { decryptedPacket[12 + i] = decrypted[i]; } @@ -172,20 +172,21 @@ class VoiceTransportBase { const rtpPacket = this.rtpPacket; this.header.copy(this.rtpPacket, 0, 0, 12); - for (let i = 0; i < packet.length; i++) { + for (var i = 0, len = packet.length; i < len; i++) { rtpPacket[12 + i] = packet[i]; } this.sequence++; this.timestamp += sampleCount; - this.sequence %= 0xFFFF + 1; - this.timestamp %= 0xFFFFFFFF + 1; + if (this.sequence >= 0xFFFF) this.sequence %= 0xFFFF + 1; + if (this.timestamp >= 0xFFFFFFFF) this.timestamp %= 0xFFFFFFFF + 1; this.packetsSent++; - this.packetsSent %= 0xFFFFFFFF + 1; this.bytesMuxed += packetLength; - this.bytesMuxed %= 0xFFFFFFFF + 1; + + if (this.packetsSent >= 0xFFFFFFFF) this.packetsSent %= 0xFFFFFFFF + 1; + if (this.bytesMuxed >= 0xFFFFFFFF) this.bytesMuxed %= 0xFFFFFFFF + 1; return rtpPacket.slice(0, packet.length + 12); }
Optimize muxing packet copy loops
qeled_discordie
train
f27bd985ee1cf5d7e6d7e30bf0ed55487161c1f5
diff --git a/server.js b/server.js index <HASH>..<HASH> 100644 --- a/server.js +++ b/server.js @@ -291,8 +291,9 @@ function sendMessage(fromDevice, data, fn){ if(!check.error){ if(securityImpl.canSend(fromDevice, check)){ - //to phone, but not from same phone - if(check.phoneNumber && (clonedMsg.fromPhone !== check.phoneNumber)){ + // //to phone, but not from same phone + // if(check.phoneNumber && (clonedMsg.fromPhone !== check.phoneNumber)){ + if(check.phoneNumber && check.type == "outboundSMS")){ // SMS handler console.log("Sending SMS to", check.phoneNumber); require('./lib/sendSms')(device, JSON.stringify(clonedMsg.payload), function(sms){
added check for type=outboundSMS to sendMessages check
octoblu_meshblu
train