hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
e91dec8195273d8690421b1e4763808874f4b1eb
diff --git a/lib/jsdom/level2/style.js b/lib/jsdom/level2/style.js index <HASH>..<HASH> 100644 --- a/lib/jsdom/level2/style.js +++ b/lib/jsdom/level2/style.js @@ -62,7 +62,7 @@ module.exports = core => { StyleSheetList.prototype.__proto__ = Array.prototype; StyleSheetList.prototype.item = function item(i) { - return this[i]; + return Object.prototype.hasOwnProperty.call(this, i) ? this[i] : null; }; core.StyleSheetList = StyleSheetList; diff --git a/test/level2/style.js b/test/level2/style.js index <HASH>..<HASH> 100644 --- a/test/level2/style.js +++ b/test/level2/style.js @@ -475,6 +475,13 @@ exports.tests = { t.done(); }, + "StyleSheetList.prototype.item returns null on index out of bounds": t => { + const document = jsdom.jsdom(); + t.strictEqual(document.styleSheets[0], undefined); + t.strictEqual(document.styleSheets.item(0), null); + t.done(); + }, + "setting background to null works correctly (GH-1499)": t => { const document = jsdom.jsdom(); document.body.innerHTML = `<div id="ctrl" style="background:#111;border:1px"></div>`;
Make StyleSheetList.prototype.item correctly return null when appropriate Per spec, "If there is no indexth object in the collection, then the method must return null."
jsdom_jsdom
train
9454abfc0af3071612e3b7b048097023e29fcb0a
diff --git a/test/index.js b/test/index.js index <HASH>..<HASH> 100644 --- a/test/index.js +++ b/test/index.js @@ -39,3 +39,9 @@ import './TreeIndex.test' import './utils.test' import './XMLExporter.test' import './XMLImporter.test' + +import { substanceGlobals } from 'substance' +// throw in failed asserts +substanceGlobals.ASSERTS = true +// enable this to see more info from the RenderingEngine +// substanceGlobals.VERBOSE_RENDERING_ENGINE = true
Enable throwing asserts for tests.
substance_substance
train
c71bf3779ea21f92f3713c58d4b50437e2b0b68f
diff --git a/src/Joomla/Application/AbstractCliApplication.php b/src/Joomla/Application/AbstractCliApplication.php index <HASH>..<HASH> 100644 --- a/src/Joomla/Application/AbstractCliApplication.php +++ b/src/Joomla/Application/AbstractCliApplication.php @@ -102,6 +102,6 @@ abstract class AbstractCliApplication extends AbstractApplication */ public function in() { - return rtrim(fread(STDIN, 8192), "\n"); + return rtrim(fread(STDIN, 8192), "\n\r"); } }
Trim \r from CliApplication::in()
joomla_joomla-framework
train
169cd43d22a6dd900756a9a4cea1a5da824b3b68
diff --git a/spec/matcher/ToBeAnInstanceOf.spec.php b/spec/matcher/ToBeAnInstanceOf.spec.php index <HASH>..<HASH> 100644 --- a/spec/matcher/ToBeAnInstanceOf.spec.php +++ b/spec/matcher/ToBeAnInstanceOf.spec.php @@ -29,23 +29,31 @@ describe('ToBeAnInstanceOf', function () { beforeEach(function () { $this->matcher = new ToBeAnInstanceOf("expect\Matcher"); $this->message = new FailedMessage(); + + $this->expectedMessage = "\nExpected stdClass to be an instance of expect\Matcher\n\n"; + $this->expectedMessage .= " expected: expect\Matcher\n"; + $this->expectedMessage .= " got: stdClass\n"; }); it('report failed message', function () { $this->matcher->match(new stdClass()); $this->matcher->reportFailed($this->message); - Assertion::same((string) $this->message, "\nexpected stdClass to be an instance of expect\Matcher\n"); + Assertion::same((string) $this->message, $this->expectedMessage); }); }); describe('#reportNegativeFailed', function () { beforeEach(function () { - $this->matcher = new ToBeAnInstanceOf("expect\Matcher"); + $this->matcher = new ToBeAnInstanceOf("expect\matcher\ToBeAnInstanceOf"); $this->message = new FailedMessage(); + + $this->expectedMessage = "\nExpected expect\matcher\ToBeAnInstanceOf not to be an instance of expect\matcher\ToBeAnInstanceOf\n\n"; + $this->expectedMessage .= " expected not: expect\matcher\ToBeAnInstanceOf\n"; + $this->expectedMessage .= " got: expect\matcher\ToBeAnInstanceOf\n"; }); it('report failed message', function () { $this->matcher->match($this->matcher); $this->matcher->reportNegativeFailed($this->message); - Assertion::same((string) $this->message, "\nexpected expect\matcher\ToBeAnInstanceOf not to be an instance of expect\Matcher\n"); + Assertion::same((string) $this->message, $this->expectedMessage); }); }); diff --git a/src/matcher/ToBeAnInstanceOf.php b/src/matcher/ToBeAnInstanceOf.php index <HASH>..<HASH> 100644 --- a/src/matcher/ToBeAnInstanceOf.php +++ b/src/matcher/ToBeAnInstanceOf.php @@ -13,12 +13,43 @@ namespace expect\matcher; use expect\FailedMessage; +/** + * Verify whether a particular instance. + * + * <code> + * $matcher = new ToBeAnInstanceOf('stdClass'); + * $matcher->match(new stdClass()); //return true + * + * $matcher->match(new Exception()); //return false + * </code> + * + * @package expect\matcher + * @author Noritaka Horio <holy.shared.design@gmail.com> + * @copyright Noritaka Horio <holy.shared.design@gmail.com> + */ final class ToBeAnInstanceOf implements ReportableMatcher { + + /** + * @var mixed + */ private $actual; + + /** + * @var string + */ private $expected; + + /** + * @var string + */ private $className; + /** + * Create a new matcher + * + * @param string $expected + */ public function __construct($expected) { $this->expected = $expected; @@ -40,10 +71,16 @@ final class ToBeAnInstanceOf implements ReportableMatcher */ public function reportFailed(FailedMessage $message) { - $message->appendText('expected ') + $message->appendText('Expected ') ->appendText($this->className) ->appendText(' to be an instance of ') - ->appendText($this->expected); + ->appendText($this->expected) + ->appendText("\n\n") + ->appendText(' expected: ') + ->appendText($this->expected) + ->appendText("\n") + ->appendText(' got: ') + ->appendText($this->className); } /** @@ -51,9 +88,15 @@ final class ToBeAnInstanceOf implements ReportableMatcher */ public function reportNegativeFailed(FailedMessage $message) { - $message->appendText('expected ') + $message->appendText('Expected ') ->appendText($this->className) ->appendText(' not to be an instance of ') - ->appendText($this->expected); + ->appendText($this->expected) + ->appendText("\n\n") + ->appendText(' expected not: ') + ->appendText($this->expected) + ->appendText("\n") + ->appendText(' got: ') + ->appendText($this->className); } }
Update ToBeAnInstanceOf spec
expectation-php_expect
train
6ccfccecc03cacfeb86ca27f5218b5897f3294f3
diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/auxiliary/MethodCallProxy.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/auxiliary/MethodCallProxy.java index <HASH>..<HASH> 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/auxiliary/MethodCallProxy.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/auxiliary/MethodCallProxy.java @@ -201,7 +201,7 @@ public class MethodCallProxy implements AuxiliaryType { Collections.<GenericTypeDescription>emptyList(), GenericTypeDescription.OBJECT, Collections.<ParameterDescription.Token>emptyList(), - Collections.singletonList(new TypeDescription.ForLoadedType(Exception.class)), + Collections.singletonList(new GenericTypeDescription.ForNonGenericType.OfLoadedType(Exception.class)), Collections.<AnnotationDescription>emptyList(), MethodDescription.NO_DEFAULT_VALUE); nodes.put(callMethod.asToken(), new MethodGraph.Node.Simple(callMethod)); diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/auxiliary/TypeProxy.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/auxiliary/TypeProxy.java index <HASH>..<HASH> 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/auxiliary/TypeProxy.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/auxiliary/TypeProxy.java @@ -737,7 +737,7 @@ public class TypeProxy implements AuxiliaryType { public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType.withField(new FieldDescription.Token(INSTANCE_FIELD, Opcodes.ACC_SYNTHETIC, - TypeProxy.this.implementationTarget.getInstrumentedType())); + implementationTarget.getInstrumentedType().asGenericType())); } @Override diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/FieldProxy.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/FieldProxy.java index <HASH>..<HASH> 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/FieldProxy.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/FieldProxy.java @@ -681,7 +681,7 @@ public @interface FieldProxy { public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType.withField(new FieldDescription.Token(AccessorProxy.FIELD_NAME, Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE, - this.instrumentedType)); + this.instrumentedType.asGenericType())); } @Override diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/Morph.java b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/Morph.java index <HASH>..<HASH> 100644 --- a/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/Morph.java +++ b/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/Morph.java @@ -513,7 +513,7 @@ public @interface Morph { public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType.withField(new FieldDescription.Token(RedirectionProxy.FIELD_NAME, Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE, - this.instrumentedType)); + this.instrumentedType.asGenericType())); } @Override
Further unification of refactored type system.
raphw_byte-buddy
train
2daa3a7dc087513172e9fe40a621036c7a468c74
diff --git a/src/core/env/iframe.js b/src/core/env/iframe.js index <HASH>..<HASH> 100644 --- a/src/core/env/iframe.js +++ b/src/core/env/iframe.js @@ -36,7 +36,9 @@ var FrameEnv = basis.ui.Node.subclass({ var frameWindow = this.element.contentWindow; var initCode = ''; - var code = require('./iframe_inject.code'); + // NOTE: to not use require here, because builder replace url for [number].code + // and basis.require wrogly theats it as namespace + var code = resource('./iframe_inject.code').fetch(); if (typeof code == 'function') code = basis.utils.info.fn(code).body;
fix iframe inject code build issue
basisjs_yatra
train
a27d55714fde86389563799d9e98b2d54dc02716
diff --git a/lib/govuk_app_config/govuk_xray.rb b/lib/govuk_app_config/govuk_xray.rb index <HASH>..<HASH> 100644 --- a/lib/govuk_app_config/govuk_xray.rb +++ b/lib/govuk_app_config/govuk_xray.rb @@ -8,9 +8,10 @@ module GovukXRay end def self.start - # if aws-sdk is loaded, we want to instrument that too - patch = Gem.loaded_specs.has_key?('aws-sdk-core') ? - %I[aws_sdk net_http] : %I[net_http] + # patching 'aws_sdk' seem to impose a large memory overhead, so + # don't do that by default + patch = ENV.has_key?('XRAY_PATCH_AWS_SDK') ? + %I[aws_sdk net_http] : %I[net_http] # if there isn't a name set, attempting to record a segment will # throw an error
Do not patch aws_sdk by default
alphagov_govuk_app_config
train
e3c5c237f0e076c60cd0b02aa6c93f84daea5cc9
diff --git a/mind-map/idea-mindmap/src/com/igormaznitsa/ideamindmap/editor/MindMapPanelControllerImpl.java b/mind-map/idea-mindmap/src/com/igormaznitsa/ideamindmap/editor/MindMapPanelControllerImpl.java index <HASH>..<HASH> 100644 --- a/mind-map/idea-mindmap/src/com/igormaznitsa/ideamindmap/editor/MindMapPanelControllerImpl.java +++ b/mind-map/idea-mindmap/src/com/igormaznitsa/ideamindmap/editor/MindMapPanelControllerImpl.java @@ -135,6 +135,8 @@ public class MindMapPanelControllerImpl implements MindMapPanelController, MindM public JPopupMenu makePopUpForMindMapPanel(final MindMapPanel source, final Point point, final AbstractElement element, final ElementPart partUnderMouse) { final JBPopupMenu result = new JBPopupMenu(); + final boolean isNonEmptyMap = this.editor.getMindMapPanel().getModel().getRoot() != null; + if (element != null) { final JBMenuItem editText = new JBMenuItem(BUNDLE.getString("MMDGraphEditor.makePopUp.miEditText"), AllIcons.PopUp.EDITTEXT); editText.addActionListener(new ActionListener() { @@ -322,6 +324,9 @@ public class MindMapPanelControllerImpl implements MindMapPanelController, MindM } }); + expandAll.setEnabled(isNonEmptyMap); + collapseAll.setEnabled(isNonEmptyMap); + result.add(showJumps); result.add(expandAll); result.add(collapseAll); @@ -358,8 +363,7 @@ public class MindMapPanelControllerImpl implements MindMapPanelController, MindM exportMenu.add(item); } - exportMenu.setEnabled(this.editor.getMindMapPanel().getModel().getRoot()!=null); - + exportMenu.setEnabled(isNonEmptyMap); result.add(exportMenu); diff --git a/mind-map/nb-mind-map/src/main/java/com/igormaznitsa/nbmindmap/nb/editor/MMDGraphEditor.java b/mind-map/nb-mind-map/src/main/java/com/igormaznitsa/nbmindmap/nb/editor/MMDGraphEditor.java index <HASH>..<HASH> 100644 --- a/mind-map/nb-mind-map/src/main/java/com/igormaznitsa/nbmindmap/nb/editor/MMDGraphEditor.java +++ b/mind-map/nb-mind-map/src/main/java/com/igormaznitsa/nbmindmap/nb/editor/MMDGraphEditor.java @@ -960,6 +960,8 @@ public final class MMDGraphEditor extends CloneableEditor implements MindMapCont public JPopupMenu makePopUpForMindMapPanel (@Nonnull final MindMapPanel source, @Nonnull final Point point, @Nullable final AbstractElement element, @Nullable final ElementPart partUnderMouse) { final JPopupMenu result = UI_COMPO_FACTORY.makePopupMenu(); + final boolean isModelNotEmpty = this.mindMapPanel.getModel().getRoot() != null; + if (element != null) { final JMenuItem editText = UI_COMPO_FACTORY.makeMenuItem(BUNDLE.getString("MMDGraphEditor.makePopUp.miEditText"), Icons.EDITTEXT.getIcon()); editText.addActionListener(new ActionListener() { @@ -1135,6 +1137,9 @@ public final class MMDGraphEditor extends CloneableEditor implements MindMapCont } }); + expandAll.setEnabled(isModelNotEmpty); + collapseAll.setEnabled(isModelNotEmpty); + result.add(showJumps); result.add(expandAll); result.add(collapseAll); @@ -1170,7 +1175,7 @@ public final class MMDGraphEditor extends CloneableEditor implements MindMapCont } result.add(exportMenu); - exportMenu.setEnabled(this.mindMapPanel.getModel().getRoot()!=null); + exportMenu.setEnabled(isModelNotEmpty); result.add(UI_COMPO_FACTORY.makeMenuSeparator());
added logic to disable some items in popup if model is empty
raydac_netbeans-mmd-plugin
train
df797b0ab2543735f87a147082a77364264d42b0
diff --git a/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/RetrofitCircuitBreaker.java b/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/RetrofitCircuitBreaker.java index <HASH>..<HASH> 100644 --- a/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/RetrofitCircuitBreaker.java +++ b/resilience4j-retrofit/src/main/java/io/github/resilience4j/retrofit/RetrofitCircuitBreaker.java @@ -16,7 +16,7 @@ import java.util.function.Predicate; * All exceptions are marked as errors or responses not matching the supplied predicate. For example: * <p> * <code> - * RetrofitCircuitBreaker.decorateCall(circuitBreaker, call, (r) -> r.isSuccessful()); + * RetrofitCircuitBreaker.decorateCall(circuitBreaker, call, Response::isSuccessful); * </code> */ public interface RetrofitCircuitBreaker {
Changed the style of the <code> example to avoid javadoc errors
resilience4j_resilience4j
train
d6052a653b1f4c4f772a625fadf32db1cfff3c3f
diff --git a/closure/goog/editor/plugins/enterhandler.js b/closure/goog/editor/plugins/enterhandler.js index <HASH>..<HASH> 100644 --- a/closure/goog/editor/plugins/enterhandler.js +++ b/closure/goog/editor/plugins/enterhandler.js @@ -584,7 +584,7 @@ goog.editor.plugins.EnterHandler.prototype.deleteCursorSelectionW3C_ = // Delete the current selection if it's is non-collapsed. // Although this is redundant in FF, it's necessary for Safari - if (!range.isCollapsed()) { + if (range && !range.isCollapsed()) { var shouldDelete = true; // Opera selects the <br> in an empty block if there is no text node // preceding it. To preserve inline formatting when pressing [enter] inside
adding truthy test to range in deleteCursorSelectionW3C_, which will occasionally throw an NPE when range is null, at `!range.isCollapsed()`
google_closure-library
train
80368a2ca21e0edc4805a0462c277e474ebddade
diff --git a/src/engine/Resolutor.js b/src/engine/Resolutor.js index <HASH>..<HASH> 100644 --- a/src/engine/Resolutor.js +++ b/src/engine/Resolutor.js @@ -70,7 +70,7 @@ Resolutor.explain = query = [query]; } - let recursiveResolution = function (remainingLiterals, thetaSoFar, variablesInUseSoFar) { + let recursiveResolution = function (remainingLiterals, thetaSoFar) { let result = []; if (remainingLiterals.length === 0) { result.push({ @@ -99,7 +99,7 @@ Resolutor.explain = otherLiteral.getVariables() .forEach(variableSetFunc); } - variablesInUse = variablesInUseSoFar.concat(Object.keys(variablesInUse)); + variablesInUse = Object.keys(variablesInUse); let renameTheta = variableArrayRename(variablesInUse); clauses.forEach((clause) => { @@ -116,17 +116,18 @@ Resolutor.explain = let bodyLiterals = clause.getBodyLiterals(); bodyLiterals = bodyLiterals.map((blArg) => { - let bl = blArg.substitute(renameTheta); - return bl.substitute(unificationTheta); + let bl = blArg.substitute(unificationTheta); + return bl.substitute(renameTheta); }); let newTheta = compactTheta(thetaSoFar, unificationTheta); - let subResult = recursiveResolution(bodyLiterals, newTheta, variablesInUse); + let subResult = recursiveResolution(bodyLiterals, {}); subResult.forEach((r) => { - let updatedHeadLiteral = headLiteral.substitute(r.theta); + let updatedHeadLiteral = headLiteral.substitute(r.theta).substitute(renameTheta); let unificationTheta = Unifier.unifies([[literal, updatedHeadLiteral]]); if (unificationTheta === null) { return; } + literalThetas.push({ theta: unificationTheta }); }); }); @@ -138,19 +139,8 @@ Resolutor.explain = let newRemainingLiterals = remainingLiterals.slice(1, remainingLiterals.length); literalThetas.forEach((t) => { - if (result === null) { - return; - } let compactedTheta = compactTheta(thetaSoFar, t.theta); - Object.keys(compactedTheta).forEach((k) => { - if (compactedTheta[k] instanceof Variable) { - let otherName = compactedTheta[k].evaluate(); - if (t.theta[otherName] !== undefined) { - compactedTheta[k] = t.theta[otherName]; - } - } - }); - let subResult = recursiveResolution(newRemainingLiterals, compactedTheta, variablesInUse); + let subResult = recursiveResolution(newRemainingLiterals, compactedTheta); result = result.concat(subResult); }); return result;
fix resolutor variable rename logic
lps-js_lps.js
train
30a4761592a341fa696439edf457b8646d81e3f8
diff --git a/python/ray/_private/gcs_pubsub.py b/python/ray/_private/gcs_pubsub.py index <HASH>..<HASH> 100644 --- a/python/ray/_private/gcs_pubsub.py +++ b/python/ray/_private/gcs_pubsub.py @@ -4,8 +4,10 @@ import logging import random import threading from typing import Optional, Tuple +import time import grpc +from grpc._channel import _InactiveRpcError try: from grpc import aio as aiogrpc except ImportError: @@ -23,6 +25,9 @@ from ray.core.generated import pubsub_pb2 logger = logging.getLogger(__name__) +# Max retries for GCS publisher connection error +MAX_GCS_PUBLISH_RETRIES = 60 + def gcs_pubsub_enabled(): """Checks whether GCS pubsub feature flag is enabled.""" @@ -181,17 +186,29 @@ class GcsPublisher(_PublisherBase): key_id=key_id, error_info_message=error_info) req = gcs_service_pb2.GcsPublishRequest(pub_messages=[msg]) - self._stub.GcsPublish(req) + self._gcs_publish(req) def publish_logs(self, log_batch: dict) -> None: """Publishes logs to GCS.""" req = self._create_log_request(log_batch) - self._stub.GcsPublish(req) + self._gcs_publish(req) def publish_function_key(self, key: bytes) -> None: """Publishes function key to GCS.""" req = self._create_function_key_request(key) - self._stub.GcsPublish(req) + self._gcs_publish(req) + + def _gcs_publish(self, req) -> None: + count = MAX_GCS_PUBLISH_RETRIES + while count > 0: + try: + self._stub.GcsPublish(req) + return + except _InactiveRpcError: + pass + time.sleep(1) + count -= 1 + raise class _SyncSubscriber(_SubscriberBase): diff --git a/python/ray/autoscaler/_private/monitor.py b/python/ray/autoscaler/_private/monitor.py index <HASH>..<HASH> 100644 --- a/python/ray/autoscaler/_private/monitor.py +++ b/python/ray/autoscaler/_private/monitor.py @@ -454,8 +454,11 @@ class Monitor: gcs_publisher=gcs_publisher) def _signal_handler(self, sig, frame): - self._handle_failure(f"Terminated with signal {sig}\n" + - "".join(traceback.format_stack(frame))) + try: + self._handle_failure(f"Terminated with signal {sig}\n" + + "".join(traceback.format_stack(frame))) + except Exception: + logger.exception("Monitor: Failure in signal handler.") sys.exit(sig + 128) def run(self):
Two issues fix for GCS connecting logic in monitor.py and log_monitor.py (#<I>) This patch fixed two issues. 1. log_monitor.py can crash when gcs is not temporarily available. Added retry logic in gcs_pubsub.py. 2. it is possible that the signal handler can raise another exception during exception handling.
ray-project_ray
train
fa0a9337800c44872e28b928541efbbafd988ca2
diff --git a/lib/mongo/util/pool.rb b/lib/mongo/util/pool.rb index <HASH>..<HASH> 100644 --- a/lib/mongo/util/pool.rb +++ b/lib/mongo/util/pool.rb @@ -49,8 +49,7 @@ module Mongo begin sock.close rescue IOError => ex - warn "IOError when attempting to close socket connected " - + "to #{@host}:#{@port}: #{ex.inspect}" + warn "IOError when attempting to close socket connected to #{@host}:#{@port}: #{ex.inspect}" end end @host = @port = nil diff --git a/test/connection_test.rb b/test/connection_test.rb index <HASH>..<HASH> 100644 --- a/test/connection_test.rb +++ b/test/connection_test.rb @@ -264,5 +264,15 @@ class TestConnection < Test::Unit::TestCase end assert_equal 0, @con.primary_pool.checked_out.size end + + should "show a proper exception message if an IOError is raised while closing a socket" do + fake_socket = Mocha::Mock.new + fake_socket.stubs(:close).raises(IOError.new) + fake_socket.stub_everything + TCPSocket.expects(:new).returns(fake_socket) + + @con.primary_pool.checkout_new_socket + assert_equal [], @con.primary_pool.close + end end end
Fix the exception message shown when there's an IOError while closing a socket in the pool.
mongodb_mongo-ruby-driver
train
4df0a41e95336fa4d75599a126e203ad6a46d2ba
diff --git a/src/strategies/best_connected_ever_strategy.js b/src/strategies/best_connected_ever_strategy.js index <HASH>..<HASH> 100644 --- a/src/strategies/best_connected_ever_strategy.js +++ b/src/strategies/best_connected_ever_strategy.js @@ -24,7 +24,7 @@ return null; } return Pusher.ParallelStrategy.connect( - this.strategies, + Pusher.MultiStrategy.filterUnsupported(this.strategies), function(i, runners) { return function(error, connection) { runners[i].error = error; diff --git a/src/strategies/first_connected_strategy.js b/src/strategies/first_connected_strategy.js index <HASH>..<HASH> 100644 --- a/src/strategies/first_connected_strategy.js +++ b/src/strategies/first_connected_strategy.js @@ -21,7 +21,7 @@ return null; } return Pusher.ParallelStrategy.connect( - this.strategies, + Pusher.MultiStrategy.filterUnsupported(this.strategies), function(i, runners) { return function(error, connection) { runners[i].error = error; diff --git a/src/strategies/multi_strategy.js b/src/strategies/multi_strategy.js index <HASH>..<HASH> 100644 --- a/src/strategies/multi_strategy.js +++ b/src/strategies/multi_strategy.js @@ -4,7 +4,7 @@ * @param {Array} substrategies list of children strategies */ function MultiStrategy(strategies, options) { - this.strategies = Pusher.MultiStrategy.filterUnsupported(strategies); + this.strategies = strategies; this.options = options || {}; } var prototype = MultiStrategy.prototype; @@ -18,7 +18,7 @@ * @returns {Boolean} */ prototype.isSupported = function() { - return this.strategies.length > 0; + return Pusher.Util.any(this.strategies, Pusher.Util.method("isSupported")); }; /** Returns an object with strategy's options diff --git a/src/strategies/sequential_strategy.js b/src/strategies/sequential_strategy.js index <HASH>..<HASH> 100644 --- a/src/strategies/sequential_strategy.js +++ b/src/strategies/sequential_strategy.js @@ -26,6 +26,7 @@ prototype.connect = function(callback) { var self = this; + var strategies = Pusher.MultiStrategy.filterUnsupported(this.strategies); var current = 0; var timeout = this.options.timeout; var runner = null; @@ -36,10 +37,10 @@ } else { current = current + 1; if (self.options.loop) { - current = current % self.strategies.length; + current = current % strategies.length; } - if (current < self.strategies.length) { + if (current < strategies.length) { if (timeout) { timeout = timeout * 2; if (self.options.timeoutLimit) { @@ -47,7 +48,7 @@ } } runner = self.tryStrategy( - self.strategies[current], timeout, tryNextStrategy + strategies[current], timeout, tryNextStrategy ); } else { callback(true); @@ -55,9 +56,7 @@ } }; - runner = this.tryStrategy( - this.strategies[current], timeout, tryNextStrategy - ); + runner = this.tryStrategy(strategies[current], timeout, tryNextStrategy); return { abort: function() {
Filter unsupported strategies on connect * remove filtering from MultiStrategy * update MultiStrategy's isSupported check * add filters in strategies inheriting from MultiStrategy
pusher_pusher-js
train
5cd60576b70fa6b641bccacff1cc9f2c3a957fa6
diff --git a/lib/core/King23_Router.php b/lib/core/King23_Router.php index <HASH>..<HASH> 100755 --- a/lib/core/King23_Router.php +++ b/lib/core/King23_Router.php @@ -112,9 +112,9 @@ class King23_Router implements King23_Singleton { if($paramstr = substr($request, strlen($route))) { - $info["router"]->dispatch($paramstr); + return $info["router"]->dispatch($paramstr); } else { // if after the match nothing is left, lets call default route.. - $info["router"]->dispatch("/"); + return $info["router"]->dispatch("/"); } } else // otherwise its a regular (direct) route @@ -157,7 +157,7 @@ class King23_Router implements King23_Singleton } $class = $info["class"]; $view = new $class(); - $view->dispatch($info["action"], $parameters); + return $view->dispatch($info["action"], $parameters); } break; } diff --git a/lib/view/King23_TemplateView.php b/lib/view/King23_TemplateView.php index <HASH>..<HASH> 100755 --- a/lib/view/King23_TemplateView.php +++ b/lib/view/King23_TemplateView.php @@ -56,17 +56,21 @@ abstract class King23_TemplateView extends King23_View * context * @param string $template * @param array $context + * @param bool $silent if set to true the method will not echo out the results */ - protected function render($template, $context = array()) + protected function render($template, $context = array(), $silent = false) { $context = array_merge($this->_context, $context); - echo $this->sith->cachedGet($template)->render($context, $this->sith); + $body = $this->sith->cachedGet($template)->render($context, $this->sith); + if(!$silent) + echo $body; + return $body; } /** * function to dispatch requests comming throuh the router - * @param <type> $action - * @param <type> $request + * @param string $action + * @param array $request */ public function dispatch($action, $request) {
a few modifications that allow to return contents back to the front controller rather then echoing it directly
ppetermann_king23
train
dbbb0fb35157b6f63cad130bac5bae3174a98d43
diff --git a/tests/Sabre/CalDAV/XMLUtilTest.php b/tests/Sabre/CalDAV/XMLUtilTest.php index <HASH>..<HASH> 100644 --- a/tests/Sabre/CalDAV/XMLUtilTest.php +++ b/tests/Sabre/CalDAV/XMLUtilTest.php @@ -282,6 +282,18 @@ XML; /** * @depends testParseICalendarDateTime */ + function testParseICalendarDateTimeUTC2() { + + $dateTime = Sabre_CalDAV_XMLUtil::parseICalendarDateTime('20101211T160000Z'); + + $compare = new DateTime('2010-12-11 16:00:00',new DateTimeZone('UTC')); + $this->assertEquals($compare, $dateTime); + + } + + /** + * @depends testParseICalendarDateTime + */ function testParseICalendarDateTimeCustomTimeZone() { $dateTime = Sabre_CalDAV_XMLUtil::parseICalendarDateTime('20100316T141405', new DateTimeZone('Europe/Amsterdam'));
Test for broken date. Updates Issue <I>.
sabre-io_dav
train
98716cf3be9724d7118933b6eefcc49451b00ebd
diff --git a/lib/bootscaf/cli.rb b/lib/bootscaf/cli.rb index <HASH>..<HASH> 100644 --- a/lib/bootscaf/cli.rb +++ b/lib/bootscaf/cli.rb @@ -1,8 +1,10 @@ require 'thor' +require 'net/http' + module Bootscaf class CLI < Thor YESSES = ['y', 'yes', 'Y', 'Yes', 'YES'] - LAST_KNOWN_BOOTSTRAP_VERSION = '3.3.1' + LAST_KNOWN_BOOTSTRAP_VERSION = '3.3.1/' desc "version", "Ouputs the current version of Bootscaf" def version @@ -14,17 +16,25 @@ module Bootscaf def update(modelname = nil) puts options[:all] ? "Running on all models scaffolds." : "Running on #{modelname} scaffolds." + + is_mac = (RbConfig::CONFIG['host_os'] =~ /^darwin/) >= 0 inplace_command = is_mac ? "-i ''" : '--in-place' print "Would you like to update app/views/layouts/application.html.erb [y/n(default)]? " update_apphtml = $stdin.gets.strip if YESSES.include?(update_apphtml) - latest_boostrap_version = LAST_KNOWN_BOOTSTRAP_VERSION + + print "Checking for most recent bootstrap cdn version... " + uri = URI.parse("https://raw.githubusercontent.com/MaxCDN/bootstrap-cdn/develop/public/twitter-bootstrap/latest") + http = Net::HTTP.new(uri.host, uri.port); http.use_ssl = true + latest_bootstrap_version = http.get(uri.request_uri).body + print "#{latest_bootstrap_version}\n" + latest_boostrap_version ||= LAST_KNOWN_BOOTSTRAP_VERSION print "Updating app/views/layouts/application.html.erb. " print `sed #{inplace_command} -e 's/<title>/<title><%= yield :page_title %>/' app/views/layouts/application.html.erb` - print `sed #{inplace_command} -e 's/<%= stylesheet_link_tag \\'application\\', media: \\'all\\', \\'data-turbolinks-track\\' => true %>/<link href="\\/\\/maxcdn.bootstrapcdn.com\\/bootstrap\\/#{latest_boostrap_version}\\/css\\/bootstrap.min.css" rel="stylesheet">\\n<%= stylesheet_link_tag \\'application\\', media: \\'all\\', \\'data-turbolinks-track\\' => true %>/' app/views/layouts/application.html.erb` + print `sed #{inplace_command} -e 's/<%= stylesheet_link_tag \\'application\\', media: \\'all\\', \\'data-turbolinks-track\\' => true %>/<link href="\\/\\/maxcdn.bootstrapcdn.com\\/bootstrap\\/#{latest_boostrap_version}css\\/bootstrap.min.css" rel="stylesheet">\\n<%= stylesheet_link_tag \\'application\\', media: \\'all\\', \\'data-turbolinks-track\\' => true %>/' app/views/layouts/application.html.erb` print "\n" end end
WIP application.html.erb
thrivesmart_bootscaf
train
d414d8de6cf7be9ed2693556e292fd4f1057f5bf
diff --git a/src/org/opencms/ui/FontOpenCms.java b/src/org/opencms/ui/FontOpenCms.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/ui/FontOpenCms.java +++ b/src/org/opencms/ui/FontOpenCms.java @@ -161,7 +161,13 @@ public enum FontOpenCms implements FontIcon { WAND(0xe610), /** The warning icon. */ - WARNING(0xed50); + WARNING(0xed50), + + /** 'plus' state icon for tree opener. */ + TREE_PLUS(0xe918), + + /** 'minus' state icon for tree opener. */ + TREE_MINUS(0xe919); /** The icon code point. */ private int m_codepoint;
Added tree opener icons to font enum.
alkacon_opencms-core
train
cdf358ce0b2d61030f09d3fd61deacdd2925b6f7
diff --git a/app/models/article.rb b/app/models/article.rb index <HASH>..<HASH> 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -219,9 +219,9 @@ class Article < Content def html_urls urls = Array.new - html.gsub(/<a [^>]*>/) do |tag| - if(tag =~ /href="([^"]+)"/) - urls.push($1) + html.gsub(/<a\s+[^>]*>/) do |tag| + if(tag =~ /\bhref=(["']?)([^ >"]+)\1/) + urls.push($2) end end diff --git a/spec/models/article_spec.rb b/spec/models/article_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/article_spec.rb +++ b/spec/models/article_spec.rb @@ -2,7 +2,6 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Article do - before do @articles = [] end @@ -24,7 +23,7 @@ describe Article do a = Factory(:article) Article.find(a.id).user.should_not be_nil end - it 'should multiple article factory valid' do + it 'should create multiple valid articles' do Factory(:article).should be_valid Factory(:article).should be_valid end @@ -119,9 +118,39 @@ describe Article do assert_equal '%E3%83%AB%E3%83%93%E3%83%BC', a.permalink end - it "test_urls" do - urls = contents(:article4).html_urls - assert_equal ["http://www.example.com/public"], urls + describe "the html_urls method" do + it "test_urls" do + urls = contents(:article4).html_urls + assert_equal ["http://www.example.com/public"], urls + end + + it "should only match the href attribute" do + a = Factory.create :article + a.body = '<a href="http://a/b">a</a> <a fhref="wrong">wrong</a>' + urls = a.html_urls + assert_equal ["http://a/b"], urls + end + + it "should match across newlines" do + a = Factory.create :article + a.body = "<a\nhref=\"http://foo/bar\">foo</a>" + urls = a.html_urls + assert_equal ["http://foo/bar"], urls + end + + it "should match with single quotes" do + a = Factory.create :article + a.body = "<a href='http://foo/bar'>foo</a>" + urls = a.html_urls + assert_equal ["http://foo/bar"], urls + end + + it "should match with no quotes" do + a = Factory.create :article + a.body = "<a href=http://foo/bar>foo</a>" + urls = a.html_urls + assert_equal ["http://foo/bar"], urls + end end ### XXX: Should we have a test here?
Spec out and fix Article#html_urls
publify_publify
train
1bae0a48847440f2b0ad0f2a54efa61f3b3035ea
diff --git a/src/PhpPact/Standalone/Installer/InstallManager.php b/src/PhpPact/Standalone/Installer/InstallManager.php index <HASH>..<HASH> 100644 --- a/src/PhpPact/Standalone/Installer/InstallManager.php +++ b/src/PhpPact/Standalone/Installer/InstallManager.php @@ -28,7 +28,7 @@ class InstallManager public function __construct() { - $this->destinationDir = \sys_get_temp_dir(); + $this->destinationDir = __DIR__.'/../../../../'; $this ->registerInstaller(new InstallerWindows()) ->registerInstaller(new InstallerMac())
Move pact binary install directory to the root of the project. This will force a version change through composer to delete the binaries.
pact-foundation_pact-php
train
e581c601a34cb18c0a609b081dc53a17a11aa83c
diff --git a/lib/bitcoin/store/db/level_db.rb b/lib/bitcoin/store/db/level_db.rb index <HASH>..<HASH> 100644 --- a/lib/bitcoin/store/db/level_db.rb +++ b/lib/bitcoin/store/db/level_db.rb @@ -74,7 +74,9 @@ module Bitcoin # generate height key def height_key(height) - KEY_PREFIX[:height] + height.to_s(16).htb.reverse.bth + height = height.to_s(16) + height = '0' + height if height.bytesize.odd? + KEY_PREFIX[:height] + height.htb.reverse.bth end def connect_entry(entry) @@ -87,6 +89,8 @@ module Bitcoin raise "block height is small than current best block." end end + + db.put(KEY_PREFIX[:best], entry.hash) db.put(KEY_PREFIX[:next] + entry.prev_hash, entry.hash) end
Fix key generation for odd height(#8)
chaintope_bitcoinrb
train
16794ab9f19c4e34a6e263bdfd2b310cddb95980
diff --git a/vk_requests/api.py b/vk_requests/api.py index <HASH>..<HASH> 100644 --- a/vk_requests/api.py +++ b/vk_requests/api.py @@ -29,6 +29,11 @@ class API(object): return self._timeout def make_request(self, request_obj): + """Make http request. This method is being called from Request object + + :param request_obj: vk_requests.api.Request + :return: dict | VkAPIError + """ return self._session.make_request(request_obj) def __getattr__(self, method_name): @@ -53,7 +58,7 @@ class Request(object): return self._method_args def __getattr__(self, method_name): - return Request(self._api, self._method_name + '.' + method_name) + return Request(self._api, '.'.join([self._method_name, method_name])) def __call__(self, **method_args): self._method_args = method_args diff --git a/vk_requests/auth.py b/vk_requests/auth.py index <HASH>..<HASH> 100644 --- a/vk_requests/auth.py +++ b/vk_requests/auth.py @@ -66,6 +66,13 @@ class BaseAuthAPI(object): def api_version(self): return self._api_version or self.DEFAULT_API_VERSION + def is_token_required(self): + """Helper method for vk_requests.auth.VKSession initialization + + :return: bool + """ + return any([self.app_id, self._login, self._password]) + @property def access_token(self): if self._access_token is None: @@ -120,6 +127,7 @@ class AuthAPI(BaseAuthAPI): with VerboseHTTPSession() as s: self.do_login(session=s) url_query_params = self.do_oauth2_authorization(session=s) + logger.debug('url_query_params: %s', url_query_params) if 'access_token' in url_query_params: logger.info('Done') @@ -299,6 +307,9 @@ class InteractiveAuthAPI(AuthAPI): if not self.app_id: self.app_id = InteractiveAuthAPI.get_app_id() + # Renew access token, cuz login is set + self.renew_access_token() + @staticmethod def get_user_login(): user_login = raw_input('VK user login: ') @@ -314,7 +325,7 @@ class InteractiveAuthAPI(AuthAPI): import getpass user_password = getpass.getpass('VK user password: ') - return user_password + return user_password.strip() def get_access_token(self): logger.debug('InteractiveMixin.get_access_token()') @@ -365,8 +376,6 @@ class VKSession(object): phone_number=phone_number, **api_kwargs) self.censored_access_token = None - # Require token if any of auth parameters are being passed - self.is_token_required = any([app_id, user_login, user_password]) # requests.Session subclass instance self.http_session = VerboseHTTPSession() @@ -404,7 +413,7 @@ class VKSession(object): logger.debug('access_token = %r', self.censored_access_token) def make_request(self, request_obj, captcha_response=None): - logger.debug('Prepare API Method request') + logger.debug('Prepare API Method request %r', request_obj) response = self.send_api_request(request=request_obj, captcha_response=captcha_response) response.raise_for_status() @@ -454,7 +463,7 @@ class VKSession(object): for values in (vk_api.get_default_kwargs(), request.get_method_args()): method_kwargs.update(stringify_values(values)) - if self.is_token_required: + if self.auth_api.is_token_required(): # Auth api call if access_token weren't be got earlier method_kwargs['access_token'] = self.access_token if captcha_response: @@ -471,4 +480,4 @@ class VKSession(object): class InteractiveVKSession(VKSession): - DEFAULT_AUTH_API_CLS = InteractiveAuthAPI \ No newline at end of file + DEFAULT_AUTH_API_CLS = InteractiveAuthAPI diff --git a/vk_requests/tests/test_auth.py b/vk_requests/tests/test_auth.py index <HASH>..<HASH> 100644 --- a/vk_requests/tests/test_auth.py +++ b/vk_requests/tests/test_auth.py @@ -63,7 +63,7 @@ class VKSessionTest(unittest.TestCase): self.assertIsInstance(session, VKSession) # Token is required, cuz auth params are being passed - self.assertTrue(session.is_token_required) + self.assertTrue(session.auth_api.is_token_required) def test_custom_auth_api_cls(self): class MyAuthAPI(AuthAPI):
Fixed interactive session, get is_token_required flag directly from auth_api; Some code refactoring
prawn-cake_vk-requests
train
897767022ea883ed5419624af02d61821c9e3317
diff --git a/build/project-template-gradle/src/main/java/com/tns/ErrorReport.java b/build/project-template-gradle/src/main/java/com/tns/ErrorReport.java index <HASH>..<HASH> 100644 --- a/build/project-template-gradle/src/main/java/com/tns/ErrorReport.java +++ b/build/project-template-gradle/src/main/java/com/tns/ErrorReport.java @@ -114,6 +114,14 @@ class ErrorReport { Class<?> errorActivityClass = ErrorReportActivity.class; + if (JsDebugger.isDebuggableApp(context)) + { + errorActivityClass = ErrorReportActivity.class; + } + else { + return null; + } + Intent intent = new Intent(context, errorActivityClass); intent.putExtra(EXTRA_NATIVESCRIPT_ERROR_REPORT, EXTRA_ERROR_REPORT_VALUE);
fixed error activity bug (shows in release)
NativeScript_android-runtime
train
bd015bb5080e8498c67a26a6b5d9220a0fd3d2eb
diff --git a/src/main/java/io/reinert/requestor/ListDoneCallback.java b/src/main/java/io/reinert/requestor/ListDoneCallback.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/reinert/requestor/ListDoneCallback.java +++ b/src/main/java/io/reinert/requestor/ListDoneCallback.java @@ -17,6 +17,8 @@ package io.reinert.requestor; import java.util.Collection; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import io.reinert.gdeferred.DoneCallback; @@ -27,8 +29,16 @@ import io.reinert.gdeferred.DoneCallback; */ public abstract class ListDoneCallback<T> implements DoneCallback<Collection<T>>, DoneCallbackOfList<T> { + private static Logger logger = Logger.getLogger(ListDoneCallback.class.getName()); + @Override public void onDone(Collection<T> result) { - onDone((List<T>) result); + try { + onDone((List<T>) result); + } catch (ClassCastException e) { + logger.log(Level.SEVERE, "Could not cast the result of type " + result.getClass().getName() + + " to java.util.List"); + throw e; + } } } diff --git a/src/main/java/io/reinert/requestor/SetDoneCallback.java b/src/main/java/io/reinert/requestor/SetDoneCallback.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/reinert/requestor/SetDoneCallback.java +++ b/src/main/java/io/reinert/requestor/SetDoneCallback.java @@ -17,6 +17,8 @@ package io.reinert.requestor; import java.util.Collection; import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; import io.reinert.gdeferred.DoneCallback; @@ -27,8 +29,16 @@ import io.reinert.gdeferred.DoneCallback; */ public abstract class SetDoneCallback<T> implements DoneCallback<Collection<T>>, DoneCallbackOfSet<T> { + private static Logger logger = Logger.getLogger(SetDoneCallback.class.getName()); + @Override public void onDone(Collection<T> result) { - onDone((Set<T>) result); + try { + onDone((Set<T>) result); + } catch (ClassCastException e) { + logger.log(Level.SEVERE, "Could not cast the result of type " + result.getClass().getName() + + " to java.util.Set"); + throw e; + } } }
Log messages in Set and List callbacks.
reinert_requestor
train
4258bb9f21f585c9d558e7a03f851b0400ed8fef
diff --git a/tools/src/main/java/org/bitcoinj/tools/WalletTool.java b/tools/src/main/java/org/bitcoinj/tools/WalletTool.java index <HASH>..<HASH> 100644 --- a/tools/src/main/java/org/bitcoinj/tools/WalletTool.java +++ b/tools/src/main/java/org/bitcoinj/tools/WalletTool.java @@ -683,7 +683,7 @@ public class WalletTool { * and returns the lock time in wire format. */ private static long parseLockTimeStr(String lockTimeStr) throws ParseException { - if (lockTimeStr.indexOf("/") != -1) { + if (lockTimeStr.contains("/")) { SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.US); Date date = format.parse(lockTimeStr); return date.getTime() / 1000;
Apply "Replace indexOf() with contains()" refactoring.
bitcoinj_bitcoinj
train
55f021bcb251eba01210fec7125958bb343f8f89
diff --git a/packages/vaex-jupyter/vaex/jupyter/_version.py b/packages/vaex-jupyter/vaex/jupyter/_version.py index <HASH>..<HASH> 100644 --- a/packages/vaex-jupyter/vaex/jupyter/_version.py +++ b/packages/vaex-jupyter/vaex/jupyter/_version.py @@ -1,2 +1,2 @@ -__version_tuple__ = (0, 2, 3) -__version__ = '0.2.3' +__version_tuple__ = (0, 3, 0) +__version__ = '0.3.0'
Release <I> of vaex-jupyter
vaexio_vaex
train
e2588432ee256ced8388809e89580f9cf0715596
diff --git a/lib/opal/parser.rb b/lib/opal/parser.rb index <HASH>..<HASH> 100644 --- a/lib/opal/parser.rb +++ b/lib/opal/parser.rb @@ -653,6 +653,8 @@ module Opal fragment("(__scope.#{part[1].to_s} != null)", sexp) when :colon2 fragment("false", sexp) + when :colon3 + fragment("(__opal.Object._scope.#{sexp[0][1]} == null ? nil : 'constant')", sexp) when :ivar ivar_name = part[1].to_s[1..-1] with_temp do |t| diff --git a/spec/rubyspec/language/defined_spec.rb b/spec/rubyspec/language/defined_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rubyspec/language/defined_spec.rb +++ b/spec/rubyspec/language/defined_spec.rb @@ -96,3 +96,12 @@ describe "The defined? keyword for ivars" do end end +describe "The defined? keyword for root constants (colon3)" do + it "returns 'constant' if assigned" do + defined?(::Object).should == "constant" + end + + it "returns nil if not assigned" do + defined?(::DOES_NOT_EXIST).should be_nil + end +end
Support defined? with ::constant (fixes #<I>) This ruby syntax now returns nil for undefined constants, or 'constant' if it exists. This commit adds 2 specs for this syntax.
opal_opal
train
c1d0fc6ce12e549f6e1fb545d5ba42d58d623c14
diff --git a/logspace-agent-controller/src/main/java/io/logspace/agent/hq/HqAgentController.java b/logspace-agent-controller/src/main/java/io/logspace/agent/hq/HqAgentController.java index <HASH>..<HASH> 100644 --- a/logspace-agent-controller/src/main/java/io/logspace/agent/hq/HqAgentController.java +++ b/logspace-agent-controller/src/main/java/io/logspace/agent/hq/HqAgentController.java @@ -320,9 +320,6 @@ public class HqAgentController extends AbstractAgentController implements AgentE int hqCommunicationInterval = Integer.parseInt(agentControllerDescription .getParameterValue(HQ_COMMUNICATION_INTERVAL_PARAMETER, HQ_COMMUNICATION_INTERVAL_DEFAULT_VALUE)); this.agentScheduler = new AgentScheduler(this, hqCommunicationInterval); - - // execute the first update within the initializing thread to ensure we're fully initialized - this.update(new Date(System.currentTimeMillis() + hqCommunicationInterval)); } private void initializeCommitRunnable() { diff --git a/logspace-agent-controller/src/main/java/io/logspace/agent/scheduling/AgentScheduler.java b/logspace-agent-controller/src/main/java/io/logspace/agent/scheduling/AgentScheduler.java index <HASH>..<HASH> 100644 --- a/logspace-agent-controller/src/main/java/io/logspace/agent/scheduling/AgentScheduler.java +++ b/logspace-agent-controller/src/main/java/io/logspace/agent/scheduling/AgentScheduler.java @@ -157,7 +157,6 @@ public class AgentScheduler { JobDetail job = newJob(UpdateJob.class).withIdentity("update", LOGSPACE_SCHEDULER_GROUP).usingJobData(jobDataMap).build(); Trigger trigger = newTrigger().withIdentity("update-trigger", LOGSPACE_SCHEDULER_GROUP) - .startAt(new Date(System.currentTimeMillis() + updateInterval)) .withSchedule(simpleSchedule().withIntervalInSeconds(updateInterval).repeatForever()) .build();
changed start date to now and removed synchronous call
Indoqa_logspace
train
97b482c47943c8ba82ad166c9605200e59024619
diff --git a/exchangelib/ewsdatetime.py b/exchangelib/ewsdatetime.py index <HASH>..<HASH> 100644 --- a/exchangelib/ewsdatetime.py +++ b/exchangelib/ewsdatetime.py @@ -77,13 +77,13 @@ class EWSDateTime(datetime.datetime): def __new__(cls, *args, **kwargs): """ - Inherits datetime and adds extra formatting required by EWS. + Inherits datetime and adds extra formatting required by EWS. Do not set tzinfo directly. Use + EWSTimeZone.localize() instead. """ - if 'tzinfo' in kwargs: - raise ValueError('Do not set tzinfo directly. Use EWSTimeZone.localize() instead') - # Some internal methods still need to set tzinfo in the constructor. Use a magic kwarg for that. - if 'ewstzinfo' in kwargs: - kwargs['tzinfo'] = kwargs.pop('ewstzinfo') + # We can't use the exact signature of datetime.datetime because we get pickle errors, and implementing pickle + # support requires copy-pasting lots of code from datetime.datetime. + if not isinstance(kwargs.get('tzinfo'), (EWSTimeZone, type(None))): + raise ValueError('tzinfo must be an EWSTimeZone instance') return super(EWSDateTime, cls).__new__(cls, *args, **kwargs) def ewsformat(self): @@ -108,7 +108,7 @@ class EWSDateTime(datetime.datetime): tz = d.tzinfo else: tz = EWSTimeZone.from_pytz(d.tzinfo) - return cls(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, ewstzinfo=tz) + return cls(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, tzinfo=tz) def astimezone(self, tz=None): t = super(EWSDateTime, self).astimezone(tz=tz) diff --git a/tests/__init__.py b/tests/__init__.py index <HASH>..<HASH> 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -455,9 +455,6 @@ class EWSDateTimeTest(unittest.TestCase): # Test summertime dt = tz.localize(EWSDateTime(2000, 8, 2, 3, 4, 5)) self.assertEqual(dt.astimezone(utc_tz).ewsformat(), '2000-08-02T01:04:05Z') - # Test error when tzinfo is set directly - with self.assertRaises(ValueError): - EWSDateTime(2000, 1, 1, tzinfo=tz) # Test normalize, for completeness self.assertEqual(tz.normalize(dt).ewsformat(), '2000-08-02T03:04:05+02:00') self.assertEqual(utc_tz.normalize(dt, is_dst=True).ewsformat(), '2000-08-02T01:04:05Z')
Remove the ewstzinfo hack. Just use the same level of sanity checking as datetime.datetime
ecederstrand_exchangelib
train
a045e59cf1b1e36b326af0c1172c3b473bfbdece
diff --git a/src/content/formats/groovy-rc.js b/src/content/formats/groovy-rc.js index <HASH>..<HASH> 100644 --- a/src/content/formats/groovy-rc.js +++ b/src/content/formats/groovy-rc.js @@ -192,7 +192,7 @@ options.getHeader = function() { + indents(1) + "void setUp() throws Exception {\n" + indents(2) + "super.setUp('${baseURL}', '*chrome')\n" + indents(2) + "setDefaultTimeout(" + timeout + ")\n" - + indents(2) + "setCaptureScreenShotOnFailure(false)\n" + + indents(2) + "setCaptureScreenshotOnFailure(false)\n" + indents(1) + "}\n\n" + indents(1) + "void ${methodName}() throws Exception {\n"; }
Casing of method name changed. r<I>
SeleniumHQ_selenium
train
121a6669a85cdb8da942de466d42d5dfdecc0b7d
diff --git a/ddl/db_partition_test.go b/ddl/db_partition_test.go index <HASH>..<HASH> 100644 --- a/ddl/db_partition_test.go +++ b/ddl/db_partition_test.go @@ -564,6 +564,14 @@ create table log_message_1 ( dbterror.ErrRangeNotIncreasing, }, { + "create table t(d datetime)" + + "partition by range columns (d) (" + + "partition p0 values less than ('2022-01-01')," + + "partition p1 values less than (MAXVALUE), " + + "partition p2 values less than (MAXVALUE));", + dbterror.ErrRangeNotIncreasing, + }, + { "CREATE TABLE t1(c0 INT) PARTITION BY HASH((NOT c0)) PARTITIONS 2;", dbterror.ErrPartitionFunctionIsNotAllowed, }, diff --git a/ddl/ddl_api.go b/ddl/ddl_api.go index <HASH>..<HASH> 100644 --- a/ddl/ddl_api.go +++ b/ddl/ddl_api.go @@ -2761,7 +2761,7 @@ func checkTwoRangeColumns(ctx sessionctx.Context, curr, prev *model.PartitionDef } for i := 0; i < len(pi.Columns); i++ { // Special handling for MAXVALUE. - if strings.EqualFold(curr.LessThan[i], partitionMaxValue) { + if strings.EqualFold(curr.LessThan[i], partitionMaxValue) && !strings.EqualFold(prev.LessThan[i], partitionMaxValue) { // If current is maxvalue, it certainly >= previous. return true, nil }
ddl: invalid multiple MAXVALUE partitions (#<I>) (#<I>) close pingcap/tidb#<I>
pingcap_tidb
train
e0d6fd6bfa9e6988036470f45192b2c7aadfced7
diff --git a/rpc/core/net.go b/rpc/core/net.go index <HASH>..<HASH> 100644 --- a/rpc/core/net.go +++ b/rpc/core/net.go @@ -38,9 +38,12 @@ func NetInfo() (*ctypes.ResponseNetInfo, error) { for _, listener := range p2pSwitch.Listeners() { listeners = append(listeners, listener.String()) } - peers := []string{} + peers := []ctypes.Peer{} for _, peer := range p2pSwitch.Peers().List() { - peers = append(peers, peer.String()) + peers = append(peers, ctypes.Peer{ + Address: peer.Connection().RemoteAddress.String(), + IsOutbound: peer.IsOutbound(), + }) } return &ctypes.ResponseNetInfo{ Network: network, diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index <HASH>..<HASH> 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -73,7 +73,12 @@ type ResponseNetInfo struct { Network string Listening bool Listeners []string - Peers []string + Peers []Peer +} + +type Peer struct { + Address string + IsOutbound bool } type ResponseSignTx struct {
RPC shows Peer{Address,IsOutbound}
tendermint_tendermint
train
6fa3a82dc5473603faeb13734bc79bdf873f002f
diff --git a/lib/sidekiq/failures/middleware.rb b/lib/sidekiq/failures/middleware.rb index <HASH>..<HASH> 100644 --- a/lib/sidekiq/failures/middleware.rb +++ b/lib/sidekiq/failures/middleware.rb @@ -16,7 +16,7 @@ module Sidekiq :failed_at => Time.now.strftime("%Y/%m/%d %H:%M:%S %Z"), :payload => msg, :exception => e.class.to_s, - :error => e.to_s, + :error => e.message, :backtrace => e.backtrace, :worker => msg['class'], :processor => "#{hostname}:#{process_id}-#{Thread.current.object_id}:default",
Use #message instead of #to_s Exceptions raised by the google-adwords-api gem return the same thing for `e.class.to_s` and `e.to_s`. Switching to `message` here makes the output match what is shown in sidekiq's retries. I believe the convention is to implement a `message` method on exceptions, so I'm thinking this issue isn't specific to this gem.
mhfs_sidekiq-failures
train
bf51fc4b59eaaa4d22f2c6ae08798349d48495bf
diff --git a/fs/local_modifications_test.go b/fs/local_modifications_test.go index <HASH>..<HASH> 100644 --- a/fs/local_modifications_test.go +++ b/fs/local_modifications_test.go @@ -1986,3 +1986,17 @@ func (t *SymlinkTest) RemoveLink() { _, err = gcsutil.ReadObject(t.ctx, t.bucket, "foo") ExpectThat(err, HasSameTypeAs(&gcs.NotFoundError{})) } + +//////////////////////////////////////////////////////////////////////// +// Rename +//////////////////////////////////////////////////////////////////////// + +type RenameTest struct { + fsTest +} + +func init() { RegisterTestSuite(&RenameTest{}) } + +func (t *RenameTest) DoesFoo() { + AssertTrue(false, "TODO") +}
Added a stub for a rename test.
jacobsa_ratelimit
train
3b9a6800924468e3875ccc3b0d1c89453b1bf576
diff --git a/eclipsePlugin/src/de/tobject/findbugs/marker/FindBugsMarker.java b/eclipsePlugin/src/de/tobject/findbugs/marker/FindBugsMarker.java index <HASH>..<HASH> 100644 --- a/eclipsePlugin/src/de/tobject/findbugs/marker/FindBugsMarker.java +++ b/eclipsePlugin/src/de/tobject/findbugs/marker/FindBugsMarker.java @@ -28,5 +28,15 @@ package de.tobject.findbugs.marker; */ public class FindBugsMarker { public static final String NAME = "de.tobject.findbugs.findbugsMarker"; + + /** + * Marker attribute recording the bug type. + */ public static final String BUG_TYPE = "BUGTYPE"; + + /** + * Marker attribute recording the unique id of the BugInstance + * in its BugCollection. + */ + public static final String UNIQUE_ID = "FINDBUGS_UNIQUE_ID"; }
Added UNIQUE_ID marker attribute. This helps us find the BugInstance object associated with each marker. git-svn-id: <URL>
spotbugs_spotbugs
train
43f560b38569280395fcd927b57c4a9bd02490a9
diff --git a/src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java b/src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java +++ b/src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java @@ -167,6 +167,7 @@ public class FaunusPipeline { return this; } + // todo: linkOut/linkIn public FaunusPipeline linkTo(final String label) throws IOException { if (state.atVertex()) { if (state.stackSize() == 1) { @@ -192,22 +193,10 @@ public class FaunusPipeline { return this; } - /*public FaunusPipeline linkFrom(final String label) throws IOException { - if (compiler.getJobState().elementType.equals(Vertex.class)) { - if (compiler.getJobState().directions.size() == 1 && compiler.getJobState().labels.size() == 1) { - compiler.closeLine(compiler.getJobState().labels.get(0).get(0), label, Tokens.Action.KEEP, true); - } else if (compiler.getJobState().directions.size() == 2 && compiler.getJobState().labels.size() == 2) { - compiler.closeTriangle(compiler.getJobState().directions.get(0), compiler.getJobState().labels.get(0).get(0), compiler.getJobState().directions.get(1), compiler.getJobState().labels.get(1).get(0), label, Tokens.Action.KEEP); - } else { - throw new RuntimeException("an exception"); - } - } else { - throw new RuntimeException("Edges can not be relinked"); - } - this.compiler.getJobState().directions.clear(); - this.compiler.getJobState().labels.clear(); + public FaunusPipeline drop() throws IOException { return this; - }*/ + } + public FaunusPipeline sideEffect(final String function) throws IOException { if (state.getElementType().equals(Vertex.class)) { diff --git a/src/main/java/com/thinkaurelius/faunus/mapreduce/ElementPicker.java b/src/main/java/com/thinkaurelius/faunus/mapreduce/ElementPicker.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/thinkaurelius/faunus/mapreduce/ElementPicker.java +++ b/src/main/java/com/thinkaurelius/faunus/mapreduce/ElementPicker.java @@ -4,6 +4,8 @@ import com.thinkaurelius.faunus.FaunusEdge; import com.thinkaurelius.faunus.FaunusElement; import com.thinkaurelius.faunus.Tokens; +import java.util.Map; + /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ @@ -12,9 +14,11 @@ public class ElementPicker { public static String getPropertyAsString(final FaunusElement element, final String key) { if (key.equals(Tokens._ID) || key.equals(Tokens.ID)) return element.getId().toString(); - else if (key.equals(Tokens._PROPERTIES)) - return element.getProperties().toString(); - else if (key.equals(Tokens.LABEL) && element instanceof FaunusEdge) + else if (key.equals(Tokens._PROPERTIES)) { + final Map<String, Object> properties = element.getProperties(); + properties.put(Tokens._ID, element.getId()); + return properties.toString(); + } else if (key.equals(Tokens.LABEL) && element instanceof FaunusEdge) return ((FaunusEdge) element).getLabel(); else { final Object value = element.getProperty(key); @@ -28,9 +32,11 @@ public class ElementPicker { public static Object getProperty(final FaunusElement element, final String key) { if (key.equals(Tokens._ID) || key.equals(Tokens.ID)) return element.getId(); - else if (key.equals(Tokens._PROPERTIES)) - return element.getProperties(); - else if (key.equals(Tokens.LABEL) && element instanceof FaunusEdge) + else if (key.equals(Tokens._PROPERTIES)) { + final Map<String, Object> properties = element.getProperties(); + properties.put(Tokens._ID, element.getId()); + return properties; + } else if (key.equals(Tokens.LABEL) && element instanceof FaunusEdge) return ((FaunusEdge) element).getLabel(); else { return element.getProperty(key);
added _id to properties in ElementPicker. Some TODO notes in FaunusPipeline.
thinkaurelius_titan
train
6baef0dd0de0258c85588259d266735f913a3c78
diff --git a/packages/node_modules/@webex/webex-core/src/webex-core.js b/packages/node_modules/@webex/webex-core/src/webex-core.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@webex/webex-core/src/webex-core.js +++ b/packages/node_modules/@webex/webex-core/src/webex-core.js @@ -78,6 +78,8 @@ const postInterceptors = [ 'RateLimitInterceptor' ]; +const MAX_FILE_SIZE_IN_MB = 2048; + /** * @class */ @@ -550,7 +552,16 @@ const WebexCore = AmpState.extend({ this.logger.debug('client: initiating upload session'); return this.request(options.phases.initialize) - .then((...args) => this._uploadApplySession(options, ...args)) + .then((...args) => { + const fileUploadSizeLimitInBytes = (args[0].body.fileUploadSizeLimit || MAX_FILE_SIZE_IN_MB) * 1024 * 1024; + const currentFileSizeInBytes = options.file.byteLength; + + if (fileUploadSizeLimitInBytes && fileUploadSizeLimitInBytes < currentFileSizeInBytes) { + return this._uploadAbortSession(currentFileSizeInBytes, ...args); + } + + return this._uploadApplySession(options, ...args); + }) .then((res) => { this.logger.debug('client: initiated upload session'); @@ -558,6 +569,26 @@ const WebexCore = AmpState.extend({ }); }, + _uploadAbortSession(currentFileSizeInBytes, response) { + this.logger.debug('client: deleting uploaded file'); + + return this.request({ + method: 'DELETE', + url: response.body.url, + headers: response.options.headers + }).then(() => { + this.logger.debug('client: deleting uploaded file complete'); + + const abortErrorDetails = { + currentFileSizeInBytes, + fileUploadSizeLimitInMB: response.body.fileUploadSizeLimit || MAX_FILE_SIZE_IN_MB, + message: 'file-upload-size-limit-enabled' + }; + + return Promise.reject(new Error(`${JSON.stringify(abortErrorDetails)}`)); + }); + }, + _uploadApplySession(options, res) { const session = res.body;
fix(upload): add abort function on file upload for webex fix(upload): resolve lint issues fix(upload): send data as error to web client
webex_spark-js-sdk
train
be046cd4d9be37a516f8ad6bcc58e892f5b2a540
diff --git a/install.js b/install.js index <HASH>..<HASH> 100644 --- a/install.js +++ b/install.js @@ -1,38 +1,37 @@ 'use strict'; -var path = require('path') - , fs = require('fs'); - // // Compatibility with older node.js as path.exists got moved to `fs`. // -var existsSync = fs.existsSync || path.existsSync +var fs = require('fs') + , path = require('path') + , hook = path.join(__dirname, './hook') , root = path.resolve(__dirname, '../..') - , hook = path.join(__dirname, './hook'); + , exists = fs.existsSync || path.existsSync; // -// The location .git and it's hooks +// Gather the location of the possible hidden .git directory, the hooks +// directory which contains all git hooks and the absolute location of the +// `pre-commit` file. The path needs to be absolute in order for the symlinking +// to work correctly. // var git = path.resolve(root, '.git') , hooks = path.resolve(git, 'hooks') , precommit = path.resolve(hooks, 'pre-commit'); // -// Check if we are in a git repository so we can bail out early when this is not -// the case. -// -if (!existsSync(git) || !fs.lstatSync(git).isDirectory()) return; - -// -// Create a hooks directory if it's missing. +// Bail out if we don't have an `.git` directory as the hooks will not get +// triggered. If we do have directory create a hooks folder if it doesn't exist. // -if (!existsSync(hooks)) fs.mkdirSync(hooks); +if (!exists(git) || !fs.lstatSync(git).isDirectory()) return; +if (!exists(hooks)) fs.mkdirSync(hooks); // // If there's an existing `pre-commit` hook we want to back it up instead of -// overriding it and losing it completely +// overriding it and losing it completely as it might contain something +// important. // -if (existsSync(precommit)) { +if (exists(precommit)) { console.log(''); console.log('pre-commit: Detected an existing git pre-commit hook'); fs.writeFileSync(precommit +'.old', fs.readFileSync(precommit)); @@ -41,8 +40,8 @@ if (existsSync(precommit)) { } // -// Everything is ready for the installation of the pre-commit hook. Write it and -// make it executable. +// We cannot create a symlink over an existing file so make sure it's gone and +// finish the installation process. // try { fs.unlinkSync(precommit); } catch (e) {}
[refactor] Cleanup some of the comments and re-organizing the code
observing_pre-commit
train
c0b371cf5f059d105b8152921b6cb2c79bd88a73
diff --git a/lib/codemirror.js b/lib/codemirror.js index <HASH>..<HASH> 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -2919,6 +2919,7 @@ updateMaxLine: false, // Set when the widest line needs to be determined anew scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet scrollToPos: null, // Used to scroll to a specific position + focus: false, id: ++nextOpId // Unique ID }; if (operationGroup) { @@ -3036,6 +3037,7 @@ if (cm.state.focused && op.updateInput) cm.display.input.reset(op.typing); + if (op.focus) ensureFocus(op.cm); } function endOperation_finish(op) { @@ -3515,7 +3517,7 @@ var lastClick, lastDoubleClick; function leftButtonDown(cm, e, start) { if (ie) setTimeout(bind(ensureFocus, cm), 0); - else ensureFocus(cm); + else cm.curOp.focus = true; var now = +new Date, type; if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { @@ -3675,7 +3677,7 @@ var cur = posFromMouse(cm, e, true, type == "rect"); if (!cur) return; if (cmp(cur, lastPos) != 0) { - ensureFocus(cm); + cm.curOp.focus = true; extendTo(cur); var visible = visibleLines(display, doc); if (cur.line >= visible.to || cur.line < visible.from) @@ -4033,7 +4035,7 @@ var lastStoppedKey = null; function onKeyDown(e) { var cm = this; - ensureFocus(cm); + cm.curOp.focus = true; if (signalDOMEvent(cm, e)) return; // IE does strange things with escape. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
Delay focusing of textarea to end of operation when possible So that the hidden textarea is actually near the cursor when it gets focused, and doesn't cause weird scroll jumps.
codemirror_CodeMirror
train
15459c18f01abcbf146777f077b68267069c338f
diff --git a/src/widget.js b/src/widget.js index <HASH>..<HASH> 100644 --- a/src/widget.js +++ b/src/widget.js @@ -30,6 +30,9 @@ class SunburstWidget { this.exclude = options.exclude || []; this.COLOR_PALLETTE = colors; this.loadingDiv = 'dummy'; + this.d3vis = null; + this.vis = null; + this.data = null; this._element = null; this._childElements = { icondefs: null, @@ -69,7 +72,7 @@ class SunburstWidget { if (!this.vis) { return; } - + var self = this; this.vis.selectAll('g').each(function() { var g = self.d3.select(this);
add initializers for properties added outside constructor
personality-insights_sunburst-chart
train
ec291721ddeb66c88ba2d86d45ee27de84013e95
diff --git a/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java b/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java +++ b/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java @@ -99,6 +99,11 @@ public class OrderPreservingPartitioner implements IPartitioner } } + public String toString(Token<String> stringToken) + { + return stringToken.token; + } + public Token<String> fromString(String string) { return new StringToken(string); diff --git a/src/java/org/apache/cassandra/dht/RandomPartitioner.java b/src/java/org/apache/cassandra/dht/RandomPartitioner.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/dht/RandomPartitioner.java +++ b/src/java/org/apache/cassandra/dht/RandomPartitioner.java @@ -92,6 +92,11 @@ public class RandomPartitioner implements IPartitioner return new BigIntegerToken(new BigInteger(bytes)); } + public String toString(Token<BigInteger> bigIntegerToken) + { + return bigIntegerToken.token.toString(); + } + public Token<BigInteger> fromString(String string) { return new BigIntegerToken(new BigInteger(string)); diff --git a/src/java/org/apache/cassandra/dht/Token.java b/src/java/org/apache/cassandra/dht/Token.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/dht/Token.java +++ b/src/java/org/apache/cassandra/dht/Token.java @@ -52,7 +52,8 @@ public abstract class Token<T extends Comparable> implements Comparable<Token<T> { public abstract byte[] toByteArray(Token<T> token); public abstract Token<T> fromByteArray(byte[] bytes); - public abstract Token<T> fromString(String string); + public abstract String toString(Token<T> token); // serialize as string, not necessarily human-readable + public abstract Token<T> fromString(String string); // deserialize } public static class TokenSerializer implements ICompactSerializer<Token> diff --git a/src/java/org/apache/cassandra/service/HttpRequestVerbHandler.java b/src/java/org/apache/cassandra/service/HttpRequestVerbHandler.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/service/HttpRequestVerbHandler.java +++ b/src/java/org/apache/cassandra/service/HttpRequestVerbHandler.java @@ -224,7 +224,7 @@ public class HttpRequestVerbHandler implements IVerbHandler { HTMLFormatter formatter = new HTMLFormatter(); - formatter.appendLine("Token: " + storageService_.getToken()); + formatter.appendLine(storageService_.getToken()); RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); formatter.appendLine("Up time (in seconds): " + (runtimeMxBean.getUptime()/1000)); diff --git a/src/java/org/apache/cassandra/service/StorageService.java b/src/java/org/apache/cassandra/service/StorageService.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/service/StorageService.java +++ b/src/java/org/apache/cassandra/service/StorageService.java @@ -468,7 +468,8 @@ public final class StorageService implements IEndPointStateChangeSubscriber, Sto Gossiper.instance().start(udpAddr_, storageMetadata_.getGeneration()); /* Make sure this token gets gossiped around. */ tokenMetadata_.update(storageMetadata_.getStorageId(), StorageService.tcpAddr_); - Gossiper.instance().addApplicationState(StorageService.nodeId_, new ApplicationState(storageMetadata_.getStorageId().toString())); + ApplicationState state = new ApplicationState(StorageService.getPartitioner().getTokenFactory().toString(storageMetadata_.getStorageId())); + Gossiper.instance().addApplicationState(StorageService.nodeId_, state); } public void killMe() throws Throwable @@ -726,7 +727,8 @@ public final class StorageService implements IEndPointStateChangeSubscriber, Sto /* Get the old token. This needs to be removed. */ tokenMetadata_.update(token, StorageService.tcpAddr_); /* Gossip this new token for the local storage instance */ - Gossiper.instance().addApplicationState(StorageService.nodeId_, new ApplicationState(token.toString())); + ApplicationState state = new ApplicationState(StorageService.getPartitioner().getTokenFactory().toString(token)); + Gossiper.instance().addApplicationState(StorageService.nodeId_, state); } /*
add string de/serialize code to TokenFactory for ApplicationState's benefit. patch by jbellis; tested by nk<I> and MarkR<I> for CASSANDRA-<I> git-svn-id: <URL>
Stratio_stratio-cassandra
train
a94a6444fee2a6a4f76436fcfb0fd23b88a3811e
diff --git a/registry.go b/registry.go index <HASH>..<HASH> 100644 --- a/registry.go +++ b/registry.go @@ -258,6 +258,36 @@ func parseString(s string) (metric string, indom string, instances []string, err } // AddMetricByString dynamically creates a PCPMetric -func (r *PCPRegistry) AddMetricByString(name string, val interface{}, s MetricSemantics, t MetricType, u MetricUnit) (Metric, error) { - return nil, nil +func (r *PCPRegistry) AddMetricByString(str string, val interface{}, s MetricSemantics, t MetricType, u MetricUnit) (Metric, error) { + metric, indom, instances, err := parseString(str) + if err != nil { + return nil, err + } + + if instances == nil { + // singleton metric + m, err := NewPCPSingletonMetric(val, metric, t, s, u, "", "") + if err != nil { + return nil, err + } + return m, nil + } + + // instance metric + mp, ok := val.(map[string]interface{}) + if !ok { + return nil, errors.New("to define an instance metric, a map[string]interface{} is required") + } + + id, err := r.AddInstanceDomainByName(indom, instances) + if err != nil { + return nil, err + } + + m, err := NewPCPInstanceMetric(mp, metric, id.(*PCPInstanceDomain), t, s, u, "", "") + if err != nil { + return nil, err + } + + return m, nil } diff --git a/registry_test.go b/registry_test.go index <HASH>..<HASH> 100644 --- a/registry_test.go +++ b/registry_test.go @@ -46,3 +46,61 @@ func TestIdentifierRegex(t *testing.T) { } } } + +func TestStringSingletonConstruction(t *testing.T) { + r := NewPCPRegistry() + + m, err := r.AddMetricByString("cow.how.now", 10, CounterSemantics, Int32Type, OneUnit) + if err != nil { + t.Error("Cannot parse, error", err) + return + } + + sm, ok := m.(*PCPSingletonMetric) + if !ok { + t.Error("Expected a PCPSingletonMetric") + } + + if sm.Name() != "cow.how.now" { + t.Errorf("Expected metric name to be %v, got %v", "cow.how.now", sm.Name()) + } + + if sm.Val() != int32(10) { + t.Errorf("Expected metric value to be %v, got %v", 10, sm.Val()) + } +} + +func TestStringInstanceConstruction(t *testing.T) { + r := NewPCPRegistry() + + m, err := r.AddMetricByString("sheep[limpy,grumpy,chumpy].legs.available", map[string]interface{}{ + "limpy": 10, + "grumpy": 20, + "chumpy": 30, + }, CounterSemantics, Int32Type, OneUnit) + if err != nil { + t.Error("Cannot parse, error", err) + return + } + + im, ok := m.(*PCPInstanceMetric) + if !ok { + t.Error("Expected a PCPInstanceMetric") + } + + if im.Name() != "sheep.legs.available" { + t.Errorf("Expected metric name to be %v, got %v", "cow.how.now", im.Name()) + } + + for i, v := range map[string]int32{"limpy": 10, "grumpy": 20, "chumpy": 30} { + val, err := im.ValInstance(i) + + if err != nil { + t.Errorf("error retrieving instance %v value", i) + } + + if val != v { + t.Errorf("wrong value for instance %v, expected %v, got %v", i, v, val) + } + } +}
registry: redefine AddMetricByString to be dynamic
performancecopilot_speed
train
c1af326b3834e7815f48596e4ca519555ad56a41
diff --git a/lib/prmd/schema.rb b/lib/prmd/schema.rb index <HASH>..<HASH> 100644 --- a/lib/prmd/schema.rb +++ b/lib/prmd/schema.rb @@ -63,7 +63,7 @@ module Prmd when Array datum.map { |element| convert_type_to_array.call(element) } when Hash - if datum.has_key?('type') + if datum.has_key?('type') && datum['type'].is_a?(String) datum['type'] = [*datum['type']] end datum.each { |k,v| datum[k] = convert_type_to_array.call(v) }
don't convert non-string types to arrays closes #<I>
interagent_prmd
train
e4fa599dbe0b20b7492d740137ea7972ca7bb0ea
diff --git a/viewer.js b/viewer.js index <HASH>..<HASH> 100644 --- a/viewer.js +++ b/viewer.js @@ -44,6 +44,9 @@ } , state = states.DEFAULT + // keeping track of event handling + , events = [] + //// buttons // default buttons that are always visible @@ -718,40 +721,38 @@ ctx.fillText(icon, x, y); } - function addEventListeners(){ - // dragging image or ui-elements - document.addEventListener('mousedown', onMouseDown); - document.addEventListener('mouseup', onMouseUp); - - // zooming - canvas.addEventListener('DOMMouseScroll', onMouseWheel); - canvas.addEventListener('mousewheel', onMouseWheel); - - // moving - canvas.addEventListener('mousemove', onMouseMove); + function addEventListener(eventTarget, eventType, listener){ + eventTarget.addEventListener(eventType, listener); + events.push({eventTarget: eventTarget, eventType: eventType, listener: listener}); + } - // setting target - canvas.addEventListener('click', onMouseClick); + function removeAllEventListeners(){ + var _i, _events = events.slice(), _current; + for(_i = 0; _i < _events.length; _i++){ + _current = _events[_i]; + _current.eventTarget.removeEventListener(_current.eventType, _current.listener); + } + events = []; } - function removeEventListeners(){ + function addEventListeners(){ // dragging image or ui-elements - document.removeEventListener('mousedown', onMouseDown); - document.removeEventListener('mouseup', onMouseUp); + addEventListener(document, 'mousedown', onMouseDown); + addEventListener(document, 'mouseup', onMouseUp); // zooming - canvas.removeEventListener('DOMMouseScroll', onMouseWheel); - canvas.removeEventListener('mousewheel', onMouseWheel); + addEventListener(canvas, 'DOMMouseScroll', onMouseWheel); + addEventListener(canvas, 'mousewheel', onMouseWheel); // moving - canvas.removeEventListener('mousemove', onMouseMove); + addEventListener(canvas, 'mousemove', onMouseMove); // setting target - canvas.removeEventListener('click', onMouseClick); + addEventListener(canvas, 'click', onMouseClick); } this.dispose = function(){ - removeEventListeners(); + removeAllEventListeners(); stopRendering = true; };
cleanup: erased code duplication and made removing of all event listeners easier
pfirpfel_image-viewer
train
9b4dbba384bc81a99abe429476729f80cb06d19a
diff --git a/src/platforms/web/runtime/directives/show.js b/src/platforms/web/runtime/directives/show.js index <HASH>..<HASH> 100644 --- a/src/platforms/web/runtime/directives/show.js +++ b/src/platforms/web/runtime/directives/show.js @@ -1,6 +1,5 @@ /* @flow */ -import { isIE9 } from 'core/util/env' import { enter, leave } from '../modules/transition' // recursively search for possible transition defined inside the component root @@ -16,7 +15,7 @@ export default { const transition = vnode.data && vnode.data.transition const originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display - if (value && transition && !isIE9) { + if (value && transition) { vnode.data.show = true enter(vnode, () => { el.style.display = originalDisplay @@ -31,7 +30,7 @@ export default { if (value === oldValue) return vnode = locateNode(vnode) const transition = vnode.data && vnode.data.transition - if (transition && !isIE9) { + if (transition) { vnode.data.show = true if (value) { enter(vnode, () => {
fix(transition): should trigger transition hooks for v-show in ie9 fix #<I>
IOriens_wxml-transpiler
train
a36bc3d9c32e59ccc8f77bf6b3dcbb1f23ed1978
diff --git a/guacamole/src/main/webapp/app/client/controllers/clientController.js b/guacamole/src/main/webapp/app/client/controllers/clientController.js index <HASH>..<HASH> 100644 --- a/guacamole/src/main/webapp/app/client/controllers/clientController.js +++ b/guacamole/src/main/webapp/app/client/controllers/clientController.js @@ -238,8 +238,25 @@ angular.module('client').controller('clientController', ['$scope', '$routeParams */ $scope.client = guacClientManager.getManagedClient($routeParams.id, $routeParams.params); + /** + * Map of all currently pressed keys by keysym. If a particular key is + * currently pressed, the value stored under that key's keysym within this + * map will be true. All keys not currently pressed will not have entries + * within this map. + * + * @type Object.<Number, Boolean> + */ var keysCurrentlyPressed = {}; + /** + * Map of all currently pressed keys (by keysym) to the clipboard contents + * received from the remote desktop while those keys were pressed. All keys + * not currently pressed will not have entries within this map. + * + * @type Object.<Number, String> + */ + var clipboardDataFromKey = {}; + /* * Check to see if all currently pressed keys are in the set of menu keys. */ @@ -379,7 +396,19 @@ angular.module('client').controller('clientController', ['$scope', '$routeParams }); + // Watch clipboard for new data, associating it with any pressed keys + $scope.$watch('client.clipboardData', function clipboardChanged(data) { + + // Associate new clipboard data with any currently-pressed key + for (var keysym in keysCurrentlyPressed) + clipboardDataFromKey[keysym] = data; + + }); + + // Track pressed keys, opening the Guacamole menu after Ctrl+Alt+Shift $scope.$on('guacKeydown', function keydownListener(event, keysym, keyboard) { + + // Record key as pressed keysCurrentlyPressed[keysym] = true; /* @@ -408,11 +437,24 @@ angular.module('client').controller('clientController', ['$scope', '$routeParams }); } } + }); - // Listen for broadcasted keyup events and fire the appropriate listeners + // Update pressed keys as they are released, synchronizing the clipboard + // with any data that appears to have come from those key presses $scope.$on('guacKeyup', function keyupListener(event, keysym, keyboard) { + + // Sync local clipboard with any clipboard data received while this + // key was pressed (if any) + var clipboardData = clipboardDataFromKey[keysym]; + if (clipboardData) { + clipboardService.setLocalClipboard(clipboardData); + delete clipboardDataFromKey[keysym]; + } + + // Mark key as released delete keysCurrentlyPressed[keysym]; + }); // Update page title when client name is received
GUAC-<I>: Sync local clipboard with received clipboard data if it appears to be due to an in-progress keyboard shortcut.
glyptodon_guacamole-client
train
731acf5d944ccea584e542d7fd944bd40c987aec
diff --git a/server.js b/server.js index <HASH>..<HASH> 100644 --- a/server.js +++ b/server.js @@ -818,6 +818,33 @@ cache(function(data, match, sendBadge) { }); })); +// Chef cookbook integration. +camp.route(/^\/cookbook\/v\/(.*)\.(svg|png|gif|jpg)$/, +cache(function(data, match, sendBadge) { + var cookbook = match[1]; // eg, chef-sugar + var format = match[2]; + var apiUrl = 'https://cookbooks.opscode.com/api/v1/cookbooks/' + cookbook + '/versions/latest'; + var badgeData = getBadgeData('version', data); + + request(apiUrl, function(err, res, buffer) { + if (err != null) { + badgeData.text[1] = 'inaccessible'; + sendBadge(format, badgeData); + } + + try { + var data = JSON.parse(buffer); + var latest = data.version; + badgeData.text[1] = latest; + badgeData.colorscheme = 'blue'; + sendBadge(format, badgeData); + } catch(e) { + badgeData.text[1] = 'invalid'; + sendBadge(format, badgeData); + } + }); +})); + // Any badge. camp.route(/^\/(:|badge\/)(([^-]|--)+)-(([^-]|--)+)-(([^-]|--)+)\.(svg|png|gif|jpg)$/, function(data, match, end, ask) {
Add a route for Chef cookbooks
badges_shields
train
e74599a6e8709171ff13a14aa9788731d77b0f8f
diff --git a/spec/acceptance/listen_spec.rb b/spec/acceptance/listen_spec.rb index <HASH>..<HASH> 100644 --- a/spec/acceptance/listen_spec.rb +++ b/spec/acceptance/listen_spec.rb @@ -74,6 +74,12 @@ describe "Listen" do }.should eq({ modified: ['file.rb'], added: [], removed: [] }) end + it "listens to file echo" do + listen { + `echo foo > #{Dir.pwd}/file.rb` + }.should eq({ modified: ['file.rb'], added: [], removed: [] }) + end + it "listens to file removal" do listen { rm 'file.rb'
Add spec for file modification with echo Close #<I>
guard_listen
train
15054ff55c51540475820a6965487255344bf6f2
diff --git a/lib/tetra/packages/maven_kit_item.rb b/lib/tetra/packages/maven_kit_item.rb index <HASH>..<HASH> 100644 --- a/lib/tetra/packages/maven_kit_item.rb +++ b/lib/tetra/packages/maven_kit_item.rb @@ -21,13 +21,14 @@ module Tetra rest, version = path_split(path) group_directory, artifact_id = path_split(rest) group_id = path_to_group(group_directory) + hash = Digest::SHA1.hexdigest(source_paths.to_s) @project = project @package_name = "kit-item-#{group_id.gsub(".", "-")}-#{artifact_id}-#{version}" @conflicts = false - @provides_symbol = "tetra-mvn(#{group_id}:#{artifact_id})" - @provides_version = version + @provides_symbol = "tetra-mvn(#{group_id}:#{artifact_id}:#{version})" + @provides_version = hash @install_dir = "m2" @source_dir = File.join("kit", "m2") diff --git a/spec/lib/maven_kit_item_spec.rb b/spec/lib/maven_kit_item_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/maven_kit_item_spec.rb +++ b/spec/lib/maven_kit_item_spec.rb @@ -21,16 +21,17 @@ describe Tetra::MavenKitItem do let(:jar) { File.join(dir, "#{artifact_id}.jar") } let(:package_name) { "kit-item-#{group_id.gsub(".", "-")}-#{artifact_id}-#{version}" } let(:maven_kit_item) { Tetra::MavenKitItem.new(@project, pom, [pom, jar]) } + let(:hash) { Digest::SHA1.hexdigest([pom, jar].to_s) } describe "#provides_symbol" do it "returns the sepec Provides: symbol" do - expect(maven_kit_item.provides_symbol).to eq("tetra-mvn(com.company.project:artifact)") + expect(maven_kit_item.provides_symbol).to eq("tetra-mvn(com.company.project:artifact:1.0)") end end describe "#provides_version" do it "returns the spec Provides: version" do - expect(maven_kit_item.provides_version).to eq("1.0") + expect(maven_kit_item.provides_version).to eq(hash) end end @@ -44,7 +45,7 @@ describe Tetra::MavenKitItem do expect(spec_lines).to include("# spec file for a build-time dependency of project \"test-project\"\n") expect(spec_lines).to include("Name: kit-item-com-company-project-artifact-1.0\n") expect(spec_lines).to include("Summary: Build-time dependency of project \"test-project\"\n") - expect(spec_lines).to include("Provides: tetra-mvn(#{group_id}:#{artifact_id}) == #{version}\n") + expect(spec_lines).to include("Provides: tetra-mvn(#{group_id}:#{artifact_id}:#{version}) == #{hash}\n") expect(spec_lines).to include("install -d -m 0755 %{buildroot}%{_datadir}/tetra/m2\n") expect(spec_lines).to include("cp -a * %{buildroot}%{_datadir}/tetra/m2\n")
Bugfix: be sure that maven kit items are sharable
moio_tetra
train
2baf22065c272151067db8b7c0af9ef6ffdb423b
diff --git a/flask_jwt_extended/tokens.py b/flask_jwt_extended/tokens.py index <HASH>..<HASH> 100644 --- a/flask_jwt_extended/tokens.py +++ b/flask_jwt_extended/tokens.py @@ -48,8 +48,12 @@ def encode_access_token(identity, secret, algorithm, expires_delta, fresh, identity_claim: identity, 'fresh': fresh, 'type': 'access', - 'user_claims': user_claims, } + + # Add `user_claims` only is not empty or None. + if user_claims: + token_data['user_claims'] = user_claims + if csrf: token_data['csrf'] = _create_csrf_token() return _encode_jwt(token_data, expires_delta, secret, algorithm) @@ -104,7 +108,7 @@ def decode_jwt(encoded_token, secret, algorithm, csrf, identity_claim): if 'fresh' not in data: raise JWTDecodeError("Missing claim: fresh") if 'user_claims' not in data: - raise JWTDecodeError("Missing claim: user_claims") + data['user_claims'] = {} if csrf: if 'csrf' not in data: raise JWTDecodeError("Missing claim: csrf") diff --git a/tests/test_jwt_encode_decode.py b/tests/test_jwt_encode_decode.py index <HASH>..<HASH> 100644 --- a/tests/test_jwt_encode_decode.py +++ b/tests/test_jwt_encode_decode.py @@ -83,6 +83,35 @@ class JWTEncodeDecodeTests(unittest.TestCase): self.assertLessEqual(exp_seconds, 60 * 5) self.assertGreater(exp_seconds, 60 * 4) + def test_encode_access_token__no_user_claims(self): + ''' + To make JWT shorter, do not add `user_claims` if empty. + ''' + secret = 'super-totally-secret-key' + algorithm = 'HS256' + token_expire_delta = timedelta(minutes=5) + identity_claim = 'sub' + + # `user_claims` is empty dict + with self.app.test_request_context(): + identity = 'user1' + token = encode_access_token(identity, secret, algorithm, token_expire_delta, + fresh=False, user_claims={}, csrf=False, + identity_claim=identity_claim) + + data = jwt.decode(token, secret, algorithms=[algorithm]) + self.assertNotIn('user_claims', data) + + # `user_claims` is None + with self.app.test_request_context(): + identity = 'user1' + token = encode_access_token(identity, secret, algorithm, token_expire_delta, + fresh=False, user_claims=None, csrf=False, + identity_claim=identity_claim) + + data = jwt.decode(token, secret, algorithms=[algorithm]) + self.assertNotIn('user_claims', data) + def test_encode_invalid_access_token(self): # Check with non-serializable json with self.app.test_request_context(): @@ -212,6 +241,29 @@ class JWTEncodeDecodeTests(unittest.TestCase): self.assertEqual(data[identity_claim], 'banana') self.assertEqual(data['type'], 'refresh') + def test_decode_access_token__no_user_claims(self): + ''' + Test decoding a valid access token without `user_claims`. + ''' + identity_claim = 'sub' + with self.app.test_request_context(): + now = datetime.utcnow() + token_data = { + 'exp': now + timedelta(minutes=5), + 'iat': now, + 'nbf': now, + 'jti': 'banana', + identity_claim: 'banana', + 'fresh': True, + 'type': 'access', + } + encoded_token = jwt.encode(token_data, 'secret', 'HS256').decode('utf-8') + data = decode_jwt(encoded_token, 'secret', 'HS256', + csrf=False, identity_claim=identity_claim) + + self.assertIn('user_claims', data) + self.assertEqual(data['user_claims'], {}) + def test_decode_invalid_jwt(self): with self.app.test_request_context(): identity_claim = 'identity' @@ -284,19 +336,6 @@ class JWTEncodeDecodeTests(unittest.TestCase): decode_jwt(encoded_token, 'secret', 'HS256', csrf=False, identity_claim=identity_claim) - # Missing user claims in access token - with self.assertRaises(JWTDecodeError): - token_data = { - 'jti': 'banana', - identity_claim: 'banana', - 'exp': datetime.utcnow() + timedelta(minutes=5), - 'type': 'access', - 'fresh': True - } - encoded_token = jwt.encode(token_data, 'secret', 'HS256').decode('utf-8') - decode_jwt(encoded_token, 'secret', 'HS256', - csrf=False, identity_claim=identity_claim) - # Bad token type with self.assertRaises(JWTDecodeError): token_data = {
Do not add `user_claims` to access token if empty If `user_claims` are empty dict (`{}`) or `None`, do not add them to JWT. This should result in shorter token length.
vimalloc_flask-jwt-extended
train
09d8dbad0a6a15d88304b8dfa5d3693a2c1d0984
diff --git a/lib/IyzipayResource.js b/lib/IyzipayResource.js index <HASH>..<HASH> 100644 --- a/lib/IyzipayResource.js +++ b/lib/IyzipayResource.js @@ -27,7 +27,7 @@ IyzipayResource.prototype._getHttpHeaders = function (method) { this._config.apiKey, IyzipayResource.SEPARATOR, this._config.secretKey, - this._api[method].path, + this._api[method].generatedPath, this._getBody(method), randomString ); @@ -52,11 +52,11 @@ IyzipayResource.prototype._preparePath = function (method) { currentPath = currentPath.replace('{' + key + '}', pathVariables[key]); } } - this._api[method].path = currentPath; + this._api[method].generatedPath = currentPath; }; IyzipayResource.prototype._getUrl = function (method) { - return this._config.uri + this._api[method].path; + return this._config.uri + this._api[method].generatedPath; }; IyzipayResource.prototype._getMethod = function (method) {
client request update (#<I>)
iyzico_iyzipay-node
train
3ae1f6c22af72dee672236521b43f08239c5cf8f
diff --git a/barge-core/src/main/java/org/robotninjas/barge/log/DefaultRaftLog.java b/barge-core/src/main/java/org/robotninjas/barge/log/DefaultRaftLog.java index <HASH>..<HASH> 100644 --- a/barge-core/src/main/java/org/robotninjas/barge/log/DefaultRaftLog.java +++ b/barge-core/src/main/java/org/robotninjas/barge/log/DefaultRaftLog.java @@ -31,6 +31,7 @@ import org.robotninjas.barge.Replica; import org.robotninjas.barge.annotations.ClusterMembers; import org.robotninjas.barge.annotations.LocalReplicaInfo; import org.robotninjas.barge.proto.ClientProto; +import org.robotninjas.barge.proto.LogProto; import org.robotninjas.barge.proto.RaftEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -95,7 +96,15 @@ class DefaultRaftLog implements RaftLog { private void storeEntry(long index, @Nonnull Entry entry) { try { - Location loc = journal.write(entry.toByteArray(), WriteType.SYNC); + + LogProto.JournalEntry journalEntry = + LogProto.JournalEntry.newBuilder() + .setAppend(LogProto.Append.newBuilder() + .setIndex(index) + .setEntry(entry)) + .build(); + + Location loc = journal.write(journalEntry.toByteArray(), WriteType.SYNC); EntryMeta meta = new EntryMeta(index, entry.getTerm(), loc); this.entryIndex.put(index, meta); this.entryCache.put(index, entry); @@ -267,7 +276,11 @@ class DefaultRaftLog implements RaftLog { EntryMeta meta = index.get(key); Location loc = meta.location; byte[] data = journal.read(loc, Journal.ReadType.ASYNC); - return Entry.parseFrom(data); + LogProto.JournalEntry journalEntry = LogProto.JournalEntry.parseFrom(data); + if (!journalEntry.hasAppend()) { + throw new IllegalStateException("Journal entry does not contain Append"); + } + return journalEntry.getAppend().getEntry(); } catch (Exception e) { e.printStackTrace(); throw e;
Write a separate log data structure to the log instead of just the entry
mgodave_barge
train
cc60dd19e75f5c83ef48816fbc888bb09a83a3f0
diff --git a/tests/Sharing/BucketsTest.php b/tests/Sharing/BucketsTest.php index <HASH>..<HASH> 100644 --- a/tests/Sharing/BucketsTest.php +++ b/tests/Sharing/BucketsTest.php @@ -321,19 +321,14 @@ class BucketsTest extends StorageApiTestCase $this->fail('Shared table delete should fail'); } catch (ClientException $e) { $this->assertEquals('tables.cannotDeletedTableWithAliases', $e->getStringCode()); - // $this->assertEquals('tables.cannotDeleteTableWithLinks', $e->getStringCode()); } - //@FIXME - /* try { $this->_client->deleteTableColumn($table['id'], 'name'); $this->fail('Shared table column delete should fail'); } catch (ClientException $e) { - $this->assertEquals('tables.cannotDeleteRowWithLinks', $e->getStringCode()); - $this->assertEquals('tables.cannotDeleteRowWithLinks', $e->getStringCode()); + $this->assertEquals('storage.buckets.alreadyLinked', $e->getStringCode()); } - */ } // bucket drop
shared-buckets: test for restricted column drop
keboola_storage-api-php-client
train
84ddabda3a48fbcc4615c37ecb8c516cf4df458f
diff --git a/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/services/domain/datacenters/filters/DataCenterFilter.java b/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/services/domain/datacenters/filters/DataCenterFilter.java index <HASH>..<HASH> 100644 --- a/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/services/domain/datacenters/filters/DataCenterFilter.java +++ b/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/services/domain/datacenters/filters/DataCenterFilter.java @@ -36,7 +36,7 @@ public class DataCenterFilter implements Filter<DataCenterFilter> { /** * Method allow to provide custom filter predicate * - * @param predicate + * @param predicate is not null filtering predicate * @return {@link DataCenterFilter} */ public DataCenterFilter where(Predicate<DataCenterMetadata> predicate) { @@ -48,16 +48,17 @@ public class DataCenterFilter implements Filter<DataCenterFilter> { } /** - * Method allow to filter data centers by IDs. Filtering is strong case sensitive. + * Method allow to filter data centers by IDs. Filtering is by full match. + * Comparison is case insensitive. * - * @param ids + * @param ids is not null target datacenter IDs * @return {@link DataCenterFilter} */ public DataCenterFilter id(String... ids) { allItemsNotNull(ids, "Data center ID list"); this.predicate = this.predicate.and(combine( - DataCenterMetadata::getId, Predicates.in(ids) + DataCenterMetadata::getId, in(asList(ids), Predicates::equalsIgnoreCase) )); return this; diff --git a/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/services/domain/datacenters/refs/DataCenter.java b/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/services/domain/datacenters/refs/DataCenter.java index <HASH>..<HASH> 100644 --- a/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/services/domain/datacenters/refs/DataCenter.java +++ b/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/services/domain/datacenters/refs/DataCenter.java @@ -21,7 +21,8 @@ public abstract class DataCenter implements Reference<DataCenterFilter> { public static final DataCenterByIdRef US_WEST_SEATTLE = refById("wa1"); /** - * Method allow to refer datacenter by it's ID. Filtering is strong case sensitive. + * Method allow to refer datacenter by it's ID. Filtering is by full match. + * Comparison is case insensitive. * * @param id is not null reference to datacenter * @return {@link DataCenterByIdRef} diff --git a/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/core/function/Predicates.java b/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/core/function/Predicates.java index <HASH>..<HASH> 100644 --- a/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/core/function/Predicates.java +++ b/clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/core/function/Predicates.java @@ -76,6 +76,10 @@ public abstract class Predicates { return upperCase(source).contains(upperCase(substring)); } + public static boolean equalsIgnoreCase(String firstString, String secondString) { + return upperCase(firstString).equals(upperCase(secondString)); + } + private static String upperCase(String source) { return nullToEmpty(source).toUpperCase(); } diff --git a/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/common/management/services/datacenters/DataCenterServiceTest.java b/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/common/management/services/datacenters/DataCenterServiceTest.java index <HASH>..<HASH> 100644 --- a/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/common/management/services/datacenters/DataCenterServiceTest.java +++ b/clc-java-sdk/sdk/src/test/java/com/centurylink/cloud/sdk/common/management/services/datacenters/DataCenterServiceTest.java @@ -73,7 +73,7 @@ public class DataCenterServiceTest extends AbstractSdkTest { List<DataCenterMetadata> results = dataCenterService .find(new DataCenterFilter() - .id("de1", "va1") + .id("DE1", "va1") ); verifyDataCenterById(results, 0, DE_FRANKFURT);
<I> design and implement integration tests framework
CenturyLinkCloud_clc-java-sdk
train
ff324798cb1c6e87d714ecacf8a8891f30249a5b
diff --git a/hazelcast/src/test/java/com/hazelcast/cluster/impl/AdvancedClusterStateTest.java b/hazelcast/src/test/java/com/hazelcast/cluster/impl/AdvancedClusterStateTest.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/test/java/com/hazelcast/cluster/impl/AdvancedClusterStateTest.java +++ b/hazelcast/src/test/java/com/hazelcast/cluster/impl/AdvancedClusterStateTest.java @@ -56,7 +56,6 @@ import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; @@ -516,17 +515,6 @@ public class AdvancedClusterStateTest extends HazelcastTestSupport { future.get(); } - private static ClusterServiceImpl spyClusterService(HazelcastInstance hz) throws Exception { - Node node = getNode(hz); - ClusterServiceImpl originalClusterService = node.clusterService; - ClusterServiceImpl spiedClusterService = spy(originalClusterService); - - Field clusterServiceField = Node.class.getField("clusterService"); - clusterServiceField.setAccessible(true); - clusterServiceField.set(node, spiedClusterService); - return spiedClusterService; - } - private static TransactionManagerServiceImpl spyTransactionManagerService(HazelcastInstance hz) throws Exception { NodeEngineImpl nodeEngine = getNode(hz).nodeEngine; TransactionManagerServiceImpl transactionManagerService @@ -546,52 +534,6 @@ public class AdvancedClusterStateTest extends HazelcastTestSupport { } } - private static class AddingMemberListAnswer extends MemberListAnswer { - - Collection<MemberImpl> onAnswer(Collection<MemberImpl> members) throws Exception { - if (addFakeMember()) { - members = new ArrayList<MemberImpl>(members); - members.add(new MemberImpl(new Address("127.0.0.1", 6000), false)); - } - return members; - } - - private boolean addFakeMember() { - return cluster.getClusterState() == ClusterState.IN_TRANSITION; - } - - } - - private static class RemovingMemberListAnswer extends MemberListAnswer { - - Collection<MemberImpl> onAnswer(Collection<MemberImpl> members) throws Exception { - if (removeMember()) { - LinkedList<MemberImpl> list = new LinkedList<MemberImpl>(members); - list.removeFirst(); - members = list; - } - return members; - } - - private boolean removeMember() { - return cluster.getClusterState() == ClusterState.IN_TRANSITION; - } - } - - private static abstract class MemberListAnswer implements Answer<Collection<MemberImpl>> { - Cluster cluster; - - @SuppressWarnings("unchecked") - @Override - public Collection<MemberImpl> answer(InvocationOnMock invocation) throws Throwable { - Collection<MemberImpl> members = (Collection<MemberImpl>) invocation.callRealMethod(); - members = onAnswer(members); - return members; - } - - abstract Collection<MemberImpl> onAnswer(Collection<MemberImpl> members) throws Exception; - } - private static abstract class TransactionAnswer implements Answer<Transaction> { @Override public Transaction answer(InvocationOnMock invocation) throws Throwable {
Removed unused cluster-state test methods/classes
hazelcast_hazelcast
train
30cf5725cfc98e10944fbbe491360789948b1e78
diff --git a/claripy/ast.py b/claripy/ast.py index <HASH>..<HASH> 100644 --- a/claripy/ast.py +++ b/claripy/ast.py @@ -278,6 +278,8 @@ class A(ana.Storable): # l.warning(ClaripyOperationError("Un-wrapped native object of type %s!" % type(a))) #pylint:enable=attribute-defined-outside-init + def make_uuid(self): + return str(self._hash) @property def uuid(self):
ASTs now use their hash as a uuid
angr_claripy
train
8852f5a407a0eee558e2f5b682e08667ab2d85bf
diff --git a/lib/dxruby_sdl/image.rb b/lib/dxruby_sdl/image.rb index <HASH>..<HASH> 100644 --- a/lib/dxruby_sdl/image.rb +++ b/lib/dxruby_sdl/image.rb @@ -49,6 +49,15 @@ module DXRubySDL return @_surface.h end + def set_color_key(color) + @_surface.set_color_key(SDL::RLEACCEL, color) + end + + def compare(x, y, color) + pixel = lock { @_surface.get_pixel(x, y) } + return @_surface.format.get_rgb(pixel) == color + end + def slice(x, y, width, height) s = @_surface.copy_rect(x, y, width, height) image = Image.new(0, 0) @@ -110,6 +119,7 @@ module DXRubySDL alias_method :load_to_array, :load_tiles alias_method :loadToArray, :load_to_array end + alias_method :setColorKey, :set_color_key alias_method :circleFill, :circle_fill alias_method :boxFill, :box_fill # rubocop:enable SymbolName @@ -122,7 +132,7 @@ module DXRubySDL else begin @_surface.lock - yield + return yield ensure @_surface.unlock end
supported Image#set_color_key and Image#compare, but not implemented spec.
takaokouji_dxruby_sdl
train
6553778c9eb9a50905db565fdbde7ccb22ad3997
diff --git a/tcp.go b/tcp.go index <HASH>..<HASH> 100644 --- a/tcp.go +++ b/tcp.go @@ -6,6 +6,7 @@ import ( "net" "os" "runtime" + "syscall" "time" "github.com/libp2p/go-libp2p-core/network" @@ -45,7 +46,7 @@ func tryKeepAlive(conn net.Conn, keepAlive bool) { // // But there's nothing we can do about invalid arguments, so we'll drop this to a // debug. - if errors.Is(err, os.ErrInvalid) { + if errors.Is(err, os.ErrInvalid) || errors.Is(err, syscall.EINVAL) { log.Debugw("failed to enable TCP keepalive", "error", err) } else { log.Errorw("failed to enable TCP keepalive", "error", err)
fix: drop raw EINVAL (from keepalives) errors as well (#<I>) It _looks_ like the standard library doesn't always wrap this error. fixes #<I>
libp2p_go-tcp-transport
train
0092a4332ba209e465d2ba24517da81960c7314b
diff --git a/qbit/admin/src/main/java/io/advantageous/qbit/admin/ServiceManagementBundle.java b/qbit/admin/src/main/java/io/advantageous/qbit/admin/ServiceManagementBundle.java index <HASH>..<HASH> 100644 --- a/qbit/admin/src/main/java/io/advantageous/qbit/admin/ServiceManagementBundle.java +++ b/qbit/admin/src/main/java/io/advantageous/qbit/admin/ServiceManagementBundle.java @@ -51,6 +51,7 @@ public class ServiceManagementBundle implements ServiceHealthManager { time = timer.time(); reactor.process(); processHandler.ifPresent(Runnable::run); + stats.clientProxyFlush(); } diff --git a/qbit/admin/src/main/java/io/advantageous/qbit/admin/ServiceManagementBundleBuilder.java b/qbit/admin/src/main/java/io/advantageous/qbit/admin/ServiceManagementBundleBuilder.java index <HASH>..<HASH> 100644 --- a/qbit/admin/src/main/java/io/advantageous/qbit/admin/ServiceManagementBundleBuilder.java +++ b/qbit/admin/src/main/java/io/advantageous/qbit/admin/ServiceManagementBundleBuilder.java @@ -140,4 +140,8 @@ public class ServiceManagementBundleBuilder { return new ServiceManagementBundle(getReactor(), getStatsCollector(), getServiceHealthManager(), getServiceName(), getTimer(), getStatKeyPrefix(), getProcessHandler()); } + + public static ServiceManagementBundleBuilder serviceManagementBundleBuilder() { + return new ServiceManagementBundleBuilder(); + } }
flush stats. created builder method.
advantageous_qbit
train
3f3498ab18f1c69ac629d09305d033ca99cb209e
diff --git a/salt/modules/lxc.py b/salt/modules/lxc.py index <HASH>..<HASH> 100644 --- a/salt/modules/lxc.py +++ b/salt/modules/lxc.py @@ -3,6 +3,9 @@ Control Linux Containers via Salt :depends: lxc package for distribution + +You need lxc >= 1.0 (even beta alpha) + ''' # Import python libs @@ -13,7 +16,7 @@ import os #import salt libs import salt.utils -import subprocess +#import subprocess # Set up logging log = logging.getLogger(__name__) @@ -25,6 +28,10 @@ __func_alias__ = { def __virtual__(): + ''' + To speed up the whole thing, we decided to not use the + subshell way and assume things are in place for lxc + Discussion made by @kiorky and @thatch45 if salt.utils.which('lxc-autostart'): return 'lxc' elif salt.utils.which('lxc-version'): @@ -38,6 +45,8 @@ def __virtual__(): log.warning('Support for lxc < 1.0 may be incomplete.') return 'lxc' return False + ''' + return 'lxc' def _lxc_profile(profile):
bypass any test for lxc virtual
saltstack_salt
train
ca5fd7a835c10e11ee79916251dc89ff52fa741b
diff --git a/lib/mongoid/commands/deletion.rb b/lib/mongoid/commands/deletion.rb index <HASH>..<HASH> 100644 --- a/lib/mongoid/commands/deletion.rb +++ b/lib/mongoid/commands/deletion.rb @@ -6,7 +6,12 @@ module Mongoid #:nodoc # otherwise delete it from it's collection. def delete(doc) parent = doc._parent - parent ? parent.remove(doc) : doc.collection.remove(:_id => doc.id) + if parent + parent.remove(doc) + parent.save + else + doc.collection.remove(:_id => doc.id) + end end end end diff --git a/spec/integration/mongoid/commands_spec.rb b/spec/integration/mongoid/commands_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/mongoid/commands_spec.rb +++ b/spec/integration/mongoid/commands_spec.rb @@ -43,34 +43,108 @@ describe Mongoid::Commands do describe "#delete" do - before do - @person.save - end + context "deleting a root document" do + + before do + @person.save + end + + it "deletes the document" do + @person.delete + lambda { Person.find(@person.id) }.should raise_error + end + + it "returns true" do + @person.delete.should be_true + end - it "deletes the document" do - @person.delete - lambda { Person.find(@person.id) }.should raise_error end - it "returns true" do - @person.delete.should be_true + context "deleting an embedded document" do + + before do + @address = Address.new(:street => "Bond Street") + @person.addresses << @address + end + + context "when the document is not yet saved" do + + it "removes the document from the parent" do + @address.delete + @person.addresses.should be_empty + @person.attributes[:addresses].should be_empty + end + + end + + context "when the document has been saved" do + + before do + @address.save + end + + it "removes the object from the parent and database" do + @address.delete + from_db = Person.find(@person.id) + from_db.addresses.should be_empty + end + + end + end end describe "#destroy" do - before do - @person.save - end + context "destroying a root document" do + + before do + @person.save + end + + it "destroys the document" do + @person.destroy + lambda { Person.find(@person.id) }.should raise_error + end + + it "returns true" do + @person.destroy.should be_true + end - it "deletes the document" do - @person.destroy - lambda { Person.find(@person.id) }.should raise_error end - it "returns true" do - @person.destroy.should be_true + context "deleting an embedded document" do + + before do + @address = Address.new(:street => "Bond Street") + @person.addresses << @address + end + + context "when the document is not yet saved" do + + it "removes the document from the parent" do + @address.destroy + @person.addresses.should be_empty + @person.attributes[:addresses].should be_empty + end + + end + + context "when the document has been saved" do + + before do + @address.save + end + + it "removes the object from the parent and database" do + @address.destroy + from_db = Person.find(@person.id) + from_db.addresses.should be_empty + end + + end + end end diff --git a/spec/unit/mongoid/scope_spec.rb b/spec/unit/mongoid/scope_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/mongoid/scope_spec.rb +++ b/spec/unit/mongoid/scope_spec.rb @@ -2,6 +2,10 @@ require "spec_helper" describe Mongoid::Scope do + before do + Person.delete_all + end + describe "#==" do before do
Document#delete and Document#destroy on embedded docs properly persists parent
mongodb_mongoid
train
8d942e145c9d1d4a0b75085ffad291c1513edb60
diff --git a/reactor-test/src/main/java/reactor/test/StepVerifier.java b/reactor-test/src/main/java/reactor/test/StepVerifier.java index <HASH>..<HASH> 100644 --- a/reactor-test/src/main/java/reactor/test/StepVerifier.java +++ b/reactor-test/src/main/java/reactor/test/StepVerifier.java @@ -174,6 +174,13 @@ public interface StepVerifier { * will use virtual time. * Each {@link #verify()} will fully (re)play the scenario. * The verification will request an unbounded amount of values. + * <p> + * Note that virtual time, {@link Step#thenAwait(Duration)} sources that are + * subscribed on a different {@link reactor.core.scheduler.Scheduler} (eg. a source + * that is initialized outside of the lambda with a dedicated Scheduler) and + * delays introduced within the data path (eg. an interval in a flatMap) are not + * always compatible, as this can perform the clock move BEFORE the interval schedules + * itself, resulting in the interval never playing out. * * @param scenarioSupplier a mandatory supplier of the {@link Publisher} to subscribe * to and verify. In order for operators to use virtual time, they must be invoked @@ -194,6 +201,13 @@ public interface StepVerifier { * will use virtual time. * Each {@link #verify()} will fully (re)play the scenario. * The verification will request a specified amount of values. + * <p> + * Note that virtual time, {@link Step#thenAwait(Duration)} sources that are + * subscribed on a different {@link reactor.core.scheduler.Scheduler} (eg. a source + * that is initialized outside of the lambda with a dedicated Scheduler) and + * delays introduced within the data path (eg. an interval in a flatMap) are not + * always compatible, as this can perform the clock move BEFORE the interval schedules + * itself, resulting in the interval never playing out. * * @param scenarioSupplier a mandatory supplier of the {@link Publisher} to subscribe * to and verify. In order for operators to use virtual time, they must be invoked @@ -216,6 +230,13 @@ public interface StepVerifier { * will use virtual time. * Each {@link #verify()} will fully (re)play the scenario. * The verification will request a specified amount of values. + * <p> + * Note that virtual time, {@link Step#thenAwait(Duration)} sources that are + * subscribed on a different {@link reactor.core.scheduler.Scheduler} (eg. a source + * that is initialized outside of the lambda with a dedicated Scheduler) and + * delays introduced within the data path (eg. an interval in a flatMap) are not + * always compatible, as this can perform the clock move BEFORE the interval schedules + * itself, resulting in the interval never playing out. * * @param scenarioSupplier a mandatory supplier of the {@link Publisher} to subscribe * to and verify. In order for operators to use virtual time, they must be invoked @@ -245,6 +266,13 @@ public interface StepVerifier { * Each {@link #verify()} will fully (re)play the scenario. * The verification will request a specified amount of values according to * the provided {@link StepVerifierOptions options}. + * <p> + * Note that virtual time, {@link Step#thenAwait(Duration)} sources that are + * subscribed on a different {@link reactor.core.scheduler.Scheduler} (eg. a source + * that is initialized outside of the lambda with a dedicated Scheduler) and + * delays introduced within the data path (eg. an interval in a flatMap) are not + * always compatible, as this can perform the clock move BEFORE the interval schedules + * itself, resulting in the interval never playing out. * * @param scenarioSupplier a mandatory supplier of the {@link Publisher} to subscribe * to and verify. In order for operators to use virtual time, they must be invoked diff --git a/reactor-test/src/test/java/reactor/test/StepVerifierTests.java b/reactor-test/src/test/java/reactor/test/StepVerifierTests.java index <HASH>..<HASH> 100644 --- a/reactor-test/src/test/java/reactor/test/StepVerifierTests.java +++ b/reactor-test/src/test/java/reactor/test/StepVerifierTests.java @@ -32,6 +32,7 @@ import java.util.concurrent.locks.LockSupport; import org.assertj.core.api.Assertions; import org.junit.Assert; +import org.junit.Ignore; import org.junit.Test; import reactor.core.Fuseable; import reactor.core.publisher.DirectProcessor; @@ -2006,6 +2007,8 @@ public class StepVerifierTests { } @Test + @Ignore + //FIXME this case of doubly-nested schedules is still not fully fixed public void gh783_withInnerFlatmap() { int size = 61; Scheduler parallel = Schedulers.newParallel("gh-783"); @@ -2022,7 +2025,7 @@ public class StepVerifierTests { .take(size) .collectList() ) - .thenAwait(Duration.ofHours(2)) + .thenAwait(Duration.ofMillis(1500 * (size + 10))) .consumeNextWith(list -> assertThat(list).hasSize(size)) .expectComplete() .verify(Duration.ofSeconds(5));
see #<I> Disable doubly-nested schedules VTS thenAwait test This case isn't fully taken care of by the previous fix, which still improves the situation for delayed schedules on a single nesting level.
reactor_reactor-core
train
09b151456f37ce60d50b582b4d136f07d3031c16
diff --git a/lib/active_record/connection_adapters/oracle_enhanced_schema_definitions.rb b/lib/active_record/connection_adapters/oracle_enhanced_schema_definitions.rb index <HASH>..<HASH> 100644 --- a/lib/active_record/connection_adapters/oracle_enhanced_schema_definitions.rb +++ b/lib/active_record/connection_adapters/oracle_enhanced_schema_definitions.rb @@ -42,7 +42,6 @@ module ActiveRecord def self.included(base) #:nodoc: base.class_eval do - alias_method_chain :references, :foreign_keys alias_method_chain :column, :virtual_columns end end @@ -85,7 +84,7 @@ module ActiveRecord # # Note: No foreign key is created if :polymorphic => true is used. # Note: If no name is specified, the database driver creates one for you! - def references_with_foreign_keys(*args) + def references(*args) options = args.extract_options! index_options = options[:index] fk_options = options.delete(:foreign_key) @@ -98,7 +97,7 @@ module ActiveRecord end end - references_without_foreign_keys(*(args << options)) + super(*(args << options)) end # Defines a foreign key for the table. +to_table+ can be a single Symbol, or @@ -129,11 +128,6 @@ module ActiveRecord end module OracleEnhancedTable - def self.included(base) #:nodoc: - base.class_eval do - alias_method_chain :references, :foreign_keys - end - end # Adds a new foreign key to the table. +to_table+ can be a single Symbol, or # an Array of Symbols. See SchemaStatements#add_foreign_key @@ -180,13 +174,13 @@ module ActiveRecord # t.references(:goat, :foreign_key => {:dependent => :delete}) # # Note: No foreign key is created if :polymorphic => true is used. - def references_with_foreign_keys(*args) + def references(*args) options = args.extract_options! polymorphic = options[:polymorphic] index_options = options[:index] fk_options = options.delete(:foreign_key) - references_without_foreign_keys(*(args << options)) + super(*(args << options)) # references_without_foreign_keys adds {:type => :integer} args.extract_options! if fk_options && !polymorphic
Remove alias_method_chain :references, :foreign_keys since Rails <I> supports native foreign key. References can create foreign keys
rsim_oracle-enhanced
train
8030c3b6ac97471705b41fdb237a0399c190feb1
diff --git a/features/pull_request.feature b/features/pull_request.feature index <HASH>..<HASH> 100644 --- a/features/pull_request.feature +++ b/features/pull_request.feature @@ -855,7 +855,6 @@ Feature: hub pull-request json :html_url => "the://url", :number => 1234 } post('/repos/mislav/coral/pulls/1234/requested_reviewers') { - halt 415 unless request.accept?('application/vnd.github.thor-preview+json') assert :reviewers => ["mislav", "josh", "pcorpet"] assert :team_reviewers => ["robots", "js"] status 201 @@ -877,7 +876,6 @@ Feature: hub pull-request :requested_teams => [{ :name => "robots" }] } post('/repos/mislav/coral/pulls/1234/requested_reviewers') { - halt 415 unless request.accept?('application/vnd.github.thor-preview+json') assert :reviewers => ["mislav", "pcorpet"] assert :team_reviewers => ["js"] status 201 diff --git a/github/client.go b/github/client.go index <HASH>..<HASH> 100644 --- a/github/client.go +++ b/github/client.go @@ -138,7 +138,7 @@ func (client *Client) RequestReview(project *Project, prNumber int, params map[s return } - res, err := api.PostReview(fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", project.Owner, project.Name, prNumber), params) + res, err := api.PostJSON(fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", project.Owner, project.Name, prNumber), params) if err = checkStatus(201, "requesting reviewer", res, err); err != nil { return } diff --git a/github/http.go b/github/http.go index <HASH>..<HASH> 100644 --- a/github/http.go +++ b/github/http.go @@ -279,12 +279,6 @@ func (c *simpleClient) PatchJSON(path string, payload interface{}) (*simpleRespo return c.jsonRequest("PATCH", path, payload, nil) } -func (c *simpleClient) PostReview(path string, payload interface{}) (*simpleResponse, error) { - return c.jsonRequest("POST", path, payload, func(req *http.Request) { - req.Header.Set("Accept", "application/vnd.github.thor-preview+json;charset=utf-8") - }) -} - func (c *simpleClient) PostFile(path, filename string) (*simpleResponse, error) { stat, err := os.Stat(filename) if err != nil {
Stop requesting `thor-preview` in API requests It wasn't necessary for github.com since December <I>.
github_hub
train
c2fefed9d71ab823d5e55c88dc7b873432ad7a7d
diff --git a/keanu-project/src/main/java/io/improbable/keanu/vertices/VertexLabel.java b/keanu-project/src/main/java/io/improbable/keanu/vertices/VertexLabel.java index <HASH>..<HASH> 100644 --- a/keanu-project/src/main/java/io/improbable/keanu/vertices/VertexLabel.java +++ b/keanu-project/src/main/java/io/improbable/keanu/vertices/VertexLabel.java @@ -21,12 +21,12 @@ public class VertexLabel { this.namespace = ImmutableList.copyOf(namespace); } - public VertexLabel inNamespace(String topLevelNamespace) { + public VertexLabel withExtraNamespace(String topLevelNamespace) { List<String> newNamespace = ImmutableList.<String>builder().addAll(namespace).add(topLevelNamespace).build(); return new VertexLabel(this.name, newNamespace); } - public VertexLabel removeOuterNamespace() throws VertexLabelException { + public VertexLabel withoutOuterNamespace() throws VertexLabelException { try { List<String> reducedNamespace = namespace.subList(0, namespace.size() - 1); return new VertexLabel(this.name, reducedNamespace); diff --git a/keanu-project/src/test/java/io/improbable/keanu/vertices/VertexLabelTest.java b/keanu-project/src/test/java/io/improbable/keanu/vertices/VertexLabelTest.java index <HASH>..<HASH> 100644 --- a/keanu-project/src/test/java/io/improbable/keanu/vertices/VertexLabelTest.java +++ b/keanu-project/src/test/java/io/improbable/keanu/vertices/VertexLabelTest.java @@ -67,7 +67,7 @@ public class VertexLabelTest { String namespace = "namespace"; String name = "foo"; VertexLabel foo = new VertexLabel(name); - VertexLabel newFoo = foo.inNamespace(namespace); + VertexLabel newFoo = foo.withExtraNamespace(namespace); assertThat(newFoo, equalTo(new VertexLabel(name, namespace))); } @@ -77,7 +77,7 @@ public class VertexLabelTest { String outerNamespace = "outer"; String name = "foo"; VertexLabel foo = new VertexLabel(name, innerNamespace); - VertexLabel newFoo = foo.inNamespace(outerNamespace); + VertexLabel newFoo = foo.withExtraNamespace(outerNamespace); assertThat(newFoo, equalTo(new VertexLabel(name, innerNamespace, outerNamespace))); } @@ -93,13 +93,13 @@ public class VertexLabelTest { String outerNamespace = "outer"; String name = "foo"; VertexLabel foo = new VertexLabel(name, innerNamespace, outerNamespace); - VertexLabel newFoo = foo.removeOuterNamespace(); + VertexLabel newFoo = foo.withoutOuterNamespace(); assertThat(newFoo, equalTo(new VertexLabel(name, innerNamespace))); } @Test(expected = VertexLabelException.class) public void itThrowsIfYouDiminishTheNamespaceButThereIsNone() throws VertexLabelException { VertexLabel foo = new VertexLabel("foo"); - foo.removeOuterNamespace(); + foo.withoutOuterNamespace(); } }
renamed methods that add/remove a namespace
improbable-research_keanu
train
bbc35fcc6adee351f33b3ce2e740f859e512104b
diff --git a/src/core/class-container.php b/src/core/class-container.php index <HASH>..<HASH> 100644 --- a/src/core/class-container.php +++ b/src/core/class-container.php @@ -18,7 +18,6 @@ namespace Hybrid\Core; use ArrayAccess; -use SplObjectStorage; use Psr\Container\ContainerInterface; /** @@ -48,15 +47,6 @@ class Container implements ContainerInterface, ArrayAccess { protected $instances = []; /** - * Set to an instance of `SplObjectStorage`. - * - * @since 5.0.0 - * @access protected - * @var object - */ - protected $factories; - - /** * Set up a new container. * * @since 5.0.0 @@ -66,8 +56,6 @@ class Container implements ContainerInterface, ArrayAccess { */ public function __construct( array $definitions = [] ) { - $this->factories = new SplObjectStorage(); - foreach ( $definitions as $abstract => $concrete ) { $this->add( $abstract, $concrete ); @@ -152,12 +140,6 @@ class Container implements ContainerInterface, ArrayAccess { return $this->instances[ $abstract ]; } - // If this is a factory, call it. - if ( isset( $this->factories[ $definition ] ) ) { - - return $definition( $this, $parameters ); - } - // Return the instance. return $definition( $this, $parameters ); } @@ -219,21 +201,6 @@ class Container implements ContainerInterface, ArrayAccess { } /** - * Adds a factory and returns the callable object. - * - * @since 5.0.0 - * @access public - * @param callable $callable - * @return callable - */ - public function factory( $callable ) { - - $this->factories->attach( $callabale ); - - return $callable; - } - - /** * Sets a property via `ArrayAccess`. * * @since 5.0.0
Remove factory-specific stuff from the container. It can already be used as a factory given other methods.
justintadlock_hybrid-core
train
4765b89927b56b4ae8758b18d8cdd822d9007dae
diff --git a/ez_setup.py b/ez_setup.py index <HASH>..<HASH> 100644 --- a/ez_setup.py +++ b/ez_setup.py @@ -30,7 +30,7 @@ try: except ImportError: USER_SITE = None -DEFAULT_VERSION = "18.8.2" +DEFAULT_VERSION = "19.0" DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" DEFAULT_SAVE_DIR = os.curdir diff --git a/setuptools/version.py b/setuptools/version.py index <HASH>..<HASH> 100644 --- a/setuptools/version.py +++ b/setuptools/version.py @@ -1 +1 @@ -__version__ = '18.8.2' +__version__ = '19.0'
Bumped to <I> in preparation for next release.
pypa_setuptools
train
7f2c6a87fe8e9ef3569bc52e0f71d4905acb7d0e
diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb index <HASH>..<HASH> 100644 --- a/actionview/test/abstract_unit.rb +++ b/actionview/test/abstract_unit.rb @@ -179,7 +179,11 @@ module ActionDispatch end class ActiveSupport::TestCase - parallelize + if Process.respond_to?(:fork) && !Gem.win_platform? + parallelize + else + parallelize(with: :threads) + end include ActiveSupport::Testing::MethodCallAssertions diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb index <HASH>..<HASH> 100644 --- a/activesupport/test/abstract_unit.rb +++ b/activesupport/test/abstract_unit.rb @@ -28,7 +28,11 @@ ActiveSupport.to_time_preserves_timezone = ENV["PRESERVE_TIMEZONES"] == "1" I18n.enforce_available_locales = false class ActiveSupport::TestCase - parallelize + if Process.respond_to?(:fork) && !Gem.win_platform? + parallelize + else + parallelize(with: :threads) + end include ActiveSupport::Testing::MethodCallAssertions
Update test helper to call parallelize according to fork support
rails_rails
train
6c6ab7b0ce6e24ff48a4cd46c66044aec47ed4eb
diff --git a/security/ChangePasswordForm.php b/security/ChangePasswordForm.php index <HASH>..<HASH> 100644 --- a/security/ChangePasswordForm.php +++ b/security/ChangePasswordForm.php @@ -81,7 +81,7 @@ class ChangePasswordForm extends Form { // The user is not logged in and no valid auto login hash is available if(!$member) { Session::clear('AutoLoginHash'); - $this->controller->redirect('loginpage'); + $this->controller->redirect($this->controller->Link('login')); return; } }
Bad redirect in ChangePasswordForm->doChangePassword()
silverstripe_silverstripe-framework
train
b5d2da5cf34c758650a1bd178fe7ce8d605d394e
diff --git a/dimsum.js b/dimsum.js index <HASH>..<HASH> 100644 --- a/dimsum.js +++ b/dimsum.js @@ -23,7 +23,7 @@ defaults = { config = {}, -punct = [',','.',';',':','?','!'], +punct = [',','.',';',':','?','!','"','—','\r','\n'], punct_reg = new RegExp('[' + punct.join('') + ']*','g'), @@ -211,7 +211,14 @@ dimsum.initialize(); function normify(strings) { return strings.join(' ') .toLowerCase() - .replace(punct_reg, ''); + .replace(punct_reg, function(match) { + if (match.match(/\r|\n/)) { + return ' '; + } + else { + return ''; + } + }); }; function dedupe(array) {
Adding quotes, mdash and new lines to punctuation filter
ninjascribble_dimsum
train
9edb8afed024234667f4cb09f5d5eefedb742029
diff --git a/pom.xml b/pom.xml index <HASH>..<HASH> 100644 --- a/pom.xml +++ b/pom.xml @@ -51,8 +51,8 @@ <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> - <source>1.5</source> - <target>1.5</target> + <source>1.3</source> + <target>1.3</target> </configuration> </plugin> <plugin> diff --git a/src/com/joml/matrix/Matrix3d.java b/src/com/joml/matrix/Matrix3d.java index <HASH>..<HASH> 100644 --- a/src/com/joml/matrix/Matrix3d.java +++ b/src/com/joml/matrix/Matrix3d.java @@ -471,7 +471,6 @@ public class Matrix3d { dest.put(source.m22 * scalar); } - @Override public String toString() { return "Matrix3d { " + this.m00 + ", " + this.m10 + ", " + this.m20 + ",\n" + " " + this.m01 + ", " + this.m11 + ", " + this.m21 + ",\n" diff --git a/src/com/joml/rot/Quaternion.java b/src/com/joml/rot/Quaternion.java index <HASH>..<HASH> 100644 --- a/src/com/joml/rot/Quaternion.java +++ b/src/com/joml/rot/Quaternion.java @@ -21,7 +21,6 @@ package com.joml.rot; import com.joml.matrix.Matrix4f; import com.joml.utils.TrigMath; import com.joml.vector.Vector3f; -import static java.lang.Math.PI; import java.nio.FloatBuffer; /** @@ -133,7 +132,7 @@ public class Quaternion { */ public final float getAngle() { final float angle = 2.0f * (float) Math.acos(w); - return (angle <= PI) ? angle : 2.0f * (float) PI - angle; + return (angle <= Math.PI) ? angle : 2.0f * (float) Math.PI - angle; } /** @@ -141,7 +140,7 @@ public class Quaternion { */ public final static float getAngle(Quaternion q) { final float angle = 2.0f * (float) Math.acos(q.w); - return (angle <= PI) ? angle : 2.0f * (float) PI - angle; + return (angle <= Math.PI) ? angle : 2.0f * (float) Math.PI - angle; } /** diff --git a/src/com/joml/utils/CamMath.java b/src/com/joml/utils/CamMath.java index <HASH>..<HASH> 100644 --- a/src/com/joml/utils/CamMath.java +++ b/src/com/joml/utils/CamMath.java @@ -19,8 +19,6 @@ package com.joml.utils; import com.joml.matrix.Matrix4f; -import static com.joml.utils.TrigMath.coTangent; -import static com.joml.utils.TrigMath.degreesToRadians; import com.joml.vector.Vector3f; import java.nio.FloatBuffer; @@ -43,7 +41,7 @@ public class CamMath { * @param dest Matrix4f to store the result */ public final static void perspective(final float fovy, final float aspect, final float zNear, final float zFar, Matrix4f dest) { - float y_scale = coTangent(degreesToRadians(fovy / 2.0f)); + float y_scale = TrigMath.coTangent(TrigMath.degreesToRadians(fovy / 2.0f)); float x_scale = y_scale / aspect; float frustrum_length = zFar - zNear; @@ -65,7 +63,7 @@ public class CamMath { * @param dest FloatBuffer to store the result */ public final static void perspective(final float fovy, final float aspect, final float zNear, final float zFar, FloatBuffer dest) { - float y_scale = coTangent(degreesToRadians(fovy / 2.0f)); + float y_scale = TrigMath.coTangent(TrigMath.degreesToRadians(fovy / 2.0f)); float x_scale = y_scale / aspect; float frustrum_length = zFar - zNear; diff --git a/src/com/joml/utils/TrigMath.java b/src/com/joml/utils/TrigMath.java index <HASH>..<HASH> 100644 --- a/src/com/joml/utils/TrigMath.java +++ b/src/com/joml/utils/TrigMath.java @@ -18,8 +18,6 @@ */ package com.joml.utils; -import static java.lang.Math.PI; - /** * TrigMath * @@ -29,8 +27,8 @@ import static java.lang.Math.PI; */ public class TrigMath { - public static final float degreesToRadians = (float) (PI / 180d); - static public final float radiansToDegrees = (float) (180d / PI); + public static final float degreesToRadians = (float) (Math.PI / 180d); + static public final float radiansToDegrees = (float) (180d / Math.PI); /** Return the coTangent of the supplied angle */ public final static float coTangent(float angle) {
Make JOML compatible with Java <I> The lower the requirements, the better. And there definitely are programs out there, that use Java <I> still... Even though those are not games nor are they being used with a Desktop JRE, but rather with an embedded JRE on an embedded system.
JOML-CI_JOML
train
df55ab92df51570e87b1dfb491673937ce290d26
diff --git a/test/cast/cast_receiver_integration.js b/test/cast/cast_receiver_integration.js index <HASH>..<HASH> 100644 --- a/test/cast/cast_receiver_integration.js +++ b/test/cast/cast_receiver_integration.js @@ -198,8 +198,10 @@ describe('CastReceiver', function() { eventManager.listenOnce(video, 'loadeddata', function() { // Wait for an update message. waitForUpdateMessage().then(function(message) { - // Check that the update message is of a reasonable size. - expect(message.length).toBeLessThan(5000); + // Check that the update message is of a reasonable size. From previous + // testing we found that the socket would silently reject data that got + // too big. 5KB is safely below the limit. + expect(message.length).toBeLessThan(5 * 1024); }).then(done); }); addOnError(done);
Add Context To The 5KB Chrome Cast Limit Added some history over the 5KB limit in the chromecast tests so that we don't risk losing the original reason for the limit. Change-Id: I7a9feacec<I>ae<I>afbcf<I>c<I>a<I>
google_shaka-player
train
7835cd8209a9fc49ad4ebb731a4f1143c3420e8a
diff --git a/src/main/java/com/jayway/maven/plugins/android/standalonemojos/RunMojo.java b/src/main/java/com/jayway/maven/plugins/android/standalonemojos/RunMojo.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/jayway/maven/plugins/android/standalonemojos/RunMojo.java +++ b/src/main/java/com/jayway/maven/plugins/android/standalonemojos/RunMojo.java @@ -16,8 +16,8 @@ package com.jayway.maven.plugins.android.standalonemojos; import com.android.ddmlib.AdbCommandRejectedException; +import com.android.ddmlib.CollectingOutputReceiver; import com.android.ddmlib.IDevice; -import com.android.ddmlib.NullOutputReceiver; import com.android.ddmlib.ShellCommandUnresponsiveException; import com.android.ddmlib.TimeoutException; import com.jayway.maven.plugins.android.AbstractAndroidMojo; @@ -283,7 +283,13 @@ public class RunMojo extends AbstractAndroidMojo { getLog().info( "Attempting to start " + info.packageName + "/" + info.activity + " on device " + device.getSerialNumber() + " (avdName = " + device.getAvdName() + ")" ); - device.executeShellCommand( command, new NullOutputReceiver() ); + + CollectingOutputReceiver shellOutput = new CollectingOutputReceiver(); + device.executeShellCommand( command, shellOutput ); + if ( shellOutput.getOutput().contains( "Error" ) ) + { + throw new MojoFailureException( shellOutput.getOutput() ); + } } catch ( IOException ex ) {
Throwing exception when 'am start' fails on RunMojo#launch. ie: Activity doesn't exist
simpligility_android-maven-plugin
train
81f0b968bdea334b92bc19256858397165bace59
diff --git a/src/article/shared/AbstractComponent.js b/src/article/shared/AbstractComponent.js index <HASH>..<HASH> 100644 --- a/src/article/shared/AbstractComponent.js +++ b/src/article/shared/AbstractComponent.js @@ -4,18 +4,16 @@ export default class AbstractComponent extends Component { render ($$) { const model = this.props.model const ModelComponent = this.getComponent(model.type) + const SectionLabel = this.getComponent('section-label') let el = $$('div') .addClass('sc-abstract') .attr('data-id', model.id) el.append( - // TODO use label provider - $$('h1').addClass('sc-heading').append('Abstract') - ) - el.append( + $$(SectionLabel, {label: 'abstract-label'}), $$(ModelComponent, { model: model, - placeholder: 'Enter Abstract', + placeholder: this.getLabel('abstract-placeholder'), name: 'abstractEditor' }) )
Add a section label for anstract.
substance_texture
train
1631fa13559c2e187004549cf35a5a939a2f3adc
diff --git a/lib/active_force/sobject.rb b/lib/active_force/sobject.rb index <HASH>..<HASH> 100644 --- a/lib/active_force/sobject.rb +++ b/lib/active_force/sobject.rb @@ -1,7 +1,7 @@ require 'active_model' require 'active_attr' require 'active_attr/dirty' -require 'query' +require './query' module ActiveForce class SObject
Inclue Query class on ActiveForce
ionia-corporation_active_force
train
88664b59ab17e58f993c165a268666c2f4d23408
diff --git a/quantum-core/lib/api.js b/quantum-core/lib/api.js index <HASH>..<HASH> 100644 --- a/quantum-core/lib/api.js +++ b/quantum-core/lib/api.js @@ -71,6 +71,7 @@ function buildPage (sourceFile, pipeline, config, logger, addLiveReload) { const start = Date.now() return Promise.resolve(pipeline(sourceFile)) .then(files => Array.isArray(files) ? files : [files]) + .then(files => Array.from(new Map(files.map(f => [f.info.dest, f])).values())) .map(file => { const shouldInjectLiveReloadScript = addLiveReload && file.info.dest.indexOf('.html') === file.info.dest.length - 5
fix(core): Reduce the number of times we attempt to write files We were writing all of the api/changelog/docs css/js for every version meaning we were writing the same 8 files <I> times - This could be reduced further by adding files to a central list instead of keeping them per-page but this should reduce the IO overhead
ocadotechnology_quantumjs
train
d857bf0bb3cdabfbd9f568f8e009355703bb5e05
diff --git a/src/Data/ManagedRepositoryEvent.php b/src/Data/ManagedRepositoryEvent.php index <HASH>..<HASH> 100644 --- a/src/Data/ManagedRepositoryEvent.php +++ b/src/Data/ManagedRepositoryEvent.php @@ -18,8 +18,4 @@ class ManagedRepositoryEvent extends Event { return $this->repository; } - public function setRepository(ManagedRepositoryInterface $repository) { - $this->repository = $repository; - } - } \ No newline at end of file
No longer any need for setRepository method
mikegibson_sentient
train
0b0cd1f3b6301df920acd48afa2b9fae84ac1bb5
diff --git a/src/Console/ProcessManager.php b/src/Console/ProcessManager.php index <HASH>..<HASH> 100644 --- a/src/Console/ProcessManager.php +++ b/src/Console/ProcessManager.php @@ -125,7 +125,7 @@ class ProcessManager $output = $log instanceof ConsoleOutputInterface && $type === Process::ERR ? $log->getErrorOutput() : $log; - $output->writeln($buffer); + $output->write($buffer); }); } catch (\Exception $e) { unset($this->processes[$pidFile]);
Remove blank lines from log in server:start
platformsh_platformsh-cli
train
8e97768d5deea2b2f9766cba77044274cef6f8b1
diff --git a/src/livestreamer/plugins/filmon_us.py b/src/livestreamer/plugins/filmon_us.py index <HASH>..<HASH> 100644 --- a/src/livestreamer/plugins/filmon_us.py +++ b/src/livestreamer/plugins/filmon_us.py @@ -5,10 +5,12 @@ from livestreamer.compat import urlparse from livestreamer.exceptions import PluginError, NoStreamsError from livestreamer.plugin import Plugin from livestreamer.stream import RTMPStream -from livestreamer.utils import urlget +from livestreamer.utils import urlget, urlresolve, prepend_www RTMP_URL = "rtmp://204.107.26.73/battlecam" +RTMP_UPLOAD_URL = "rtmp://204.107.26.75/streamer" SWF_URL = "http://www.filmon.us/application/themes/base/flash/broadcast/VideoChatECCDN_debug_withoutCenteredOwner.swf" +SWF_UPLOAD_URL = "http://www.battlecam.com/application/themes/base/flash/MediaPlayer.swf" class Filmon_us(Plugin): @@ -20,10 +22,44 @@ class Filmon_us(Plugin): if not RTMPStream.is_usable(self.session): raise PluginError("rtmpdump is not usable and required by Filmon_us plugin") - self.logger.debug("Fetching room_id") - self.rsession = requests.session() - res = urlget(self.url, session=self.rsession) + streams = {} + + try: + # uploaded video + if "filmon.us/video" in self.url: + streams['default'] = self._get_stream_upload() + # live video + else: + streams['default'] = self._get_stream_live() + except NoStreamsError: + pass + + return streams + + def _get_stream_upload(self): + video = urlparse(self.url).path + + if urlresolve(prepend_www(self.url)) == 'http://www.filmon.us/channels': + raise PluginError(video + " don't exist") + + playpath = "mp4:resources" + video + '/v_3.mp4' + + rtmp = RTMP_UPLOAD_URL + parsed = urlparse(rtmp) + app = parsed.path[1:] + + return RTMPStream(self.session, { + "rtmp": rtmp, + "pageUrl": self.url, + "swfUrl": SWF_UPLOAD_URL, + "playpath": playpath, + "app": app, + "live": True + }) + def _get_stream_live(self): + self.logger.debug("Fetching room_id") + res = urlget(self.url) match = re.search("room/id/(\d+)", res.text) if not match: return @@ -39,31 +75,16 @@ class Filmon_us(Plugin): if (channel_name != base_name): return - streams = {} - try: - streams['default'] = self._get_stream(room_id) - except NoStreamsError: - pass - - return streams - - def _get_stream(self, room_id): playpath = "mp4:bc_" + room_id if not playpath: raise NoStreamsError(self.url) rtmp = RTMP_URL parsed = urlparse(rtmp) - if not parsed.scheme.startswith("rtmp"): - raise NoStreamsError(self.url) - - if parsed.query: - app = "{0}?{1}".format(parsed.path[1:], parsed.query) - else: - app = parsed.path[1:] + app = parsed.path[1:] return RTMPStream(self.session, { - "rtmp": rtmp, + "rtmp": RTMP_URL, "pageUrl": self.url, "swfUrl": SWF_URL, "playpath": playpath, diff --git a/src/livestreamer/utils.py b/src/livestreamer/utils.py index <HASH>..<HASH> 100644 --- a/src/livestreamer/utils.py +++ b/src/livestreamer/utils.py @@ -82,6 +82,15 @@ def absolute_url(baseurl, url): return url +# change google.com to www.google.com +def prepend_www(url): + parsed = urlparse(url) + if parsed.netloc.split(".")[0] != 'www': + return parsed.scheme + '://www.' + parsed.netloc + parsed.path + else: + return url + + def parse_json(data, jsontype="JSON", exception=PluginError): try: jsondata = json.loads(data)
FilmOn Social TV: Adding support for uploaded videos
streamlink_streamlink
train
26b853aa9bad14f947c1235d42b09f34c17f374d
diff --git a/src/main/java/biweekly/ICalendar.java b/src/main/java/biweekly/ICalendar.java index <HASH>..<HASH> 100644 --- a/src/main/java/biweekly/ICalendar.java +++ b/src/main/java/biweekly/ICalendar.java @@ -227,7 +227,7 @@ public class ICalendar extends ICalComponent { * Adds a to-do. * @param todo the to-do */ - public void addVTodo(VTodo todo) { + public void addTodo(VTodo todo) { addComponent(todo); }
Renamed "ICalendar.addVTodo()" to "ICalendar.addTodo()".
mangstadt_biweekly
train
67516980580f69b413c7dd60a5375e0ed5d8f3dd
diff --git a/question/type/numerical/db/upgrade.php b/question/type/numerical/db/upgrade.php index <HASH>..<HASH> 100644 --- a/question/type/numerical/db/upgrade.php +++ b/question/type/numerical/db/upgrade.php @@ -19,16 +19,11 @@ function xmldb_qtype_numerical_upgrade($oldversion=0) { - global $CFG, $THEME, $db; + global $CFG, $THEME, $DB; $result = true; - // In numerical questions, we are changing the 'match anything' answer - // from the empty string to *, to be like short answer questions. - if ($result && $oldversion < 2006121500) { - $result = set_field_select('question_answers', 'answer', '*', - sql_compare_text('answer') . " = '" . sql_empty() . "' AND question IN (SELECT id FROM {$CFG->prefix}question WHERE qtype = '" . NUMERICAL . "')"); - } +//===== 1.9.0 upgrade line ======// return $result; }
MDL-<I> removed pre <I> upgrade code
moodle_moodle
train
fa87c0896dc69563891e7b71750f9eac62aa51a8
diff --git a/src/Component/Money/PriceAggregate.php b/src/Component/Money/PriceAggregate.php index <HASH>..<HASH> 100644 --- a/src/Component/Money/PriceAggregate.php +++ b/src/Component/Money/PriceAggregate.php @@ -28,6 +28,11 @@ class PriceAggregate extends PriceBase const SUBTRACT = '-'; /** + * @var bool Keep empty tax rates (or not) + */ + protected $keepEmptyTaxRates = false; + + /** * @var array List of prices per tax rate */ protected $perTaxRate = []; @@ -147,7 +152,11 @@ class PriceAggregate extends PriceBase $this->perTaxRate[$percent]['net'] += $price->get('net'); // Remove tax block if price is now 0.00 - if (!Price::round($this->perTaxRate[$percent]['gross']) && !Price::round($this->perTaxRate[$percent]['net'])) { + if ( + !$this->getKeepEmptyTaxRates() + && !Price::round($this->perTaxRate[$percent]['gross']) + && !Price::round($this->perTaxRate[$percent]['net']) + ) { unset($this->perTaxRate[$percent]); } @@ -258,6 +267,7 @@ class PriceAggregate extends PriceBase return $this; } + // Note: do not round here! foreach (array_keys($this->perTaxRate) as $percent) { foreach (['gross', 'net'] as $property) { $this->perTaxRate[$percent][$property] *= $factor; @@ -283,6 +293,10 @@ class PriceAggregate extends PriceBase $result = null; switch ($property) { + case 'keepEmptyTaxRates': + $result = $this->keepEmptyTaxRates; + break; + case 'perTaxRate': $result = $this->getPerTaxRate(); break; @@ -303,6 +317,14 @@ class PriceAggregate extends PriceBase } /** + * @return bool + */ + public function getKeepEmptyTaxRates() + { + return $this->get('keepEmptyTaxRates'); + } + + /** * @return Price[] */ public function getPerTaxRate() @@ -345,6 +367,20 @@ class PriceAggregate extends PriceBase } /** + * @return $this + */ + public function round() + { + foreach (array_keys($this->perTaxRate) as $percent) { + foreach (['gross', 'net'] as $property) { + $this->perTaxRate[$percent][$property] = Price::round($this->perTaxRate[$percent][$property]); + } + } + + return $this; + } + + /** * @param string $property * @param float $value * @@ -354,7 +390,12 @@ class PriceAggregate extends PriceBase { $this->validateProperty($property); - $old = $this->get($property); + // Note: do not round here! + $old = 0; + foreach (array_keys($this->perTaxRate) as $percent) { + $old += $this->perTaxRate[$percent][$property]; + } + if ($old) { $this->changeToFactor($value / $old); } @@ -373,6 +414,18 @@ class PriceAggregate extends PriceBase } /** + * @param bool $round + * + * @return $this + */ + public function setKeepEmptyTaxRates($keepEmptyTaxRates) + { + $this->keepEmptyTaxRates = (bool) $keepEmptyTaxRates; + + return $this; + } + + /** * @param float $value * * @return $this
Added PriceAggregate::round() & bugfixes
ansas_php-component
train
a4b7aada0ea5330650a91ae5155e22805fd6e827
diff --git a/examples/nats-bench.go b/examples/nats-bench.go index <HASH>..<HASH> 100644 --- a/examples/nats-bench.go +++ b/examples/nats-bench.go @@ -47,7 +47,7 @@ func main() { usage() } - if *numMsgs < 1 { + if *numMsgs <= 0 { log.Fatal("Number of messages should be greater than zero.") }
Adressing Derek's comment.
nats-io_go-nats
train
4f23d537e58772995593e725cf4be7b789b14be5
diff --git a/fluid-api/src/main/java/com/fluidbpm/program/api/util/cache/CacheUtil.java b/fluid-api/src/main/java/com/fluidbpm/program/api/util/cache/CacheUtil.java index <HASH>..<HASH> 100644 --- a/fluid-api/src/main/java/com/fluidbpm/program/api/util/cache/CacheUtil.java +++ b/fluid-api/src/main/java/com/fluidbpm/program/api/util/cache/CacheUtil.java @@ -375,7 +375,6 @@ public class CacheUtil extends ABaseUtil { response = this.jedis.echo(uuid); returnVal.add(this.jedis.clientGetname()); returnVal.add(this.jedis.ping()); - returnVal.add(this.jedis.clusterFailover()); } returnVal.add(String.format("Echo-Request-[%s]", uuid));
Complete CacheUtil for Redis support.
Koekiebox-PTY-LTD_Fluid
train
6b8674c379b318a98499bea6a37c189382797c99
diff --git a/app/controllers/humpyard/elements_controller.rb b/app/controllers/humpyard/elements_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/humpyard/elements_controller.rb +++ b/app/controllers/humpyard/elements_controller.rb @@ -42,7 +42,7 @@ module Humpyard else render :json => { :status => :failed, - :errors => @element.errors + :errors => @element.content_data.errors } end else
send content data errors, to have something for text elements, not sure if this will hold
humpyard_humpyard
train
91b2d6f39edb22787c2b763e28c6545ed951425a
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java @@ -646,7 +646,8 @@ public class CheckpointCoordinator { } int numUnsuccessful = numUnsuccessfulCheckpointsTriggers.incrementAndGet(); - LOG.warn("Failed to trigger checkpoint (" + numUnsuccessful + " consecutive failed attempts so far)", t); + LOG.warn("Failed to trigger checkpoint {}. ({} consecutive failed attempts so far)", + checkpointID, numUnsuccessful, t); if (!checkpoint.isDiscarded()) { checkpoint.abortError(new Exception("Failed to trigger checkpoint", t));
[hotfix] [runtime] Minor improvement to logging in CheckpointCoordinator
apache_flink
train
aba6db75343c9f9b657ffed2f2547887fc04ac68
diff --git a/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java b/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java index <HASH>..<HASH> 100644 --- a/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java +++ b/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java @@ -132,18 +132,18 @@ public final class TelegramBot { return ChannelChatImpl.createChannelChat(chatID); } else { - int intChatID; + long longChatID; try { - intChatID = Integer.parseInt(chatID); + longChatID = Long.parseLong(chatID); } catch (NumberFormatException e) { System.err.println("TelegramBot#getChat(String chatID) was called with invalid ChatID."); return null; } - return getChat(intChatID); + return getChat(longChatID); } }
Fixed issue with TelegramBot.getChat(String chatID) not accepting supergroup IDs as they are to large for integer conversion
zackpollard_JavaTelegramBot-API
train
8e0baa2360a998f76a8e70dbee7bbf7339caf501
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index <HASH>..<HASH> 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -62,7 +62,7 @@ class NumericIndex(Index): None Methods - ---------- + ------- None See Also diff --git a/pandas/io/orc.py b/pandas/io/orc.py index <HASH>..<HASH> 100644 --- a/pandas/io/orc.py +++ b/pandas/io/orc.py @@ -41,7 +41,7 @@ def read_orc( DataFrame Notes - ------- + ----- Before using this function you should read the :ref:`user guide about ORC <io.orc>` and :ref:`install optional dependencies <install.warn_orc>`. """
DOC: Fix warnings on underline length (#<I>)
pandas-dev_pandas
train
921c10c48d78e969561f2420af0a2df59ec8f396
diff --git a/aegean.py b/aegean.py index <HASH>..<HASH> 100755 --- a/aegean.py +++ b/aegean.py @@ -1481,9 +1481,9 @@ def find_sources_in_image(filename, hdu_index=0, outfile=None, rms=None, max_sum if len(island_group) > 0: fit_parallel(island_group) - for sources in queue: - if sources: # ignore empty lists - for src in sources: + for srcs in queue: + if srcs: # ignore empty lists + for src in srcs: # ignore sources that we have been told to ignore if (src.peak_flux > 0 and nopositive) or (src.peak_flux < 0 and nonegative): continue @@ -2019,7 +2019,7 @@ if __name__ == "__main__": except AttributeError, e: if 'poll' in e.message: log.warn("Your O/S doesn't support select.poll(): Reverting to cores=1") - cores = 1 + options.cores = 1 queue = None temp = None else:
bugfix: when an os doesn't support os.poll the cores are now correctly set to 1 bugfix: no more infinite loop when source finding.
PaulHancock_Aegean
train
4de877eba05fd67b18b6b7f9bc17c7911afc10fe
diff --git a/admin/tool/lp/classes/api.php b/admin/tool/lp/classes/api.php index <HASH>..<HASH> 100644 --- a/admin/tool/lp/classes/api.php +++ b/admin/tool/lp/classes/api.php @@ -1383,10 +1383,13 @@ class api { if (!$plan->can_manage()) { $context = context_user::instance($plan->get_userid()); throw new required_capability_exception($context, 'tool/lp:planmanage', 'nopermissions', ''); - } + + // Prevent a plan based on a template to be edited. + } else if ($plan->is_based_on_template()) { + throw new coding_exception('Cannot update a plan that is based on a template.'); // Prevent change of ownership as the capabilities are checked against that. - if (isset($record->userid) && $plan->get_userid() != $record->userid) { + } else if (isset($record->userid) && $plan->get_userid() != $record->userid) { throw new coding_exception('A plan cannot be transfered to another user'); } @@ -1397,6 +1400,10 @@ class api { if (!$plan->can_manage()) { $context = context_user::instance($plan->get_userid()); throw new required_capability_exception($context, 'tool/lp:planmanage', 'nopermissions', ''); + + // Prevent a plan to be updated to use a template. + } else if ($plan->is_based_on_template()) { + throw new coding_exception('Cannot update a plan to be based on a template.'); } // Are we trying to set the plan as complete? diff --git a/admin/tool/lp/tests/api_test.php b/admin/tool/lp/tests/api_test.php index <HASH>..<HASH> 100644 --- a/admin/tool/lp/tests/api_test.php +++ b/admin/tool/lp/tests/api_test.php @@ -420,7 +420,6 @@ class tool_lp_api_testcase extends advanced_testcase { $record->name = 'plan create own modified'; $plan = api::update_plan($record); $this->assertInstanceOf('\tool_lp\plan', $plan); - } public function test_create_plan_from_template() { @@ -449,6 +448,47 @@ class tool_lp_api_testcase extends advanced_testcase { $plan = api::create_plan($record); } + public function test_update_plan_based_on_template() { + $this->resetAfterTest(true); + $dg = $this->getDataGenerator(); + $lpg = $dg->get_plugin_generator('tool_lp'); + $u1 = $dg->create_user(); + $u2 = $dg->create_user(); + + $this->setAdminUser(); + $tpl1 = $lpg->create_template(); + $tpl2 = $lpg->create_template(); + $up1 = $lpg->create_plan(array('userid' => $u1->id, 'templateid' => $tpl1->get_id())); + $up2 = $lpg->create_plan(array('userid' => $u2->id, 'templateid' => null)); + + try { + // Trying to remove the template dependency. + $record = $up1->to_record(); + $record->templateid = null; + api::update_plan($record); + $this->fail('A plan cannot be unlinked using api::update_plan()'); + } catch (coding_exception $e) { + } + + try { + // Trying to switch to another template. + $record = $up1->to_record(); + $record->templateid = $tpl2->get_id(); + api::update_plan($record); + $this->fail('A plan cannot be moved to another template.'); + } catch (coding_exception $e) { + } + + try { + // Trying to switch to using a template. + $record = $up2->to_record(); + $record->templateid = $tpl1->get_id(); + api::update_plan($record); + $this->fail('A plan cannot be update to use a template.'); + } catch (coding_exception $e) { + } + } + /** * Test that the method to complete a plan. */
MDL-<I> tool_lp: Prevent updates on a plan based on a template
moodle_moodle
train
86abcf6ea8bd7bc60761d9c0da28e6feaf1f3cfc
diff --git a/src/Connection/Socket.php b/src/Connection/Socket.php index <HASH>..<HASH> 100644 --- a/src/Connection/Socket.php +++ b/src/Connection/Socket.php @@ -54,7 +54,7 @@ class Socket extends BaseConnection implements ConnectionInterface if (!$this->isConnected()) { return; } - stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR); + fclose($this->socket); $this->socket = null; }
Changing back from stream_socket_shutdown to fclose to fix UT in HHVM
mariano_disque-php
train
73e1beeaf3d47a38557303cdfbccea773f0f3994
diff --git a/libkbfs/block_types.go b/libkbfs/block_types.go index <HASH>..<HASH> 100644 --- a/libkbfs/block_types.go +++ b/libkbfs/block_types.go @@ -97,6 +97,7 @@ func (cb *CommonBlock) Set(other Block) { func (cb *CommonBlock) DeepCopy() CommonBlock { return CommonBlock{ IsInd: cb.IsInd, + // We don't need to copy UnknownFieldSetHandler because it's immutable. UnknownFieldSetHandler: cb.UnknownFieldSetHandler, cachedEncodedSize: cb.GetEncodedSize(), } @@ -128,15 +129,18 @@ func (db *DirBlock) NewEmpty() Block { return NewDirBlock() } +// ToCommonBlock implements the Block interface for DirBlock. +func (db *DirBlock) ToCommonBlock() *CommonBlock { + return &db.CommonBlock +} + // Set implements the Block interface for DirBlock func (db *DirBlock) Set(other Block) { otherDb := other.(*DirBlock) dbCopy := otherDb.DeepCopy() db.Children = dbCopy.Children db.IPtrs = dbCopy.IPtrs - db.CommonBlock.IsInd = dbCopy.IsInd - db.CommonBlock.UnknownFieldSetHandler = dbCopy.UnknownFieldSetHandler - db.CommonBlock.SetEncodedSize(dbCopy.GetEncodedSize()) + db.ToCommonBlock().Set(dbCopy.ToCommonBlock()) } // DeepCopy makes a complete copy of a DirBlock @@ -154,11 +158,6 @@ func (db *DirBlock) DeepCopy() *DirBlock { } } -// ToCommonBlock implements the Block interface for DirBlock. -func (db *DirBlock) ToCommonBlock() *CommonBlock { - return &db.CommonBlock -} - // FileBlock is the contents of a file type FileBlock struct { CommonBlock @@ -244,9 +243,7 @@ func (fb *FileBlock) Set(other Block) { fbCopy := otherFb.DeepCopy() fb.Contents = fbCopy.Contents fb.IPtrs = fbCopy.IPtrs - fb.CommonBlock.IsInd = fbCopy.IsInd - fb.CommonBlock.UnknownFieldSetHandler = fbCopy.UnknownFieldSetHandler - fb.CommonBlock.SetEncodedSize(fbCopy.GetEncodedSize()) + fb.ToCommonBlock().Set(fbCopy.ToCommonBlock()) } // DeepCopy makes a complete copy of a FileBlock diff --git a/libkbfs/file_data.go b/libkbfs/file_data.go index <HASH>..<HASH> 100644 --- a/libkbfs/file_data.go +++ b/libkbfs/file_data.go @@ -11,7 +11,6 @@ import ( "github.com/keybase/client/go/logger" "github.com/keybase/client/go/protocol/keybase1" "github.com/keybase/kbfs/kbfsblock" - "github.com/keybase/kbfs/kbfscodec" "github.com/keybase/kbfs/tlf" "golang.org/x/net/context" "golang.org/x/sync/errgroup" @@ -1733,8 +1732,7 @@ func (fd *fileData) findIPtrsAndClearSize( // and making new random BlockPointers for all indirect blocks. It // returns the new top pointer of the copy, and all the new child // pointers in the copy. -func (fd *fileData) deepCopy(ctx context.Context, codec kbfscodec.Codec, - dataVer DataVer) ( +func (fd *fileData) deepCopy(ctx context.Context, dataVer DataVer) ( newTopPtr BlockPointer, allChildPtrs []BlockPointer, err error) { topBlock, _, err := fd.getter(ctx, fd.kmd, fd.rootBlockPointer(), fd.file, blockRead) diff --git a/libkbfs/folder_block_ops.go b/libkbfs/folder_block_ops.go index <HASH>..<HASH> 100644 --- a/libkbfs/folder_block_ops.go +++ b/libkbfs/folder_block_ops.go @@ -642,7 +642,7 @@ func (fbo *folderBlockOps) DeepCopyFile( defer fbo.blockLock.RUnlock(lState) var uid keybase1.UID // Data reads don't depend on the uid. fd := fbo.newFileDataWithCache(lState, file, uid, kmd, dirtyBcache) - return fd.deepCopy(ctx, fbo.config.Codec(), dataVer) + return fd.deepCopy(ctx, dataVer) } func (fbo *folderBlockOps) UndupChildrenInCopy(ctx context.Context,
block_types: Implemented strib's PR feedback
keybase_client
train
6a642dc570dbb6a2010d19a7a4b5ca3c8c954e09
diff --git a/presto-main/src/main/java/com/facebook/presto/event/query/QueryCreatedEvent.java b/presto-main/src/main/java/com/facebook/presto/event/query/QueryCreatedEvent.java index <HASH>..<HASH> 100644 --- a/presto-main/src/main/java/com/facebook/presto/event/query/QueryCreatedEvent.java +++ b/presto-main/src/main/java/com/facebook/presto/event/query/QueryCreatedEvent.java @@ -1,6 +1,5 @@ package com.facebook.presto.event.query; -import com.facebook.presto.execution.QueryState; import io.airlift.event.client.EventField; import io.airlift.event.client.EventType; import org.joda.time.DateTime; @@ -13,20 +12,17 @@ import java.net.URI; public class QueryCreatedEvent { private final String queryId; - private final QueryState queryState; private final URI uri; private final String query; private final DateTime createTime; public QueryCreatedEvent( String queryId, - QueryState queryState, URI uri, String query, DateTime createTime) { this.queryId = queryId; - this.queryState = queryState; this.uri = uri; this.query = query; this.createTime = createTime; @@ -39,12 +35,6 @@ public class QueryCreatedEvent } @EventField - public String getQueryState() - { - return queryState.name(); - } - - @EventField public String getUri() { return uri.toString(); diff --git a/presto-main/src/main/java/com/facebook/presto/event/query/QueryMonitor.java b/presto-main/src/main/java/com/facebook/presto/event/query/QueryMonitor.java index <HASH>..<HASH> 100644 --- a/presto-main/src/main/java/com/facebook/presto/event/query/QueryMonitor.java +++ b/presto-main/src/main/java/com/facebook/presto/event/query/QueryMonitor.java @@ -30,7 +30,6 @@ public class QueryMonitor eventClient.post( new QueryCreatedEvent( queryInfo.getQueryId(), - queryInfo.getState(), queryInfo.getSelf(), queryInfo.getQuery(), queryInfo.getQueryStats().getCreateTime()
Remove state from QueryCreatedEvent
prestodb_presto
train
d58a1d383fa7c17c19b570817c6ca126dc42a11c
diff --git a/recipient/client_test.go b/recipient/client_test.go index <HASH>..<HASH> 100644 --- a/recipient/client_test.go +++ b/recipient/client_test.go @@ -234,7 +234,7 @@ func TestRecipientUpdate(t *testing.T) { Del(target.ID) } -func TestRecipientUpdateToken(t *testing.T) { +func TestRecipientUpdateBankAccount(t *testing.T) { tokenParams := &stripe.TokenParams{ Bank: &stripe.BankAccountParams{ Country: "US", @@ -254,13 +254,13 @@ func TestRecipientUpdateToken(t *testing.T) { original, _ := New(recipientParams) - updated := &stripe.RecipientParams{ + updateParamsToken := &stripe.RecipientParams{ Bank: &stripe.BankAccountParams{ Token: tok.ID, }, } - target, err := Update(original.ID, updated) + target, err := Update(original.ID, updateParamsToken) if err != nil { t.Error(err) @@ -286,7 +286,41 @@ func TestRecipientUpdateToken(t *testing.T) { t.Errorf("Bank name is not set\n") } - Del(target.ID) + updateParamsBankAccount := &stripe.RecipientParams{ + Bank: &stripe.BankAccountParams{ + Country: "US", + Routing: "110000000", + Account: "000333333335", + }, + } + + target2, err := Update(original.ID, updateParamsBankAccount) + + if err != nil { + t.Error(err) + } + + if target2.Bank == nil { + t.Errorf("Bank account is not set\n") + } + + if target2.Bank.Country != tokenParams.Bank.Country { + t.Errorf("Bank country %q does not match expected country %q\n", target2.Bank.Country, tokenParams.Bank.Country) + } + + if target2.Bank.Currency != currency.USD { + t.Errorf("Bank currency %q does not match expected value\n", target2.Bank.Currency) + } + + if target2.Bank.LastFour != "3335" { + t.Errorf("Bank last four %q does not match expected value\n", target2.Bank.LastFour) + } + + if len(target2.Bank.Name) == 0 { + t.Errorf("Bank name is not set\n") + } + + Del(target2.ID) } func TestRecipientDel(t *testing.T) {
Improved the test to update bank account with and without token
stripe_stripe-go
train
e383971e576e750f0b8096ccaf0c59003c467d5b
diff --git a/Lib/fontbakery/specifications/googlefonts.py b/Lib/fontbakery/specifications/googlefonts.py index <HASH>..<HASH> 100644 --- a/Lib/fontbakery/specifications/googlefonts.py +++ b/Lib/fontbakery/specifications/googlefonts.py @@ -1987,17 +1987,18 @@ def com_google_fonts_check_052(ttFont): # a specific table providing a detailed description of the rationale # behind it. - tables = set(ttFont.reader.tables.keys()) - if OPTIONAL_TABLES & tables: - optional_tables = [str(t) for t in (OPTIONAL_TABLES & tables)] + optional_tables = [opt for opt in OPTIONAL_TABLES if opt in ttFont.keys()] + if optional_tables: yield INFO, ("This font contains the following" " optional tables [{}]").format(", ".join(optional_tables)) - glyphs = set(["glyf"] if "glyf" in ttFont.keys() else ["CFF "]) - if (REQUIRED_TABLES | glyphs) - tables: - missing_tables = [str(t) for t in (REQUIRED_TABLES | glyphs - tables)] + missing_tables = [req for req in REQUIRED_TABLES if req not in ttFont.keys()] + if "glyf" not in ttFont.keys() and "CFF " not in ttFont.keys(): + missing_tables.append("CFF ' or 'glyf") + + if missing_tables: yield FAIL, ("This font is missing the following required tables:" - " [{}]").format(", ".join(missing_tables)) + " ['{}']").format("', '".join(missing_tables)) else: yield PASS, "Font contains all required tables."
reimplementation of check/<I> to address issue #<I>
googlefonts_fontbakery
train
6e0312db3d63b4575c1505acd4220182681f9423
diff --git a/code/libraries/koowa/dispatcher/abstract.php b/code/libraries/koowa/dispatcher/abstract.php index <HASH>..<HASH> 100644 --- a/code/libraries/koowa/dispatcher/abstract.php +++ b/code/libraries/koowa/dispatcher/abstract.php @@ -166,37 +166,6 @@ abstract class KDispatcherAbstract extends KControllerAbstract } /** - * Get the action that is was/will be performed. - * - * If the action cannot be found in the POST request it will determined based on the request - * method and mapped to one of the 5 BREAD actions. - * - * - GET : display (either 'browse' (for list views) or 'read' (for item views)). - * - POST : add - * - PUT : edit - * - DELETE : delete - * - * @return string Action name - */ - public function getAction() - { - $action = KRequest::get('post.action', 'cmd'); - - if(empty($action)) - { - switch(KRequest::method()) - { - case 'GET' : $action = 'display'; break; - case 'POST' : $action = 'edit' ; break; - case 'PUT' : $action = 'add' ; break; - case 'DELETE' : $action = 'delete' ; break; - } - } - - return $action; - } - - /** * Get the data from the reques based the request method * * @return array An array with the request data @@ -229,8 +198,11 @@ abstract class KDispatcherAbstract extends KControllerAbstract //Set the data from the data in the request $context->data = $this->getData(); + //Get the action + $action = KRequest::get('post.action', 'cmd', strtolower(KRequest::method())); + //Execute the controller - $result = $this->getController()->execute($this->getAction(), $context); + $result = $this->getController()->execute($action, $context); //Set the response header if($context->status) { @@ -288,8 +260,8 @@ abstract class KDispatcherAbstract extends KControllerAbstract */ protected function _actionRender(KCommandContext $context) { - if(is_string($context->result) && $context->status != KHttpResponse::NOT_FOUND) { - return $context->result; + if(is_string($context->result)) { + return $context->result; } } } \ No newline at end of file
Removed getAction function. Action mapping has been moved to KControllerView.
timble_kodekit
train
3d9eeaab4baa210d8007e793a6ba5b0dce038b46
diff --git a/Twilio/Rest/Api/V2010/Account/AvailablePhoneNumberCountryContext.php b/Twilio/Rest/Api/V2010/Account/AvailablePhoneNumberCountryContext.php index <HASH>..<HASH> 100644 --- a/Twilio/Rest/Api/V2010/Account/AvailablePhoneNumberCountryContext.php +++ b/Twilio/Rest/Api/V2010/Account/AvailablePhoneNumberCountryContext.php @@ -79,8 +79,8 @@ class AvailablePhoneNumberCountryContext extends InstanceContext { if (!$this->_local) { $this->_local = new LocalList( $this->version, - $this->solution['countryCode'], - $this->solution['accountSid'] + $this->solution['accountSid'], + $this->solution['countryCode'] ); } @@ -96,8 +96,8 @@ class AvailablePhoneNumberCountryContext extends InstanceContext { if (!$this->_tollFree) { $this->_tollFree = new TollFreeList( $this->version, - $this->solution['countryCode'], - $this->solution['accountSid'] + $this->solution['accountSid'], + $this->solution['countryCode'] ); } @@ -113,8 +113,8 @@ class AvailablePhoneNumberCountryContext extends InstanceContext { if (!$this->_mobile) { $this->_mobile = new MobileList( $this->version, - $this->solution['countryCode'], - $this->solution['accountSid'] + $this->solution['accountSid'], + $this->solution['countryCode'] ); } diff --git a/Twilio/Rest/Client.php b/Twilio/Rest/Client.php index <HASH>..<HASH> 100644 --- a/Twilio/Rest/Client.php +++ b/Twilio/Rest/Client.php @@ -104,8 +104,8 @@ class Client { * @return Response Response from the Twilio API */ public function request($method, $uri, $params = array(), $data = array(), $headers = array(), $username = null, $password = null, $timeout = null) { - $username = $username || $this->username; - $password = $password || $this->password; + $username = $username ? $username : $this->username; + $password = $password ? $password : $this->password; $headers['User-Agent'] = 'twilio-php/' . VersionInfo::string() . ' (PHP ' . phpversion() . ')'; diff --git a/Twilio/Tests/Holodeck.php b/Twilio/Tests/Holodeck.php index <HASH>..<HASH> 100644 --- a/Twilio/Tests/Holodeck.php +++ b/Twilio/Tests/Holodeck.php @@ -37,6 +37,8 @@ class Holodeck implements Client { return true; } } + var_dump($this->requests); + var_dump($request); return false; } diff --git a/Twilio/Values.php b/Twilio/Values.php index <HASH>..<HASH> 100644 --- a/Twilio/Values.php +++ b/Twilio/Values.php @@ -12,7 +12,7 @@ class Values implements \ArrayAccess { public static function of($array) { $result = array(); foreach ($array as $key => $value) { - if ($value == self::NONE) { + if ($value === self::NONE) { continue; } $result[$key] = $value;
Fix Values NONE assertion, fix context ordering
twilio_twilio-php
train
5e646ebb688bfd7f31399e7562503bfe4e61842c
diff --git a/ui/js/dfv/src/fields/code/index.js b/ui/js/dfv/src/fields/code/index.js index <HASH>..<HASH> 100644 --- a/ui/js/dfv/src/fields/code/index.js +++ b/ui/js/dfv/src/fields/code/index.js @@ -9,30 +9,41 @@ import 'codemirror/lib/codemirror.css'; import './code.scss'; const Code = ( { + fieldConfig, setValue, value, setHasBlurred, -} ) => ( - <div className="pods-code-field"> - <CodeMirror - value={ value } - options={ { - lineNumbers: true, - matchBrackets: true, - mode: 'php', - indentUnit: 4, - indentWithTabs: false, - lineWrapping: true, - enterMode: 'keep', - tabMode: 'shift', - } } - onBeforeChange={ ( editor, data, newValue ) => { - setValue( newValue ); - } } - onBlur={ () => setHasBlurred() } - /> - </div> -); +} ) => { + const { name } = fieldConfig; + + return ( + <div className="pods-code-field"> + <input + name={ name } + type="hidden" + value={ value } + /> + + <CodeMirror + value={ value } + options={ { + lineNumbers: true, + matchBrackets: true, + mode: 'php', + indentUnit: 4, + indentWithTabs: false, + lineWrapping: true, + enterMode: 'keep', + tabMode: 'shift', + } } + onBeforeChange={ ( editor, data, newValue ) => { + setValue( newValue ); + } } + onBlur={ () => setHasBlurred() } + /> + </div> + ); +}; Code.propTypes = { ...FIELD_COMPONENT_BASE_PROPS, diff --git a/ui/js/dfv/src/fields/color/index.js b/ui/js/dfv/src/fields/color/index.js index <HASH>..<HASH> 100644 --- a/ui/js/dfv/src/fields/color/index.js +++ b/ui/js/dfv/src/fields/color/index.js @@ -9,14 +9,23 @@ import { FIELD_COMPONENT_BASE_PROPS } from 'dfv/src/config/prop-types'; import './color.scss'; const Color = ( { + fieldConfig, setValue, value, setHasBlurred, } ) => { + const { name } = fieldConfig; + const [ isOpen, setIsOpen ] = useState( false ); return ( <div> + <input + name={ name } + type="hidden" + value={ value } + /> + <button onClick={ ( event ) => { event.preventDefault();
Fix for color and code fields not saving
pods-framework_pods
train
8dbb11422081b01be18f1a972a1e57c398a23a83
diff --git a/engines/bastion/app/assets/javascripts/bastion/products/details/product-repositories.controller.js b/engines/bastion/app/assets/javascripts/bastion/products/details/product-repositories.controller.js index <HASH>..<HASH> 100644 --- a/engines/bastion/app/assets/javascripts/bastion/products/details/product-repositories.controller.js +++ b/engines/bastion/app/assets/javascripts/bastion/products/details/product-repositories.controller.js @@ -32,7 +32,8 @@ angular.module('Bastion.products').controller('ProductRepositoriesController', 'product_id': $scope.$stateParams.productId, 'library': true, 'organization_id': CurrentOrganization, - 'enabled': true + 'enabled': true, + 'full_result': true }); $scope.successMessages = [];
Fixes #<I>/BZ<I>: get full result of product's repositories. We were only getting the (default) first <I> results for a product's repositories. This commit ensures we fetch all of a product's repositories for display. <URL>
Katello_katello
train
60c06fdf831b1f80413344d9fdcd017c64bdb4b3
diff --git a/spring-soy-view/src/main/java/pl/matisoft/soy/SoyTemplateViewResolver.java b/spring-soy-view/src/main/java/pl/matisoft/soy/SoyTemplateViewResolver.java index <HASH>..<HASH> 100644 --- a/spring-soy-view/src/main/java/pl/matisoft/soy/SoyTemplateViewResolver.java +++ b/spring-soy-view/src/main/java/pl/matisoft/soy/SoyTemplateViewResolver.java @@ -56,6 +56,8 @@ public class SoyTemplateViewResolver extends AbstractTemplateViewResolver { private boolean ignoreHtmlView = false; + private String indexView = "index"; + public SoyTemplateViewResolver() { super(); setExposeSpringMacroHelpers(false); @@ -83,8 +85,8 @@ public class SoyTemplateViewResolver extends AbstractTemplateViewResolver { Preconditions.checkNotNull(viewName, "viewName cannot be null!"); Preconditions.checkNotNull(templateRenderer, "templateRenderer cannot be null!"); - final SoyView view = (SoyView) super.buildView(viewName); - view.setTemplateName(viewName); + final SoyView view = (SoyView) super.buildView(orIndexView(normalize(viewName))); + view.setTemplateName(view.getUrl()); view.setContentType(contentType()); view.setTemplateRenderer(templateRenderer); view.setModelAdjuster(modelAdjuster); @@ -107,6 +109,35 @@ public class SoyTemplateViewResolver extends AbstractTemplateViewResolver { return view; } + /** + * Map / to a default view name. + * @param viewName The view name. + * @return The defaulted view name. + */ + private String orIndexView(String viewName) { + return viewName == "" ? indexView : viewName; + } + + /** + * Remove beginning and ending slashes, then replace all occurrences of / with . + * + * @param viewName The Spring viewName + * @return The name of the view, dot separated. + */ + private String normalize(final String viewName) { + String normalized = viewName; + + if (normalized.startsWith("/")) { + normalized = normalized.substring(0); + } + + if (normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + + return normalized.replaceAll("/", "."); + } + private String contentType() { return "text/html; charset=" + encoding; } @@ -168,4 +199,7 @@ public class SoyTemplateViewResolver extends AbstractTemplateViewResolver { this.soyMsgBundleResolver = soyMsgBundleResolver; } + public void setIndexView(String indexView) { + this.indexView = indexView; + } }
normalize slashes to dots, remove starting and ending slashes, and provide default view name.
matiwinnetou_spring-soy-view
train