hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
f42bcdbebe062dcdffea5eca826781f7affaa129
diff --git a/src/Omnipay/NetBanx/Message/AuthorizeRequest.php b/src/Omnipay/NetBanx/Message/AuthorizeRequest.php index <HASH>..<HASH> 100644 --- a/src/Omnipay/NetBanx/Message/AuthorizeRequest.php +++ b/src/Omnipay/NetBanx/Message/AuthorizeRequest.php @@ -35,7 +35,7 @@ class AuthorizeRequest extends AbstractRequest */ public function getData() { - if ($this->getTransactionReference()) { + if ($this->getTransactionReference() || $this->getCardReference()) { $this->txnMode = $this->getStoredDataMode(); $this->validate('amount'); } else { @@ -57,7 +57,7 @@ class AuthorizeRequest extends AbstractRequest */ protected function getXmlString() { - if ($this->getTransactionReference()) { + if ($this->getTransactionReference() || $this->getCardReference()) { $xmlRoot = 'ccStoredDataRequestV1'; } else { $xmlRoot = 'ccAuthRequestV1'; @@ -79,8 +79,8 @@ class AuthorizeRequest extends AbstractRequest $sxml->addChild('merchantRefNum', $this->getCustomerId() ?: 'ref-num - ' . time()); - if ($this->getTransactionReference()) { - $sxml->addChild('confirmationNumber', $this->getTransactionReference()); + if ($this->getTransactionReference() || $this->getCardReference()) { + $sxml->addChild('confirmationNumber', $this->getTransactionReference() ?: $this->getCardReference()); $sxml->addChild('amount', $this->getAmountDecimal()); } else { /** @var $card CreditCard */
check for cardReference as well as transactionReference
thephpleague_omnipay-netbanx
train
77f4cf163b21a3f0f615ee54c28ac3056a25119f
diff --git a/chisel/resource/pyodbc_connect.py b/chisel/resource/pyodbc_connect.py index <HASH>..<HASH> 100644 --- a/chisel/resource/pyodbc_connect.py +++ b/chisel/resource/pyodbc_connect.py @@ -15,7 +15,8 @@ class PyodbcConnectResourceType(ResourceType): def __init__(self, autocommit = True): self.autocommit = autocommit - ResourceType.__init__(self, "pyodbc_connect", self._open, self._close) + resourceTypeName = "pyodbc_connect" if autocommit else "pyodbc_connect_noautocommit" + ResourceType.__init__(self, resourceTypeName, self._open, self._close) def _open(self, resourceString): diff --git a/chisel/resource/pyodbc_connect_mock.py b/chisel/resource/pyodbc_connect_mock.py index <HASH>..<HASH> 100644 --- a/chisel/resource/pyodbc_connect_mock.py +++ b/chisel/resource/pyodbc_connect_mock.py @@ -10,10 +10,12 @@ from ..app import ResourceType # pyodbc.connect resource type mock class PyodbcConnectResourceTypeMock(ResourceType): - def __init__(self, executeCallback): + def __init__(self, executeCallback, autocommit = True): self._executeCallback = executeCallback - ResourceType.__init__(self, "pyodbc_connect", self._open, self._close) + self.autocommit = autocommit + resourceTypeName = "pyodbc_connect" if autocommit else "pyodbc_connect_noautocommit" + ResourceType.__init__(self, resourceTypeName, self._open, self._close) def _open(self, resourceString): diff --git a/chisel/tests/resource/test_pyodbc_connect.py b/chisel/tests/resource/test_pyodbc_connect.py index <HASH>..<HASH> 100644 --- a/chisel/tests/resource/test_pyodbc_connect.py +++ b/chisel/tests/resource/test_pyodbc_connect.py @@ -37,7 +37,7 @@ class TestResourcePyodbcConnect(unittest.TestCase): # Create the resource type (autocommit = False) resourceType = PyodbcConnectResourceType(autocommit = False) - self.assertEqual(resourceType.name, "pyodbc_connect") + self.assertEqual(resourceType.name, "pyodbc_connect_noautocommit") # Create a resource resource = resourceType.open("MyConnectionString2")
PyodbcConnectResourceType with autocommit = False acts like a different resource type so give it a different resource type name.
craigahobbs_chisel
train
69a3bd190173ee7ea85c1a1156292858500bf23f
diff --git a/eventsourcing/tests/test_readme.py b/eventsourcing/tests/test_readme.py index <HASH>..<HASH> 100644 --- a/eventsourcing/tests/test_readme.py +++ b/eventsourcing/tests/test_readme.py @@ -9,14 +9,17 @@ from unittest.case import TestCase, expectedFailure import eventsourcing +base_dir = dirname(dirname(eventsourcing.__file__)) + + class TestDocs(TestCase): def test_code_snippets_in_readme(self): - path = join(dirname(dirname(eventsourcing.__file__)), 'README.md') + path = join(base_dir, 'README.md') self.check_code_snippets_in_file(path) @expectedFailure def test_code_snippets_in_docs(self): - for path in glob(join(dirname(dirname(eventsourcing.__file__)), 'docs', '*', '*.rst')): + for path in glob(join(base_dir, 'docs', '*', '*.rst')): print("Testing code snippets in {}".format(path)) self.check_code_snippets_in_file(path) @@ -71,7 +74,7 @@ class TestDocs(TestCase): tempfile.flush() # Run the code and catch errors. - p = Popen([sys.executable, temp_path], stdout=PIPE, stderr=PIPE) + p = Popen([sys.executable, temp_path], stdout=PIPE, stderr=PIPE, env={'PYTHONPATH': base_dir}) out, err = p.communicate() out = out.decode('utf8').replace(temp_path, doc_path) err = err.decode('utf8').replace(temp_path, doc_path)
Attempt to fix test on Travis.
johnbywater_eventsourcing
train
d792c2916848d6604807f4a823292662e9c23e46
diff --git a/src/guake/guake_app.py b/src/guake/guake_app.py index <HASH>..<HASH> 100644 --- a/src/guake/guake_app.py +++ b/src/guake/guake_app.py @@ -167,10 +167,10 @@ class Guake(SimpleGladeApp): self.preventHide = False # trayicon! + img = pixmapfile('guake-tray.png') try: import appindicator except ImportError: - img = pixmapfile('guake-tray.png') self.tray_icon = gtk.status_icon_new_from_file(img) self.tray_icon.set_tooltip(_('Guake Terminal')) self.tray_icon.connect('popup-menu', self.show_menu) @@ -178,7 +178,7 @@ class Guake(SimpleGladeApp): else: self.tray_icon = appindicator.Indicator( _("guake-indicator"), _("guake-tray"), appindicator.CATEGORY_OTHER) - self.tray_icon.set_icon("guake-tray") + self.tray_icon.set_icon(img) self.tray_icon.set_status(appindicator.STATUS_ACTIVE) menu = self.get_widget('tray-menu') show = gtk.MenuItem(_('Show'))
use full path to tray icon with libappindicator
Guake_guake
train
a69fc6b1ea93fdb257401172002c457b35750c4b
diff --git a/honeybadger/tests/test_connection.py b/honeybadger/tests/test_connection.py index <HASH>..<HASH> 100644 --- a/honeybadger/tests/test_connection.py +++ b/honeybadger/tests/test_connection.py @@ -1,7 +1,8 @@ import json import logging from nose.tools import eq_ -from mock import patch + +from .utils import mock_urlopen from honeybadger.connection import send_notice from honeybadger.config import Configuration @@ -11,13 +12,14 @@ def test_connection_success(): payload = {'test': 'payload'} config = Configuration(api_key=api_key) - with patch('six.moves.urllib.request.urlopen') as request_mock: - send_notice(config, payload) - - assert request_mock.called == True - ((request_object,), mock_kwargs) = request_mock.call_args + def test_request(request_object): eq_(request_object.get_header('X-api-key'), api_key) eq_(request_object.get_full_url(), '{}/v1/notices/'.format(config.endpoint)) eq_(request_object.data, json.dumps(payload)) + with mock_urlopen(test_request) as request_mock: + send_notice(config, payload) + assert request_mock.called == True + + # TODO: figure out how to test logging output diff --git a/honeybadger/tests/test_core.py b/honeybadger/tests/test_core.py index <HASH>..<HASH> 100644 --- a/honeybadger/tests/test_core.py +++ b/honeybadger/tests/test_core.py @@ -3,8 +3,8 @@ import json from nose.tools import eq_ from nose.tools import raises +from .utils import mock_urlopen from honeybadger import Honeybadger -from .utils import setup_mock_urlopen def test_set_context(): honeybadger = Honeybadger() @@ -16,37 +16,42 @@ def test_set_context(): def test_notify_with_custom_params(): def test_payload(request): - payload = json.loads(request.get_data()) + payload = json.loads(request.data) eq_(payload['request']['context'], dict(foo='bar')) eq_(payload['error']['class'], 'Exception') eq_(payload['error']['message'], 'Test message.') hb = Honeybadger() - setup_mock_urlopen(test_payload) - hb.configure(api_key='aaa') - hb.notify(error_class='Exception', error_message='Test message.', context={'foo': 'bar'}) + with mock_urlopen(test_payload) as request_mock: + hb.configure(api_key='aaa') + hb.notify(error_class='Exception', error_message='Test message.', context={'foo': 'bar'}) + assert request_mock.called == True + + def test_notify_with_exception(): def test_payload(request): - payload = json.loads(request.get_data()) + payload = json.loads(request.data) eq_(payload['error']['class'], 'ValueError') eq_(payload['error']['message'], 'Test value error.') hb = Honeybadger() - setup_mock_urlopen(test_payload) - hb.configure(api_key='aaa') - hb.notify(ValueError('Test value error.')) + with mock_urlopen(test_payload) as request_mock: + hb.configure(api_key='aaa') + hb.notify(ValueError('Test value error.')) + assert request_mock.called == True def test_notify_context_merging(): def test_payload(request): - payload = json.loads(request.get_data()) + payload = json.loads(request.data) eq_(payload['request']['context'], dict(foo='bar', bar='foo')) hb = Honeybadger() - setup_mock_urlopen(test_payload) - hb.configure(api_key='aaa') - hb.set_context(foo='bar') - hb.notify(error_class='Exception', error_message='Test.', context=dict(bar='foo')) + with mock_urlopen(test_payload) as request_mock: + hb.configure(api_key='aaa') + hb.set_context(foo='bar') + hb.notify(error_class='Exception', error_message='Test.', context=dict(bar='foo')) + assert request_mock.called == True diff --git a/honeybadger/tests/utils.py b/honeybadger/tests/utils.py index <HASH>..<HASH> 100644 --- a/honeybadger/tests/utils.py +++ b/honeybadger/tests/utils.py @@ -1,21 +1,9 @@ -from mocker import Mocker -from mocker import ANY +from contextlib import contextmanager +from mock import patch -def setup_mock_urlopen(func, status=201): - def func_wrap(request): - func(request) - return get_mock_response(status) - - mocker = Mocker() - urlopen = mocker.replace('urllib2.urlopen') - urlopen(ANY) - mocker.call(func_wrap) - mocker.replay() - -def get_mock_response(status=201): - m = Mocker() - response = m.mock() - response.getcode() - m.result(status) - m.replay() - return response +@contextmanager +def mock_urlopen(func, status=201): + with patch('six.moves.urllib.request.urlopen') as request_mock: + yield request_mock + ((request_object,), mock_kwargs) = request_mock.call_args + func(request_object)
Refactor test utils to use mock library. Update connection and core test modules to use new mock_urlopen util.
honeybadger-io_honeybadger-python
train
e0f5688a549a67d269b4a1144909be53f5a66b2e
diff --git a/tools/run_tests/run_tests.py b/tools/run_tests/run_tests.py index <HASH>..<HASH> 100755 --- a/tools/run_tests/run_tests.py +++ b/tools/run_tests/run_tests.py @@ -645,18 +645,11 @@ class RubyLanguage(object): _check_compiler(self.args.compiler, ['default']) def test_specs(self): - #TODO(apolcyn) turn mac ruby tests back on once ruby 2.4 issues done - if platform_string() == 'mac': - print('skipping ruby test_specs on mac until running on 2.4') - return [] return [self.config.job_spec(['tools/run_tests/helper_scripts/run_ruby.sh'], timeout_seconds=10*60, environ=_FORCE_ENVIRON_FOR_WRAPPERS)] def pre_build_steps(self): - if platform_string() == 'mac': - print('skipping ruby pre_build_steps on mac until running on 2.4') - return [] return [['tools/run_tests/helper_scripts/pre_build_ruby.sh']] def make_targets(self): @@ -666,15 +659,9 @@ class RubyLanguage(object): return [] def build_steps(self): - if platform_string() == 'mac': - print('skipping ruby build_steps on mac until running on 2.4') - return [] return [['tools/run_tests/helper_scripts/build_ruby.sh']] def post_tests_steps(self): - if platform_string() == 'mac': - print('skipping ruby post_test_steps on mac until running on 2.4') - return [] return [['tools/run_tests/helper_scripts/post_tests_ruby.sh']] def makefile_name(self):
re-enable ruby tests on mac
grpc_grpc
train
82043f14ed40143e6f437e69d48045394d53b907
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,8 +4,8 @@ import sys from setuptools import setup, find_packages -if sys.version_info < (3, 5): - raise SystemError('Python version must be at least 3.5') +if sys.version_info < (3, 6): + raise SystemError('Python version must be at least 3.6') # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) @@ -63,7 +63,7 @@ setup( 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', ], install_requires=install_requires, extras_require=extras_require,
Support only python <I> explicitly (which has been the assumption for a while)
ministryofjustice_money-to-prisoners-common
train
26b873541866a4d622ce63e8cd825da0d763f013
diff --git a/src/java/com/threerings/gwt/ui/WidgetUtil.java b/src/java/com/threerings/gwt/ui/WidgetUtil.java index <HASH>..<HASH> 100644 --- a/src/java/com/threerings/gwt/ui/WidgetUtil.java +++ b/src/java/com/threerings/gwt/ui/WidgetUtil.java @@ -172,5 +172,5 @@ public class WidgetUtil return value.substring(0, index); } - protected static WidgetUtilImpl _impl = (WidgetUtilImpl)GWT.create(WidgetUtilImpl.class); + protected static WidgetUtilImpl _impl = GWT.create(WidgetUtilImpl.class); }
No need to cast the results of GWT.create().
threerings_gwt-utils
train
f0adb19b0aec06c5d94970855f1f6da47b7da574
diff --git a/src/Actor/ActorEventCdbXmlEnricher.php b/src/Actor/ActorEventCdbXmlEnricher.php index <HASH>..<HASH> 100644 --- a/src/Actor/ActorEventCdbXmlEnricher.php +++ b/src/Actor/ActorEventCdbXmlEnricher.php @@ -184,7 +184,6 @@ class ActorEventCdbXmlEnricher implements EventListenerInterface, LoggerAwareInt $xml = $response->getBody()->getContents(); $xmlErrors = $this->xmlValidationService->validate($xml); - if (!empty($xmlErrors)) { throw XMLValidationException::fromXMLValidationErrors($xmlErrors); }
III-<I>: Spacing.
cultuurnet_udb3-udb2-bridge
train
f8e6854197cd337b652c1260999a8a397d0d4703
diff --git a/mempool/policy.go b/mempool/policy.go index <HASH>..<HASH> 100644 --- a/mempool/policy.go +++ b/mempool/policy.go @@ -172,17 +172,10 @@ func checkPkScriptStandard(pkScript []byte, scriptClass txscript.ScriptClass) er return nil } -// IsDust returns whether or not the passed transaction output amount is -// considered dust or not based on the passed minimum transaction relay fee. -// Dust is defined in terms of the minimum transaction relay fee. In -// particular, if the cost to the network to spend coins is more than 1/3 of the -// minimum transaction relay fee, it is considered dust. -func IsDust(txOut *wire.TxOut, minRelayTxFee btcutil.Amount) bool { - // Unspendable outputs are considered dust. - if txscript.IsUnspendable(txOut.PkScript) { - return true - } - +// GetDustThreshold calculates the dust limit for a *wire.TxOut by taking the +// size of a typical spending transaction and multiplying it by 3 to account +// for the minimum dust relay fee of 3000sat/kvb. +func GetDustThreshold(txOut *wire.TxOut) int64 { // The total serialized size consists of the output and the associated // input script to redeem it. Since there is no input script // to redeem it yet, use the minimum size of a typical input script. @@ -253,6 +246,20 @@ func IsDust(txOut *wire.TxOut, minRelayTxFee btcutil.Amount) bool { totalSize += 107 } + return 3 * int64(totalSize) +} + +// IsDust returns whether or not the passed transaction output amount is +// considered dust or not based on the passed minimum transaction relay fee. +// Dust is defined in terms of the minimum transaction relay fee. In +// particular, if the cost to the network to spend coins is more than 1/3 of the +// minimum transaction relay fee, it is considered dust. +func IsDust(txOut *wire.TxOut, minRelayTxFee btcutil.Amount) bool { + // Unspendable outputs are considered dust. + if txscript.IsUnspendable(txOut.PkScript) { + return true + } + // The output is considered dust if the cost to the network to spend the // coins is more than 1/3 of the minimum free transaction relay fee. // minFreeTxRelayFee is in Satoshi/KB, so multiply by 1000 to @@ -265,7 +272,7 @@ func IsDust(txOut *wire.TxOut, minRelayTxFee btcutil.Amount) bool { // // The following is equivalent to (value/totalSize) * (1/3) * 1000 // without needing to do floating point math. - return txOut.Value*1000/(3*int64(totalSize)) < int64(minRelayTxFee) + return txOut.Value*1000/GetDustThreshold(txOut) < int64(minRelayTxFee) } // checkTransactionStandard performs a series of checks on a transaction to
mempool: introduce GetDustThreshold to export dust limit calculation This commit modifies no behavior and would allow other projects to retrieve the dust limit for a particular output type before the amount of the output is known. This is particularly useful in the Lightning Network for channel negotiation.
btcsuite_btcd
train
e7d1686eae99b6e2175579df4e14553867f5b43a
diff --git a/envelope.go b/envelope.go index <HASH>..<HASH> 100644 --- a/envelope.go +++ b/envelope.go @@ -3,7 +3,7 @@ package smtpd import ( "crypto/tls" "fmt" - "strings" + "net" "time" ) @@ -34,10 +34,15 @@ func (env *Envelope) AddReceivedLine(peer Peer) { ) } + peerIP := "" + if addr, ok := peer.Addr.(*net.TCPAddr); ok { + peerIP = addr.IP.String() + } + line := wrap([]byte(fmt.Sprintf( "Received: from %s [%s] by %s with %s;%s\r\n\t%s\r\n", peer.HeloName, - strings.Split(peer.Addr.String(), ":")[0], + peerIP, peer.ServerName, peer.Protocol, tlsDetails,
Fix client IP in Received line for IPv6 IP addresses
chrj_smtpd
train
1da5ce70a2e4e757bb0d591b309c659a2933e67f
diff --git a/src/engine/engine_test.go b/src/engine/engine_test.go index <HASH>..<HASH> 100644 --- a/src/engine/engine_test.go +++ b/src/engine/engine_test.go @@ -324,7 +324,132 @@ func (self *EngineSuite) TestCountQueryWithGroupByClause(c *C) { "int_value": 1 }, { + "string_value": "another_value" + } + ], + "timestamp": 1381346631, + "sequence_number": 1 + } + ], + "name": "foo", + "fields": [ + { + "type": "INT32", + "name": "count" + }, + { + "type": "STRING", + "name": "column_one" + } + ] + } +] +`) + +} + +func (self *EngineSuite) TestCountQueryWithGroupByClauseWithMultipleColumns(c *C) { + // make the mock coordinator return some data + engine := createEngine(c, ` +[ + { + "points": [ + { + "values": [ + { "string_value": "some_value" + }, + { + "int_value": 1 + } + ], + "timestamp": 1381346631, + "sequence_number": 1 + }, + { + "values": [ + { + "string_value": "some_value" + }, + { + "int_value": 2 + } + ], + "timestamp": 1381346631, + "sequence_number": 1 + }, + { + "values": [ + { + "string_value": "another_value" + }, + { + "int_value": 1 + } + ], + "timestamp": 1381346631, + "sequence_number": 1 + } + ], + "name": "foo", + "fields": [ + { + "type": "STRING", + "name": "column_one" + }, + { + "type": "INT32", + "name": "column_two" + } + + ] + } +] +`) + + runQuery(engine, "select count(*), column_one, column_two from foo group by column_one, column_two;", c, `[ + { + "points": [ + { + "values": [ + { + "int_value": 1 + }, + { + "string_value": "some_value" + }, + { + "int_value": 1 + } + ], + "timestamp": 1381346631, + "sequence_number": 1 + }, + { + "values": [ + { + "int_value": 1 + }, + { + "string_value": "some_value" + }, + { + "int_value": 2 + } + ], + "timestamp": 1381346631, + "sequence_number": 1 + }, + { + "values": [ + { + "int_value": 1 + }, + { + "string_value": "another_value" + }, + { + "int_value": 1 } ], "timestamp": 1381346631, @@ -352,6 +477,10 @@ func (self *EngineSuite) TestCountQueryWithGroupByClause(c *C) { { "type": "STRING", "name": "column_one" + }, + { + "type": "INT32", + "name": "column_two" } ] }
add a group by test for grouping by multiple columns.
influxdata_influxdb
train
51ba4f7aba9ce4a7cbb11f0311a2f2cb97b354a8
diff --git a/lib/boson/manager.rb b/lib/boson/manager.rb index <HASH>..<HASH> 100644 --- a/lib/boson/manager.rb +++ b/lib/boson/manager.rb @@ -82,28 +82,36 @@ module Boson accepted.each {|cmd| Scientist.redefine_command(lib.namespace_object, cmd) } end + # Handles an error from a load action + def handle_load_action_error(library, load_method, err) + case err + when LoaderError + add_failed_library library + warn "Unable to #{load_method} library #{library}. Reason: #{err.message}" + else + add_failed_library library + message = "Unable to #{load_method} library #{library}. Reason: #{err}" + if Boson.debug + message += "\n" + err.backtrace.map {|e| " " + e }.join("\n") + elsif @options[:verbose] + message += "\n" + err.backtrace.slice(0,3).map {|e| " " + e }.join("\n") + end + $stderr.puts message + end + end + private - def rescue_load_action(library, load_method) + def call_load_action(library, load_method) yield - rescue LoaderError=>e - add_failed_library library - warn "Unable to #{load_method} library #{library}. Reason: #{e.message}" - rescue StandardError, SyntaxError, LoadError =>e - add_failed_library library - message = "Unable to #{load_method} library #{library}. Reason: #{$!}" - if Boson.debug - message += "\n" + e.backtrace.map {|e| " " + e }.join("\n") - elsif @options[:verbose] - message += "\n" + e.backtrace.slice(0,3).map {|e| " " + e }.join("\n") - end - $stderr.puts message + rescue StandardError, SyntaxError, LoadError => err + handle_load_action_error(library, load_method, err) ensure Inspector.disable if Inspector.enabled end def load_once(source, options={}) @options = options - rescue_load_action(source, :load) do + call_load_action(source, :load) do lib = loader_create(source) if loaded?(lib.name) if options[:verbose] && !options[:dependency] diff --git a/test/manager_test.rb b/test/manager_test.rb index <HASH>..<HASH> 100644 --- a/test/manager_test.rb +++ b/test/manager_test.rb @@ -5,7 +5,7 @@ describe "Manager" do def load_library(hash) new_attributes = {:name=>hash[:name], :commands=>[], :created_dependencies=>[], :loaded=>true} [:module, :commands].each {|e| new_attributes[e] = hash.delete(e) if hash[e] } - Manager.expects(:rescue_load_action).returns(Library.new(new_attributes)) + Manager.expects(:call_load_action).returns(Library.new(new_attributes)) Manager.load([hash[:name]]) end
allow load action error handling to be supered, rename manager meth
cldwalker_boson
train
de5a0631c095ca107e579042c7a0c29e6ce63ee5
diff --git a/lib/paratrooper/default_formatter.rb b/lib/paratrooper/default_formatter.rb index <HASH>..<HASH> 100644 --- a/lib/paratrooper/default_formatter.rb +++ b/lib/paratrooper/default_formatter.rb @@ -1,13 +1,29 @@ -require 'stringio' - module Paratrooper + + # Public: Formatter used as default for outputting messages to command line + # class DefaultFormatter attr_reader :output + # Public: Initializes DefaultFormatter + # + # output - IO object (default: STDOUT) def initialize(output = STDOUT) @output = output end + # Public: Displays message with decoration + # + # message - String message to be displayed + # + # Examples + # + # display("Excellent Message") + # # => + # # => ========================================================================== + # # => >> Excellent Message + # # => ========================================================================== + # # => def display(message) output.puts output.puts "=" * 80 diff --git a/lib/paratrooper/deploy.rb b/lib/paratrooper/deploy.rb index <HASH>..<HASH> 100644 --- a/lib/paratrooper/deploy.rb +++ b/lib/paratrooper/deploy.rb @@ -3,10 +3,26 @@ require 'paratrooper/default_formatter' require 'paratrooper/system_caller' module Paratrooper + + # Public: Entry point into the library. + # class Deploy attr_reader :app_name, :formatter, :system_caller, :heroku, :tag_name, :match_tag + # Public: Initializes a Deploy + # + # app_name - A String naming the Heroku application to be interacted with. + # options - The Hash options is used to provide additional functionality. + # :formatter - Object responsible for displaying message + # output (optional). + # :heroku - Object wrapper around heroku-api. (optional). + # :tag - String name to be used as a git reference + # point (optional). + # :match_tag_to - String name of git reference point to match + # :tag to (optional). + # :system_caller - Object responsible for calling system + # commands (optional). def initialize(app_name, options = {}) @app_name = app_name @formatter = options[:formatter] || DefaultFormatter.new @@ -16,16 +32,22 @@ module Paratrooper @system_caller = options[:system_caller] || SystemCaller.new end + # Public: Activates Heroku maintenance mode. + # def activate_maintenance_mode notify_screen("Activating Maintenance Mode") heroku.app_maintenance_on end + # Public: Deactivates Heroku maintenance mode. + # def deactivate_maintenance_mode notify_screen("Deactivating Maintenance Mode") heroku.app_maintenance_off end + # Public: Creates a git tag and pushes it to repository. + # def update_repo_tag unless tag_name.nil? || tag_name.empty? notify_screen("Updating Repo Tag: #{tag_name}") @@ -34,28 +56,48 @@ module Paratrooper end end + # Public: Pushes repository to Heroku. + # def push_repo reference_point = tag_name || 'master' notify_screen("Pushing #{reference_point} to Heroku") system_call "git push -f #{git_remote} #{reference_point}:master" end + # Public: Runs rails database migrations on your application. + # def run_migrations notify_screen("Running database migrations") system_call "heroku run rake db:migrate --app #{app_name}" end + # Public: Restarts application on Heroku. + # def app_restart notify_screen("Restarting application") heroku.app_restart end + # Public: cURL for application URL to start your Heroku dyno. + # def warm_instance(wait_time = 3) sleep wait_time notify_screen("Accessing #{app_url} to warm up your application") system_call "curl -Il http://#{app_url}" end + # Public: Execute common deploy steps. + # + # Default deploy consists of: + # * Activating maintenance page + # * Updating repository tag + # * Pushing repository to Heroku + # * Running database migrations + # * Restarting application on Heroku + # * Deactivating maintenance page + # * cURL'ing application URL to warm Heroku dyno + # + # Alias: #deploy def default_deploy activate_maintenance_mode update_repo_tag @@ -76,10 +118,16 @@ module Paratrooper "git@heroku.com:#{app_name}.git" end + # Internal: Displays a message to user + # + # message - String message meant for display def notify_screen(message) formatter.display(message) end + # Internal: Calls commands meant to go to system + # + # call - String version of system command def system_call(call) system_caller.execute(call) end diff --git a/spec/paratrooper/default_formatter_spec.rb b/spec/paratrooper/default_formatter_spec.rb index <HASH>..<HASH> 100644 --- a/spec/paratrooper/default_formatter_spec.rb +++ b/spec/paratrooper/default_formatter_spec.rb @@ -1,5 +1,6 @@ require 'spec_helper' require 'paratrooper/default_formatter' +require 'stringio' describe Paratrooper::DefaultFormatter do let(:formatter) { described_class.new(output_stub) }
Documentation for Deploy and DefaultFormatter
mattpolito_paratrooper
train
2ce3171c2425c52edef3174b821b5c3826e9928c
diff --git a/tests/test_provider.py b/tests/test_provider.py index <HASH>..<HASH> 100644 --- a/tests/test_provider.py +++ b/tests/test_provider.py @@ -45,17 +45,3 @@ def xtest_provider_microsoft_make_request(mock_requests_get, mock_requests_post) provider._make_request('test') assert mock_requests_get.called assert mock_requests_post.called - -@mock.patch("requests.post") -def test_provider_libre_make_request(mock_requests_get, mock_requests_post): - from_lang = "zh" - to_lang = "en" - provider = LibreProvider( - to_lang=to_lang, - from_lang=from_lang, - headers={}, - base_url="http://localhost:5000/", - ) - - provider._make_request("test") - assert mock_requests_post.called
Remove old LibreTranslate test This test tested that the LibreTranslate binding used requests and the LibreTranslate binding now uses the Python standard library for network calls.
terryyin_translate-python
train
1b9f1b5ba97f6e6f5fb14d7cb1bca363590599b3
diff --git a/dev.py b/dev.py index <HASH>..<HASH> 100755 --- a/dev.py +++ b/dev.py @@ -271,9 +271,6 @@ elif args.command == 'docker-test': 'python:3.5-alpine3.8', 'python:3.6-alpine3.8', 'python:3.7-alpine3.8', - 'python:3.5-alpine3.7', - 'python:3.6-alpine3.7', - 'python:3.7-alpine3.7', ] docker_runs = []
No longer test with Alpine<I>
mathiasertl_django-ca
train
2fe59e03694c1bee4f410097c5dc22b69282e7bd
diff --git a/lib/calabash/android/operations.rb b/lib/calabash/android/operations.rb index <HASH>..<HASH> 100644 --- a/lib/calabash/android/operations.rb +++ b/lib/calabash/android/operations.rb @@ -1,6 +1,11 @@ module Calabash module Android module Operations + def _reinstall(opt={}) + uninstall(Application.default) + install(Application.default) + end + def _calabash_start_app(options={}) test_options = options.dup diff --git a/lib/calabash/operations.rb b/lib/calabash/operations.rb index <HASH>..<HASH> 100644 --- a/lib/calabash/operations.rb +++ b/lib/calabash/operations.rb @@ -12,8 +12,7 @@ module Calabash # @!visibility private def _reinstall(opt={}) - uninstall(Application.default) - install(Application.default) + abstract_method! end # @!visibility private
Operations: Moved #_reinstall impl from Calabash to Calabash::Android
calabash_calabash
train
f35287cb7a371ea9c0e786ed8f5b8371df36d91a
diff --git a/system/src/Grav/Common/Page/Medium.php b/system/src/Grav/Common/Page/Medium.php index <HASH>..<HASH> 100644 --- a/system/src/Grav/Common/Page/Medium.php +++ b/system/src/Grav/Common/Page/Medium.php @@ -93,6 +93,12 @@ class Medium extends Data */ protected $linkAttributes = []; + /** + * Construct. + * + * @param array $items + * @param Blueprint $blueprint + */ public function __construct($items = array(), Blueprint $blueprint = null) { parent::__construct($items, $blueprint); @@ -134,9 +140,6 @@ class Medium extends Data */ public function path() { - /** @var Config $config */ - $config = self::$grav['config']; - if ($this->image) { $output = $this->saveImage(); $this->reset(); @@ -150,6 +153,7 @@ class Medium extends Data /** * Return URL to file. * + * @param bool $reset * @return string */ public function url($reset = true) @@ -165,11 +169,12 @@ class Medium extends Data return self::$grav['base_url'] . '/'. $output; } - + /** - * Return srcset string for this Medium and its alternatives - * + * Return srcset string for this Medium and its alternatives. + * + * @param bool $reset * @return string */ public function srcset($reset = true) @@ -195,6 +200,7 @@ class Medium extends Data * @param string $class * @param string $type * @param int $quality + * @param bool $reset * @return string */ public function img($title = null, $class = null, $type = null, $quality = 80, $reset = true) @@ -213,8 +219,7 @@ class Medium extends Data * * @param string $title * @param string $class - * @param string $type - * @param int $quality + * @param bool $reset * @return string */ public function html($title = null, $class = null, $reset = true) @@ -244,6 +249,12 @@ class Medium extends Data return $output; } + /** + * Return HTML array from medium. + * + * @param bool $reset + * @return array + */ public function htmlRaw($reset = true) { $output = []; @@ -256,9 +267,6 @@ class Medium extends Data } if ($this->linkTarget) { - /** @var Config $config */ - $config = self::$grav['config']; - $output['a_href'] = $this->linkTarget; $output['a_attributes'] = $this->linkAttributes; @@ -301,11 +309,9 @@ class Medium extends Data /** * Enable link for the medium object * - * @param int $width - * @param int $height * @return $this */ - public function link($width = null, $height = null) + public function link() { if ($this->image) { $this->linkTarget = $this->url(false); @@ -326,15 +332,13 @@ class Medium extends Data /** * Enable lightbox for the medium. * - * @param int $width - * @param int $height * @return $this */ - public function lightbox($width = null, $height = null) + public function lightbox() { $this->linkAttributes['rel'] = 'lightbox'; - return $this->link($width, $height); + return $this->link(); } /** @@ -407,11 +411,15 @@ class Medium extends Data */ public function image($variable = 'thumb') { + $locator = self::$grav['locator']; + + $images_dir = $locator->findResource('image://'); + // TODO: add default file $file = $this->get($variable); $this->image = ImageFile::open($file) - ->setCacheDir(basename(IMAGES_DIR)) - ->setActualCacheDir(IMAGES_DIR) + ->setCacheDir(basename($images_dir)) + ->setActualCacheDir($images_dir) ->setPrettyName(basename($this->get('basename'))); $this->filter(); @@ -419,6 +427,11 @@ class Medium extends Data return $this; } + /** + * Save the image with cache. + * + * @return mixed|string + */ protected function saveImage() { if (!$this->image) { @@ -432,8 +445,9 @@ class Medium extends Data $ratio = 1; } - $overlay = SYSTEM_DIR . '/assets/responsive-overlays/' . $ratio . 'x.png'; - $overlay = file_exists($overlay) ? $overlay : SYSTEM_DIR . '/assets/responsive-overlays/unknown.png'; + $locator = self::$grav['locator']; + + $overlay = $locator->findReference("system://assets/responsive-overlays/{$ratio}x.png") ?: $locator->findResource('system://assets/responsive-overlays/unknown.png'); $this->image->merge(ImageFile::open($overlay)); } @@ -463,11 +477,10 @@ class Medium extends Data } /** - * Add alternative Medium to this Medium + * Add alternative Medium to this Medium. * - * @param $type - * @param $alternative - * @return $this + * @param $ratio + * @param Medium $alternative */ public function addAlternative($ratio, Medium $alternative) {
- Removed unused variables. - Add missed phpdoc params. - Update constants with locator.
getgrav_grav
train
dcd5a6c2c7f6fa10a8fc6da01986f5ac32365ffd
diff --git a/icyparser/icyparser.py b/icyparser/icyparser.py index <HASH>..<HASH> 100755 --- a/icyparser/icyparser.py +++ b/icyparser/icyparser.py @@ -29,7 +29,9 @@ import os import re import sys +import time import threading +import tempfile import urllib.parse import urllib.request import http @@ -142,8 +144,8 @@ class IcyParser(object): self.icy_br = int(headers_dict["icy-br"]) self.icy_metaint = int(headers_dict["icy-metaint"]) - self.icystream = open("/tmp/icystream.txt", "w") - + self.icystream = tempfile.NamedTemporaryFile(mode="w+", delete=False) + ## Turn on to write all the non-ICY bytes to a playable MP3 file. #self.audiostream = open("audiostream.mp3", "w+b", buffering=0) @@ -177,7 +179,8 @@ class IcyParser(object): self.icy_streamtitle = \ re.findall("(?<=StreamTitle=').*(?=';)", streamtitle)[0] #print(self.icy_streamtitle) - self.icystream.write(self.icy_streamtitle + "\n") + self.icystream.write("{} {}".format(time.strftime("%d-%m-%Y %H:%M:%S"), \ + self.icy_streamtitle + "\n")) self.icystream.flush() except http.client.BadStatusLine as e: diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ try: setup( name = "icyparser", packages = ["icyparser"], - version = "1.1.0", + version = "1.1.1", description = "A script to download the ICY information for a stream and return it as a dict", author = "Gijs Timmers", author_email = "gijs.timmers@student.kuleuven.be",
Integration of the tempfile module instead of an arbitrary filename
GijsTimmers_icyparser
train
77f4460f7f2dd0a8b8e095410e57a988decff71a
diff --git a/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/TaskCommentServiceImpl.java b/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/TaskCommentServiceImpl.java index <HASH>..<HASH> 100644 --- a/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/TaskCommentServiceImpl.java +++ b/jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/TaskCommentServiceImpl.java @@ -44,6 +44,10 @@ public class TaskCommentServiceImpl implements TaskCommentService { public long addComment(long taskId, Comment comment) { Task task = persistenceContext.findTask(taskId); + + if (persistenceContext.findUser(comment.getAddedBy().getId()) == null) { + persistenceContext.persistUser(comment.getAddedBy()); + } persistenceContext.persistComment(comment); ((InternalTaskData) task.getTaskData()).addComment(comment); return comment.getId();
BPMSPL-<I> - fixed unsaved user who added a comment
kiegroup_jbpm
train
5143c80d478b0739350bc9502981d156164c4ebd
diff --git a/bin/browser.js b/bin/browser.js index <HASH>..<HASH> 100755 --- a/bin/browser.js +++ b/bin/browser.js @@ -1,6 +1,7 @@ const puppeteer = require('puppeteer'); const fs = require('fs'); const URL = require('url').URL; +const URLParse = require('url').parse; const [, , ...args] = process.argv; @@ -70,6 +71,18 @@ const callChrome = async () => { request.continue(); }); } + + if (request.options && request.options.blockDomains) { + await page.setRequestInterception(true); + var domainsArray = JSON.parse(request.options.blockDomains); + page.on('request', request => { + const hostname = URLParse(request.url()).hostname; + domainsArray.forEach(function(value){ + if (hostname.indexOf(value) >= 0) request.abort(); + }); + request.continue(); + }); + } if (request.options && request.options.dismissDialogs) { page.on('dialog', async dialog => {
Added blockDomains() method to block domains (#<I>) * Added blockDomains to block domains With blockDomains() method we can now block a list of domains passed as array. It uses indexOf() to check if each item in the domains array is present in the URL domain. * Added const URLParse = require('url').parse; * Changed const name from "blockedArray" to "domainsArray" * Fixed indexOf() with >= 0 matching
spatie_browsershot
train
642f7daa175a39d28cf1c40809ba4e34c125d659
diff --git a/Tests/Utility/Reflection/ClassUtilityTest.php b/Tests/Utility/Reflection/ClassUtilityTest.php index <HASH>..<HASH> 100644 --- a/Tests/Utility/Reflection/ClassUtilityTest.php +++ b/Tests/Utility/Reflection/ClassUtilityTest.php @@ -96,6 +96,23 @@ final class ClassUtilityTest extends PHPUnit_Framework_TestCase { } /** + * Tests the getName() method. + * + * @return void + */ + public function testGetName() { + + try { + ClassUtility::getName("classnotfound"); + } catch (Exception $ex) { + $this->assertInstanceOf(ReflectionException::class, $ex); + $this->assertEquals("Class classnotfound does not exist", $ex->getMessage()); + } + + $this->assertEquals("WBW\Library\Core\Tests\Utility\Reflection\ClassUtilityTest", ClassUtility::getName($this)); + } + + /** * Tests the getShortName() method. * * @return void diff --git a/Utility/Reflection/ClassUtility.php b/Utility/Reflection/ClassUtility.php index <HASH>..<HASH> 100644 --- a/Utility/Reflection/ClassUtility.php +++ b/Utility/Reflection/ClassUtility.php @@ -106,13 +106,23 @@ final class ClassUtility { } /** + * Get the class name. + * + * @param mixed $object The class name or object. + * @return string Returns the class name. + */ + public static function getName($object) { + return (new ReflectionClass($object))->getName(); + } + + /** * Get the short class name. * - * @param mixed $classname The class name or object. + * @param mixed $object The class name or object. * @return string Returns the short class name. */ - public static function getShortName($classname) { - return (new ReflectionClass($classname))->getShortName(); + public static function getShortName($object) { + return (new ReflectionClass($object))->getShortName(); } }
Add getName() method into ClassUtility
webeweb_core-library
train
de1c0140e824a47aa81f7f633c74833855cfd9f6
diff --git a/tests/I18n/bootstrap.php b/tests/I18n/bootstrap.php index <HASH>..<HASH> 100644 --- a/tests/I18n/bootstrap.php +++ b/tests/I18n/bootstrap.php @@ -3,5 +3,6 @@ require __DIR__.'/kohana.php'; // Load some required classes -require DOCROOT.'Testcase'.EXT; -require DOCROOT.'Plural/Testcase'.EXT; \ No newline at end of file +require_once DOCROOT.'helpers'.EXT; +require_once DOCROOT.'Testcase'.EXT; +require_once DOCROOT.'Plural/Testcase'.EXT; \ No newline at end of file diff --git a/tests/I18n/kohana.php b/tests/I18n/kohana.php index <HASH>..<HASH> 100644 --- a/tests/I18n/kohana.php +++ b/tests/I18n/kohana.php @@ -29,7 +29,4 @@ Kohana::$config->attach(new Kohana_Config_File); Kohana::modules(array( 'plurals' => MODPATH.'plurals', 'unittest' => MODPATH.'unittest', -)); - -// Load some required classes -require_once DOCROOT.'helpers'.EXT; \ No newline at end of file +)); \ No newline at end of file
Moved some 'requires' around
czukowski_I18n_Plural
train
ca3ce6d3b8229f5ab7a740789bdf497d54db17fc
diff --git a/bugwarrior/db.py b/bugwarrior/db.py index <HASH>..<HASH> 100644 --- a/bugwarrior/db.py +++ b/bugwarrior/db.py @@ -2,6 +2,9 @@ import taskw import pprint +MARKUP = "(bw)" + + def clean_issues(issues): """ Change "s into &dqout;s. """ # TODO -- is it better to use http://wiki.python.org/moin/EscapingXml ? @@ -13,24 +16,39 @@ def clean_issues(issues): return issues -def prune_issues(issues): - known_tasks = taskw.load_tasks() - known_tasks = known_tasks['pending'] + known_tasks['completed'] - known_descriptions = [t['description'] for t in known_tasks] - novel = lambda issue: issue['description'] not in known_descriptions - return filter(novel, issues) - def synchronize(issues): + # Load info about the task database + tasks = taskw.load_tasks() + is_bugwarrior_task = lambda task: task['description'].startswith(MARKUP) + + # Prune down to only tasks managed by bugwarrior + for key in tasks.keys(): + tasks[key] = filter(is_bugwarrior_task, tasks[key]) - # TODO -- 'complete' issues that are closed upstream. + # Build a list of only the descriptions of those local bugwarrior tasks + local_descs = [t['description'] for t in sum(tasks.values(), [])] - # Escape any dangerous characters + + # Now the remote data. + # Escape any dangerous characters. issues = clean_issues(issues) - # Select only 'new' tasks - issues = prune_issues(issues) + # Build a list of only the descriptions of those remote issues + remote_descs = [i['description'] for i in issues] + + # Build the list of tasks that need to be added + is_new = lambda issue: issue['description'] not in local_descs + new_issues = filter(is_new, issues) - for issue in issues: + # Build the list of local tasks that need to be completed + is_done = lambda task: task['description'] not in remote_descs + done_tasks = filter(is_done, tasks['pending']) + + for issue in new_issues: print "Adding task:", pprint.pformat(issue) taskw.task_add(**issue) + + for task in done_tasks: + print "Completed task:", pprint.pformat(task) + taskw.task_done(id=None, uuid=task['uuid']) diff --git a/bugwarrior/services/__init__.py b/bugwarrior/services/__init__.py index <HASH>..<HASH> 100644 --- a/bugwarrior/services/__init__.py +++ b/bugwarrior/services/__init__.py @@ -1,7 +1,7 @@ import bitlyapi - from bugwarrior.config import die +from bugwarrior.db import MARKUP class IssueService(object): @@ -23,7 +23,7 @@ class IssueService(object): def description(self, title, url): # TODO -- get the '35' here from the config. - return "(bw) %s .. %s" % (title[:35], self.shorten(url)) + return "%s %s .. %s" % (MARKUP, title[:35], self.shorten(url)) def include(self, issue): """ Return true if the issue in question should be included """ diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from setuptools import setup, find_packages import sys, os -version = '0.1b2' +version = '0.1b3' f = open('README.rst') long_description = f.read().strip() @@ -33,7 +33,7 @@ setup(name='bugwarrior', "decorator", "github2", "offtrac", - "taskw>=0.1.5", + "taskw>=0.1.6", ], entry_points=""" [console_scripts]
Close tasks on issue fix. Fixes #1
ralphbean_bugwarrior
train
97c8f97fa0c8c21af70d13658d5c6a4135d89449
diff --git a/pybar/ViTablesPlugin/pybar_plugin.py b/pybar/ViTablesPlugin/pybar_plugin.py index <HASH>..<HASH> 100644 --- a/pybar/ViTablesPlugin/pybar_plugin.py +++ b/pybar/ViTablesPlugin/pybar_plugin.py @@ -29,10 +29,11 @@ translate = QtGui.QApplication.translate def plot_1d_hist(hist, yerr=None, title=None, x_axis_title=None, y_axis_title=None, x_ticks=None, color='r', plot_range=None, log_y=False, filename=None): plt.clf() + hist = np.array(hist) if plot_range is None: plot_range = range(0, len(hist)) - if len(plot_range) > len(hist): - plot_range = plot_range[0:len(hist)] + plot_range = np.array(plot_range) + plot_range = plot_range[plot_range < len(hist)] if yerr is not None: plt.bar(x=plot_range, height=hist[plot_range], color=color, align='center', yerr=yerr) else: diff --git a/pybar/analysis/plotting/plotting.py b/pybar/analysis/plotting/plotting.py index <HASH>..<HASH> 100644 --- a/pybar/analysis/plotting/plotting.py +++ b/pybar/analysis/plotting/plotting.py @@ -387,13 +387,12 @@ def plot_tot(hist, title=None, filename=None): def plot_tdc(hist, title=None, filename=None): masked_hist, indices = hist_quantiles(hist, prob=(0.0, 0.99), return_indices=True) - print masked_hist, indices - plot_1d_hist(hist=masked_hist, title=('TDC Hit distribution' + r' ($\Sigma$ = %d)' % (np.sum(hist))) if title is None else title, plot_range=range(*indices), x_axis_title='hit TDC', y_axis_title='#', color='b', filename=filename) + plot_1d_hist(hist=masked_hist, title=('TDC Hit distribution' + r' ($\Sigma$ = %d)' % (np.sum(hist))) if title is None else title, plot_range=range(indices[0], indices[1] + 1), x_axis_title='hit TDC', y_axis_title='#', color='b', filename=filename) def plot_tdc_counter(hist, title=None, filename=None): masked_hist, indices = hist_quantiles(hist, prob=(0.0, 0.99), return_indices=True) - plot_1d_hist(hist=masked_hist, title=('TDC counter distribution' + r' ($\Sigma$ = %d)' % (np.sum(hist))) if title is None else title, plot_range=range(*indices), x_axis_title='TDC value', y_axis_title='#', color='b', filename=filename) + plot_1d_hist(hist=masked_hist, title=('TDC counter distribution' + r' ($\Sigma$ = %d)' % (np.sum(hist))) if title is None else title, plot_range=range(indices[0], indices[1] + 1), x_axis_title='TDC value', y_axis_title='#', color='b', filename=filename) def plot_event_errors(hist, title=None, filename=None): @@ -568,10 +567,11 @@ def plot_1d_hist(hist, yerr=None, title=None, x_axis_title=None, y_axis_title=No fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) + hist = np.array(hist) if plot_range is None: plot_range = range(0, len(hist)) - if len(plot_range) > len(hist): - plot_range = plot_range[0:len(hist)] + plot_range = np.array(plot_range) + plot_range = plot_range[plot_range < len(hist)] if yerr is not None: ax.bar(x=plot_range, height=hist[plot_range], color=color, align='center', yerr=yerr) else:
BUG: fixes plot range when indices are out of range
SiLab-Bonn_pyBAR
train
7472e7a5817587bf94a510aea5cca2d71f66844b
diff --git a/hazelcast/reactor.py b/hazelcast/reactor.py index <HASH>..<HASH> 100644 --- a/hazelcast/reactor.py +++ b/hazelcast/reactor.py @@ -6,7 +6,7 @@ import socket import sys import threading import time -from Queue import PriorityQueue +from Queue import PriorityQueue, Empty from collections import deque from hazelcast.connection import Connection, BUFFER_SIZE @@ -55,7 +55,10 @@ class AsyncoreReactor(object): return if timer.check_timer(now): - self._timers.get_nowait() + try: + self._timers.get_nowait() + except Empty: + pass else: return
ignore raised Empty on reactor queue since queue is also consumed when timer is cancelled
hazelcast_hazelcast-python-client
train
d2068f5e87719faee5389510e1384bd4099115ad
diff --git a/agent/agent.go b/agent/agent.go index <HASH>..<HASH> 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -29,7 +29,6 @@ const ( StorageAddr = "STORAGE_ADDR" SharedStorageDir = "SHARED_STORAGE_DIR" SharedStorageAddr = "SHARED_STORAGE_ADDR" - LoggingConfig = "LOGGING_CONFIG" ) // The Config interface is the sole way that the agent gets access to the
Don't need to store the logging config in the agent config.
juju_juju
train
737b1663ec31322bc016efe0eb0fdf50bcb32613
diff --git a/lib/plugins.js b/lib/plugins.js index <HASH>..<HASH> 100644 --- a/lib/plugins.js +++ b/lib/plugins.js @@ -19,35 +19,43 @@ function load(flyfile, hook) { _('beginning to look for plugins') - // `flyfile` should also be in project's root - var dir = path.dirname(flyfile) - var modules = path.join(dir, 'node_modules') - - // find `package.json` then parse & all fly plugins - return readPackages(dir).then(function (pkg) { - return parse(pkg).map(function (name) { - return { - name: name, - plugin: req(path.join(modules, name)) - } + // find `package.json` within the project + return findPkg(path.dirname(flyfile)).then(function (fp) { + var modules = path.join(path.dirname(fp), 'node_modules') + + // then parse all fly plugins + return readPackages(fp).then(function (pkg) { + return parse(pkg).map(function (name) { + return { + name: name, + plugin: req(path.join(modules, name)) + } + }) }) }) } /** + * Find a project's `package.json` starting in `dir`, traversing upwards + * @param {String} dir The directory to begin searching + * @return {String} The `package.json` filepath + */ +function findPkg(dir) { + return utils.find('package.json', dir) +} + +/** * Find a sibling `package.json` file & return its contents. - * @param {String} dir The directory to start looking + * @param {String} fp The `package.json` file path to use * @return {Object} The file's contents, or {} */ -function readPackages(dir) { - return utils.find('package.json', dir).then(function (fp) { - if (!fp) { - return {} - } - - return utils.read(fp).then(function (pkg) { - return JSON.parse(pkg) - }) +function readPackages(fp) { + if (!fp) { + return {} + } + + return utils.read(fp).then(function (pkg) { + return JSON.parse(pkg) }) } @@ -103,5 +111,6 @@ function parse(pkg, blacklist) { module.exports = { load: load, parse: parse, + findPkg: findPkg, readPackages: readPackages } diff --git a/test/plugins.js b/test/plugins.js index <HASH>..<HASH> 100644 --- a/test/plugins.js +++ b/test/plugins.js @@ -36,10 +36,17 @@ test('utils.find (package.json)', function (t) { }) }) +test('plugins.findPkg', function (t) { + plugins.findPkg(alt).then(function (fp) { + t.equal(fp, pkg, 'found a package.json file!') + t.end() + }) +}) + test('plugins.readPackages', function (t) { var expect = JSON.parse(fs.readFileSync(pkg, 'utf8')) - plugins.readPackages(alt).then(function (contents) { + plugins.readPackages(pkg).then(function (contents) { t.ok(contents !== undefined, 'found package.json file contents') t.deepEqual(contents.dependencies, expect.dependencies, 'correctly read the contents') t.end() @@ -49,7 +56,7 @@ test('plugins.readPackages', function (t) { test('plugins.parse (simple)', function (t) { var expect = ['fly-fake-plugin'] - plugins.readPackages(alt).then(function (data) { + plugins.readPackages(pkg).then(function (data) { t.deepEqual(plugins.parse(data), expect, 'returns an array of fly-* plugin names') t.end() })
don't require pkg and flyfile to be sibling files - allows for '-f' flag to designate a deeply nested flyfile while referencing root-level 'node_modules' - updated tests
lukeed_taskr
train
ebcd5c9711cfc9b1745711b26d4e8bc4b3753646
diff --git a/connection_maker.go b/connection_maker.go index <HASH>..<HASH> 100644 --- a/connection_maker.go +++ b/connection_maker.go @@ -27,7 +27,7 @@ type connectionMaker struct { targets map[string]*target connections map[Connection]struct{} directPeers peerAddrs - actionChan chan connectionMakerAction + actionChan chan<- connectionMakerAction } // TargetState describes the connection state of a remote target. @@ -57,6 +57,7 @@ type connectionMakerAction func() bool // port. If discovery is true, ConnectionMaker will attempt to // initiate new connections with peers it's not directly connected to. func newConnectionMaker(ourself *localPeer, peers *Peers, localAddr string, port int, discovery bool) *connectionMaker { + actionChan := make(chan connectionMakerAction, ChannelSize) cm := &connectionMaker{ ourself: ourself, peers: peers, @@ -66,9 +67,9 @@ func newConnectionMaker(ourself *localPeer, peers *Peers, localAddr string, port directPeers: peerAddrs{}, targets: make(map[string]*target), connections: make(map[Connection]struct{}), - actionChan: make(chan connectionMakerAction, ChannelSize), + actionChan: actionChan, } - go cm.queryLoop() + go cm.queryLoop(actionChan) return cm } @@ -189,12 +190,12 @@ func (cm *connectionMaker) refresh() { cm.actionChan <- func() bool { return true } } -func (cm *connectionMaker) queryLoop() { +func (cm *connectionMaker) queryLoop(actionChan <-chan connectionMakerAction) { timer := time.NewTimer(maxDuration) run := func() { timer.Reset(cm.checkStateAndAttemptConnections()) } for { select { - case action := <-cm.actionChan: + case action := <-actionChan: if action() { run() } diff --git a/gossip.go b/gossip.go index <HASH>..<HASH> 100644 --- a/gossip.go +++ b/gossip.go @@ -61,8 +61,8 @@ type gossipSender struct { sender protocolSender gossip GossipData broadcasts map[PeerName]GossipData - more chan struct{} - flush chan chan<- bool // for testing + more chan<- struct{} + flush chan<- chan<- bool // for testing } // NewGossipSender constructs a usable GossipSender. @@ -72,36 +72,37 @@ func newGossipSender( sender protocolSender, stop <-chan struct{}, ) *gossipSender { + more := make(chan struct{}, 1) + flush := make(chan chan<- bool) s := &gossipSender{ makeMsg: makeMsg, makeBroadcastMsg: makeBroadcastMsg, sender: sender, broadcasts: make(map[PeerName]GossipData), - more: make(chan struct{}, 1), - flush: make(chan chan<- bool), + more: more, + flush: flush, } - go s.run(stop) + go s.run(stop, more, flush) return s } -// TODO(pb): no need to parameterize more and flush -func (s *gossipSender) run(stop <-chan struct{}) { +func (s *gossipSender) run(stop <-chan struct{}, more <-chan struct{}, flush <-chan chan<- bool) { sent := false for { select { case <-stop: return - case <-s.more: + case <-more: sentSomething, err := s.deliver(stop) if err != nil { return } sent = sent || sentSomething - case ch := <-s.flush: // for testing + case ch := <-flush: // for testing // send anything pending, then reply back whether we sent // anything since previous flush select { - case <-s.more: + case <-more: sentSomething, err := s.deliver(stop) if err != nil { return
Re-apply chan direction restrictions Fixes #1
weaveworks_mesh
train
d2da2ec6f590cfcb7a651ae88a48c433a1a6bcf6
diff --git a/param/__init__.py b/param/__init__.py index <HASH>..<HASH> 100644 --- a/param/__init__.py +++ b/param/__init__.py @@ -21,7 +21,6 @@ __version__='$Revision$' import os.path -from numpy import ndarray from parameterized import Parameterized, Parameter, String, \ descendents, ParameterizedFunction, ParamOverrides @@ -831,6 +830,8 @@ class Array(ClassSelector): Parameter whose value is a numpy array. """ def __init__(self, **params): + # CEBALERT: instead use python array as default? + from numpy import ndarray super(Array,self).__init__(ndarray, allow_None=True, **params)
Moved numpy array inside param.Array so that param does not depend on numpy.
pyviz_param
train
77360ce710a849979cc875af8b743f289d7e5b9b
diff --git a/lib/seaworld/index.js b/lib/seaworld/index.js index <HASH>..<HASH> 100644 --- a/lib/seaworld/index.js +++ b/lib/seaworld/index.js @@ -1,15 +1,11 @@ "use strict"; var Park = require("../park"); -var Settings = require("../settings"); var Moment = require("moment-timezone"); var s_parkID = Symbol(); - -var api_authToken = "c2Vhd29ybGQ6MTM5MzI4ODUwOA=="; -var api_baseURL = "https://seas.te2.biz/v1/rest/venue/"; - -var cacheKey = "seaworldCache_"; +var s_authToken = Symbol(); +var s_apiBase = Symbol(); /** * Implements the Seaworld API framework. @@ -21,7 +17,9 @@ class SeaworldPark extends Park { * Create new SeaworldPark Object. * This object should not be called directly, but rather extended for each of the individual SeaWorld parks * @param {Object} options - * @param {String} options.park_id + * @param {String} options.park_id ID of the park to access the API for + * @param {String} [options.auth_token] Auth token to use to connect to the API + * @param {String} [options.api_base] Base URL to access the API */ constructor(options = {}) { options.name = options.name || "SeaWorld Park"; @@ -32,14 +30,18 @@ class SeaworldPark extends Park { // assign park configurations if (!options.park_id) throw new Error("Missing park's API ID"); this[s_parkID] = options.park_id; + + // accept API options to override defaults if needed + this[s_authToken] = options.auth_token || "***REMOVED***"; + this[s_apiBase] = options.api_base || "https://seas.te2.biz/v1/rest/venue/"; } FetchWaitTimes() { return new Promise(function(resolve, reject) { // first make sure we have our ride names - this.FetchRideNames().then(function(rideNames) { + this.GetRideNames().then(function(rideNames) { this.GetAPIUrl({ - url: `${api_baseURL}${this[s_parkID]}/poi/all/status` + url: `${this[s_apiBase]}${this[s_parkID]}/poi/all/status` }).then(function(waitTimeData) { for (var i = 0, ride; ride = waitTimeData[i++];) { // find/create this ride object (only if we have a name for it) @@ -65,7 +67,7 @@ class SeaworldPark extends Park { FetchOpeningTimes() { return new Promise(function(resolve, reject) { this.GetAPIUrl({ - url: `${api_baseURL}${this[s_parkID]}/hours/${Moment().tz(this.Timezone).format("YYYY-MM-DD")}`, + url: `${this[s_apiBase]}${this[s_parkID]}/hours/${Moment().tz(this.Timezone).format("YYYY-MM-DD")}`, data: { days: 30 } @@ -86,34 +88,41 @@ class SeaworldPark extends Park { } /** - * Fetch all the rides and ride names for this park + * Get cached (or fresh fetch) of ride names + * @returns {Promise<Object>} Object of RideID => Ride name in English + */ + GetRideNames() { + return new Promise(function(resolve, reject) { + // wrap cache request (cache ride names for 24 hours) + this.Cache.Wrap("ridenames", this.FetchRideNames.bind(this), 60 * 60 * 24).then(resolve, reject); + }.bind(this)); + } + + /** + * Fetch all the rides and ride names for this park from the API (skip the cache) * @returns {Promise<Object>} Object of RideID => Ride name in English */ FetchRideNames() { return new Promise(function(resolve, reject) { - Settings.Cache.wrap(cacheKey + `${this[s_parkID]}_ridenames`, function(callback) { - this.GetAPIUrl({ - url: `${api_baseURL}${this[s_parkID]}/poi/all` - }).then(function(rideData) { - if (!rideData) return reject("No POI data returned from TDR API"); - - var rideNames = {}; - for (var i = 0, poi; poi = rideData[i++];) { - // only include POIs of configured types - if (poi.type == "Ride") { - rideNames[poi.id] = poi.label; - } + this.Log(`Fetching ride names for ${this.Name}`); + + // fetch POI (points-of-interest) data from API + this.GetAPIUrl({ + url: `${this[s_apiBase]}${this[s_parkID]}/poi/all` + }).then(function(rideData) { + if (!rideData) return reject("No POI data returned from Seaworld API"); + + var rideNames = {}; + for (var i = 0, poi; poi = rideData[i++];) { + // only include POI data for rides + if (poi.type == "Ride") { + // grab "label", which is the English title for each POI + rideNames[poi.id] = poi.label; } + } - callback(null, rideNames); - }.bind(this), callback); - }.bind(this), { - // cache for 24 hours - ttl: 60 * 60 * 24 - }, function(err, rideNames) { - if (err) return reject(err); resolve(rideNames); - }.bind(this)); + }.bind(this), reject); }.bind(this)); } @@ -121,7 +130,7 @@ class SeaworldPark extends Park { return new Promise(function(resolve, reject) { // make sure headers exist if they weren't set already if (!requestObject.headers) requestObject.headers = []; - requestObject.headers.Authorization = "Basic " + api_authToken; + requestObject.headers.Authorization = "Basic " + new Buffer(this[s_authToken]).toString("base64"); // make sure we get JSON back requestObject.forceJSON = true;
Use new cache module and optionaly accept the API settings on construction (useful if things change and users need a quick-fix while updates are rolling out)
cubehouse_themeparks
train
191e28934eed917d027e761c96d4c8bff65ce468
diff --git a/src/Unicode/CharBuffer.php b/src/Unicode/CharBuffer.php index <HASH>..<HASH> 100644 --- a/src/Unicode/CharBuffer.php +++ b/src/Unicode/CharBuffer.php @@ -31,6 +31,8 @@ class CharBuffer implements CharBufferInterface, TokenExtractInterface private $buffer = []; + private $sourcePreviewOffset = 0; + public function __construct(CharBufferInterface $source) { $this->source = $source; @@ -72,6 +74,7 @@ class CharBuffer implements CharBufferInterface, TokenExtractInterface if ($this->source->isEnd()) { throw new Exception("Unexpected end of source buffer on preview at index {$this->previewOffset}"); } + $positionBeforeMatch = $this->source->getTokenPosition(); $result = $this ->getMatcher() ->match($this->source, $this->getTokenFactory()); @@ -84,9 +87,9 @@ class CharBuffer implements CharBufferInterface, TokenExtractInterface if ($token->getType() != TokenType::SYMBOL) { throw new Exception("Invalid Unicode char token"); } - $char = $token->getAttribute(TokenAttribute::UNICODE_CHAR); - $this->buffer[] = $char; - return $char; + $positionAfterMatch = $this->source->getTokenPosition(); + $this->sourcePreviewOffset = $positionAfterMatch->getFinishOffset() - $positionBeforeMatch->getFinishOffset(); + return $token->getAttribute(TokenAttribute::UNICODE_CHAR); } /** @@ -94,9 +97,8 @@ class CharBuffer implements CharBufferInterface, TokenExtractInterface */ public function nextSymbol(): void { - if (!isset($this->char)) { - $this->getMatchedChar(); - } + $this->buffer[] = $this->char ?? $this->getMatchedChar(); + $this->sourcePreviewOffset = 0; unset($this->char); $this->previewOffset++; } @@ -122,6 +124,7 @@ class CharBuffer implements CharBufferInterface, TokenExtractInterface $this->previewOffset = $this->startOffset; $this->source->resetToken(); $this->buffer = []; + $this->sourcePreviewOffset = 0; unset($this->char); } @@ -141,7 +144,11 @@ class CharBuffer implements CharBufferInterface, TokenExtractInterface public function getTokenAsString(): string { if ($this->source instanceof TokenExtractInterface) { - return $this->source->getTokenAsString(); + $result = $this->source->getTokenAsString(); + if ($this->sourcePreviewOffset > 0) { + $result = substr($result, 0, -$this->sourcePreviewOffset); + } + return $result; } throw new Exception("Source buffer doesn't support extracting strings"); } diff --git a/tests/Lexer/TokenMatcherGeneratorTest.php b/tests/Lexer/TokenMatcherGeneratorTest.php index <HASH>..<HASH> 100644 --- a/tests/Lexer/TokenMatcherGeneratorTest.php +++ b/tests/Lexer/TokenMatcherGeneratorTest.php @@ -8,6 +8,7 @@ use Remorhaz\UniLex\Grammar\ContextFree\TokenFactory; use Remorhaz\UniLex\Lexer\TokenMatcherGenerator; use Remorhaz\UniLex\Lexer\TokenMatcherInterface; use Remorhaz\UniLex\Lexer\TokenMatcherSpec; +use Remorhaz\UniLex\Lexer\TokenReader; use Remorhaz\UniLex\Lexer\TokenSpec; use Remorhaz\UniLex\Lexer\TokenMatcherTemplate; use Remorhaz\UniLex\Unicode\CharBufferFactory; @@ -167,6 +168,42 @@ class TokenMatcherGeneratorTest extends TestCase $generator->load(); } + /** + * @param string $text + * @param string $regExp + * @param string $expectedValue + * @throws \Remorhaz\UniLex\Exception + * @dataProvider providerValidRegExpInput + */ + public function testLoad_ValidInput_MatchesValidToken(string $text, string $regExp, string $expectedValue): void + { + $matcherClass = $this->createTokenMatcherClassName(); + $spec = new TokenMatcherSpec($matcherClass, TokenMatcherTemplate::class); + $code = <<<SOURCE +\$context + ->setNewToken(0) + ->setTokenAttribute('text', \$context->getSymbolString()); +SOURCE; + $tokenSpec = new TokenSpec($regExp, $code); + $spec->addTokenSpec(TokenMatcherInterface::DEFAULT_CONTEXT, $tokenSpec); + $generator = new TokenMatcherGenerator($spec); + $buffer = CharBufferFactory::createFromString($text); + $lexer = new TokenReader($buffer, $generator->load(), new \Remorhaz\UniLex\Lexer\TokenFactory(0xFF)); + $actualValue = $lexer + ->read() + ->getAttribute('text'); + self::assertSame($expectedValue, $actualValue); + } + + public function providerValidRegExpInput(): array + { + return [ + "Single latin char" => ['ab', 'a', 'a'], + "Zero or many latin char" => ['aabc', 'a*', 'aa'], + "Number without leading zero" => ['103abc', '[1-9][0-9]*', '103'], + ]; + } + private function createTokenMatcherClassName(): string { static $nextMatcherClassIndex = 1;
Unicode: bug fixed in char buffer
remorhaz_php-unilex
train
61b083de3c43f86f152c810ddf888c5dad073165
diff --git a/sos/report/plugins/candlepin.py b/sos/report/plugins/candlepin.py index <HASH>..<HASH> 100644 --- a/sos/report/plugins/candlepin.py +++ b/sos/report/plugins/candlepin.py @@ -58,6 +58,7 @@ class Candlepin(Plugin, RedHatPlugin): # Allow limiting on logrotated logs self.add_copy_spec([ "/etc/candlepin/candlepin.conf", + "/etc/candlepin/broker.xml", "/var/log/candlepin/audit*.log*", "/var/log/candlepin/candlepin.log[.-]*", "/var/log/candlepin/cpdb*.log*", @@ -110,5 +111,9 @@ class Candlepin(Plugin, RedHatPlugin): self.do_file_sub("/etc/candlepin/candlepin.conf", reg, repl) cpdbreg = r"(--password=)([a-zA-Z0-9]*)" self.do_file_sub("/var/log/candlepin/cpdb.log", cpdbreg, repl) + for key in ["trustStorePassword", "keyStorePassword"]: + self.do_file_sub("/etc/candlepin/broker.xml", + r"%s=(\w*)([;<])" % key, + r"%s=********\2" % key) # vim: set et ts=4 sw=4 :
[candlepin] collect /etc/candlepin/broker.xml The file contains important config about internal candlepin broker routing. Also, apply scrubbing of two passwords on a single line / in one URI. Resolves: #<I>
sosreport_sos
train
055fc09ae582bc0ff70e7eeadf8df71d3631777a
diff --git a/android/lib/src/main/java/com/swmansion/gesturehandler/PanGestureHandler.java b/android/lib/src/main/java/com/swmansion/gesturehandler/PanGestureHandler.java index <HASH>..<HASH> 100644 --- a/android/lib/src/main/java/com/swmansion/gesturehandler/PanGestureHandler.java +++ b/android/lib/src/main/java/com/swmansion/gesturehandler/PanGestureHandler.java @@ -41,33 +41,49 @@ public class PanGestureHandler extends GestureHandler<PanGestureHandler> { */ private static float getLastPointerX(MotionEvent event, boolean averageTouches) { float offset = event.getRawX() - event.getX(); + int excludeIndex = event.getActionMasked() == MotionEvent.ACTION_POINTER_UP ? + event.getActionIndex() : -1; if (averageTouches) { float sum = 0f; - int count = event.getPointerCount(); - for (int i = 0; i < count; i++) { - sum += event.getX(i) + offset; + int count = 0; + for (int i = 0, size = event.getPointerCount(); i < size; i++) { + if (i != excludeIndex) { + sum += event.getX(i) + offset; + count++; + } } return sum / count; } else { - int last = event.getActionMasked() == MotionEvent.ACTION_POINTER_UP ? 2 : 1; - return event.getX(event.getPointerCount() - last) + offset; + int lastPointerIdx = event.getPointerCount() - 1; + if (lastPointerIdx == excludeIndex) { + lastPointerIdx--; + } + return event.getX(lastPointerIdx) + offset; } } private static float getLastPointerY(MotionEvent event, boolean averageTouches) { float offset = event.getRawY() - event.getY(); + int excludeIndex = event.getActionMasked() == MotionEvent.ACTION_POINTER_UP ? + event.getActionIndex() : -1; if (averageTouches) { float sum = 0f; - int count = event.getPointerCount(); - for (int i = 0; i < count; i++) { - sum += event.getY(i) + offset; + int count = 0; + for (int i = 0, size = event.getPointerCount(); i < size; i++) { + if (i != excludeIndex) { + sum += event.getY(i) + offset; + count++; + } } return sum / count; } else { - int last = event.getActionMasked() == MotionEvent.ACTION_POINTER_UP ? 2 : 1; - return event.getY(event.getPointerCount() - last) + offset; + int lastPointerIdx = event.getPointerCount() - 1; + if (lastPointerIdx == excludeIndex) { + lastPointerIdx -= 1; + } + return event.getY(lastPointerIdx) + offset; } }
Fix translation offset when number of pointers changes.
kmagiera_react-native-gesture-handler
train
65dedaaac276a4d24884d401cb897307a2528584
diff --git a/scrapy_dotpersistence.py b/scrapy_dotpersistence.py index <HASH>..<HASH> 100644 --- a/scrapy_dotpersistence.py +++ b/scrapy_dotpersistence.py @@ -37,8 +37,8 @@ class DotScrapyPersistence(object): 'AWS_ACCESS_KEY_ID': self.AWS_ACCESS_KEY_ID, 'AWS_SECRET_ACCESS_KEY': self.AWS_SECRET_ACCESS_KEY } - crawler.signals.connect(self._store_data, signals.engine_stopped) self._load_data() + crawler.signals.connect(self._store_data, signals.engine_stopped) def _load_data(self): if self._bucket_folder:
Don't sync data back unless it was loaded successfully Otherwise you risk corrupting stored data because of a temporary network glitch.
scrapy-plugins_scrapy-dotpersistence
train
5c2d8cff57bd6ef0fb27527c500a5c2203f53dd2
diff --git a/src/chart/bar/BarView.js b/src/chart/bar/BarView.js index <HASH>..<HASH> 100644 --- a/src/chart/bar/BarView.js +++ b/src/chart/bar/BarView.js @@ -96,7 +96,7 @@ export default echarts.extendChartView({ var coordSysClipArea = coord.getArea && coord.getArea(); - var needsClip = seriesModel.get('clip'); + var needsClip = seriesModel.get('clip', true); // If there is clipPath created in large mode. Remove it. group.removeClipPath(); @@ -189,7 +189,7 @@ export default echarts.extendChartView({ createLarge(seriesModel, this.group); // Use clipPath in large mode. - var clipPath = seriesModel.get('clip') + var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null; if (clipPath) { diff --git a/src/chart/custom.js b/src/chart/custom.js index <HASH>..<HASH> 100644 --- a/src/chart/custom.js +++ b/src/chart/custom.js @@ -167,7 +167,7 @@ ChartView.extend({ .execute(); // Do clipping - var clipPath = customSeries.get('clip') + var clipPath = customSeries.get('clip', true) ? createClipPath(customSeries.coordinateSystem, false, customSeries) : null; if (clipPath) { diff --git a/src/chart/line/LineView.js b/src/chart/line/LineView.js index <HASH>..<HASH> 100644 --- a/src/chart/line/LineView.js +++ b/src/chart/line/LineView.js @@ -269,7 +269,7 @@ function createLineClipPath(coordSys, hasAnimation, seriesModel) { var isHorizontal = coordSys.getBaseAxis().isHorizontal(); var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel); // Expand clip shape to avoid clipping when line value exceeds axis - if (!seriesModel.get('clip')) { + if (!seriesModel.get('clip', true)) { var rectShape = clipPath.shape; var expandSize = Math.max(rectShape.width, rectShape.height); if (isHorizontal) { diff --git a/src/chart/lines/LinesView.js b/src/chart/lines/LinesView.js index <HASH>..<HASH> 100644 --- a/src/chart/lines/LinesView.js +++ b/src/chart/lines/LinesView.js @@ -77,7 +77,7 @@ export default echarts.extendChartView({ lineDraw.updateData(data); - var clipPath = seriesModel.get('clip') && createClipPath( + var clipPath = seriesModel.get('clip', true) && createClipPath( seriesModel.coordinateSystem, false, seriesModel ); if (clipPath) { diff --git a/src/chart/scatter/ScatterView.js b/src/chart/scatter/ScatterView.js index <HASH>..<HASH> 100644 --- a/src/chart/scatter/ScatterView.js +++ b/src/chart/scatter/ScatterView.js @@ -84,7 +84,7 @@ echarts.extendChartView({ _getClipShape: function (seriesModel) { var coordSys = seriesModel.coordinateSystem; var clipArea = coordSys && coordSys.getArea && coordSys.getArea(); - return seriesModel.get('clip') ? clipArea : null; + return seriesModel.get('clip', true) ? clipArea : null; }, _updateSymbolDraw: function (data, seriesModel) {
fix(clip): only access clip option in series.
apache_incubator-echarts
train
2eee4f13951b66a731fb146aa077b62e9de6c2c1
diff --git a/modules/kueezBidAdapter.js b/modules/kueezBidAdapter.js index <HASH>..<HASH> 100644 --- a/modules/kueezBidAdapter.js +++ b/modules/kueezBidAdapter.js @@ -244,6 +244,7 @@ function generateBidParameters(bid, bidderRequest) { const bidObject = { adUnitCode: getBidIdParameter('adUnitCode', bid), bidId: getBidIdParameter('bidId', bid), + loop: getBidIdParameter('bidderRequestsCount', bid), bidderRequestId: getBidIdParameter('bidderRequestId', bid), floorPrice: Math.max(getFloorPrice(bid, mediaType), paramsFloorPrice), mediaType, diff --git a/test/spec/modules/kueezBidAdapter_spec.js b/test/spec/modules/kueezBidAdapter_spec.js index <HASH>..<HASH> 100644 --- a/test/spec/modules/kueezBidAdapter_spec.js +++ b/test/spec/modules/kueezBidAdapter_spec.js @@ -53,6 +53,7 @@ describe('kueezBidAdapter', function () { 'org': 'test-publisher-id' }, 'bidId': '5wfg9887sd5478', + 'loop': 1, 'bidderRequestId': 'op87952ewq8567', 'auctionId': '87se98rt-5789-8735-2546-t98yh5678231', 'mediaTypes': { @@ -71,6 +72,7 @@ describe('kueezBidAdapter', function () { 'org': 'test-publisher-id' }, 'bidId': '5wfg9887sd5478', + 'loop': 1, 'bidderRequestId': 'op87952ewq8567', 'auctionId': '87se98rt-5789-8735-2546-t98yh5678231', 'mediaTypes': { @@ -91,6 +93,7 @@ describe('kueezBidAdapter', function () { 'testMode': true }, 'bidId': '5wfg9887sd5478', + 'loop': 2, 'bidderRequestId': 'op87952ewq8567', 'auctionId': '87se98rt-5789-8735-2546-t98yh5678231', }
added logic to detect the loop number (#<I>)
prebid_Prebid.js
train
1a47a28a437d30db2134a27a5b8b3c618e762f07
diff --git a/ArgusClient/src/main/java/com/salesforce/dva/argus/client/Alerter.java b/ArgusClient/src/main/java/com/salesforce/dva/argus/client/Alerter.java index <HASH>..<HASH> 100644 --- a/ArgusClient/src/main/java/com/salesforce/dva/argus/client/Alerter.java +++ b/ArgusClient/src/main/java/com/salesforce/dva/argus/client/Alerter.java @@ -46,7 +46,7 @@ class Alerter implements Runnable { //~ Static fields/initializers ******************************************************************************************************************* - private static final long POLL_INTERVAL_MS = 100; + private static final long POLL_INTERVAL_MS = 500; private static final Logger LOGGER = LoggerFactory.getLogger(Alerter.class); //~ Instance fields ****************************************************************************************************************************** @@ -76,7 +76,7 @@ class Alerter implements Runnable { public void run() { while (!Thread.currentThread().isInterrupted()) { try { - jobCounter.addAndGet(service.executeScheduledAlerts(10, timeout).size()); + jobCounter.addAndGet(service.executeScheduledAlerts(50, timeout).size()); LOGGER.info("alerts evaluated so far: {}", jobCounter.get()); Thread.sleep(POLL_INTERVAL_MS); } catch (InterruptedException ex) {
Dequeue more alerts in a single batch.
salesforce_Argus
train
fce6c1c342bb196303ae023fe18239df1c848209
diff --git a/treeherder/model/derived/artifacts.py b/treeherder/model/derived/artifacts.py index <HASH>..<HASH> 100644 --- a/treeherder/model/derived/artifacts.py +++ b/treeherder/model/derived/artifacts.py @@ -111,8 +111,12 @@ class ArtifactsModel(TreeherderModelBase): for perf_data in performance_artifact_placeholders: job_guid = perf_data["job_guid"] ref_data_signature = job_data[job_guid]['signature'] + # FIXME: I think this could theoretically fail, as we + # allow signature and repository to be the same as long + # as we have different build system type and/or name ref_data = model_to_dict(ReferenceDataSignatures.objects.get( - signature=ref_data_signature)) + signature=ref_data_signature, + repository=self.project)) # adapt and load data into placeholder structures if perf_data['name'] == 'talos_data':
Bug <I> - Fix performance artifact ingestion We weren't taking the repository into account when getting the reference data signature.
mozilla_treeherder
train
899de434e244ab063b97446159ba4da796f57312
diff --git a/src/storage/FileStorage.php b/src/storage/FileStorage.php index <HASH>..<HASH> 100644 --- a/src/storage/FileStorage.php +++ b/src/storage/FileStorage.php @@ -86,7 +86,7 @@ class FileStorage extends BaseObject implements StorageInterface return true; } $error = error_get_last(); - Yii::warning("Unable to write file '{$file}': {$error['message']}", __METHOD__); + Yii::error("Unable to write file '{$file}': {$error['message']}"); return false; } diff --git a/src/storage/PhpFileStorage.php b/src/storage/PhpFileStorage.php index <HASH>..<HASH> 100644 --- a/src/storage/PhpFileStorage.php +++ b/src/storage/PhpFileStorage.php @@ -10,6 +10,10 @@ namespace lav45\settings\storage; use yii\helpers\VarDumper; +/** + * Class PhpFileStorage + * @package lav45\settings\storage + */ class PhpFileStorage extends FileStorage { /** diff --git a/tests/tests/storage/FileStorageTest.php b/tests/tests/storage/FileStorageTest.php index <HASH>..<HASH> 100644 --- a/tests/tests/storage/FileStorageTest.php +++ b/tests/tests/storage/FileStorageTest.php @@ -18,7 +18,7 @@ class FileStorageTest extends TestCase { $storage = $this->getStorage(); - $key = md5(uniqid()); + $key = md5(uniqid('', false)); $value = 'a:1:{s:13:"template";s:1:"1";}'; chmod($storage->path, 0444); @@ -29,7 +29,7 @@ class FileStorageTest extends TestCase $message = array_pop(Yii::getLogger()->messages); - $this->assertEquals('lav45\settings\storage\FileStorage::setValue', $message[2]); + $this->assertEquals('application', $message[2]); $this->assertStringEndsWith('Permission denied', $message[0]); } } \ No newline at end of file
Update error category for FileStorage
lav45_yii2-settings
train
d6c8074c0cbcdeeefac3ccd877ba0d6b37df0154
diff --git a/test/server/api/index.spec.js b/test/server/api/index.spec.js index <HASH>..<HASH> 100644 --- a/test/server/api/index.spec.js +++ b/test/server/api/index.spec.js @@ -2115,7 +2115,10 @@ describe('API', function () { function (done) { var requestBody = { pluginId: 'ExportImport', - projectId: importResult.project.projectId + projectId: importResult.project.projectId, + pluginConfig: { + type: 'Import' + } }; agent.post(server.getUrl() + '/api/v1/plugins/ExportImport/execute') .send(requestBody)
#<I> Make the time-outing plugin test, fail and return immediately. Former-commit-id: bf4e<I>a<I>f5c<I>eba<I>cbd<I>ebf3c<I>
webgme_webgme-engine
train
9a91222e30920a02cca1a76ce1fa66bdece6ffd8
diff --git a/lib/lotus/utils/load_paths.rb b/lib/lotus/utils/load_paths.rb index <HASH>..<HASH> 100644 --- a/lib/lotus/utils/load_paths.rb +++ b/lib/lotus/utils/load_paths.rb @@ -37,6 +37,53 @@ module Lotus blk.call Utils::Kernel.Pathname(path).realpath end end + + # Adds the given path(s). + # + # It returns self, so that multiple operations can be performed. + # + # @param paths [String, Pathname, Array<String>, Array<Pathname>] A single + # or a collection of objects that can be converted into a Pathname + # + # @return [Lotus::Utils::LoadPaths] self + # + # @since 0.2.0 + # + # @see http://ruby-doc.org/stdlib-2.1.2/libdoc/pathname/rdoc/Pathname.html + # @see Lotus::Utils::Kernel.Pathname + # + # @example Basic usage + # require 'lotus/utils/load_paths' + # + # paths = Lotus::Utils::LoadPaths.new + # paths.push '.' + # paths.push '..', '../..' + # + # @example Chainable calls + # require 'lotus/utils/load_paths' + # + # paths = Lotus::Utils::LoadPaths.new + # paths.push('.') + # .push('..', '../..') + # + # @example Shovel alias (#<<) + # require 'lotus/utils/load_paths' + # + # paths = Lotus::Utils::LoadPaths.new + # paths << '.' + # paths << ['..', '../..'] + # + # @example Chainable calls with shovel alias (#<<) + # require 'lotus/utils/load_paths' + # + # paths = Lotus::Utils::LoadPaths.new + # paths << '.' << '../..' + def push(*paths) + @paths.push(*paths) + self + end + + alias_method :<<, :push end end end diff --git a/test/load_paths_test.rb b/test/load_paths_test.rb index <HASH>..<HASH> 100644 --- a/test/load_paths_test.rb +++ b/test/load_paths_test.rb @@ -52,4 +52,66 @@ describe Lotus::Utils::LoadPaths do }.must_raise Errno::ENOENT end end + + describe '#push' do + it 'adds the given path' do + paths = Lotus::Utils::LoadPaths.new '.' + paths.push '..' + + paths.must_include '.' + paths.must_include '..' + end + + it 'adds the given paths' do + paths = Lotus::Utils::LoadPaths.new '.' + paths.push '..', '../..' + + paths.must_include '.' + paths.must_include '..' + paths.must_include '../..' + end + + it 'returns self so multiple operations can be performed' do + paths = Lotus::Utils::LoadPaths.new + + returning = paths.push('.') + returning.must_be_same_as(paths) + + paths.push('..').push('../..') + + paths.must_include '.' + paths.must_include '..' + paths.must_include '../..' + end + end + + describe '#<< (alias of #push)' do + it 'adds the given path' do + paths = Lotus::Utils::LoadPaths.new '.' + paths << '..' + + paths.must_include '.' + paths.must_include '..' + end + + it 'adds the given paths' do + paths = Lotus::Utils::LoadPaths.new '.' + paths << ['..', '../..'] + + paths.must_include ['..', '../..'] + end + + it 'returns self so multiple operations can be performed' do + paths = Lotus::Utils::LoadPaths.new + + returning = paths << '.' + returning.must_be_same_as(paths) + + paths << '..' << '../..' + + paths.must_include '.' + paths.must_include '..' + paths.must_include '../..' + end + end end
Implemented Lotus::Utils::LoadPaths#push, also aliased as #<<
hanami_utils
train
9a7b23440f5dd8972fe619da5e6fc8f51beaaa0b
diff --git a/physical/dynamodb/dynamodb.go b/physical/dynamodb/dynamodb.go index <HASH>..<HASH> 100644 --- a/physical/dynamodb/dynamodb.go +++ b/physical/dynamodb/dynamodb.go @@ -500,7 +500,7 @@ func (d *DynamoDBBackend) HAEnabled() bool { func (d *DynamoDBBackend) batchWriteRequests(requests []*dynamodb.WriteRequest) error { for len(requests) > 0 { batchSize := int(math.Min(float64(len(requests)), 25)) - batch := map[string][]*dynamodb.WriteRequest{ d.table: requests[:batchSize] } + batch := map[string][]*dynamodb.WriteRequest{d.table: requests[:batchSize]} requests = requests[batchSize:] var err error @@ -511,19 +511,20 @@ func (d *DynamoDBBackend) batchWriteRequests(requests []*dynamodb.WriteRequest) boff.MaxElapsedTime = 600 * time.Second for len(batch) > 0 { - output, err := d.client.BatchWriteItem(&dynamodb.BatchWriteItemInput{ + var output *dynamodb.BatchWriteItemOutput + output, err = d.client.BatchWriteItem(&dynamodb.BatchWriteItemInput{ RequestItems: batch, }) - if err != nil{ + if err != nil { break } if len(output.UnprocessedItems) == 0 { break } else { - duration := boff.NextBackOff(); - if (duration != backoff.Stop) { + duration := boff.NextBackOff() + if duration != backoff.Stop { batch = output.UnprocessedItems time.Sleep(duration) } else {
Fix err shadowing (#<I>)
hashicorp_vault
train
ab6ff133ad17398d4b95a0c7bf9346a167ccd72c
diff --git a/h2o-samples/src/main/java/samples/LoadDatasets.java b/h2o-samples/src/main/java/samples/LoadDatasets.java index <HASH>..<HASH> 100644 --- a/h2o-samples/src/main/java/samples/LoadDatasets.java +++ b/h2o-samples/src/main/java/samples/LoadDatasets.java @@ -18,8 +18,12 @@ public class LoadDatasets extends Job { } void load() { + TestUtil.parseFromH2OFolder("smalldata/./logreg/prostate.csv"); TestUtil.parseFromH2OFolder("smalldata/./mnist/test.csv.gz"); TestUtil.parseFromH2OFolder("smalldata/./mnist/train.csv.gz"); + TestUtil.parseFromH2OFolder("smalldata/./cars.csv"); + TestUtil.parseFromH2OFolder("smalldata/./iris/iris.csv"); + TestUtil.parseFromH2OFolder("smalldata/./covtype/covtype.20k.data"); TestUtil.parseFromH2OFolder("smalldata/./1_100kx7_logreg.data.gz"); TestUtil.parseFromH2OFolder("smalldata/./2_100kx7_logreg.data.gz"); TestUtil.parseFromH2OFolder("smalldata/./AID362red_test.csv.gz"); @@ -39,7 +43,6 @@ public class LoadDatasets extends Job { TestUtil.parseFromH2OFolder("smalldata/./auto.csv"); TestUtil.parseFromH2OFolder("smalldata/./badchars.csv"); TestUtil.parseFromH2OFolder("smalldata/./baddata.data"); - TestUtil.parseFromH2OFolder("smalldata/./cars.csv"); TestUtil.parseFromH2OFolder("smalldata/./categoricals/30k_categoricals.csv.gz"); TestUtil.parseFromH2OFolder("smalldata/./categoricals/40k_categoricals.csv.gz"); TestUtil.parseFromH2OFolder("smalldata/./categoricals/AllBedrooms_Rent_Neighborhoods.csv.gz"); @@ -88,7 +91,6 @@ public class LoadDatasets extends Job { TestUtil.parseFromH2OFolder("smalldata/./chess/chess_2x2x500/weka/test.csv.arff"); TestUtil.parseFromH2OFolder("smalldata/./chess/chess_2x2x500/weka/train.csv.arff"); TestUtil.parseFromH2OFolder("smalldata/./constantColumn.csv"); - TestUtil.parseFromH2OFolder("smalldata/./covtype/covtype.20k.data"); TestUtil.parseFromH2OFolder("smalldata/./cuse.data.csv"); TestUtil.parseFromH2OFolder("smalldata/./cusedataREADME.rtf"); TestUtil.parseFromH2OFolder("smalldata/./cuseexpanded.csv"); @@ -110,7 +112,6 @@ public class LoadDatasets extends Job { TestUtil.parseFromH2OFolder("smalldata/./hhp.cut3.214.data.gz"); TestUtil.parseFromH2OFolder("smalldata/./hhp_107_01.data.gz"); TestUtil.parseFromH2OFolder("smalldata/./hhp_9_17_12.predict.data.gz"); - TestUtil.parseFromH2OFolder("smalldata/./iris/iris.csv"); TestUtil.parseFromH2OFolder("smalldata/./iris/iris.csv.gz"); TestUtil.parseFromH2OFolder("smalldata/./iris/iris.csv.zip"); TestUtil.parseFromH2OFolder("smalldata/./iris/iris.xls"); @@ -141,7 +142,6 @@ public class LoadDatasets extends Job { TestUtil.parseFromH2OFolder("smalldata/./logreg/princeton/cuse.dat"); TestUtil.parseFromH2OFolder("smalldata/./logreg/princeton/housing.raw"); TestUtil.parseFromH2OFolder("smalldata/./logreg/pros.xls"); - TestUtil.parseFromH2OFolder("smalldata/./logreg/prostate.csv"); TestUtil.parseFromH2OFolder("smalldata/./logreg/prostate_long.csv.gz"); TestUtil.parseFromH2OFolder("smalldata/./logreg/prostate_test.csv"); TestUtil.parseFromH2OFolder("smalldata/./logreg/prostate_train.csv");
Load frequently used datasets first.
h2oai_h2o-2
train
c0684d1d0cd4c25d13386ac017839cfc9c26c765
diff --git a/src/Frozennode/Administrator/AdministratorServiceProvider.php b/src/Frozennode/Administrator/AdministratorServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/Frozennode/Administrator/AdministratorServiceProvider.php +++ b/src/Frozennode/Administrator/AdministratorServiceProvider.php @@ -30,7 +30,9 @@ class AdministratorServiceProvider extends ServiceProvider { //make sure the Laravel Validator is using our custom Validator that we can pass to various constructors LValidator::resolver(function($translator, $data, $rules, $messages) { - return new \Frozennode\Administrator\Validator($translator, $data, $rules, $messages); + $validator = new \Frozennode\Administrator\Validator($translator, $data, $rules, $messages); + $validator->setUrlInstance(\App::make('url')); + return $validator; }); //set up the shared instances
making sure the validator's uri instance is set up
FrozenNode_Laravel-Administrator
train
fbebec784b4b0dec433e045bfd11ed92c4a3d18c
diff --git a/aws.js b/aws.js index <HASH>..<HASH> 100644 --- a/aws.js +++ b/aws.js @@ -638,7 +638,7 @@ aws.ec2DeregisterImage = function(ami_id, options, callback) core.forEachSeries(volumes, function(vol, next) { if (!vol.ebs || !vol.ebs.snapshotId) return next(); - self.queryEC2("DeleteSnapshot", { snapshotId: vol.ebs.snapshotId }, next); + self.queryEC2("DeleteSnapshot", { SnapshotId: vol.ebs.snapshotId }, next); }, callback) }); }); diff --git a/core.js b/core.js index <HASH>..<HASH> 100644 --- a/core.js +++ b/core.js @@ -2785,6 +2785,11 @@ core.mergeObj = function(obj, options) } // Flatten a javascript object into a single-depth object, all nested values will have property names appended separated by comma +// +// Example +// +// > core.flattenObj({ a: { c: 1 }, b: { d: 1 } } ) +// { 'a.c': 1, 'b.d': 1 } core.flattenObj = function(obj, options) { var rc = {}; @@ -2863,9 +2868,10 @@ core.searchObj = function(obj, options) // // Example: // -// core.objGet({ response: { item : { id: 123, name: "Test" } } }, "response.item.name") -// core.objGet({ response: { item : { id: 123, name: "Test" } } }, "response.item.name", { list: 1 }) -// +// > core.objGet({ response: { item : { id: 123, name: "Test" } } }, "response.item.name") +// "Test" +// > core.objGet({ response: { item : { id: 123, name: "Test" } } }, "response.item.name", { list: 1 }) +// [ "Test" ] core.objGet = function(obj, name, options) { if (!obj) return options ? (options.list ? [] : options.obj ? {} : options.str ? "" : options.num ? 0 : null) : null; @@ -2916,7 +2922,7 @@ core.objSet = function(obj, name, value, options) return v; } -// JSON stringify without exceptions, on error return empty string +// JSON stringify without exceptions, on error just returns an empty string and logs the error core.stringify = function(obj, filter) { try { return JSON.stringify(obj, filter); } catch(e) { logger.error("stringify:", e); return "" } diff --git a/web/doc.html b/web/doc.html index <HASH>..<HASH> 100644 --- a/web/doc.html +++ b/web/doc.html @@ -4570,7 +4570,10 @@ or an object with message, code, status, and name properties to build full error <ul> <li><p><code>core.flattenObj(obj, options)</code></p> <p> Flatten a javascript object into a single-depth object, all nested values will have property names appended separated by comma</p> -</li> +<p>Example</p> +<pre><code> &gt; core.flattenObj({ a: { c: 1 }, b: { d: 1 } } ) + { &#39;a.c&#39;: 1, &#39;b.d&#39;: 1 } +</code></pre></li> </ul> <ul> @@ -4614,8 +4617,10 @@ Options may contains the following properties:</p> <li>num - return the value as a number, convert any other type by using toNumber</li> </ul> <p>Example:</p> -<pre><code> core.objGet({ response: { item : { id: 123, name: &quot;Test&quot; } } }, &quot;response.item.name&quot;) - core.objGet({ response: { item : { id: 123, name: &quot;Test&quot; } } }, &quot;response.item.name&quot;, { list: 1 }) +<pre><code> &gt; core.objGet({ response: { item : { id: 123, name: &quot;Test&quot; } } }, &quot;response.item.name&quot;) + &quot;Test&quot; + &gt; core.objGet({ response: { item : { id: 123, name: &quot;Test&quot; } } }, &quot;response.item.name&quot;, { list: 1 }) + [ &quot;Test&quot; ] </code></pre></li> </ul> @@ -4635,7 +4640,7 @@ objects will be create automatically. The options can have the folowing properti <ul> <li><p><code>core.stringify(obj, filter)</code></p> -<p> JSON stringify without exceptions, on error return empty string</p> +<p> JSON stringify without exceptions, on error just returns an empty string and logs the error</p> </li> </ul>
Updated docs, minor bugfixes
vseryakov_backendjs
train
f712fec100c76ded8f09efa587796faeb4f64794
diff --git a/rest-api/src/main/java/org/jboss/pnc/rest/configuration/SwaggerConstants.java b/rest-api/src/main/java/org/jboss/pnc/rest/configuration/SwaggerConstants.java index <HASH>..<HASH> 100644 --- a/rest-api/src/main/java/org/jboss/pnc/rest/configuration/SwaggerConstants.java +++ b/rest-api/src/main/java/org/jboss/pnc/rest/configuration/SwaggerConstants.java @@ -76,7 +76,7 @@ public interface SwaggerConstants { + "the Maitai process instance creating the repository ('buildConfig' key is null)"; public static final String TEMPORARY_BUILD_DESC = "Is it a temporary build or a standard build?"; - public static final String TIMESTAMP_ALIGNMENT_DESC = "Should we add a timestamp during the alignment? Valid only for temporary builds."; + public static final String TIMESTAMP_ALIGNMENT_DESC = "This feature was disabled. Setting this value has no effect on the build."; public static final String REBUILD_MODE_DESC = "What should varant rebuild?"; public static final String DEFAULT_REBUILD_MODE = "IMPLICIT_DEPENDENCY_CHECK"; public static final String BUILD_DEPENDENCIES_DESC = "Should we build also dependencies of this Build Config?"; diff --git a/rest/src/main/java/org/jboss/pnc/rest/endpoints/BuildConfigurationEndpointImpl.java b/rest/src/main/java/org/jboss/pnc/rest/endpoints/BuildConfigurationEndpointImpl.java index <HASH>..<HASH> 100644 --- a/rest/src/main/java/org/jboss/pnc/rest/endpoints/BuildConfigurationEndpointImpl.java +++ b/rest/src/main/java/org/jboss/pnc/rest/endpoints/BuildConfigurationEndpointImpl.java @@ -309,7 +309,7 @@ public class BuildConfigurationEndpointImpl implements BuildConfigurationEndpoin buildParams.isTemporaryBuild(), buildParams.isBuildDependencies(), buildParams.isKeepPodOnFailure(), - buildParams.isTimestampAlignment(), + false, buildParams.getRebuildMode()); checkBuildOptionsValidity(buildOptions); return buildOptions; diff --git a/rest/src/main/java/org/jboss/pnc/rest/endpoints/GroupConfigurationEndpointImpl.java b/rest/src/main/java/org/jboss/pnc/rest/endpoints/GroupConfigurationEndpointImpl.java index <HASH>..<HASH> 100644 --- a/rest/src/main/java/org/jboss/pnc/rest/endpoints/GroupConfigurationEndpointImpl.java +++ b/rest/src/main/java/org/jboss/pnc/rest/endpoints/GroupConfigurationEndpointImpl.java @@ -171,7 +171,7 @@ public class GroupConfigurationEndpointImpl implements GroupConfigurationEndpoin buildParams.isTemporaryBuild(), false, false, - buildParams.isTimestampAlignment(), + false, buildParams.getRebuildMode()); checkBuildOptionsValidity(buildOptions); return buildOptions; diff --git a/spi/src/main/java/org/jboss/pnc/spi/BuildOptions.java b/spi/src/main/java/org/jboss/pnc/spi/BuildOptions.java index <HASH>..<HASH> 100644 --- a/spi/src/main/java/org/jboss/pnc/spi/BuildOptions.java +++ b/spi/src/main/java/org/jboss/pnc/spi/BuildOptions.java @@ -67,4 +67,8 @@ public class BuildOptions { public boolean isForceRebuild() { return RebuildMode.FORCE.equals(rebuildMode); } + + public boolean isTimestampAlignment() { + return false; + } }
[NCL-<I>] [NCL-<I>]: Deprecate option to build temporary builds with timestamp alignment
project-ncl_pnc
train
f4d18417232bccab46cf87658a22786c1ff9ba63
diff --git a/packages/@vue/cli-plugin-e2e-nightwatch/generator/template/test/e2e/custom-assertions/elementCount.js b/packages/@vue/cli-plugin-e2e-nightwatch/generator/template/test/e2e/custom-assertions/elementCount.js index <HASH>..<HASH> 100644 --- a/packages/@vue/cli-plugin-e2e-nightwatch/generator/template/test/e2e/custom-assertions/elementCount.js +++ b/packages/@vue/cli-plugin-e2e-nightwatch/generator/template/test/e2e/custom-assertions/elementCount.js @@ -7,12 +7,13 @@ // For more information on custom assertions see: // http://nightwatchjs.org/guide#writing-custom-assertions -exports.assertion = function (selector, count) { +exports.assertion = function elementCount (selector, count) { this.message = `Testing if element <${selector}> has count: ${count}` this.expected = count this.pass = val => val === count this.value = res => res.value - this.command = cb => this.api.execute(function (selector) { - return document.querySelectorAll(selector).length - }, [selector], cb) + function evaluator (_selector) { + return document.querySelectorAll(_selector).length + } + this.command = cb => this.api.execute(evaluator, [selector], cb) }
fix: nightwatch helper compat with airbnb linter close #<I>
vuejs_vue-cli
train
2d7c0b043047b9a4c59bb260c9fa6b508f9a72a0
diff --git a/moco-core/src/main/java/com/github/dreamhead/moco/internal/MocoSocketServer.java b/moco-core/src/main/java/com/github/dreamhead/moco/internal/MocoSocketServer.java index <HASH>..<HASH> 100644 --- a/moco-core/src/main/java/com/github/dreamhead/moco/internal/MocoSocketServer.java +++ b/moco-core/src/main/java/com/github/dreamhead/moco/internal/MocoSocketServer.java @@ -5,7 +5,7 @@ import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; -public class MocoSocketServer extends BaseServerRunner<SocketResponseSetting, ActualSocketServer> { +public final class MocoSocketServer extends BaseServerRunner<SocketResponseSetting, ActualSocketServer> { private final ActualSocketServer serverSetting; public MocoSocketServer(final ActualSocketServer serverSetting) {
added missing final to moco socket server
dreamhead_moco
train
be2c3455f1da7eed17f7a8c9efa1f138bc8cc3f4
diff --git a/tests/hdx/utilities/test_dateparse.py b/tests/hdx/utilities/test_dateparse.py index <HASH>..<HASH> 100755 --- a/tests/hdx/utilities/test_dateparse.py +++ b/tests/hdx/utilities/test_dateparse.py @@ -73,10 +73,6 @@ class TestDateParse: parse_date('02/2013', '%m/%Y') def test_get_datetime_from_timestamp(self): - expected_date = datetime(2020, 7, 31, 7, 33, 54) - expected_timestamp = 1596173634.0 - timestamp = get_timestamp_from_datetime(expected_date) - assert timestamp == expected_timestamp expected_timestamp = 1596180834.0 expected_date = datetime(2020, 7, 31, 7, 33, 54, tzinfo=tzutc()) timestamp = get_timestamp_from_datetime(expected_date)
timestamp fns for Python2 compatibility
OCHA-DAP_hdx-python-utilities
train
b474d14059728d41705322b63a616982090833b3
diff --git a/src/basic.js b/src/basic.js index <HASH>..<HASH> 100644 --- a/src/basic.js +++ b/src/basic.js @@ -16,9 +16,9 @@ class Basic extends Permit { } check(req) { - const { query } = this + const { query, proxy } = this const auth = req.headers - ? req.headers.authorization || req.headers['proxy-authorization'] + ? proxy ? req.headers['proxy-authorization'] : req.headers.authorization : null if (auth) { diff --git a/src/bearer.js b/src/bearer.js index <HASH>..<HASH> 100644 --- a/src/bearer.js +++ b/src/bearer.js @@ -17,9 +17,9 @@ class Bearer extends Permit { } check(req) { - const { basic, query } = this + const { basic, query, proxy } = this const auth = req.headers - ? req.headers.authorization || req.headers['proxy-authorization'] + ? proxy ? req.headers['proxy-authorization'] : req.headers.authorization : null if (auth) { diff --git a/src/permit.js b/src/permit.js index <HASH>..<HASH> 100644 --- a/src/permit.js +++ b/src/permit.js @@ -6,9 +6,10 @@ class Permit { constructor(options = {}) { - const { scheme, realm = 'auth' } = options + const { scheme, proxy, realm = 'auth' } = options this.scheme = scheme this.realm = realm + this.proxy = proxy } check() { @@ -16,13 +17,13 @@ class Permit { } fail(res) { - const { scheme, realm } = this + const { proxy, realm, scheme } = this const schemes = Array.isArray(scheme) ? scheme : [scheme] res.statusCode = 401 schemes.forEach(s => { - const header = `${s} realm="${realm}"` - res.setHeader('www-authenticate', header) - res.setHeader('proxy-authenticate', header) + const value = `${s} realm="${realm}"` + const key = proxy ? 'proxy-authenticate' : 'www-authenticate' + res.setHeader(key, value) }) } }
fix proxy to be behind a flag
ianstormtaylor_permit
train
b40c8896323dac22a4ddc069b8180091fffc9d69
diff --git a/jbpm-designer-client/src/main/java/org/jbpm/designer/client/popup/AssignmentListItemWidget.java b/jbpm-designer-client/src/main/java/org/jbpm/designer/client/popup/AssignmentListItemWidget.java index <HASH>..<HASH> 100644 --- a/jbpm-designer-client/src/main/java/org/jbpm/designer/client/popup/AssignmentListItemWidget.java +++ b/jbpm-designer-client/src/main/java/org/jbpm/designer/client/popup/AssignmentListItemWidget.java @@ -32,6 +32,8 @@ import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; +import com.google.gwt.event.dom.client.KeyDownEvent; +import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.text.shared.Renderer; @@ -327,6 +329,23 @@ public class AssignmentListItemWidget extends Composite implements HasModel<Assi } }); + name.addKeyDownHandler(new KeyDownHandler() { + @Override public void onKeyDown(KeyDownEvent event) { + int iChar = event.getNativeKeyCode(); + if (iChar == ' ') { + event.preventDefault(); + } + } + }); + + customDataType.addKeyDownHandler(new KeyDownHandler() { + @Override public void onKeyDown(KeyDownEvent event) { + int iChar = event.getNativeKeyCode(); + if (iChar == ' ') { + event.preventDefault(); + } + } + }); } @PreDestroy
BZ<I> - prevent typing space character in name and custom datatype fields of DataIOEditor
kiegroup_jbpm-designer
train
0f48e398c306155fd53df4d2a66b45b8078342d1
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -35,11 +35,11 @@ function getReleaseFile(names,cb) { var index = 0 return function checkExists() { fs.stat(names[index],function(e,stat) { + if(names.length <= index) return cb(new Error("No file unique file found!")) if(e || !stat.isFile()) { index++ return checkExists() } - if(names.length <= index) return cb(new Error("No file unique file found!")) cb(null,names[index]) }) }
Ensure loop exists if no file is found.
retrohacker_getos
train
692134e2ee452aaeec7cfa5ddfc4b862ab4b8865
diff --git a/lib/milestoner/git/kit.rb b/lib/milestoner/git/kit.rb index <HASH>..<HASH> 100644 --- a/lib/milestoner/git/kit.rb +++ b/lib/milestoner/git/kit.rb @@ -4,16 +4,44 @@ module Milestoner module Git # A lightweight Git wrapper. class Kit + def initialize + @git_dir = File.join Dir.pwd, ".git" + end + def supported? - File.exist? File.join(Dir.pwd, ".git") + File.exist? git_dir end def commits? - system "git log > /dev/null 2>&1" + !shell("git log").empty? + end + + def push_tags + shell "git push --tags" + end + + def tagged? + !shell("git tag").empty? + end + + def tag_local? tag + shell("git tag --list #{tag}").match?(/\A#{tag}\Z/) + end + + def tag_remote? tag + shell("git ls-remote --tags origin #{tag}").match?(%r(.+tags\/#{tag}\Z)) end def remote? - system "git config remote.origin.url" + !shell("git config remote.origin.url").empty? + end + + private + + attr_reader :git_dir + + def shell command + String `#{command}` end end end diff --git a/spec/lib/milestoner/git/kit_spec.rb b/spec/lib/milestoner/git/kit_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/milestoner/git/kit_spec.rb +++ b/spec/lib/milestoner/git/kit_spec.rb @@ -6,7 +6,7 @@ RSpec.describe Milestoner::Git::Kit, :temp_dir do subject { described_class.new } let(:git_dir) { File.join temp_dir, ".git" } - describe "#git_supported?" do + describe "#supported?" do context "when .git directory exists" do before { FileUtils.mkdir_p git_dir } @@ -22,7 +22,7 @@ RSpec.describe Milestoner::Git::Kit, :temp_dir do end end - describe "#git_commits?" do + describe "#commits?" do context "when repository has commits", :git_repo do it "answers true" do Dir.chdir(git_repo_dir) { expect(subject.commits?).to eq(true) } @@ -38,7 +38,85 @@ RSpec.describe Milestoner::Git::Kit, :temp_dir do end end - describe "#git_remote?" do + describe "push_tags", :git_repo do + it "successfully pushes tags" do + allow(subject).to receive(:`).and_return("") + expect(subject.push_tags).to eq("") + end + + it "fails to push tags" do + allow(subject).to receive(:`).and_return("error") + expect(subject.push_tags).to eq("error") + end + end + + describe "#tagged?", :git_repo do + context "with exiting tags" do + it "answers true" do + Dir.chdir git_repo_dir do + `git tag v0.1.0` + expect(subject.tagged?).to eq(true) + end + end + end + + context "without existing tags" do + it "answers false" do + Dir.chdir git_repo_dir do + expect(subject.tagged?).to eq(false) + end + end + end + + context "with uninitialized repository" do + it "answers false" do + ClimateControl.modify GIT_DIR: temp_dir do + expect(subject.tagged?).to eq(false) + end + end + end + end + + describe "#tag_local?", :git_repo do + let(:tag) { "v0.1.0" } + + context "with matching tag" do + it "answers true" do + Dir.chdir(git_repo_dir) do + `git tag #{tag}` + expect(subject.tag_local?(tag)).to eq(true) + end + end + end + + context "without matching tag" do + it "answers false" do + Dir.chdir(git_repo_dir) do + expect(subject.tag_local?(tag)).to eq(false) + end + end + end + end + + describe "#tag_remote?", :git_repo do + context "with matching tag" do + it "answers true" do + Dir.chdir(git_repo_dir) do + expect(subject.tag_remote?("v1.0.0")).to eq(true) + end + end + end + + context "without matching tag" do + it "answers false" do + Dir.chdir(git_repo_dir) do + expect(subject.tag_remote?("v0.1.0")).to eq(false) + end + end + end + end + + describe "#remote?" do before { Dir.chdir(temp_dir) { `git init` } } context "when remote repository is defined" do
Added Git tag support. - Will be used by the `Tagger` object and keeps Git-related methods centralized within this class. - Refactored execution of Git commands so there is consistency in how the Git commands are executed and results answered.
bkuhlmann_milestoner
train
19b34f9476fbbefd7bcf8fb988bea1ce6f1f17d5
diff --git a/src/system/modules/metamodels/languages/it/tl_metamodel_rendersettings.php b/src/system/modules/metamodels/languages/it/tl_metamodel_rendersettings.php index <HASH>..<HASH> 100644 --- a/src/system/modules/metamodels/languages/it/tl_metamodel_rendersettings.php +++ b/src/system/modules/metamodels/languages/it/tl_metamodel_rendersettings.php @@ -8,7 +8,7 @@ * * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL * - * last-updated: 2013-06-23T00:12:30+02:00 + * last-updated: 2013-07-10T10:02:32+02:00 */ $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['additionalCss']['0'] = 'Ulteriori file CSS'; @@ -31,8 +31,8 @@ $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['formatOptions']['xhtml'] = ' $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['general_legend'] = 'Impostazioni generali'; $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['hideEmptyValues']['0'] = 'Nasconde i valori vuoti'; $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['hideEmptyValues']['1'] = 'Nasconde i valori vuoti sia nel backend che nel frontend.'; -$GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['hideLabels']['0'] = 'Nasconde i labels'; -$GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['hideLabels']['1'] = 'Nasconde i labels sia nel backend che nel frontend.'; +$GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['hideLabels']['0'] = 'Nascondi le etichette'; +$GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['hideLabels']['1'] = 'Nascondi le etichette sia nel backend che nel frontend.'; $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['isdefault']['0'] = 'È default'; $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['isdefault']['1'] = 'Determina che questa impostazione deve essere utilizzata come predefinito per il MetaModel di parent.'; $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['jumpTo']['0'] = 'Pagina JumpTo'; @@ -59,3 +59,4 @@ $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['title_legend'] = ' $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['tstamp']['0'] = 'Data di revisione'; $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['tstamp']['1'] = 'Data e ora dell\'ultima revisione.'; $GLOBALS['TL_LANG']['tl_metamodel_rendersettings']['view_legend'] = 'Visualizza le impostazioni'; +
Updated translations from transifex.
MetaModels_core
train
9ebb3fd7808ecac0c48b5f00c0cc5984d1bb7e9c
diff --git a/src/dropin.js b/src/dropin.js index <HASH>..<HASH> 100644 --- a/src/dropin.js +++ b/src/dropin.js @@ -699,10 +699,7 @@ Dropin.prototype.requestPaymentMethod = function (options) { options = options || {}; return this._mainView.requestPaymentMethod().then(function (payload) { - if (self._threeDSecure && - (payload.type === constants.paymentMethodTypes.card || - (payload.type === constants.paymentMethodTypes.googlePay && payload.details.isNetworkTokenized === false)) && - payload.liabilityShifted == null) { + if (self._shouldPerformThreeDSecureVerification(payload)) { self._mainView.showLoadingIndicator(); return self._threeDSecure.verify(payload, options.threeDSecure).then(function (newPayload) { @@ -732,6 +729,26 @@ Dropin.prototype.requestPaymentMethod = function (options) { }); }; +Dropin.prototype._shouldPerformThreeDSecureVerification = function (payload) { + if (!this._threeDSecure) { + return false; + } + + if (payload.liabilityShifted != null) { + return false; + } + + if (payload.type === constants.paymentMethodTypes.card) { + return true; + } + + if (payload.type === constants.paymentMethodTypes.googlePay && payload.details.isNetworkTokenized === false) { + return true; + } + + return false; +}; + Dropin.prototype._removeStylesheet = function () { var stylesheet = document.getElementById(constants.STYLESHEET_ID);
Refactor 3DS logic into new method
braintree_braintree-web-drop-in
train
0c30610fdc7642bd607752730721109b4af7aa80
diff --git a/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php b/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php index <HASH>..<HASH> 100644 --- a/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php +++ b/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php @@ -98,4 +98,43 @@ class DefaultPolicyTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expected, $selected); } + + public function testSelectAllProviders() + { + $this->markTestIncomplete(); + + $this->repo->addPackage($packageA = new MemoryPackage('A', '1.0')); + $this->repo->addPackage($packageB = new MemoryPackage('B', '2.0')); + + $packageA->setProvides(array(new Link('A', 'X', new VersionConstraint('==', '1.0'), 'provides'))); + $packageB->setProvides(array(new Link('B', 'X', new VersionConstraint('==', '1.0'), 'provides'))); + + $this->pool->addRepository($this->repo); + + $literals = array(new Literal($packageA, true), new Literal($packageB, true)); + $expected = $literals; + + $selected = $this->policy->selectPreferedPackages($this->pool, $this->repoInstalled, $literals); + + $this->assertEquals($expected, $selected); + } + + public function testSelectNonReplacingFromSameRepo() + { + $this->markTestIncomplete(); + + $this->repo->addPackage($packageA = new MemoryPackage('A', '1.0')); + $this->repo->addPackage($packageB = new MemoryPackage('B', '2.0')); + + $packageB->setReplaces(array(new Link('B', 'A', new VersionConstraint('==', '1.0'), 'replaces'))); + + $this->pool->addRepository($this->repo); + + $literals = array(new Literal($packageA, true), new Literal($packageB, true)); + $expected = array(new Literal($packageA, true)); + + $selected = $this->policy->selectPreferedPackages($this->pool, $this->repoInstalled, $literals); + + $this->assertEquals($expected, $selected); + } }
Complete the policy tests with provider and replacement tests
mothership-ec_composer
train
d0d3be3ee8333d38aac6a7b43b8ba6df4e9d32c8
diff --git a/src/sap.ui.table/src/sap/ui/table/AnalyticalTable.js b/src/sap.ui.table/src/sap/ui/table/AnalyticalTable.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.table/src/sap/ui/table/AnalyticalTable.js +++ b/src/sap.ui.table/src/sap/ui/table/AnalyticalTable.js @@ -361,9 +361,16 @@ sap.ui.define(['jquery.sap.global', './AnalyticalColumn', './Table', './TreeTabl if (!oBindingInfo.parameters.hasOwnProperty("sumOnTop")) { oBindingInfo.parameters.sumOnTop = this.getSumOnTop(); } + if (!oBindingInfo.parameters.hasOwnProperty("numberOfExpandedLevels")) { oBindingInfo.parameters.numberOfExpandedLevels = this.getNumberOfExpandedLevels(); } + + // The binding does not support the number of expanded levels to be bigger than the number of grouped columns. + if (oBindingInfo.parameters.numberOfExpandedLevels > this._aGroupedColumns.length) { + oBindingInfo.parameters.numberOfExpandedLevels = 0; + } + if (!oBindingInfo.parameters.hasOwnProperty("autoExpandMode")) { var sExpandMode = this.getAutoExpandMode(); if (sExpandMode != TreeAutoExpandMode.Bundled && sExpandMode != TreeAutoExpandMode.Sequential) { diff --git a/src/sap.ui.table/test/sap/ui/table/qunit/AnalyticalTable.qunit.js b/src/sap.ui.table/test/sap/ui/table/qunit/AnalyticalTable.qunit.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.table/test/sap/ui/table/qunit/AnalyticalTable.qunit.js +++ b/src/sap.ui.table/test/sap/ui/table/qunit/AnalyticalTable.qunit.js @@ -465,14 +465,27 @@ this.oTable._applyAnalyticalBindingInfo(oBindingInfo); assert.equal(oBindingInfo.parameters.numberOfExpandedLevels, 0, "Property NumberOfExpandedLevels - Default"); + this.oTable._aGroupedColumns = new Array(5); oBindingInfo = {parameters: {numberOfExpandedLevels: 5}}; this.oTable._applyAnalyticalBindingInfo(oBindingInfo); assert.equal(oBindingInfo.parameters.numberOfExpandedLevels, 5, "Property NumberOfExpandedLevels - From BindingInfo"); + this.oTable._aGroupedColumns = []; + oBindingInfo = {parameters: {numberOfExpandedLevels: 5}}; + this.oTable._applyAnalyticalBindingInfo(oBindingInfo); + assert.equal(oBindingInfo.parameters.numberOfExpandedLevels, 0, "Property NumberOfExpandedLevels (no grouped columns) - From BindingInfo"); + + this.oTable._aGroupedColumns = new Array(4); + oBindingInfo = {}; + this.oTable.setNumberOfExpandedLevels(4); + this.oTable._applyAnalyticalBindingInfo(oBindingInfo); + assert.equal(oBindingInfo.parameters.numberOfExpandedLevels, 4, "Property NumberOfExpandedLevels - Custom"); + + this.oTable._aGroupedColumns = []; oBindingInfo = {}; this.oTable.setNumberOfExpandedLevels(4); this.oTable._applyAnalyticalBindingInfo(oBindingInfo); - assert.equal(oBindingInfo.parameters.numberOfExpandedLevels, 4, "Property SumOnTop - Custom"); + assert.equal(oBindingInfo.parameters.numberOfExpandedLevels, 0, "Property NumberOfExpandedLevels (no grouped columns) - Custom"); }); QUnit.test("Simple expand/collapse", function (assert) {
[FIX] AnalyticalTable: Consider groups on initial numberOfExpandedLevels The analytical binding does not support the number of expanded levels to be bigger then the number of grouped columns. If, on creation of the binding, the initial value is bigger, it is reduced to 0. This behavior is coherent with another solution when generating the analytical info. Change-Id: I1db<I>d<I>eb<I>c<I>b<I>e<I>aa1a7d3c BCP: <I>
SAP_openui5
train
9920ec86cd4ba6ccb05a4b6ed106870bdac6b130
diff --git a/src/DurationExtension.php b/src/DurationExtension.php index <HASH>..<HASH> 100644 --- a/src/DurationExtension.php +++ b/src/DurationExtension.php @@ -2,6 +2,7 @@ namespace UAM\Twig\Extension\I18n; +use DateInterval; use DateTime; use Locale; use Twig_Extension; @@ -120,15 +121,30 @@ class DurationExtension extends Twig_Extension return implode(' ' , $result); } + // TODO[DA 2016-09-14] assume small date as a start date public function getDateInterval($from, $to, $locale = null) { + $parsed = date_parse($from); + + if (!is_int($parsed['hour'])) { + $from .= ' 00:00:00'; + } + $start_date = new DateTime($from); - $end_date = new DateTime($to); + $parsed = date_parse($to); + + if (!is_int($parsed['hour'])) { + $to .= ' 23:59:59'; + $end_date = new DateTime($to); + $end_date->add(new DateInterval('PT1S')); + } else { + $end_date = new DateTime($to); + } - $interval_day = $start_date->diff($end_date)->days; + $interval = $start_date->diff($end_date)->format('%ad'); - return $interval_day; + return $interval; } // TODO convert Month to days. diff --git a/tests/DurationExtensionTest.php b/tests/DurationExtensionTest.php index <HASH>..<HASH> 100644 --- a/tests/DurationExtensionTest.php +++ b/tests/DurationExtensionTest.php @@ -339,15 +339,15 @@ class DurationExtensionTest extends PHPUnit_Framework_TestCase array('2015-1-1', '2015-12-31', 'D', '365d'), array('2016-1-1', '2016-12-31', 'D', '366d'), array('2016-1-2', '2016-12-30', 'D', '364d'), - array('2016-3-1', '2016-6-1', 'D', '92d'), + array('2016-3-1', '2016-6-1', 'D', '93d'), array('2016-1-1', '2024-1-1', 'D', '2923d'), - array('2016-1-1', '2024-3-1', 'D', '2981d'), - array('2016-1-1', '2020-1-1', 'D', '1461d'), - array('2011-1-1', '2015-1-1', 'D', '1460d'), + array('2016-1-1', '2024-3-1', 'D', '2983d'), + array('2016-1-1', '2020-1-1', 'D', '1462d'), + array('2011-1-1', '2015-1-1', 'D', '1462d'), array('2009-3-1', '2009-3-31', 'D', '31d'), - array('2015-1-1', '2015-3-1', 'D', '59d'), - array('2015-2-25', '2015-3-1', 'D', '4d'), - array('2016-3-25', '2016-4-1', 'D', '7d'), + array('2015-1-1', '2015-3-1', 'D', '60d'), + array('2015-2-25', '2015-3-1', 'D', '5d'), + array('2016-3-25', '2016-4-1', 'D', '8d'), array('2010-1-3', '2010-1-5', 'D', '3d'), ); }
improved getDateInterval method in duration extension
united-asian_twig-i18n-extension
train
ad81e99b8f2d6cd078b949816544235852c48dd2
diff --git a/externs/ie_dom.js b/externs/ie_dom.js index <HASH>..<HASH> 100644 --- a/externs/ie_dom.js +++ b/externs/ie_dom.js @@ -1015,6 +1015,12 @@ Element.prototype.innerText; Element.prototype.isContentEditable; /** + * @param {number} pointerId Id of the pointer that is assign to the element. + * @see http://msdn.microsoft.com/en-us/library/ie/hh771882(v=vs.85).aspx + */ +Element.prototype.msSetPointerCapture = function(pointerId) {}; + +/** * @type {?function(Event)} * @see http://msdn.microsoft.com/en-us/library/ms536903(v=vs.85).aspx */
Added Element.prototype.msSetPointerCapture(pointerId) for IE<I> javascript. R=nicksantos DELTA=6 (6 added, 0 deleted, 0 changed) Revision created by MOE tool push_codebase. MOE_MIGRATION=<I> git-svn-id: <URL>
google_closure-compiler
train
e74356e4994478ac129bc476719a9b0bd6679906
diff --git a/src/postmark/core.py b/src/postmark/core.py index <HASH>..<HASH> 100644 --- a/src/postmark/core.py +++ b/src/postmark/core.py @@ -62,7 +62,7 @@ class PMMail(object): acceptable_keys = ( 'api_key', - 'from', + 'sender', 'reply_to', 'to', 'recipient', # 'recipient' is legacy 'cc', @@ -90,10 +90,7 @@ class PMMail(object): from django.conf import settings as django_settings self.__api_key = django_settings.POSTMARK_API_KEY self.__user_agent = '%s (Django %s)' % (self.__user_agent, '_'.join([str(var) for var in VERSION])) - - # Allow either POSTMARK_SENDER or POSTMARK_FROM - self.__sender = getattr(django_settings, 'POSTMARK_SENDER', None) - self.__sender = getattr(django_settings, 'POSTMARK_FROM', None) + self.__sender = django_settings.POSTMARK_SENDER except ImportError: pass
Fixed small bug with 'sender' not being an accepted arg
themartorana_python-postmark
train
39a54389d626cdab067dd5a66bd1a45932848e95
diff --git a/rails_event_store/lib/rails_event_store/actions/append_event_to_stream.rb b/rails_event_store/lib/rails_event_store/actions/append_event_to_stream.rb index <HASH>..<HASH> 100644 --- a/rails_event_store/lib/rails_event_store/actions/append_event_to_stream.rb +++ b/rails_event_store/lib/rails_event_store/actions/append_event_to_stream.rb @@ -10,7 +10,7 @@ module RailsEventStore raise WrongExpectedEventVersion if version_incorrect?(stream_name, expected_version) event.validate! save_event(event, stream_name) - return event + event end private
We don't need return keyword in Ruby
RailsEventStore_rails_event_store
train
9496f6a502c79ec3acb4e222e190e76264db02cf
diff --git a/semantic_release/history/parser_tag.py b/semantic_release/history/parser_tag.py index <HASH>..<HASH> 100644 --- a/semantic_release/history/parser_tag.py +++ b/semantic_release/history/parser_tag.py @@ -22,27 +22,36 @@ def parse_commit_message(message): :return: A tuple of (level to bump, type of change, scope of change, a tuple with descriptions) """ - match = re_parser.match(message) + parsed = re_parser.match(message) - if not match: + if not parsed: raise UnknownCommitMessageStyleError( 'Unable to parse the given commit message: {0}'.format(message) ) + subject = parsed.group('subject') + if config.get('semantic_release', 'minor_tag') in message: level = 'feature' + level_bump = 2 + if subject: + subject = subject.replace(config.get('semantic_release', 'minor_tag'.format(level)), '') elif config.get('semantic_release', 'fix_tag') in message: level = 'fix' + level_bump = 1 + if subject: + subject = subject.replace(config.get('semantic_release', 'fix_tag'.format(level)), '') + else: raise UnknownCommitMessageStyleError( 'Unable to parse the given commit message: {0}'.format(message) ) - subject = match.group('subject') - if subject: - subject = subject.replace(config.get('semantic_release', '{0}_tag'.format(level)), '') + if parsed.group('text') and 'BREAKING CHANGE' in parsed.group('text'): + level = 'breaking' + level_bump = 3 - body, footer = parse_text_block(match.group('text')) + body, footer = parse_text_block(parsed.group('text')) - return level, level, None, (subject.strip(), body.strip(), footer.strip()) + return level_bump, level, None, (subject.strip(), body.strip(), footer.strip()) diff --git a/tests/parsers/test_tag.py b/tests/parsers/test_tag.py index <HASH>..<HASH> 100644 --- a/tests/parsers/test_tag.py +++ b/tests/parsers/test_tag.py @@ -12,35 +12,41 @@ def test_parser_raises_unknown_message_style(): pytest.raises(UnknownCommitMessageStyleError, tag_parser, '') -def test_parser_return_correct_bump_level(): - assert tag_parser(':guardsman: Remove emoji parser')[0] == 3 - assert tag_parser(':feature: Add emoji parser')[0] == 3 +def test_parser_return_major_bump_level(): + commit = ':sparkles: Add new parser pattern\n\nBREAKING CHANGE:' + assert tag_parser(commit)[0] == 3 + + +def test_parser_return_minor_bump_level(): + assert tag_parser(':sparkles: Add emoji parser')[0] == 2 + + +def test_parser_return_patch_bump_level(): assert tag_parser(':nut_and_bolt: Fix regex in angular parser')[0] == 1 - assert tag_parser('Add a test for angular parser')[0] == 0 -def test_parser_return_type_from_commit_message(): - assert tag_parser(':guardsman: ...')[1] == 'breaking' +def test_parser_return_type_breaking_from_commit_message(): + commit = ':sparkles: Add new parser pattern\n\nBREAKING CHANGE:' + assert tag_parser(commit)[1] == 'breaking' + + +def test_parser_return_type_feature_from_commit_message(): assert tag_parser(':sparkles: ...')[1] == 'feature' + + +def test_parser_return_type_fix_from_commit_message(): assert tag_parser(':nut_and_bolt: ...')[1] == 'fix' def test_parser_return_subject_from_commit_message(): - assert ( - tag_parser(':sparkles: Add emoji parser')[3][0] == - 'Add emoji parser' - ) + assert tag_parser(':sparkles: Add emoji parser')[3][0] == 'Add emoji parser' def test_parser_return_text_from_commit_message(): - assert ( - tag_parser(':nut_and_bolt: Fix regex in an parser\n\n{}'.format(text))[3][1] == - text - ) + commit = ':nut_and_bolt: Fix regex in an parser\n\n{}'.format(text) + assert tag_parser(commit)[3][1] == text def test_parser_return_footer_from_commit_message(): commit = ':nut_and_bolt: Fix env \n\n{t[text]}\n\n{t[footer]}'.format(t=globals()) - assert ( - tag_parser(commit)[3][2] == footer - ) + assert tag_parser(commit)[3][2] == footer
fix: Make tag parser work correctly with breaking changes The tag parser did not work correctly, this went undiscovered for a while because the tests was not ran by pytest.
relekang_python-semantic-release
train
0a27f88cc42179298f769a88d9c722af97b815a8
diff --git a/cli-config.php b/cli-config.php index <HASH>..<HASH> 100644 --- a/cli-config.php +++ b/cli-config.php @@ -6,6 +6,7 @@ use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Command\GenerateEmbeddable use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Command\GenerateEntityCommand; use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Command\GenerateFieldCommand; use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Command\GenerateRelationsCommand; +use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Command\OverrideCreateCommand; use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Command\OverridesUpdateCommand; use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Command\RemoveUnusedRelationsCommand; use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\Command\SetEmbeddableCommand; @@ -48,6 +49,7 @@ try { $container->get(SetEmbeddableCommand::class), $container->get(GenerateEmbeddableFromArchetypeCommand::class), $container->get(RemoveUnusedRelationsCommand::class), + $container->get(OverrideCreateCommand::class), $container->get(OverridesUpdateCommand::class), ];
forgot to add teh overrides create command to cli config
edmondscommerce_doctrine-static-meta
train
0f2ab8409d426b243204806a52e5b3a908417543
diff --git a/construct_mutation_rates.py b/construct_mutation_rates.py index <HASH>..<HASH> 100755 --- a/construct_mutation_rates.py +++ b/construct_mutation_rates.py @@ -11,6 +11,7 @@ import os import copy import math import argparse +import tempfile from src.load_gene import construct_gene_object from src.ensembl_requester import EnsemblRequest @@ -144,7 +145,7 @@ def get_mutation_rates(gene_id, transcripts, mut_dict, ensembl, use_cov, cov_dir for transcript_id in transcripts[gene_id]: - # get the gene coordinates, sequence etc, but if the transcript is + # get the gene coordinates, sequence etc, but if the transcript is # unusable (hence raises an error), simply move to the next transcript try: transcript = construct_gene_object(ensembl, transcript_id) @@ -207,6 +208,63 @@ def log_transform(values): return transformed +def include_indel_rates(path): + """ add per-gene indel mutation rates to the output file + + We estimate the indel mutation rate as per Nature Genetics 46:944-950 + (2014) doi:10.1038/ng.3050, in which the overall (ie summed across all + genes) indel mutation rate is estimated as 1.25 x the overall nonsense + rate. Given this, the indel mutation rate is portioned out to each gene, + according to the proportion of each gene's CDS length to the length of all + CDS regions from all genes. + + Note that this is an approximation, and doesn't allow for divergence due to + the base compostion of the CDS. + + Args: + path: path to the output mutation rates (for the nonsense, missense etc) + """ + + # we copy the rates file to a temporary file, so that we can stream through + # it later while writing amended lines to the correct rates path + temp = tempfile.TemporaryFile() + + # run through the file of rates to find the overall nonsense mutation rate, + # and the total length of CDS regions in the file. + nonsense_sum = 0 + length_sum = 0 + with open(path) as handle: + for line in handle: + temp.write(line) + if line.startswith("transcript_id"): + continue + + line = line.strip().split("\t") + nonsense_sum += 10**float(line[3]) + length_sum += int(line[1]) + + handle.close() + temp.seek(0) + + # add the frameshift rates to each line in turn, while writing the output + # back to the output path + frameshift_sum = nonsense_sum * 1.25 + with open(path, "w") as handle: + for line in temp: + line = line.strip().split("\t") + if line[0] == "transcript_id": + line.append("frameshift_rate") + else: + # estimate the frameshift rate for the gene + frameshift_rate = (float(line[1])/length_sum) * frameshift_sum + frameshift_rate = math.log10(frameshift_rate) + line.append(str(frameshift_rate)) + + line = "\t".join(line) +"\n" + handle.write(line) + + temp.close() + def main(): input_transcripts, input_genes, output_file, rates_file, cache_dir, \ @@ -242,9 +300,10 @@ def main(): continue output.write(line) - + output.close() + + include_indel_rates(output_file) if __name__ == '__main__': main() - diff --git a/identify_transcripts.py b/identify_transcripts.py index <HASH>..<HASH> 100755 --- a/identify_transcripts.py +++ b/identify_transcripts.py @@ -75,14 +75,15 @@ def main(): gene_id = old_gene_ids[gene_id] # find the counts per transcript, depending on whether we want to count - # for all transcripts containing one or more de novos, or to find the + # for all transcripts containing one or more de novos, or to find the # minimum set of transcripts to contain the de novos try: if all_transcripts: counts = count_de_novos_per_transcript(ensembl, gene_id, func_events) elif minimal_transcripts: counts = minimise_transcripts(ensembl, gene_id, func_events) - except ValueError: + except (ValueError, IndexError): + print("error occured with {0}".format(gene_id)) continue # write the transcript details to a file @@ -94,5 +95,3 @@ def main(): if __name__ == '__main__': main() - -
adjustments to generating mutation rates - handle exception from no useable transcript when identifying transcripts - include frameshift rate, as per the Nature Genetics <I>:<I>-<I> model
jeremymcrae_denovonear
train
33db79a5ad4c755cf7b744119f9172dd7a15c049
diff --git a/git_repo/services/service.py b/git_repo/services/service.py index <HASH>..<HASH> 100644 --- a/git_repo/services/service.py +++ b/git_repo/services/service.py @@ -171,7 +171,7 @@ class RepositoryService: self.fqdn = c.get('fqdn', self.fqdn) self.scheme = c.get('scheme', 'https') - self.port = c.get('port', '443') + self.port = c.get('port', None) self.default_create_private = c.get('default-create-private', 'n').lower() in CONFIG_TRUE self.ssh_url = c.get('ssh-url', self.fqdn)
🚒 makes port default to <I> when scheme is HTTP fixes #<I>
guyzmo_git-repo
train
b3b2544ba5845e24253fa97465a30af027b534fe
diff --git a/tests/Buffer.php b/tests/Buffer.php index <HASH>..<HASH> 100644 --- a/tests/Buffer.php +++ b/tests/Buffer.php @@ -23,7 +23,7 @@ namespace GameQ\Tests; * * @package GameQ\Tests */ -class Buffer extends \PHPUnit\Framework\TestCase +class Buffer extends TestBase { /** * Build a mock Buffer diff --git a/tests/Filters/Normalize.php b/tests/Filters/Normalize.php index <HASH>..<HASH> 100644 --- a/tests/Filters/Normalize.php +++ b/tests/Filters/Normalize.php @@ -53,7 +53,7 @@ class Normalize extends Base ->getMock(); // Create a mock filter - $filter = $this->getMockBuilder(\GameQ\Filters\Normalize::class) + $filter = $this->getMockBuilder('\GameQ\Filters\Normalize') ->enableProxyingToOriginalMethods() ->getMock(); @@ -78,7 +78,7 @@ class Normalize extends Base ->getMock(); // Create a mock filter - $filter = $this->getMockBuilder(\GameQ\Filters\Normalize::class) + $filter = $this->getMockBuilder('\GameQ\Filters\Normalize') ->enableProxyingToOriginalMethods() ->getMock(); diff --git a/tests/Protocol.php b/tests/Protocol.php index <HASH>..<HASH> 100644 --- a/tests/Protocol.php +++ b/tests/Protocol.php @@ -23,7 +23,7 @@ namespace GameQ\Tests; * * @package GameQ\Tests */ -class Protocol extends \PHPUnit\Framework\TestCase +class Protocol extends TestBase { /** diff --git a/tests/Query/Core.php b/tests/Query/Core.php index <HASH>..<HASH> 100644 --- a/tests/Query/Core.php +++ b/tests/Query/Core.php @@ -18,12 +18,14 @@ namespace GameQ\Tests\Query; +use GameQ\Tests\TestBase; + /** * Class Core testing * * @package GameQ\Tests\Query */ -class Core extends \PHPUnit\Framework\TestCase +class Core extends TestBase { /** * Test setting the properties for the query core
Missed other ::class
Austinb_GameQ
train
f73973783dd2600e460588b9056b09cc616de942
diff --git a/components/Flute/src/Http/Traits/FluteRoutesTrait.php b/components/Flute/src/Http/Traits/FluteRoutesTrait.php index <HASH>..<HASH> 100644 --- a/components/Flute/src/Http/Traits/FluteRoutesTrait.php +++ b/components/Flute/src/Http/Traits/FluteRoutesTrait.php @@ -84,6 +84,11 @@ trait FluteRoutesTrait */ protected static function controller(GroupInterface $group, string $subUri, string $controllerClass): GroupInterface { + // normalize url to have predictable URLs and their names + if ($subUri[-1] === '/') { + $subUri = substr($subUri, 0, -1); + } + $groupPrefix = $group->getUriPrefix(); $slugged = $subUri . '/{' . CI::ROUTE_KEY_INDEX . '}'; $params = function (string $method) use ($groupPrefix, $subUri) : array { @@ -148,15 +153,25 @@ trait FluteRoutesTrait /** * @param string $prefix - * @param string $name + * @param string $subUri * @param string $method * * @return string */ - protected static function routeName(string $prefix, string $name, string $method): string + protected static function routeName(string $prefix, string $subUri, string $method): string { - assert(empty($name) === false && empty($method) === false); + assert(empty($method) === false); + + // normalize prefix and url to have predictable name + + if (empty($prefix) === true || $prefix[-1] !== '/') { + $prefix .= '/'; + } + + if (empty($subUri) === false && $subUri[-1] === '/') { + $subUri = substr($subUri, 0, -1); + } - return $prefix . '/' . $name . '::' . $method; + return $prefix . $subUri . '::' . $method; } } diff --git a/components/Flute/tests/Http/Traits/FluteRoutesTraitTest.php b/components/Flute/tests/Http/Traits/FluteRoutesTraitTest.php index <HASH>..<HASH> 100644 --- a/components/Flute/tests/Http/Traits/FluteRoutesTraitTest.php +++ b/components/Flute/tests/Http/Traits/FluteRoutesTraitTest.php @@ -42,13 +42,14 @@ class FluteRoutesTraitTest extends TestCase /** @var Mock $group */ $group = Mockery::mock(GroupInterface::class); - $group->shouldReceive('get')->twice()->withAnyArgs()->andReturnSelf(); - $group->shouldReceive('post')->times(3)->withAnyArgs()->andReturnSelf(); - $group->shouldReceive('getUriPrefix')->times(1)->withNoArgs()->andReturn(''); + $group->shouldReceive('get')->times(4)->withAnyArgs()->andReturnSelf(); + $group->shouldReceive('post')->times(6)->withAnyArgs()->andReturnSelf(); + $group->shouldReceive('getUriPrefix')->times(2)->withNoArgs()->andReturn(''); /** @var GroupInterface $group */ $this->controller($group, '/categories', ApiCategoriesController::class); + $this->controller($group, '/products/', ApiCategoriesController::class); // mockery will do checks when the test finished $this->assertTrue(true); @@ -103,4 +104,17 @@ class FluteRoutesTraitTest extends TestCase // mockery will do checks when the test finished $this->assertTrue(true); } + + /** + * Test how predictable/stable generated route names are. + * + * @return void + */ + public function testRouteNamePredictability(): void + { + $this->assertEquals('/::index', static::routeName('', '', 'index')); + $this->assertEquals('/::index', static::routeName('/', '', 'index')); + $this->assertEquals('/::index', static::routeName('', '/', 'index')); + $this->assertEquals('/::index', static::routeName('/', '/', 'index')); + } }
Improve stability/predictability for auto-generated route names.
limoncello-php_framework
train
5889858cc5237ab2303337f847616be70d0a8aab
diff --git a/mod/feedback/classes/complete_form.php b/mod/feedback/classes/complete_form.php index <HASH>..<HASH> 100644 --- a/mod/feedback/classes/complete_form.php +++ b/mod/feedback/classes/complete_form.php @@ -399,8 +399,8 @@ class mod_feedback_complete_form extends moodleform { */ protected function add_item_label($item, $element) { if (strlen($item->label) && ($this->mode == self::MODE_EDIT || $this->mode == self::MODE_VIEW_TEMPLATE)) { - $name = $element->getLabel(); - $name = '('.format_string($item->label).') '.$name; + $name = get_string('nameandlabelformat', 'mod_feedback', + (object)['label' => format_string($item->label), 'name' => $element->getLabel()]); $element->setLabel($name); } } diff --git a/mod/feedback/classes/responses_table.php b/mod/feedback/classes/responses_table.php index <HASH>..<HASH> 100644 --- a/mod/feedback/classes/responses_table.php +++ b/mod/feedback/classes/responses_table.php @@ -314,7 +314,15 @@ class mod_feedback_responses_table extends table_sql { $tablecolumns[] = "val{$nr}"; $itemobj = feedback_get_item_class($item->typ); - $tableheaders[] = $itemobj->get_display_name($item, $headernamepostfix); + $columnheader = $itemobj->get_display_name($item, $headernamepostfix); + if (!$this->is_downloading()) { + $columnheader = shorten_text($columnheader); + } + if (strval($item->label) !== '') { + $columnheader = get_string('nameandlabelformat', 'mod_feedback', + (object)['label' => format_string($item->label), 'name' => $columnheader]); + } + $tableheaders[] = $columnheader; } // Add 'Delete entry' column. diff --git a/mod/feedback/lang/en/feedback.php b/mod/feedback/lang/en/feedback.php index <HASH>..<HASH> 100644 --- a/mod/feedback/lang/en/feedback.php +++ b/mod/feedback/lang/en/feedback.php @@ -195,6 +195,7 @@ $string['multiplesubmit'] = 'Allow multiple submissions'; $string['multiplesubmit_help'] = 'If enabled for anonymous surveys, users can submit feedback an unlimited number of times.'; $string['name'] = 'Name'; $string['name_required'] = 'Name required'; +$string['nameandlabelformat'] = '({$a->label}) {$a->name}'; $string['next_page'] = 'Next page'; $string['no_handler'] = 'No action handler exists for'; $string['no_itemlabel'] = 'No label';
MDL-<I> mod_feedback: export question labels This was present in export in <I> but got lost during export refactoring in <I>
moodle_moodle
train
9d29c4f43daa3d64bffdc9026c87c5bff2c758c4
diff --git a/server.go b/server.go index <HASH>..<HASH> 100644 --- a/server.go +++ b/server.go @@ -1368,7 +1368,7 @@ func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq, // We'll ensure that we locate the proper port to use within the peer's // address for reconnecting purposes. - if tcpAddr, ok := addr.(*net.TCPAddr); ok { + if tcpAddr, ok := addr.(*net.TCPAddr); ok && !inbound { targetPort := s.fetchNodeAdvertisedPort(pubKey, tcpAddr) // Once we have the correct port, we'll make a new copy of the
server: only swap out the port for inbound connections Note that the check is actually reversed to the quirk atm in the server logic, where inbound and outbound are reversed. Fixes #<I>.
lightningnetwork_lnd
train
5ea4615d4d20d87650a01ee2726709a311b4b142
diff --git a/core/ArrayData.php b/core/ArrayData.php index <HASH>..<HASH> 100755 --- a/core/ArrayData.php +++ b/core/ArrayData.php @@ -1,6 +1,6 @@ <?php /** - * Lets you wrap a bunch of array data into a {@link ViewableData} object. + * Lets you wrap a bunch of array data, or object members, into a {@link ViewableData} object. * * <code> * new ArrayData(array( @@ -21,20 +21,19 @@ class ArrayData extends ViewableData { protected $array; /** - * @param object|array $array Either an object with simple properties or an associative array. - * Converts object-properties to indices of an associative array. + * @param object|array $value An associative array, or an object with simple properties. + * Converts object properties to keys of an associative array. */ - public function __construct($array) { - if(is_object($array)) { - $this->array = self::object_to_array($array); - } elseif(is_array($array) && (ArrayLib::is_associative($array) || count($array) === 0)) { - $this->array = $array; + public function __construct($value) { + if (is_object($value)) { + $this->array = get_object_vars($value); + } elseif (ArrayLib::is_associative($value)) { + $this->array = $value; + } elseif (is_array($value) && count($value) === 0) { + $this->array = array(); } else { - $this->array = $array; - user_error( - "ArrayData::__construct: Parameter needs to be an object or associative array", - E_USER_WARNING - ); + $message = 'Parameter to ArrayData constructor needs to be an object or associative array'; + throw new InvalidArgumentException($message); } parent::__construct(); } @@ -49,19 +48,27 @@ class ArrayData extends ViewableData { } /** - * Get a value from a given field + * Gets a field from this object. * - * @param string $f field key - * @return mixed + * @param string $field + * + * If the value is an object but not an instance of + * ViewableData, it will be converted recursively to an + * ArrayData. + * + * If the value is an associative array, it will likewise be + * converted recursively to an ArrayData. */ public function getField($f) { - if((is_object($this->array[$f]) && !$this->array[$f] instanceof ViewableData) || (is_array($this->array[$f]) && ArrayLib::is_associative($this->array[$f]))) { - return new ArrayData($this->array[$f]); + $value = $this->array[$f]; + if (is_object($value) && !$value instanceof ViewableData) { + return new ArrayData($value); + } elseif (ArrayLib::is_associative($value)) { + return new ArrayData($value); + } else { + return $value; } - - return $this->array[$f]; } - /** * Add or set a field on this object. * @@ -83,19 +90,15 @@ class ArrayData extends ViewableData { } /** - * Converts an object with simple properties to + * @deprecated Use get_object_vars($obj) + * Converts an object with simple properties to * an associative array. * * @param obj $obj * @return array */ protected static function object_to_array($obj) { - $arr = array(); - foreach($obj as $k=>$v) { - $arr[$k] = $v; - } - - return $arr; + return get_object_vars($obj); } /**
ENHANCEMENT: Refactoring and documenting the ArrayData class. Deprecating the "object_to_array" method (fixes #<I>, thanks tobych)
silverstripe_silverstripe-framework
train
7610a9f6ece43b96b10cf5843e300178c0ef55d8
diff --git a/py3status/__init__.py b/py3status/__init__.py index <HASH>..<HASH> 100755 --- a/py3status/__init__.py +++ b/py3status/__init__.py @@ -591,13 +591,13 @@ class Py3statusWrapper(): Create the py3status based on command line options we received. """ # get home path - home = '{}{}'.format(os.path.expanduser('~'), '/') + home_path = '{}{}'.format(os.path.expanduser('~'), '/') # defaults config = { 'cache_timeout': 60, 'i3status_config_path': '/etc/i3status.conf', - 'include_paths': ['{}{}'.format(home, '.i3/py3status/')], + 'include_paths': ['{}{}'.format(home_path, '.i3/py3status/')], 'interval': 1 }
Variable renamed, home -> home_path
ultrabug_py3status
train
ee660b1ccd7984d5095a0a5d167839ea14daaf2d
diff --git a/lib/assert/version.rb b/lib/assert/version.rb index <HASH>..<HASH> 100644 --- a/lib/assert/version.rb +++ b/lib/assert/version.rb @@ -1,3 +1,3 @@ module Assert - VERSION = "2.13.0" + VERSION = "2.14.0" end
version to <I> * changed ref CLI opt #<I> * `-l` option for listing out test files that would be loaded and run #<I> /cc @jcredding
redding_assert
train
d5a7e27dace1fb13194a239dfe84be25fc18bcb1
diff --git a/voluptuous.py b/voluptuous.py index <HASH>..<HASH> 100644 --- a/voluptuous.py +++ b/voluptuous.py @@ -723,11 +723,15 @@ class Schema(object): resulting `Schema` inherits the `required` and `extra` parameters of this, unless overridden. + Both schemas must be dictionary-based. + :param schema: dictionary to extend this `Schema` with :param required: if set, overrides `required` of this `Schema` :param extra: if set, overrides `extra` of this `Schema` """ + assert type(self.schema) == dict and type(schema) == dict, 'Both schemas must be dictionary-based' + result = self.schema.copy() result.update(schema)
Schema.extend works only for dicts
alecthomas_voluptuous
train
86eb0519a3343e0002dada9c9c5283eb6f88b8d0
diff --git a/client.go b/client.go index <HASH>..<HASH> 100644 --- a/client.go +++ b/client.go @@ -223,11 +223,26 @@ func (c *Client) PutJSON(endpoint string, data interface{}) (*Response, error) { }) } -// Delete executes DELETE request to the endpoint with optional query arguments +// Delete executes DELETE request to the endpoint with no body // // re, err := c.Delete(c.Endpoint("users", "id1"), url.Values{"force": []string{"true"}}) // -func (c *Client) Delete(endpoint string, params url.Values) (*Response, error) { +func (c *Client) Delete(endpoint string) (*Response, error) { + return c.RoundTrip(func() (*http.Response, error) { + req, err := http.NewRequest("DELETE", endpoint, nil) + if err != nil { + return nil, err + } + c.addAuth(req) + return c.client.Do(req) + }) +} + +// DeleteP executes DELETE request to the endpoint with optional query arguments +// +// re, err := c.Delete(c.Endpoint("users", "id1"), url.Values{"force": []string{"true"}}) +// +func (c *Client) DeleteP(endpoint string, params url.Values) (*Response, error) { baseURL, err := url.Parse(endpoint) if err != nil { return nil, err diff --git a/client_test.go b/client_test.go index <HASH>..<HASH> 100644 --- a/client_test.go +++ b/client_test.go @@ -128,6 +128,25 @@ func (s *ClientSuite) TestDelete(c *C) { var method string var user, pass string var ok bool + srv := serveHandler(func(w http.ResponseWriter, r *http.Request) { + user, pass, ok = r.BasicAuth() + method = r.Method + }) + defer srv.Close() + + clt := newC(srv.URL, "v1", BasicAuth("user", "pass")) + re, err := clt.Delete(clt.Endpoint("a", "b")) + c.Assert(err, IsNil) + c.Assert(method, Equals, "DELETE") + c.Assert(re.Code(), Equals, http.StatusOK) + c.Assert(user, DeepEquals, "user") + c.Assert(pass, DeepEquals, "pass") +} + +func (s *ClientSuite) TestDeleteP(c *C) { + var method string + var user, pass string + var ok bool var query url.Values srv := serveHandler(func(w http.ResponseWriter, r *http.Request) { user, pass, ok = r.BasicAuth() @@ -138,7 +157,7 @@ func (s *ClientSuite) TestDelete(c *C) { clt := newC(srv.URL, "v1", BasicAuth("user", "pass")) values := url.Values{"force": []string{"true"}} - re, err := clt.Delete(clt.Endpoint("a", "b"), values) + re, err := clt.DeleteP(clt.Endpoint("a", "b"), values) c.Assert(err, IsNil) c.Assert(method, Equals, "DELETE") c.Assert(re.Code(), Equals, http.StatusOK)
Introduce new method DeleteP instead of modifying Delete
gravitational_roundtrip
train
48d366ba0db7d4a893aefd7d457357377dc0900e
diff --git a/features/step_definitions/manage_patients_steps.rb b/features/step_definitions/manage_patients_steps.rb index <HASH>..<HASH> 100644 --- a/features/step_definitions/manage_patients_steps.rb +++ b/features/step_definitions/manage_patients_steps.rb @@ -64,13 +64,13 @@ When(/^I complete the add a new patient form$/) do select "White", from: "Ethnicity" within "#patient_birth_date_1i" do - select '1960' + select "1960" end within "#patient_birth_date_2i" do - select 'January' + select "January" end within "#patient_birth_date_3i" do - select '1' + select "1" end uncheck "If under 18 years, is the recipient being treated in a paediatric unit?"
Replaced single quotes for double quotes within manage patient cuke steps.
airslie_renalware-core
train
3684bc5522996204b57be26b99c3ce4578026b3b
diff --git a/guacamole-common-js/src/main/resources/layer.js b/guacamole-common-js/src/main/resources/layer.js index <HASH>..<HASH> 100644 --- a/guacamole-common-js/src/main/resources/layer.js +++ b/guacamole-common-js/src/main/resources/layer.js @@ -345,7 +345,7 @@ Guacamole.Layer = function(width, height) { function doCopyRect() { if (layer.autosize != 0) fitRect(x, y, srcw, srch); - displayContext.drawImage(srcLayer, srcx, srcy, srcw, srch, x, y, srcw, srch); + displayContext.drawImage(srcLayer.getCanvas(), srcx, srcy, srcw, srch, x, y, srcw, srch); } // If we ARE the source layer, no need to sync.
Fixed type error in copy rect of Layer.
glyptodon_guacamole-client
train
7db9a03a6875a47a28e88d415e75448c0b9a3f31
diff --git a/common/src/main/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabase.java b/common/src/main/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabase.java index <HASH>..<HASH> 100644 --- a/common/src/main/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabase.java +++ b/common/src/main/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabase.java @@ -14,6 +14,7 @@ package org.cloudfoundry.identity.uaa.user; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -36,14 +37,12 @@ import org.springframework.util.StringUtils; */ public class JdbcUaaUserDatabase implements UaaUserDatabase { - public static final String USER_FIELDS = "id,username,password,email,givenName,familyName,created,lastModified "; + public static final String USER_FIELDS = "id,username,password,email,givenName,familyName,created,lastModified, authorities "; public static final String DEFAULT_USER_BY_USERNAME_QUERY = "select " + USER_FIELDS + "from users " + "where lower(username) = ? and active=?"; - public static final String DEFAULT_USER_AUTHORITIES_QUERY = "select authorities from users where id = ?"; - - private String userAuthoritiesQuery = DEFAULT_USER_AUTHORITIES_QUERY; + private String userAuthoritiesQuery = null; private String userByUserNameQuery = DEFAULT_USER_BY_USERNAME_QUERY; @@ -74,8 +73,7 @@ public class JdbcUaaUserDatabase implements UaaUserDatabase { public UaaUser retrieveUserByName(String username) throws UsernameNotFoundException { try { return jdbcTemplate.queryForObject(userByUserNameQuery, mapper, username.toLowerCase(Locale.US), true); - } - catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException e) { throw new UsernameNotFoundException(username); } } @@ -84,10 +82,24 @@ public class JdbcUaaUserDatabase implements UaaUserDatabase { @Override public UaaUser mapRow(ResultSet rs, int rowNum) throws SQLException { String id = rs.getString(1); - List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(getAuthorities(id)); - return new UaaUser(id, rs.getString(2), rs.getString(3), rs.getString(4), + if (userAuthoritiesQuery==null) { + return new UaaUser(id, rs.getString(2), rs.getString(3), rs.getString(4), + getDefaultAuthorities(rs.getString(9)), rs.getString(5), rs.getString(6), + rs.getTimestamp(7), rs.getTimestamp(8)); + } else { + List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(getAuthorities(id)); + return new UaaUser(id, rs.getString(2), rs.getString(3), rs.getString(4), authorities, rs.getString(5), rs.getString(6), rs.getTimestamp(7), rs.getTimestamp(8)); + } + } + + private List<GrantedAuthority> getDefaultAuthorities(String defaultAuth) { + List<String> authorities = new ArrayList<String>(); + authorities.addAll(StringUtils.commaDelimitedListToSet(defaultAuth)); + authorities.addAll(defaultAuthorities); + String authsString = StringUtils.collectionToCommaDelimitedString(new HashSet<String>(authorities)); + return AuthorityUtils.commaSeparatedStringToAuthorityList(authsString); } private String getAuthorities(final String userId) {
small optimization if the authorities field is being used then avoid making a 2nd query for authorities
cloudfoundry_uaa
train
4abb60fe0c7060db273cd11eb5ad402a2181bdee
diff --git a/pypfopt/base_optimizer.py b/pypfopt/base_optimizer.py index <HASH>..<HASH> 100644 --- a/pypfopt/base_optimizer.py +++ b/pypfopt/base_optimizer.py @@ -337,10 +337,12 @@ class BaseConvexOptimizer(BaseOptimizer): ef.add_constraint(lambda x: x <= np.array([0.01, 0.08, ..., 0.5])) :param new_constraint: the constraint to be added - :type constraintfunc: lambda function + :type new_constraint: callable (e.g lambda function) """ if not callable(new_constraint): - raise TypeError("New constraint must be provided as a lambda function") + raise TypeError( + "New constraint must be provided as a callable (e.g lambda function)" + ) if self._opt is not None: raise exceptions.InstantiationError( "Adding constraints to an already solved problem might have unintended consequences. "
change lambda to callable in docs
robertmartin8_PyPortfolioOpt
train
9b25e733f98434c2f00d9dc8f41847ef02d7ab2d
diff --git a/sfsimodels/output.py b/sfsimodels/output.py index <HASH>..<HASH> 100644 --- a/sfsimodels/output.py +++ b/sfsimodels/output.py @@ -54,7 +54,7 @@ def format_value(value): def add_table_ends(para, oformat='latex', caption="caption-text", label="table"): fpara = "" if oformat == 'latex': - fpara += "\\begin{table}\n" + fpara += "\\begin{table}[H]\n" fpara += "\\centering\n" fpara += "\\begin{tabular}{cc}\n" fpara += "\\toprule\n"
locked position of table in latex output.
eng-tools_sfsimodels
train
e1c6587dd3c180bafe65ab79773b2483fb4bf9c2
diff --git a/dev/com.ibm.ws.security.acme_fat/fat/src/com/ibm/ws/security/acme/fat/AcmeSimpleTest.java b/dev/com.ibm.ws.security.acme_fat/fat/src/com/ibm/ws/security/acme/fat/AcmeSimpleTest.java index <HASH>..<HASH> 100644 --- a/dev/com.ibm.ws.security.acme_fat/fat/src/com/ibm/ws/security/acme/fat/AcmeSimpleTest.java +++ b/dev/com.ibm.ws.security.acme_fat/fat/src/com/ibm/ws/security/acme/fat/AcmeSimpleTest.java @@ -26,6 +26,7 @@ import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import org.junit.After; import org.junit.AfterClass; @@ -611,6 +612,10 @@ public class AcmeSimpleTest { } protected void stopServer(String ...msgs) throws Exception { - AcmeFatUtils.stopServer(server, msgs); + String alwaysAdd = "CWWKG0027W"; // update timeouts are okay, sometimes the acme certificate fetch takes longer + + List<String> tempList = new ArrayList<String>(Arrays.asList(msgs)); + tempList.add(alwaysAdd); + AcmeFatUtils.stopServer(server, tempList.toArray(new String[tempList.size()])); } } diff --git a/dev/com.ibm.ws.security.acme_fat/fat/src/com/ibm/ws/security/acme/utils/AcmeFatUtils.java b/dev/com.ibm.ws.security.acme_fat/fat/src/com/ibm/ws/security/acme/utils/AcmeFatUtils.java index <HASH>..<HASH> 100644 --- a/dev/com.ibm.ws.security.acme_fat/fat/src/com/ibm/ws/security/acme/utils/AcmeFatUtils.java +++ b/dev/com.ibm.ws.security.acme_fat/fat/src/com/ibm/ws/security/acme/utils/AcmeFatUtils.java @@ -882,7 +882,7 @@ public class AcmeFatUtils { Log.info(AcmeFatUtils.class, methodName, "Checking os.name: " + os + " java.vendor: " + javaVendor + " java.version: " + javaVersion); if (os.startsWith("win") && (javaVendor.contains("openjdk") || javaVendor.contains(("oracle"))) - && (javaVersion.equals("11.0.5") || javaVersion.equals("14.0.1") || javaVersion.equals("11") + && (javaVersion.startsWith("11") || javaVersion.equals("14.0.1") || javaVersion.equals("1.8.0_181") || javaVersion.equals("15") || javaVersion.equals("16"))) { /* * On Windows with OpenJDK 11.0.5 (and others), we sometimes get an exception
Issue <I>: Skip new winJDK level and ignore config update msg ACME FATs
OpenLiberty_open-liberty
train
02c36cf5cb736a6c7321c8cb9a632a3a74344f25
diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb index <HASH>..<HASH> 100644 --- a/actionpack/lib/action_view/template/handlers/erb.rb +++ b/actionpack/lib/action_view/template/handlers/erb.rb @@ -7,7 +7,7 @@ module ActionView class OutputBuffer < ActiveSupport::SafeBuffer def initialize(*) super - encode! + encode! if encoding_aware? end def <<(value) @@ -106,6 +106,8 @@ module ActionView if !encoding && (template.source.encoding == Encoding::BINARY) raise WrongEncodingError.new(template_source, Encoding.default_external) end + else + erb = template.source.dup end result = self.class.erb_implementation.new( diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/template/template_test.rb +++ b/actionpack/test/template/template_test.rb @@ -1,9 +1,11 @@ require "abstract_unit" -# These are the normal settings that will be set up by Railties -# TODO: Have these tests support other combinations of these values -Encoding.default_internal = "UTF-8" -Encoding.default_external = "UTF-8" +if "ruby".encoding_aware? + # These are the normal settings that will be set up by Railties + # TODO: Have these tests support other combinations of these values + Encoding.default_internal = "UTF-8" + Encoding.default_external = "UTF-8" +end class TestERBTemplate < ActiveSupport::TestCase ERBHandler = ActionView::Template::Handlers::ERB
Make sure encoding changes don't break <I>
rails_rails
train
bdb0e6f1d196f6c541c1d23fd8f11bcd9faf465e
diff --git a/lib/magic_lamp.rb b/lib/magic_lamp.rb index <HASH>..<HASH> 100644 --- a/lib/magic_lamp.rb +++ b/lib/magic_lamp.rb @@ -49,6 +49,8 @@ module MagicLamp registered_fixtures[fixture_name] = [controller_class, block] end + alias_method :register, :register_fixture + alias_method :fixture, :register_fixture alias_method :rub, :register_fixture alias_method :wish, :register_fixture diff --git a/spec/lib/magic_lamp_spec.rb b/spec/lib/magic_lamp_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/magic_lamp_spec.rb +++ b/spec/lib/magic_lamp_spec.rb @@ -10,6 +10,8 @@ describe MagicLamp do end context "aliases" do + it { is_expected.to alias_the_method(:register_fixture).to(:register) } + it { is_expected.to alias_the_method(:register_fixture).to(:fixture) } it { is_expected.to alias_the_method(:register_fixture).to(:rub) } it { is_expected.to alias_the_method(:register_fixture).to(:wish) } end
aliased register_fixture to register and fixture
crismali_magic_lamp
train
21e51cb0294cc271205bd208ace6fee9a75b880a
diff --git a/daemon/cmd/endpoint.go b/daemon/cmd/endpoint.go index <HASH>..<HASH> 100644 --- a/daemon/cmd/endpoint.go +++ b/daemon/cmd/endpoint.go @@ -309,17 +309,16 @@ func (d *Daemon) createEndpoint(ctx context.Context, owner regeneration.Owner, e if epTemplate.DatapathConfiguration == nil { dpConfig := endpoint.NewDatapathConfiguration() epTemplate.DatapathConfiguration = &dpConfig + } + if option.Config.EnableEndpointRoutes { + epTemplate.DatapathConfiguration.InstallEndpointRoute = true + epTemplate.DatapathConfiguration.RequireEgressProg = true + disabled := false + epTemplate.DatapathConfiguration.RequireRouting = &disabled } else { - if option.Config.EnableEndpointRoutes { - epTemplate.DatapathConfiguration.InstallEndpointRoute = true - epTemplate.DatapathConfiguration.RequireEgressProg = true - disabled := false - epTemplate.DatapathConfiguration.RequireRouting = &disabled - } else { - epTemplate.DatapathConfiguration.InstallEndpointRoute = false - epTemplate.DatapathConfiguration.RequireEgressProg = false - epTemplate.DatapathConfiguration.RequireRouting = nil - } + epTemplate.DatapathConfiguration.InstallEndpointRoute = false + epTemplate.DatapathConfiguration.RequireEgressProg = false + epTemplate.DatapathConfiguration.RequireRouting = nil } log.WithFields(logrus.Fields{
daemon: Fix the init of the endpoints' datapath config An incorrect refactor, <I> ("endpoint: Refactor init of EndpointDatapathConfiguration"), changed the behavior of that function. This commit fixes it to restore the intended behavior. See [1] for more details. 1 - <URL>
cilium_cilium
train
3d1f4fe56d1dface96c31af6b680f9476488b62f
diff --git a/test.py b/test.py index <HASH>..<HASH> 100644 --- a/test.py +++ b/test.py @@ -81,13 +81,6 @@ print('\nGetting details for %s\n' % testApps[0]) details = server.details(testApps[0]) print(details) -# USER PROFILE -print('\nGettung user profile information\n') -user = server.userProfile() -if 'Noto Sans' not in user['title']: - raise Exception("Wrong userProfile behaviour") - sys.exit(1) - # REVIEWS print('\nGetting reviews for %s\n' % testApps[0]) revs = server.reviews(testApps[0])
Removed unstable userProfile from test
NoMore201_googleplay-api
train
8e3c6aae3c94e4cdbb46f7e9412eb7dea5721b73
diff --git a/src/lokijs.js b/src/lokijs.js index <HASH>..<HASH> 100644 --- a/src/lokijs.js +++ b/src/lokijs.js @@ -1942,8 +1942,9 @@ // if an index exists for the property being queried against, use it // for now only enabling for non-chained query (who's set of docs matches index) // or chained queries where it is the first filter applied and prop is indexed - if ((!this.searchIsChained || (this.searchIsChained && !this.filterInitialized)) && - indexedOpsList.indexOf(operator) !== -1 && this.collection.binaryIndices.hasOwnProperty(property)) { + if ((!this.searchIsChained || !this.filterInitialized) + && indexedOpsList.indexOf(operator) !== -1 + && this.collection.binaryIndices[property]) { // this is where our lazy index rebuilding will take place // basically we will leave all indexes dirty until we need them // so here we will rebuild only the index tied to this property
Minor improvement (simplification) to the logical condition expression.
techfort_LokiJS
train
d5a0c8ecd4a2477ea6141011c42e8258f9ddf577
diff --git a/test/sass/conversion_test.rb b/test/sass/conversion_test.rb index <HASH>..<HASH> 100755 --- a/test/sass/conversion_test.rb +++ b/test/sass/conversion_test.rb @@ -94,6 +94,12 @@ foo bar baz bang { baz: bang; } SCSS + + assert_scss_to_scss <<SCSS +foo bar +baz bang { + baz: bang; } +SCSS end def test_escaped_selector @@ -169,6 +175,19 @@ foo bar { bam boon; } SCSS + + assert_scss_to_scss <<OUT, <<IN +foo bar { + baz: bip + bam + boon; } +OUT +foo bar { + baz: + bip + bam + boon; } +IN end def test_multiline_dynamic_properties @@ -182,6 +201,17 @@ foo bar { "bam" 12px; } SCSS + + assert_scss_to_scss <<OUT, <<IN +foo bar { + baz= !bip "bam" 12px; } +OUT +foo bar { + baz= + !bip + "bam" + 12px; } +IN end def test_silent_comments @@ -263,6 +293,16 @@ foo bar { a: b; } SCSS + assert_scss_to_scss <<SCSS +/* foo + bar + baz + bang */ + +foo bar { + a: b; } +SCSS + assert_renders <<SASS, <<SCSS /* foo bar @@ -635,9 +675,17 @@ SCSS "Expected SCSS to transform to Sass") end - def assert_scss_to_scss(scss, options = {}) - assert_equal(scss.rstrip, to_scss(scss, options.merge(:syntax => :scss)).rstrip, - "Expected SCSS to transform to itself") + def assert_scss_to_scss(scss, in_scss = nil, options = nil) + if in_scss.is_a?(Hash) + options = in_scss + in_scss = nil + end + + in_scss ||= scss + options ||= {} + + assert_equal(scss.rstrip, to_scss(in_scss, options.merge(:syntax => :scss)).rstrip, + "Expected SCSS to transform to #{scss == in_scss ? 'itself' : 'SCSS'}k") end def assert_sass_to_scss(scss, sass, options = {})
[Sass] [SCSS] Add a few more sass2scss tests.
sass_ruby-sass
train
b7e39c142e51d8b66536de536131c2fece6cc58e
diff --git a/src/SocialiteManager.php b/src/SocialiteManager.php index <HASH>..<HASH> 100644 --- a/src/SocialiteManager.php +++ b/src/SocialiteManager.php @@ -35,7 +35,7 @@ class SocialiteManager extends Manager implements Contracts\Factory */ protected function createGithubDriver() { - $config = $this->container['config']['services.github']; + $config = $this->container->make('config')['services.github']; return $this->buildProvider( GithubProvider::class, $config @@ -49,7 +49,7 @@ class SocialiteManager extends Manager implements Contracts\Factory */ protected function createFacebookDriver() { - $config = $this->container['config']['services.facebook']; + $config = $this->container->make('config')['services.facebook']; return $this->buildProvider( FacebookProvider::class, $config @@ -63,7 +63,7 @@ class SocialiteManager extends Manager implements Contracts\Factory */ protected function createGoogleDriver() { - $config = $this->container['config']['services.google']; + $config = $this->container->make('config')['services.google']; return $this->buildProvider( GoogleProvider::class, $config @@ -77,7 +77,7 @@ class SocialiteManager extends Manager implements Contracts\Factory */ protected function createLinkedinDriver() { - $config = $this->container['config']['services.linkedin']; + $config = $this->container->make('config')['services.linkedin']; return $this->buildProvider( LinkedInProvider::class, $config @@ -91,7 +91,7 @@ class SocialiteManager extends Manager implements Contracts\Factory */ protected function createBitbucketDriver() { - $config = $this->container['config']['services.bitbucket']; + $config = $this->container->make('config')['services.bitbucket']; return $this->buildProvider( BitbucketProvider::class, $config @@ -105,7 +105,7 @@ class SocialiteManager extends Manager implements Contracts\Factory */ protected function createGitlabDriver() { - $config = $this->container['config']['services.gitlab']; + $config = $this->container->make('config')['services.gitlab']; return $this->buildProvider( GitlabProvider::class, $config @@ -122,7 +122,7 @@ class SocialiteManager extends Manager implements Contracts\Factory public function buildProvider($provider, $config) { return new $provider( - $this->container['request'], $config['client_id'], + $this->container->make('request'), $config['client_id'], $config['client_secret'], $this->formatRedirectUrl($config), Arr::get($config, 'guzzle', []) ); @@ -135,10 +135,10 @@ class SocialiteManager extends Manager implements Contracts\Factory */ protected function createTwitterDriver() { - $config = $this->container['config']['services.twitter']; + $config = $this->container->make('config')['services.twitter']; return new TwitterProvider( - $this->container['request'], new TwitterServer($this->formatConfig($config)) + $this->container->make('request'), new TwitterServer($this->formatConfig($config)) ); } @@ -168,7 +168,7 @@ class SocialiteManager extends Manager implements Contracts\Factory $redirect = value($config['redirect']); return Str::startsWith($redirect, '/') - ? $this->container['url']->to($redirect) + ? $this->container->make('url')->to($redirect) : $redirect; }
removed array access on the container instance in SocialiteManger.php
laravel_socialite
train
880128c339b2f5725374a0e42d8842eb9c7edc2b
diff --git a/system/src/Grav/Console/Cli/InstallCommand.php b/system/src/Grav/Console/Cli/InstallCommand.php index <HASH>..<HASH> 100644 --- a/system/src/Grav/Console/Cli/InstallCommand.php +++ b/system/src/Grav/Console/Cli/InstallCommand.php @@ -117,7 +117,7 @@ class InstallCommand extends ConsoleCommand $this->destination = rtrim($this->destination, DS); $path = $this->destination . DS . $data['path']; if (!file_exists($path)) { - exec('cd "' . $this->destination . '" && git clone -b ' . $data['branch'] . ' ' . $data['url'] . ' ' . $data['path'], $output, $return); + exec('cd "' . $this->destination . '" && git clone -b ' . $data['branch'] . ' --depth 1 ' . $data['url'] . ' ' . $data['path'], $output, $return); if (!$return) { $this->output->writeln('<green>SUCCESS</green> cloned <magenta>' . $data['url'] . '</magenta> -> <cyan>' . $path . '</cyan>');
Update Grav Console Cli InstallCommand.php (#<I>) why do I have to clone the entire history of the plugin?
getgrav_grav
train
5073c205e3a5c189a8bf0eae52a4c48ee1b88eb1
diff --git a/poetry/inspection/info.py b/poetry/inspection/info.py index <HASH>..<HASH> 100644 --- a/poetry/inspection/info.py +++ b/poetry/inspection/info.py @@ -450,7 +450,9 @@ class PackageInfo: except PackageInfoError: pass - with ephemeral_environment(pip=True, wheel=True, setuptools=True) as venv: + with ephemeral_environment( + with_pip=True, with_wheel=True, with_setuptools=True + ) as venv: # TODO: cache PEP 517 build environment corresponding to each project venv dest_dir = venv.path.parent / "dist" dest_dir.mkdir() diff --git a/poetry/utils/env.py b/poetry/utils/env.py index <HASH>..<HASH> 100644 --- a/poetry/utils/env.py +++ b/poetry/utils/env.py @@ -1464,9 +1464,10 @@ class NullEnv(SystemEnv): @contextmanager def ephemeral_environment( executable=None, - pip: bool = False, - wheel: Optional[bool] = None, - setuptools: Optional[bool] = None, + flags: Dict[str, bool] = None, + with_pip: bool = False, + with_wheel: Optional[bool] = None, + with_setuptools: Optional[bool] = None, ) -> ContextManager[VirtualEnv]: with temporary_directory() as tmp_dir: # TODO: cache PEP 517 build environment corresponding to each project venv @@ -1474,9 +1475,10 @@ def ephemeral_environment( EnvManager.build_venv( path=venv_dir.as_posix(), executable=executable, - with_pip=pip, - with_wheel=wheel, - with_setuptools=setuptools, + flags=flags, + with_pip=with_pip, + with_wheel=with_wheel, + with_setuptools=with_setuptools, ) yield VirtualEnv(venv_dir, venv_dir) diff --git a/poetry/utils/pip.py b/poetry/utils/pip.py index <HASH>..<HASH> 100644 --- a/poetry/utils/pip.py +++ b/poetry/utils/pip.py @@ -47,7 +47,7 @@ def pip_install( # Under certain Python3.6 installs vendored pip wheel does not contain zip-safe # pep517 lib. In this cases we create an isolated ephemeral virtual environment. with ephemeral_environment( - executable=environment.python, pip=True, setuptools=True + executable=environment.python, with_pip=True, with_setuptools=True ) as env: return environment.run( env._bin("pip"),
env: align ephemeral environment interface to build
sdispater_poetry
train
c46a2a123c0d7bd6ae7dbab27d93b71e77cf41b2
diff --git a/.ruby-version b/.ruby-version index <HASH>..<HASH> 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -2.1.5 +2.2.0 diff --git a/lib/mongoid/extensions.rb b/lib/mongoid/extensions.rb index <HASH>..<HASH> 100644 --- a/lib/mongoid/extensions.rb +++ b/lib/mongoid/extensions.rb @@ -13,8 +13,15 @@ class Symbol end class BSON::Document - def symbolize_keys - to_h.symbolize_keys + # We need to override this as ActiveSupport creates a new Object, instead of a new Hash + # see https://github.com/rails/rails/commit/f1bad130d0c9bd77c94e43b696adca56c46a66aa + def transform_keys + return enum_for(:transform_keys) unless block_given? + result = {} + each_key do |key| + result[yield(key)] = self[key] + end + result end end diff --git a/lib/mongoid/tasks/database.rb b/lib/mongoid/tasks/database.rb index <HASH>..<HASH> 100644 --- a/lib/mongoid/tasks/database.rb +++ b/lib/mongoid/tasks/database.rb @@ -45,8 +45,7 @@ module Mongoid model.collection.indexes.each do |index| # ignore default index unless index['name'] == '_id_' - # to_h because BSON::Document does not allow symbolic keys - key = index['key'].to_h.symbolize_keys + key = index['key'].symbolize_keys spec = model.index_specification(key) unless spec # index not specified @@ -73,8 +72,7 @@ module Mongoid def remove_undefined_indexes(models = ::Mongoid.models) undefined_indexes(models).each do |model, indexes| indexes.each do |index| - # to_h because BSON::Document does not allow symbolic keys - key = index['key'].to_h.symbolize_keys + key = index['key'].symbolize_keys model.collection.indexes.drop(key) logger.info("MONGOID: Removing index: #{index['name']} on #{model}.") end
override transform_keys on BSON::Document instead, to fix symbolize_keys We cannot use to_hash , on a Hash object as that will not work on ruby <I>
mongodb_mongoid
train
fb3e0591d054be596ddd4bdebaf58d0c71c21b1c
diff --git a/commerce-product-definitions-web/src/main/java/com/liferay/commerce/product/definitions/web/internal/portlet/action/EditCPDefinitionLinkMVCActionCommand.java b/commerce-product-definitions-web/src/main/java/com/liferay/commerce/product/definitions/web/internal/portlet/action/EditCPDefinitionLinkMVCActionCommand.java index <HASH>..<HASH> 100644 --- a/commerce-product-definitions-web/src/main/java/com/liferay/commerce/product/definitions/web/internal/portlet/action/EditCPDefinitionLinkMVCActionCommand.java +++ b/commerce-product-definitions-web/src/main/java/com/liferay/commerce/product/definitions/web/internal/portlet/action/EditCPDefinitionLinkMVCActionCommand.java @@ -16,8 +16,10 @@ package com.liferay.commerce.product.definitions.web.internal.portlet.action; import com.liferay.commerce.product.constants.CPPortletKeys; import com.liferay.commerce.product.exception.NoSuchCPDefinitionLinkException; +import com.liferay.commerce.product.model.CPDefinition; import com.liferay.commerce.product.model.CPDefinitionLink; import com.liferay.commerce.product.service.CPDefinitionLinkService; +import com.liferay.commerce.product.service.CPDefinitionService; import com.liferay.portal.kernel.portlet.bridges.mvc.BaseMVCActionCommand; import com.liferay.portal.kernel.portlet.bridges.mvc.MVCActionCommand; import com.liferay.portal.kernel.security.auth.PrincipalException; @@ -70,8 +72,14 @@ public class EditCPDefinitionLinkMVCActionCommand extends BaseMVCActionCommand { ServiceContext serviceContext = ServiceContextFactory.getInstance( CPDefinitionLink.class.getName(), actionRequest); - _cpDefinitionLinkService.updateCPDefinitionLinks( - cpDefinitionId, cpDefinitionIds2, type, serviceContext); + for (long curCPDefinitionId : cpDefinitionIds2) { + CPDefinition cpDefinition = _cpDefinitionService.getCPDefinition( + curCPDefinitionId); + + _cpDefinitionLinkService.addCPDefinitionLink( + cpDefinitionId, cpDefinition.getCProductId(), 0.0, type, + serviceContext); + } } protected void deleteCPDefinitionLinks(ActionRequest actionRequest) @@ -152,4 +160,7 @@ public class EditCPDefinitionLinkMVCActionCommand extends BaseMVCActionCommand { @Reference private CPDefinitionLinkService _cpDefinitionLinkService; + @Reference + private CPDefinitionService _cpDefinitionService; + } \ No newline at end of file
COMMERCE-<I> We should be using the add method not update
liferay_com-liferay-commerce
train
1d8a7477734cbedc7e43a8b4628095ddb0c18626
diff --git a/test/socket.io.js b/test/socket.io.js index <HASH>..<HASH> 100644 --- a/test/socket.io.js +++ b/test/socket.io.js @@ -202,4 +202,21 @@ describe('socket.io', function(){ }); }); }); + + describe('socket', function(){ + it('should receive message events through `send`', function(done){ + var srv = http(); + var sio = io(srv); + srv.listen(function(){ + var socket = client(srv); + sio.on('connection', function(s){ + s.on('message', function(a){ + expect(a).to.be(1337); + done(); + }); + socket.send(1337); + }); + }); + }); + }); });
test: added `socket#send` test
socketio_socket.io
train
758124d2bf86c87e62b959cc0afaa27b26ace44d
diff --git a/openquake/hazardlib/contexts.py b/openquake/hazardlib/contexts.py index <HASH>..<HASH> 100644 --- a/openquake/hazardlib/contexts.py +++ b/openquake/hazardlib/contexts.py @@ -440,7 +440,15 @@ class PmapMaker(): acc = AccumDict(accum=[]) distmax = max(dctx.rrup.max() for rup, sctx, dctx in ctxs) for rup, sctx, dctx in ctxs: - tup = [getattr(rup, p) for p in self.REQUIRES_RUPTURE_PARAMETERS] + tup = [] + for p in self.REQUIRES_RUPTURE_PARAMETERS: + if (p != 'mag' and self.pointsource_distance is not None and + dctx.rrup.min() > self.pointsource_distance): + tup.append(0) + # all nonmag rupture parameters are collapsed to 0 + # over the pointsource_distance + else: + tup.append(getattr(rup, p)) for name in self.REQUIRES_DISTANCES: dists = getattr(dctx, name) tup.extend(I16(dists / distmax / precision))
Extended pointsource_distance to non-point sources
gem_oq-engine
train
8b71c7036b1b772888e4dbd227de37df3905e54c
diff --git a/src/babel.js b/src/babel.js index <HASH>..<HASH> 100644 --- a/src/babel.js +++ b/src/babel.js @@ -15,8 +15,8 @@ const STYLE_COMPONENT_ID = 'styleId' const STYLE_COMPONENT_CSS = 'css' export default function ({types: t}) { - const isGlobalEl = el => el.attributes.some(attr => ( - attr.name.name === GLOBAL_ATTRIBUTE + const isGlobalEl = el => el.attributes.some(({name}) => ( + name && name.name === GLOBAL_ATTRIBUTE )) const isStyledJsx = ({node: el}) => ( @@ -93,8 +93,11 @@ export default function ({types: t}) { name !== STYLE_COMPONENT && name.charAt(0) !== name.charAt(0).toUpperCase() ) { - for (const attr of el.attributes) { - if (attr.name === MARKUP_ATTRIBUTE || attr.name.name === MARKUP_ATTRIBUTE) { + for (const {name} of el.attributes) { + if (!name) { + continue + } + if (name === MARKUP_ATTRIBUTE || name.name === MARKUP_ATTRIBUTE) { // avoid double attributes return } diff --git a/test/fixtures/multiple-jsx.js b/test/fixtures/multiple-jsx.js index <HASH>..<HASH> 100644 --- a/test/fixtures/multiple-jsx.js +++ b/test/fixtures/multiple-jsx.js @@ -1,6 +1,10 @@ +const attrs = { + id: 'test' +} + const Test1 = () => ( <div> - <span>test</span> + <span {...attrs} data-test="test">test</span> <Component /> <style jsx>{` span { diff --git a/test/fixtures/multiple-jsx.out.js b/test/fixtures/multiple-jsx.out.js index <HASH>..<HASH> 100644 --- a/test/fixtures/multiple-jsx.out.js +++ b/test/fixtures/multiple-jsx.out.js @@ -1,6 +1,10 @@ import _JSXStyle from "styled-jsx/style"; +const attrs = { + id: 'test' +}; + const Test1 = () => <div data-jsx={1535297024}> - <span data-jsx={1535297024}>test</span> + <span {...attrs} data-test="test" data-jsx={1535297024}>test</span> <Component /> <_JSXStyle styleId={1535297024} css={"span[data-jsx=\"1535297024\"] {color: red;}"} /> </div>;
Add support for spread attributes (patch) (#<I>)
zeit_styled-jsx
train
ed6ac4634a58f3d64b714e3e5c919b0d294fe3cc
diff --git a/completion/tests/privacy_test.php b/completion/tests/privacy_test.php index <HASH>..<HASH> 100644 --- a/completion/tests/privacy_test.php +++ b/completion/tests/privacy_test.php @@ -193,13 +193,13 @@ class core_completion_privacy_test extends \core_privacy\tests\provider_testcase $hasno = array_search('No', $coursecompletion1['criteria'], true); $this->assertFalse($hasno); $coursecompletion2 = \core_completion\privacy\provider::get_course_completion_info($user2, $this->course); - $hasyes = array_search('Yes', $coursecompletion1['criteria'], true); + $hasyes = array_search('Yes', $coursecompletion2['criteria'], true); $this->assertFalse($hasyes); $coursecompletion3 = \core_completion\privacy\provider::get_course_completion_info($user3, $this->course); - $hasno = array_search('No', $coursecompletion1['criteria'], true); + $hasno = array_search('No', $coursecompletion3['criteria'], true); $this->assertFalse($hasno); $coursecompletion4 = \core_completion\privacy\provider::get_course_completion_info($user4, $this->course); - $hasyes = array_search('Yes', $coursecompletion1['criteria'], true); + $hasyes = array_search('Yes', $coursecompletion4['criteria'], true); $this->assertFalse($hasyes); }
MDL-<I> completion: fixed assertions in privacy test
moodle_moodle
train
afbf44fbedeed586add2d0308280f6372fcedb76
diff --git a/src/Renderer/Text.php b/src/Renderer/Text.php index <HASH>..<HASH> 100644 --- a/src/Renderer/Text.php +++ b/src/Renderer/Text.php @@ -24,8 +24,6 @@ class Text protected $buffer = ''; - protected $formatterHelper; - protected $useBuffer = false; public function __construct(OutputInterface $output, FormatterHelper $formatterHelper, $buffer = false, $colors = true) @@ -35,7 +33,6 @@ class Text $this->type = OutputInterface::OUTPUT_PLAIN; } $this->useBuffer = $buffer; - $this->formatterHelper = $formatterHelper; } public function write($string, $eol = true) @@ -91,8 +88,9 @@ class Text $error[] = 'Stderr:'; $error = array_merge($error, $this->indent($result['stderr'], true)); } - $formattedBlock = $this->formatterHelper->formatBlock($error, 'fg=red', false); - $this->write($formattedBlock); + foreach ($error as $err) { + $this->write('<fg=red>' . $err . '</fg=red>'); + } } /**
Tidy up error block on initial test runs; less in your face red background!
humbug_humbug
train
1e24208012a338bdf0fafdcfcf90dcf036f240f3
diff --git a/lib/deep_unrest.rb b/lib/deep_unrest.rb index <HASH>..<HASH> 100644 --- a/lib/deep_unrest.rb +++ b/lib/deep_unrest.rb @@ -464,7 +464,7 @@ module DeepUnrest def self.perform_update(params, user) # reject new resources marked for destruction viable_params = params.reject do |param| - temp_id?(param[:path]) && param[:destroy] + temp_id?(param[:path]) && param[:destroy].present? end # identify requested scope(s)
[bugfix] another case of bad :destroy check
graveflex_deep_unrest
train
38d43ff260bd67b02a4fbb4d013482e723cb9b61
diff --git a/app/models/concerns/socializer/object_type_base.rb b/app/models/concerns/socializer/object_type_base.rb index <HASH>..<HASH> 100644 --- a/app/models/concerns/socializer/object_type_base.rb +++ b/app/models/concerns/socializer/object_type_base.rb @@ -10,7 +10,12 @@ module Socializer before_create :activity_object_builder after_create :append_to_activity_stream + end + module ClassMethods + def guids + joins(:activity_object).select(activity_object: :id) + end end def guid
add a guids class method
socializer_socializer
train
8101150e61648a0cd46c5a7d9913e70a87f1f522
diff --git a/packages/material-ui/src/Input/InputLabel.js b/packages/material-ui/src/Input/InputLabel.js index <HASH>..<HASH> 100644 --- a/packages/material-ui/src/Input/InputLabel.js +++ b/packages/material-ui/src/Input/InputLabel.js @@ -24,6 +24,7 @@ export const styles = theme => ({ shrink: { transform: 'translate(0, 1.5px) scale(0.75)', transformOrigin: 'top left', + width: '133.33%', }, animated: { transition: theme.transitions.create('transform', {
Increase scaled-down label width to match <I>% input width (#<I>) Input label is shrunk using CSS `scale`. The <I>% default width is becoming smaller than full input width. Increasing accordingly the shrunk input label `width` let it occupy as much space as possible, avoiding in some case the wrapping of text, which is very inelegant in this component.
mui-org_material-ui
train