hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
07397cea84fc3775281f552d947cfb66fba54a24
diff --git a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php @@ -383,8 +383,10 @@ trait QueriesRelationships $relation = $this->getRelationWithoutConstraints($name); if ($function) { + $predictedColumn = $this->getQuery()->from === $relation->getQuery()->getQuery()->from ? "{$relation->getRelationCountHash(true)}.$column" : $column; + $expression = sprintf('%s(%s)', $function, $this->getQuery()->getGrammar()->wrap( - $column === '*' ? $column : $relation->getRelated()->qualifyColumn($column) + $column === '*' ? $column : $relation->getRelated()->qualifyColumn($predictedColumn) )); } else { $expression = $column; diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php b/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php @@ -282,11 +282,12 @@ class BelongsTo extends Relation /** * Get a relationship join table hash. * + * @param bool $lockCount * @return string */ - public function getRelationCountHash() + public function getRelationCountHash($lockCount = false) { - return 'laravel_reserved_'.static::$selfJoinCount++; + return 'laravel_reserved_'.($lockCount ? static::$selfJoinCount : static::$selfJoinCount++); } /** diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -1170,11 +1170,12 @@ class BelongsToMany extends Relation /** * Get a relationship join table hash. * + * @param bool $lockCount * @return string */ - public function getRelationCountHash() + public function getRelationCountHash($lockCount = false) { - return 'laravel_reserved_'.static::$selfJoinCount++; + return 'laravel_reserved_'.($lockCount ? static::$selfJoinCount : static::$selfJoinCount++); } /** diff --git a/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php b/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php @@ -599,11 +599,12 @@ class HasManyThrough extends Relation /** * Get a relationship join table hash. * + * @param bool $lockCount * @return string */ - public function getRelationCountHash() + public function getRelationCountHash($lockCount = false) { - return 'laravel_reserved_'.static::$selfJoinCount++; + return 'laravel_reserved_'.($lockCount ? static::$selfJoinCount : static::$selfJoinCount++); } /** diff --git a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php @@ -366,11 +366,12 @@ abstract class HasOneOrMany extends Relation /** * Get a relationship join table hash. * + * @param bool $lockCount * @return string */ - public function getRelationCountHash() + public function getRelationCountHash($lockCount = false) { - return 'laravel_reserved_'.static::$selfJoinCount++; + return 'laravel_reserved_'.($lockCount ? static::$selfJoinCount : static::$selfJoinCount++); } /**
Modify getRelationCountHash to prevent changing the counter and provide a way to predict the hash
laravel_framework
train
9d2ff10c0e1a6ddf73a9400107ed95b025f979aa
diff --git a/lib/ajax-datatables-rails.rb b/lib/ajax-datatables-rails.rb index <HASH>..<HASH> 100644 --- a/lib/ajax-datatables-rails.rb +++ b/lib/ajax-datatables-rails.rb @@ -4,25 +4,11 @@ class AjaxDatatablesRails VERSION = '0.0.1' - class << self - - def columns(column_array) - @@columns ||= column_array - end - - def model_name(model_name) - @@model_name ||= model_name - end - - def searchable_columns(columns_array) - @@searchable_columns ||= columns_array - end - - end - def initialize(view) @view = view end + + attr_reader :columns, :model_name, :searchable_columns def method_missing(meth, *args, &block) @view.send(meth, *args, &block) @@ -31,7 +17,7 @@ class AjaxDatatablesRails def as_json(options = {}) { sEcho: params[:sEcho].to_i, - iTotalRecords: @@model_name.count, + iTotalRecords: @model_name.count, iTotalDisplayRecords: get_raw_records.count, aaData: data } @@ -57,7 +43,7 @@ private def search_records(records) if params[:sSearch].present? - query = @@searchable_columns.map do |column| + query = @searchable_columns.map do |column| "#{column} LIKE :search" end.join(" OR ") records = records.where(query, search: "%#{params[:sSearch]}%") @@ -74,7 +60,7 @@ private end def sort_column - @@columns[params[:iSortCol_0].to_i] + @columns[params[:iSortCol_0].to_i] end def sort_direction diff --git a/lib/generators/ajaxdatatable/templates/datatable.rb b/lib/generators/ajaxdatatable/templates/datatable.rb index <HASH>..<HASH> 100644 --- a/lib/generators/ajaxdatatable/templates/datatable.rb +++ b/lib/generators/ajaxdatatable/templates/datatable.rb @@ -1,7 +1,11 @@ class <%= model.classify.pluralize %>Datatable < AjaxDatatablesRails - model_name <%= model.classify %> - columns # insert array of column names here - searchable_columns #insert array of columns that will be searched + + def initialize(view) + @model_name = <%= model.classify %> + @columns = # insert array of column names here + @searchable_columns = #insert array of columns that will be searched + super(view) + end private
changed the class variables over to instance variables and updated the template"
jbox-web_ajax-datatables-rails
train
f521e12f634be829fe36a5b36321b0139751df8d
diff --git a/structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java b/structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java index <HASH>..<HASH> 100644 --- a/structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java +++ b/structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java @@ -976,7 +976,8 @@ public class HtmlServlet extends HttpServlet implements HttpServiceServlet { private Page findPage(final SecurityContext securityContext, List<Page> pages, final String path, final EditMode edit) throws FrameworkException { if (pages == null) { - pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).sort(Page.position).order(false).getAsList(); + pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).getAsList(); + Collections.sort(pages, new GraphObjectComparator(Page.position, GraphObjectComparator.ASCENDING)); } for (final Page page : pages) { @@ -993,7 +994,7 @@ public class HtmlServlet extends HttpServlet implements HttpServiceServlet { } /** - * Find the page with the lowest position value which is visible in the + * Find the page with the lowest non-empty position value which is visible in the * current security context and for the given site. * * @param securityContext @@ -1005,13 +1006,22 @@ public class HtmlServlet extends HttpServlet implements HttpServiceServlet { private Page findIndexPage(final SecurityContext securityContext, List<Page> pages, final EditMode edit) throws FrameworkException { if (pages == null) { - pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).sort(Page.position).order(false).getAsList(); + pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).getAsList(); Collections.sort(pages, new GraphObjectComparator(Page.position, GraphObjectComparator.ASCENDING)); } for (Page page : pages) { + + if (page.getProperty(Page.position) == null) { + continue; + } - if (securityContext.isVisible(page) && (EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page))) { + boolean isProtectedAndHasBasicAuthEnabled = page.getProperty(Page.enableBasicAuth) != null && page.getProperty(Page.visibleToAuthenticatedUsers); + boolean isPublicOrVisibleForAuthenticatedUser = securityContext.isVisible(page); + boolean isVisibleForSiteOrIsEditMode = (EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page)); + + if (isProtectedAndHasBasicAuthEnabled || isPublicOrVisibleForAuthenticatedUser || isVisibleForSiteOrIsEditMode) { + return page; } }
Take only pages with non-null position attribute into account when looking for the index page. Removed unnecessary sorting from the index query. Take also basic-auth enabled protected pages into account as index pages.
structr_structr
train
afd51bfa2fdc3ab7e3aa52ea6ae54148e06bbc5b
diff --git a/input/_multiple/checkbox.js b/input/_multiple/checkbox.js index <HASH>..<HASH> 100644 --- a/input/_multiple/checkbox.js +++ b/input/_multiple/checkbox.js @@ -14,6 +14,7 @@ var clear = require('es5-ext/lib/Array/prototype/clear') module.exports = DOMMultiple = function (document, ns/*, options*/) { DOMInput.apply(this, arguments); + this.allItems = []; this.reload(); }; @@ -42,7 +43,7 @@ DOMMultiple.prototype = Object.create(DOMInput.prototype, extend({ return this.items.map(function (item) { return item.value; }) .filter(function (value) { return value != null; }); }, function (value) { - this.items.forEach(function (item) { + this.allItems.forEach(function (item) { var obj = this.ns.fromInputValue(item.control.value); item.value = value.has(obj) ? obj : null; }, this); @@ -74,5 +75,6 @@ DOMMultiple.prototype = Object.create(DOMInput.prototype, extend({ input.listItem = dom; input.control.setAttribute('value', value); input.on('change', this.onChange); + this.allItems.push(input); return { dom: dom, input: input }; }, { method: 'renderItem', length: 1 })));
Reset values of all created inputs As they may be reused in next turn
medikoo_dbjs-dom
train
d249695c88653b085523e798a81bc4a4456527cc
diff --git a/tests/test_runner.py b/tests/test_runner.py index <HASH>..<HASH> 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -88,7 +88,11 @@ def test_run_max_threads(event_loop, max_threads): def test_event_loop_policy(caplog, policy, policy_name): """Test that a the runner switches to a different event loop policy when instructed to.""" component = ShutdownComponent() - run_application(component, event_loop_policy=policy) + old_policy = asyncio.get_event_loop_policy() + try: + run_application(component, event_loop_policy=policy) + finally: + asyncio.set_event_loop_policy(old_policy) records = [record for record in caplog.records if record.name == 'asphalt.core.runner'] assert len(records) == 6
Restore the event loop policy after testing Not doing this lets the last set event loop policy to leak onto other tests where it may cause unexpected results.
asphalt-framework_asphalt
train
4b307d357ece202633ea69fb41a13fa426bf4fa3
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -40,7 +40,7 @@ except ImportError as e: if __name__ == '__main__': setup( name='pyensembl', - version="0.8.2", + version="0.8.3", description="Python interface to ensembl reference genome metadata", author="Alex Rubinsteyn", author_email="alex {dot} rubinsteyn {at} mssm {dot} edu",
version bump for gtftools usage
openvax_pyensembl
train
4dbb8b6dc2fe0eb45462039464a5ab74b26818d0
diff --git a/test/python/transpiler/test_hoare_opt.py b/test/python/transpiler/test_hoare_opt.py index <HASH>..<HASH> 100644 --- a/test/python/transpiler/test_hoare_opt.py +++ b/test/python/transpiler/test_hoare_opt.py @@ -299,16 +299,16 @@ class TestHoareOptimizer(QiskitTestCase): """ The is_identity function determines whether a pair of gates forms the identity, when ignoring control qubits. """ - seq = [DAGNode({'type': 'op', 'op': XGate().control()}), - DAGNode({'type': 'op', 'op': XGate().control(2)})] + seq = [DAGNode(type='op', op=XGate().control()), + DAGNode(type='op', op=XGate().control(2))] self.assertTrue(HoareOptimizer()._is_identity(seq)) - seq = [DAGNode({'type': 'op', 'op': RZGate(-pi/2).control()}), - DAGNode({'type': 'op', 'op': RZGate(pi/2).control(2)})] + seq = [DAGNode(type='op', op=RZGate(-pi/2).control()), + DAGNode(type='op', op=RZGate(pi/2).control(2))] self.assertTrue(HoareOptimizer()._is_identity(seq)) - seq = [DAGNode({'type': 'op', 'op': CSwapGate()}), - DAGNode({'type': 'op', 'op': SwapGate()})] + seq = [DAGNode(type='op', op=CSwapGate()), + DAGNode(type='op', op=SwapGate())] self.assertTrue(HoareOptimizer()._is_identity(seq))
Fix deprecation warnings in hoare optimization tests (#<I>) The tests for the hoare optimization pass were emitting deprecation warnings because they were manually creating DAGNode objects and passing in the parameters as a dictionary instead of kwargs. This was deprecated in #<I> and actually adds some overhead. This commit fixes this oversight and uses kwargs for the test's DAGNode creation.
Qiskit_qiskit-terra
train
e0a5eecf2afd5cdc413cd20136bb980d03fd9ffa
diff --git a/src/Symfony/Component/DependencyInjection/ServiceLocator.php b/src/Symfony/Component/DependencyInjection/ServiceLocator.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/DependencyInjection/ServiceLocator.php +++ b/src/Symfony/Component/DependencyInjection/ServiceLocator.php @@ -22,7 +22,6 @@ use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; class ServiceLocator implements PsrContainerInterface { private $factories; - private $values = array(); /** * @param callable[] $factories @@ -53,13 +52,12 @@ class ServiceLocator implements PsrContainerInterface throw new ServiceCircularReferenceException($id, array($id, $id)); } - if (false !== $factory) { - $this->factories[$id] = true; - $this->values[$id] = $factory(); - $this->factories[$id] = false; + $this->factories[$id] = true; + try { + return $factory(); + } finally { + $this->factories[$id] = $factory; } - - return $this->values[$id]; } public function __invoke($id) diff --git a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php @@ -40,15 +40,20 @@ class ServiceLocatorTest extends TestCase $this->assertSame('baz', $locator->get('bar')); } - public function testGetDoesNotExecuteTheSameCallableTwice() + public function testGetDoesNotMemoize() { $i = 0; - $locator = new ServiceLocator(array('foo' => function () use (&$i) { $i++; return 'bar'; })); + $locator = new ServiceLocator(array( + 'foo' => function () use (&$i) { + ++$i; + + return 'bar'; + }, + )); $this->assertSame('bar', $locator->get('foo')); $this->assertSame('bar', $locator->get('foo')); - $this->assertSame('bar', $locator->get('foo')); - $this->assertSame(1, $i); + $this->assertSame(2, $i); } /**
[DI] Remove useless state from ServiceLocator
symfony_symfony
train
2c90f35faf8e79e43537dd9bab805ad1516bd77a
diff --git a/test/processImage.js b/test/processImage.js index <HASH>..<HASH> 100644 --- a/test/processImage.js +++ b/test/processImage.js @@ -571,7 +571,7 @@ describe('express-processimage', () => { body: expect.it('to have metadata satisfying', { format: 'PNG', size: { - width: 40 + width: expect.it('to be a number') // FIXME: output should be 40 } }) } @@ -587,7 +587,7 @@ describe('express-processimage', () => { body: expect.it('to have metadata satisfying', { size: { width: 100, - height: 88 + height: expect.it('to be a number') // FIXME: output should be 88 }, Interlace: 'Line' }) @@ -1415,7 +1415,10 @@ describe('express-processimage', () => { }, body: expect.it('to have metadata satisfying', { format: 'PNG', - size: { width: 40, height: 17 } + size: { + width: 40, + height: expect.it('to be a number') // FIXME: output should be 17 + } }) }); });
Mark a couple of places where the output sizes do not match correctly.
papandreou_express-processimage
train
700d46e0975373addf2a06cc9ca7e140636716ac
diff --git a/zhmcclient/_cpc.py b/zhmcclient/_cpc.py index <HASH>..<HASH> 100644 --- a/zhmcclient/_cpc.py +++ b/zhmcclient/_cpc.py @@ -13,8 +13,8 @@ # limitations under the License. """ -A **Central Processor Complex (CPC)** is a physical z Systems computer. -A particular HMC can manage multiple CPCs. +A **Central Processor Complex (CPC)** is a physical z Systems or LinuxONE +computer. A particular HMC can manage multiple CPCs. The HMC can manage a range of old and new CPC generations. Some older CPC generations are not capable of supporting the HMC Web Services API; these older @@ -23,6 +23,19 @@ API. Therefore, such older CPCs will not show up at the HMC Web Services API, and thus will not show up in the API of this Python package. TODO: List earliest CPC generation that supports the HMC Web Services API. + +A CPC can be in any of the following three modes: + +- DPM mode: Dynamic Partition Manager is enabled for the CPC. +- Ensemble mode: The CPC is member of an ensemble. This Python client + does not support the functionality that is specific to ensemble mode. +- Classic mode: The CPC does not have Dynamic Partition Manager enabled, + and is not member of an ensemble. + +The functionality supported at the HMC API and thus also for users of this +Python client, depends on the mode in which the CPC currently is. If a +particular functionality is available only in a specific mode, that is +indicated in the description of the functionality. """ from __future__ import absolute_import @@ -112,7 +125,7 @@ class Cpc(BaseResource): def lpars(self): """ :class:`~zhmcclient.LparManager`: Manager object for the LPARs in this - CPC. + CPC. `None`, if the CPC is in DPM mode. """ # We do here some lazy loading. if not self._lpars: @@ -125,8 +138,8 @@ class Cpc(BaseResource): @property def partitions(self): """ - :class:`~zhmcclient.PartitionManager`: Manager object for the LPARs in - this CPC. + :class:`~zhmcclient.PartitionManager`: Manager object for the + partitions in this CPC. `None`, if the CPC is not in DPM mode. """ # We do here some lazy loading. if not self._partitions:
Added definition of the three CPC modes.
zhmcclient_python-zhmcclient
train
5c7e6966663aa91393acb7b0cd69702bea85773c
diff --git a/input/_relation.js b/input/_relation.js index <HASH>..<HASH> 100644 --- a/input/_relation.js +++ b/input/_relation.js @@ -19,3 +19,6 @@ relation.set('toDOMInputBox', function (document/*, options*/) { relation.set('toDOMInput', Db.Base.prototype.toDOMInput); relation._getRel_('fieldHint').ns = Db.String; +relation.set('DOMId', function () { + return this._id_.replace(/:/g, '-'); +});
DOMId property for relations Provides html safe id value
medikoo_dbjs-dom
train
c5834f553224ecb0f05c72d451cd32682ded1f01
diff --git a/visidata/cmdlog.py b/visidata/cmdlog.py index <HASH>..<HASH> 100644 --- a/visidata/cmdlog.py +++ b/visidata/cmdlog.py @@ -283,7 +283,7 @@ def replayOne(vd, r): vd.currentReplayRow = r longname = getattr(r, 'longname', None) - if r.sheet and not (r.sheet == 'override' and longname in ['set-option', 'unset-option']): + if r.sheet and longname not in ['set-option', 'unset-option']: vs = vd.getSheet(r.sheet) or vd.error('no sheet named %s' % r.sheet) else: vs = None
[replay] do not grab sheets for set-option; might not be loaded, yet
saulpw_visidata
train
f4af69cdbe56f55ba7b456f52e56c9526acf741b
diff --git a/detail/TimeForwarder.js b/detail/TimeForwarder.js index <HASH>..<HASH> 100644 --- a/detail/TimeForwarder.js +++ b/detail/TimeForwarder.js @@ -15,11 +15,12 @@ function delayByCycling(schedule, cycleCount, f) { })(f); } -function TimeForwarder(timeServer, timerInterceptor, immediateInterceptor) { +function TimeForwarder(timeServer, timerInterceptor, immediateInterceptor, debugLogger) { this.forwardingStartedSavedStack = undefined; this.timerInterceptor = timerInterceptor; this.timeServer = timeServer; this.immediateInterceptor = immediateInterceptor; + this.debugLogger = debugLogger; } TimeForwarder.prototype.prepareTimeReport = function() { @@ -88,6 +89,7 @@ TimeForwarder.prototype.advanceTime = function(timeToForward) { } that.timeServer.targetTime = that.timeServer.currentTime.extended(advanceStep); + that.debugLogger('advancing time to ' + that.timeServer.targetTime.toNanoseconds() + 'ns'); that.startExpiringEvents(); // that's a workaround - in certain cases I believe this might not work (pathological chains of setImmediate/process.nextTick) @@ -202,4 +204,4 @@ TimeForwarder.prototype.blockSystem = function(timeToBlock) { this.fireAllOutdatedTimers(); }; -module.exports = TimeForwarder; \ No newline at end of file +module.exports = TimeForwarder; diff --git a/tests/DebugLoggingTests.js b/tests/DebugLoggingTests.js index <HASH>..<HASH> 100644 --- a/tests/DebugLoggingTests.js +++ b/tests/DebugLoggingTests.js @@ -15,7 +15,6 @@ describe('zurvan', function() { .then(function() { assert(messages.length === 1); assert(messages[0] === 'intercepting timers'); - }).then(function() { return zurvan.releaseTimers(); }).then(function() { assert(messages.length === 2); @@ -30,11 +29,31 @@ describe('zurvan', function() { }; return zurvan.interceptTimers({debugLogger: logger}) .then(function() { + assert(messages.length === 1); + assert(messages[0] === 'intercepting timers'); return zurvan.forcedReleaseTimers(); }).then(function() { assert(messages.length === 2); assert(messages[1] === 'releasing timers (forced)'); }); }); + + it('logs on advancing time', function() { + var messages = [] + var logger = function(message) { + messages.push(message); + }; + return zurvan.interceptTimers({debugLogger: logger}) + .then(function() { + assert(messages.length === 2); + assert(messages[0] === 'intercepting timers'); + assert(messages[1] === 'advancing time to 0ns'); + return zurvan.advanceTime(1000); + }).then(function() { + assert(messages.length === 3); + assert(messages[2] === 'advancing time to 1000000000ns'); + return zurvan.releaseTimers(); + }); + }); }); }); diff --git a/zurvan.js b/zurvan.js index <HASH>..<HASH> 100644 --- a/zurvan.js +++ b/zurvan.js @@ -72,7 +72,11 @@ Zurvan.prototype.resetSubcomponents = function() { this.immediateInterceptor = new ImmediateInterceptor(); this.allTimersInterceptor = new AllTimersInterceptor(this.timeServer); - this.timeForwarder = new TimeForwarder(this.timeServer, this.allTimersInterceptor, this.immediateInterceptor); + this.timeForwarder = new TimeForwarder( + this.timeServer, + this.allTimersInterceptor, + this.immediateInterceptor, + function(message) { this.config.debugLogger(message); }); this.processTimerInterceptor = new ProcessTimerInterceptor(this.timeServer); this.dateInterceptor = new DateInterceptor(this.timeServer);
Also debug-log advancing time
tlewowski_zurvan
train
4211d738a330822224e9616413861a4d034acde1
diff --git a/core.js b/core.js index <HASH>..<HASH> 100644 --- a/core.js +++ b/core.js @@ -105,7 +105,7 @@ NativeModule.prototype.compile = function() { lineOffset: 0, displayErrors: true }); - fn(this.exports, NativeModule.require, this, this.filename); + fn(this.exports, require, this, this.filename); this.loaded = true; };
only recompile timers
mafintosh_why-is-node-running
train
32fe18cf987b3171b2134031957a19ef53be7d9d
diff --git a/cukedoctor-reporter/src/main/java/com/github/cukedoctor/api/DocumentAttributes.java b/cukedoctor-reporter/src/main/java/com/github/cukedoctor/api/DocumentAttributes.java index <HASH>..<HASH> 100644 --- a/cukedoctor-reporter/src/main/java/com/github/cukedoctor/api/DocumentAttributes.java +++ b/cukedoctor-reporter/src/main/java/com/github/cukedoctor/api/DocumentAttributes.java @@ -9,7 +9,7 @@ public class DocumentAttributes { private String docTitle; private String backend = "html5"; - private String docType = "article"; + private String docType = "book"; private String toc = "right"; private String icons = "font"; private boolean linkCss = false; diff --git a/cukedoctor-reporter/src/test/java/com/github/cukedoctor/reporter/CukedoctorReporterTest.java b/cukedoctor-reporter/src/test/java/com/github/cukedoctor/reporter/CukedoctorReporterTest.java index <HASH>..<HASH> 100644 --- a/cukedoctor-reporter/src/test/java/com/github/cukedoctor/reporter/CukedoctorReporterTest.java +++ b/cukedoctor-reporter/src/test/java/com/github/cukedoctor/reporter/CukedoctorReporterTest.java @@ -113,7 +113,7 @@ public class CukedoctorReporterTest { String expected = ":toc: right" + newLine() + ":backend: html5" + newLine() + ":doctitle: Documentation Title" + newLine() + - ":doctype: article" + newLine() + + ":doctype: book" + newLine() + ":icons: font" + newLine() + ":!numbered:" + newLine() + ":!linkcss:" + newLine() + @@ -136,7 +136,7 @@ public class CukedoctorReporterTest { String expected = ":toc: right" + newLine() + ":backend: html5" + newLine() + ":doctitle: Documentation Title" + newLine() + - ":doctype: article" + newLine() + + ":doctype: book" + newLine() + ":icons: font" + newLine() + ":!numbered:" + newLine() + ":!linkcss:" + newLine() +
doctype 'book' by default
rmpestano_cukedoctor
train
a0751d27c52185b86370baf6a565e757092646de
diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -5,6 +5,16 @@ module ActiveRecord module Serialization extend ActiveSupport::Concern + class ColumnNotSerializableError < StandardError + def initialize(name, type) + super <<-EOS.strip_heredoc + Column `#{name}` of type #{type.class} does not support `serialize` feature. + Usually it means that you are trying to use `serialize` + on a column that already implements serialization natively. + EOS + end + end + module ClassMethods # If you have an attribute that needs to be saved to the database as an # object, and retrieved as the same object, then specify the name of that @@ -60,9 +70,23 @@ module ActiveRecord end decorate_attribute_type(attr_name, :serialize) do |type| + if type_incompatible_with_serialize?(type) + raise ColumnNotSerializableError.new(attr_name, type) + end + Type::Serialized.new(type, coder) end end + + private + + def type_incompatible_with_serialize?(type) + type.is_a?(ActiveRecord::Type::Json) || + ( + defined?(ActiveRecord::ConnectionAdapters::PostgreSQL) && + type.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array) + ) + end end end end diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -47,6 +47,15 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase assert ratings_column.array? end + def test_not_compatible_with_serialize + new_klass = Class.new(PgArray) do + serialize :tags, Array + end + assert_raises(ActiveRecord::AttributeMethods::Serialization::ColumnNotSerializableError) do + new_klass.new + end + end + def test_default @connection.add_column "pg_arrays", "score", :integer, array: true, default: [4, 4, 2] PgArray.reset_column_information diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/adapters/postgresql/json_test.rb +++ b/activerecord/test/cases/adapters/postgresql/json_test.rb @@ -33,6 +33,15 @@ module PostgresqlJSONSharedTestCases x.reload assert_equal ["foo" => "bar"], x.objects end + + def test_not_compatible_with_serialize_macro + new_klass = Class.new(klass) do + serialize :payload, JSON + end + assert_raises(ActiveRecord::AttributeMethods::Serialization::ColumnNotSerializableError) do + new_klass.new + end + end end class PostgresqlJSONTest < ActiveRecord::PostgreSQLTestCase
Do not let use `serialize` on native JSON/array column
rails_rails
train
bbf07ac253e12cdc2ec76dcdde46f5bc6c7dd51b
diff --git a/bin/init_model.py b/bin/init_model.py index <HASH>..<HASH> 100644 --- a/bin/init_model.py +++ b/bin/init_model.py @@ -29,8 +29,6 @@ from shutil import copytree import codecs from collections import defaultdict -from spacy.en import get_lex_props -from spacy.en.lemmatizer import Lemmatizer from spacy.vocab import Vocab from spacy.vocab import write_binary_vectors from spacy.strings import hash_string @@ -38,6 +36,11 @@ from preshed.counter import PreshCounter from spacy.parts_of_speech import NOUN, VERB, ADJ +import spacy.en +import spacy.de + + + def setup_tokenizer(lang_data_dir, tok_dir): if not tok_dir.exists(): @@ -139,7 +142,7 @@ def _read_senses(loc): return lexicon -def setup_vocab(src_dir, dst_dir): +def setup_vocab(get_lex_attr, src_dir, dst_dir): if not dst_dir.exists(): dst_dir.mkdir() @@ -148,13 +151,13 @@ def setup_vocab(src_dir, dst_dir): write_binary_vectors(str(vectors_src), str(dst_dir / 'vec.bin')) else: print("Warning: Word vectors file not found") - vocab = Vocab(data_dir=None, get_lex_props=get_lex_props) + vocab = Vocab(data_dir=None, get_lex_attr=get_lex_attr) clusters = _read_clusters(src_dir / 'clusters.txt') probs, oov_prob = _read_probs(src_dir / 'words.sgt.prob') if not probs: probs, oov_prob = _read_freqs(src_dir / 'freqs.txt') if not probs: - oov_prob = 0.0 + oov_prob = -20 else: oov_prob = min(probs.values()) for word in clusters: @@ -163,23 +166,30 @@ def setup_vocab(src_dir, dst_dir): lexicon = [] for word, prob in reversed(sorted(list(probs.items()), key=lambda item: item[1])): - entry = get_lex_props(word) - entry['prob'] = float(prob) - cluster = clusters.get(word, '0') + lexeme = vocab[word] + lexeme.prob = prob + lexeme.is_oov = False # Decode as a little-endian string, so that we can do & 15 to get # the first 4 bits. See _parse_features.pyx - entry['cluster'] = int(cluster[::-1], 2) - vocab[word] = entry + if word in clusters: + lexeme.cluster = int(clusters[word][::-1], 2) + else: + lexeme.cluster = 0 vocab.dump(str(dst_dir / 'lexemes.bin')) vocab.strings.dump(str(dst_dir / 'strings.txt')) with (dst_dir / 'oov_prob').open('w') as file_: file_.write('%f' % oov_prob) -def main(lang_data_dir, corpora_dir, model_dir): +def main(lang_id, lang_data_dir, corpora_dir, model_dir): + languages = { + 'en': spacy.en.get_lex_attr, + 'de': spacy.en.get_lex_attr + } + model_dir = Path(model_dir) - lang_data_dir = Path(lang_data_dir) - corpora_dir = Path(corpora_dir) + lang_data_dir = Path(lang_data_dir) / lang_id + corpora_dir = Path(corpora_dir) / lang_id assert corpora_dir.exists() assert lang_data_dir.exists() @@ -188,12 +198,12 @@ def main(lang_data_dir, corpora_dir, model_dir): model_dir.mkdir() setup_tokenizer(lang_data_dir, model_dir / 'tokenizer') - setup_vocab(corpora_dir, model_dir / 'vocab') + setup_vocab(languages[lang_id], corpora_dir, model_dir / 'vocab') if (lang_data_dir / 'gazetteer.json').exists(): copyfile(str(lang_data_dir / 'gazetteer.json'), str(model_dir / 'vocab' / 'gazetteer.json')) - if not (model_dir / 'wordnet').exists(): + if not (model_dir / 'wordnet').exists() and (corpora_dir / 'wordnet').exists(): copytree(str(corpora_dir / 'wordnet' / 'dict'), str(model_dir / 'wordnet'))
* Cut down init_model to work on more languages
explosion_spaCy
train
56978221e9dd43ffc79fa8b4aa1719c1ff300ed3
diff --git a/jest.config.js b/jest.config.js index <HASH>..<HASH> 100644 --- a/jest.config.js +++ b/jest.config.js @@ -124,7 +124,6 @@ module.exports = { // A list of paths to modules that run some code to configure or set up the testing framework before each test // setupFilesAfterEnv: [], - setupFilesAfterEnv: ['<rootDir>/tests/unit/setupTests.js'], // A list of paths to snapshot serializer modules Jest should use for snapshot testing // snapshotSerializers: [],
Reverting jest.config.js changes from this PR
foliojs_pdfkit
train
765d406730609988090af5e2efeaf64b221c6358
diff --git a/lib/mongoid/versioning.rb b/lib/mongoid/versioning.rb index <HASH>..<HASH> 100644 --- a/lib/mongoid/versioning.rb +++ b/lib/mongoid/versioning.rb @@ -131,7 +131,7 @@ module Mongoid #:nodoc: # @since 2.0.0 def previous_revision _loading_revision do - self.class. + self.class.unscoped. where(:_id => id). any_of({ :version => version }, { :version => nil }).first end diff --git a/spec/mongoid/versioning_spec.rb b/spec/mongoid/versioning_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mongoid/versioning_spec.rb +++ b/spec/mongoid/versioning_spec.rb @@ -37,73 +37,158 @@ describe Mongoid::Versioning do describe "#version" do - context "when the document is new" do + context "when there is no default scope" do - it "returns 1" do - WikiPage.new.version.should eq(1) + context "when the document is new" do + + it "returns 1" do + WikiPage.new.version.should eq(1) + end end - end - context "when the document is persisted once" do + context "when the document is persisted once" do + + let(:page) do + WikiPage.create(:title => "1") + end + + it "returns 1" do + page.version.should eq(1) + end + end + + context "when the document is persisted more than once" do + + let(:page) do + WikiPage.create(:title => "1") + end + + before do + 3.times { |n| page.update_attribute(:title, "#{n}") } + end - let(:page) do - WikiPage.create(:title => "1") + it "returns the number of versions" do + page.version.should eq(4) + end end - it "returns 1" do - page.version.should eq(1) + context "when maximum versions is defined" do + + let(:page) do + WikiPage.create(:title => "1") + end + + context "when saving over the max versions limit" do + + before do + 10.times { |n| page.update_attribute(:title, "#{n}") } + end + + it "returns the number of versions" do + page.version.should eq(11) + end + end + end + + context "when performing versionless saves" do + + let(:page) do + WikiPage.create(:title => "1") + end + + before do + 10.times do |n| + page.versionless { |doc| doc.update_attribute(:title, "#{n}") } + end + end + + it "does not increment the version number" do + page.version.should eq(1) + end end end - context "when the document is persisted more than once" do + context "when there is a default scope" do - let(:page) do - WikiPage.create(:title => "1") + before :all do + class WikiPage + default_scope where(:author => "Jim") + end end - before do - 3.times { |n| page.update_attribute(:title, "#{n}") } + after :all do + WikiPage.default_scoping.clear end - it "returns the number of versions" do - page.version.should eq(4) + context "when the document is new" do + + it "returns 1" do + WikiPage.new.version.should eq(1) + end end - end - context "when maximum versions is defined" do + context "when the document is persisted once" do - let(:page) do - WikiPage.create(:title => "1") + let(:page) do + WikiPage.create(:title => "1") + end + + it "returns 1" do + page.version.should eq(1) + end end - context "when saving over the max versions limit" do + context "when the document is persisted more than once" do + + let(:page) do + WikiPage.create(:title => "1") + end before do - 10.times { |n| page.update_attribute(:title, "#{n}") } + 3.times { |n| page.update_attribute(:title, "#{n}") } end it "returns the number of versions" do - page.version.should eq(11) + page.version.should eq(4) end end - end - context "when performing versionless saves" do + context "when maximum versions is defined" do - let(:page) do - WikiPage.create(:title => "1") - end + let(:page) do + WikiPage.create(:title => "1") + end - before do - 10.times do |n| - page.versionless { |doc| doc.update_attribute(:title, "#{n}") } + context "when saving over the max versions limit" do + + before do + 10.times { |n| page.update_attribute(:title, "#{n}") } + end + + it "returns the number of versions" do + page.version.should eq(11) + end end end - it "does not increment the version number" do - page.version.should eq(1) + context "when performing versionless saves" do + + let(:page) do + WikiPage.create(:title => "1") + end + + before do + 10.times do |n| + page.versionless { |doc| doc.update_attribute(:title, "#{n}") } + end + end + + it "does not increment the version number" do + page.version.should eq(1) + end end end + end describe "#versionless" do
Default scope no longer breaks versioning! Described and solved here: #<I>.
mongodb_mongoid
train
b05699eec5b2650e1e5836a66ba853c1cad113b3
diff --git a/test/specs/core.controller.tests.js b/test/specs/core.controller.tests.js index <HASH>..<HASH> 100644 --- a/test/specs/core.controller.tests.js +++ b/test/specs/core.controller.tests.js @@ -728,6 +728,8 @@ describe('Chart', function() { } }); + var wrapper = chart.canvas.parentNode; + waitForResize(chart, function() { var canvas = chart.canvas; expect(chart).toBeChartOfSize({ @@ -749,6 +751,8 @@ describe('Chart', function() { rw: 455, rh: 455, }); + chart.destroy(); + window.document.body.removeChild(wrapper); done(); }); canvas.parentNode.style.width = '455px'; diff --git a/test/specs/plugin.tooltip.tests.js b/test/specs/plugin.tooltip.tests.js index <HASH>..<HASH> 100644 --- a/test/specs/plugin.tooltip.tests.js +++ b/test/specs/plugin.tooltip.tests.js @@ -148,7 +148,7 @@ describe('Core.Tooltip', function() { done(); }); - jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: chart.chartArea.top}); + jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: chart.chartArea.top + 10}); }); it('Should only display if intersecting if intersect is set', function(done) {
Clean up after test (#<I>) * Clean up * Make sure the event is inside chart are
chartjs_Chart.js
train
0b7906df23d812f1efba4b8f87844bad2bdbb6da
diff --git a/lib/discordrb/cache.rb b/lib/discordrb/cache.rb index <HASH>..<HASH> 100644 --- a/lib/discordrb/cache.rb +++ b/lib/discordrb/cache.rb @@ -49,6 +49,7 @@ module Discordrb id = id.resolve_id return @users[id] if @users[id] + LOGGER.out("Resolving user #{id}") response = API.user(token, id) user = User.new(JSON.parse(response), self) @users[id] = user
Add an out message to Cache that tracks resolved users
meew0_discordrb
train
2947981b6137df0e8e9ed89c36c40cbafef86e7b
diff --git a/render/render.go b/render/render.go index <HASH>..<HASH> 100644 --- a/render/render.go +++ b/render/render.go @@ -64,6 +64,11 @@ func (_ plainRender) Render(w http.ResponseWriter, code int, data ...interface{} writeHeader(w, code, "text/plain") format := data[0].(string) args := data[1].([]interface{}) - _, err := w.Write([]byte(fmt.Sprintf(format, args))) + var err error + if len(args) > 0 { + _, err = w.Write([]byte(fmt.Sprintf(format, args...))) + } else { + _, err = w.Write([]byte(format)) + } return err }
Fix Corrupted plainRender
gin-gonic_gin
train
674bc96662285b25e395fd3dddf9291a602fc183
diff --git a/flink-connectors/flink-connector-elasticsearch-base/src/main/java/org/apache/flink/connector/elasticsearch/table/KeyExtractor.java b/flink-connectors/flink-connector-elasticsearch-base/src/main/java/org/apache/flink/connector/elasticsearch/table/KeyExtractor.java index <HASH>..<HASH> 100644 --- a/flink-connectors/flink-connector-elasticsearch-base/src/main/java/org/apache/flink/connector/elasticsearch/table/KeyExtractor.java +++ b/flink-connectors/flink-connector-elasticsearch-base/src/main/java/org/apache/flink/connector/elasticsearch/table/KeyExtractor.java @@ -19,7 +19,6 @@ package org.apache.flink.connector.elasticsearch.table; import org.apache.flink.annotation.Internal; -import org.apache.flink.table.api.TableColumn; import org.apache.flink.table.data.RowData; import org.apache.flink.table.types.logical.DistinctType; import org.apache.flink.table.types.logical.LogicalType; @@ -60,24 +59,6 @@ class KeyExtractor implements SerializableFunction<RowData, String> { return builder.toString(); } - private static class ColumnWithIndex { - public TableColumn column; - public int index; - - public ColumnWithIndex(TableColumn column, int index) { - this.column = column; - this.index = index; - } - - public LogicalType getType() { - return column.getType().getLogicalType(); - } - - public int getIndex() { - return index; - } - } - public static SerializableFunction<RowData, String> createKeyExtractor( List<LogicalTypeWithIndex> primaryKeyTypesWithIndex, String keyDelimiter) { if (!primaryKeyTypesWithIndex.isEmpty()) {
[FLINK-<I>][elsaticsearch] Remove unused private class
apache_flink
train
7ab7eae4254f8ee62b3a8620982c72b07c2299e4
diff --git a/tests/__init__.py b/tests/__init__.py index <HASH>..<HASH> 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -9,11 +9,9 @@ class CustomError(Exception): pass -def defer(callback, *args, **kwargs): - sleep = kwargs.pop('sleep', DEFAULT_SLEEP) - expected_return = kwargs.pop('expected_return', None) - call = kwargs.pop('call', True) - +def defer(callback, *args, + sleep=DEFAULT_SLEEP, expected_return=None, call=True, + **kwargs): def func(): time.sleep(sleep) if call:
Use named kwargs after *args Another Python 3 thing.
FichteFoll_resumeback
train
7c7a9fbe04f0fd772226a329ddccfdfc9d26736d
diff --git a/aws/resource_aws_lambda_alias.go b/aws/resource_aws_lambda_alias.go index <HASH>..<HASH> 100644 --- a/aws/resource_aws_lambda_alias.go +++ b/aws/resource_aws_lambda_alias.go @@ -29,6 +29,7 @@ func resourceAwsLambdaAlias() *schema.Resource { "function_name": { Type: schema.TypeString, Required: true, + ForceNew: true, }, "function_version": { Type: schema.TypeString,
resource/aws_lambda_alias: Add ForceNew to function_name attribute (#<I>)
terraform-providers_terraform-provider-aws
train
6deffe3daa018d750bbb5cb478fee7b77f9b30d2
diff --git a/images.go b/images.go index <HASH>..<HASH> 100644 --- a/images.go +++ b/images.go @@ -3,10 +3,11 @@ package triton import ( "encoding/json" "fmt" - "github.com/hashicorp/errwrap" "net/http" "net/url" "time" + + "github.com/hashicorp/errwrap" ) type ImagesClient struct { @@ -138,3 +139,33 @@ func (client *ImagesClient) ExportImage(input *ExportImageInput) (*MantaLocation return result, nil } + +type CreateImageFromMachineInput struct { + MachineID string `json:"machine"` + Name string `json:"name"` + Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` + HomePage string `json:"homepage,omitempty"` + EULA string `json:"eula,omitempty"` + ACL []string `json:"acl,omitempty"` + tags map[string]string `json:"tags,omitempty"` +} + +func (client *ImagesClient) CreateImageFromMachine(input *CreateImageFromMachineInput) (*Image, error) { + path := fmt.Sprintf("/%s/images", client.accountName) + respReader, err := client.executeRequest(http.MethodPost, path, input) + if respReader != nil { + defer respReader.Close() + } + if err != nil { + return nil, errwrap.Wrapf("Error executing CreateImageFromMachine request: {{err}}", err) + } + + var result *Image + decoder := json.NewDecoder(respReader) + if err = decoder.Decode(&result); err != nil { + return nil, errwrap.Wrapf("Error decoding CreateImageFromMachine response: {{err}}", err) + } + + return result, nil +}
images: Add CreateImageFromMachine operation
joyent_triton-go
train
d84cbb5dab810c80a1b56c1ada69ae9dd744d722
diff --git a/molgenis-core-ui/src/main/javascript/modules/react-components/Questionnaire.js b/molgenis-core-ui/src/main/javascript/modules/react-components/Questionnaire.js index <HASH>..<HASH> 100644 --- a/molgenis-core-ui/src/main/javascript/modules/react-components/Questionnaire.js +++ b/molgenis-core-ui/src/main/javascript/modules/react-components/Questionnaire.js @@ -7,6 +7,7 @@ import FormFactory from "./Form"; import Spinner from "./Spinner"; import Button from "./Button"; import _ from "underscore"; +import moment from "moment"; var div = React.DOM.div; @@ -110,6 +111,12 @@ var Questionnaire = React.createClass({ case 'COMPOUND': //nothing, no value break; + case 'DATE': + values[attr.name] = moment(value, 'YYYY-MM-DD', true); + break; + case 'DATE_TIME': + values[attr.name] = moment(value, moment.ISO_8601, true); + break; default: values[attr.name] = value; break;
Fix #<I> Translate date and dateTime values back into moments before form submission. This fixes the bug whereby the age function would fail due to the difference between now() and a 'string would result in a NaN. This would result in the values being set to null on the form and then the validation would fail in the backend.
molgenis_molgenis
train
215294fbc06acd15871180df0b14c4260695f147
diff --git a/app/assets/javascripts/pageflow/editor/views/embedded/background_image_embedded_view.js b/app/assets/javascripts/pageflow/editor/views/embedded/background_image_embedded_view.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/pageflow/editor/views/embedded/background_image_embedded_view.js +++ b/app/assets/javascripts/pageflow/editor/views/embedded/background_image_embedded_view.js @@ -10,7 +10,7 @@ pageflow.BackgroundImageEmbeddedView = Backbone.Marionette.View.extend({ update: function() { this.$el.css({ - backgroundImage: 'url("' + this.model.getImageFileUrl(this.options.propertyName) + '")', + backgroundImage: this.imageValue(), backgroundPosition: this.model.getFilePosition(this.options.propertyName, 'x') + '% ' + this.model.getFilePosition(this.options.propertyName, 'y') + '%' }); @@ -28,5 +28,10 @@ pageflow.BackgroundImageEmbeddedView = Backbone.Marionette.View.extend({ } this.$el.css({backgroundPosition:'0 0'}); } + }, + + imageValue: function() { + var url = this.model.getImageFileUrl(this.options.propertyName); + return url ? 'url("' + url + '")' : 'none'; } }); \ No newline at end of file
Fix Image <I> in Editor Do not set background image url if no image is configured.
codevise_pageflow
train
4c5a1a3b26297d84b2f997b741097184ea1e28f6
diff --git a/rest_api/api.py b/rest_api/api.py index <HASH>..<HASH> 100644 --- a/rest_api/api.py +++ b/rest_api/api.py @@ -307,7 +307,8 @@ def fetch_model(): cx = process_ndex_network(network_id) network_attr = [x for x in cx.cx if x.get('networkAttributes')] network_attr = network_attr[0]['networkAttributes'] - keep_keys = ['model_elements', 'preset_pos', 'stmts', + keep_keys = ['txt_input', 'parser', + 'model_elements', 'preset_pos', 'stmts', 'sentences', 'evidence', 'cell_line', 'mrna', 'mutations'] stored_data = {} for d in network_attr:
store txt input and parser on ndex upload
sorgerlab_indra
train
54153097696d0f41b8e95a4caff2db18ee4983b7
diff --git a/google/datalab/bigquery/_utils.py b/google/datalab/bigquery/_utils.py index <HASH>..<HASH> 100644 --- a/google/datalab/bigquery/_utils.py +++ b/google/datalab/bigquery/_utils.py @@ -40,13 +40,13 @@ TableName = collections.namedtuple('TableName', """ # Absolute project-qualified name pattern: <project>.<dataset> -_ABS_DATASET_NAME_PATTERN = r'^([a-z\d\-_\.]+)\.(\w+)$' +_ABS_DATASET_NAME_PATTERN = r'^([a-z\d\-_\.:]+)\.(\w+)$' # Relative name pattern: <dataset> _REL_DATASET_NAME_PATTERN = r'^(\w+)$' # Absolute project-qualified name pattern: <project>.<dataset>.<table> -_ABS_TABLE_NAME_PATTERN = r'^([a-z\d\-_\.]+)\.(\w+)\.(\w+)(@[\d\-]+)?$' +_ABS_TABLE_NAME_PATTERN = r'^([a-z\d\-_\.:]+)\.(\w+)\.(\w+)(@[\d\-]+)?$' # Relative name pattern: <dataset>.<table> _REL_TABLE_NAME_PATTERN = r'^(\w+)\.(\w+)(@[\d\-]+)?$'
Allow colons in table names. (#<I>) With Standard SQL, the separator between project name and dataset name was changed from a colon to a period. As such, we changed our regex to replace periods with colons. However, colons are still allowed within a project name, so the regex needs to still allow colons in the project name.
googledatalab_pydatalab
train
9e7d2fe74e7e6e52ff30a79c8d20eec35f8bcf52
diff --git a/libnetwork/iptables/iptables.go b/libnetwork/iptables/iptables.go index <HASH>..<HASH> 100644 --- a/libnetwork/iptables/iptables.go +++ b/libnetwork/iptables/iptables.go @@ -99,7 +99,8 @@ func NewChain(name, bridge string, table Table, hairpinMode bool) (*Chain, error case Nat: preroute := []string{ "-m", "addrtype", - "--dst-type", "LOCAL"} + "--dst-type", "LOCAL", + "-j", c.Name} if !Exists(Nat, "PREROUTING", preroute...) { if err := c.Prerouting(Append, preroute...); err != nil { return nil, fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err) @@ -107,7 +108,8 @@ func NewChain(name, bridge string, table Table, hairpinMode bool) (*Chain, error } output := []string{ "-m", "addrtype", - "--dst-type", "LOCAL"} + "--dst-type", "LOCAL", + "-j", c.Name} if !hairpinMode { output = append(output, "!", "--dst", "127.0.0.0/8") } @@ -228,7 +230,7 @@ func (c *Chain) Prerouting(action Action, args ...string) error { if len(args) > 0 { a = append(a, args...) } - if output, err := Raw(append(a, "-j", c.Name)...); err != nil { + if output, err := Raw(a...); err != nil { return err } else if len(output) != 0 { return ChainError{Chain: "PREROUTING", Output: output} @@ -242,7 +244,7 @@ func (c *Chain) Output(action Action, args ...string) error { if len(args) > 0 { a = append(a, args...) } - if output, err := Raw(append(a, "-j", c.Name)...); err != nil { + if output, err := Raw(a...); err != nil { return err } else if len(output) != 0 { return ChainError{Chain: "OUTPUT", Output: output} @@ -254,9 +256,9 @@ func (c *Chain) Output(action Action, args ...string) error { func (c *Chain) Remove() error { // Ignore errors - This could mean the chains were never set up if c.Table == Nat { - c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL") - c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8") - c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL") // Created in versions <= 0.1.6 + c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) + c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name) + c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6 c.Prerouting(Delete) c.Output(Delete)
Fix duplicated iptables rules The `iptables.Exists` function is wrong in two ways: 1. The iptables -C call doesn't add `-j DOCKER` and fails to match 2. The long path takes ordering into account in comparison and fails to match This patch fixes issue 1 by including `-j DOCKER` in the check.
moby_moby
train
71c7c43748cc6fba43f86ff8213fd028393586fc
diff --git a/activiti-cycle/src/main/java/org/activiti/cycle/CycleComponentFactory.java b/activiti-cycle/src/main/java/org/activiti/cycle/CycleComponentFactory.java index <HASH>..<HASH> 100644 --- a/activiti-cycle/src/main/java/org/activiti/cycle/CycleComponentFactory.java +++ b/activiti-cycle/src/main/java/org/activiti/cycle/CycleComponentFactory.java @@ -83,7 +83,7 @@ public abstract class CycleComponentFactory { private boolean initialized = false; private void guaranteeInitialization() { - if (!initialized){ + if (!initialized) { synchronized (this) { if (!initialized) { init(); @@ -92,7 +92,6 @@ public abstract class CycleComponentFactory { } } - @SuppressWarnings("unchecked") private Object getComponentInstance(Class< ? > clazz) { Object obj = getComponentInstance(clazz.getCanonicalName()); return obj; @@ -370,7 +369,6 @@ public abstract class CycleComponentFactory { */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void removeExcludedComponents(Set components) { - // TODO: do this more generally Set<Object> excludedComponents = new HashSet<Object>(); for (Object object : components) { ExcludesCycleComponents excludesAnnotation = object.getClass().getAnnotation(ExcludesCycleComponents.class); @@ -378,13 +376,21 @@ public abstract class CycleComponentFactory { continue; } String[] componentNames = excludesAnnotation.value(); - if (componentNames == null) { - continue; + if (componentNames != null) { + for (String componentName : componentNames) { + Object excludedComponentInstance = getCycleComponentInstance(componentName); + if (excludedComponentInstance != null) { + excludedComponents.add(excludedComponentInstance); + } + } } - for (String componentName : componentNames) { - Object excludedComponentInstance = getCycleComponentInstance(componentName); - if (excludedComponentInstance != null) { - excludedComponents.add(excludedComponentInstance); + Class[] classes = excludesAnnotation.classes(); + if (classes != null) { + for (Class excludedComponentClass : classes) { + Object excludedComponentInstance = getCycleComponentInstance(excludedComponentClass); + if (object != null) { + excludedComponents.add(excludedComponentInstance); + } } } } diff --git a/activiti-cycle/src/main/java/org/activiti/cycle/annotations/ExcludesCycleComponents.java b/activiti-cycle/src/main/java/org/activiti/cycle/annotations/ExcludesCycleComponents.java index <HASH>..<HASH> 100644 --- a/activiti-cycle/src/main/java/org/activiti/cycle/annotations/ExcludesCycleComponents.java +++ b/activiti-cycle/src/main/java/org/activiti/cycle/annotations/ExcludesCycleComponents.java @@ -31,19 +31,21 @@ import org.activiti.cycle.action.ParameterizedAction; * </ul> * On other component types (i.e. connectors) it is ignored. * - * TODO: This annotation should be able to work with classes as well, to avoid - * having hard coded class names in the annotation IF the component we try to - * disable available on the classpath. * * @author daniel.meyer@camunda.com */ @Retention(RetentionPolicy.RUNTIME) -@Target( { ElementType.TYPE }) +@Target({ ElementType.TYPE }) public @interface ExcludesCycleComponents { /** * The name of the component to exclude. */ - String[] value(); + String[] value() default {}; + + /** + * Classes of the components to exclude + */ + Class[] classes() default {}; } diff --git a/activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/signavio/action/CopySignavioModelAction.java b/activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/signavio/action/CopySignavioModelAction.java index <HASH>..<HASH> 100644 --- a/activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/signavio/action/CopySignavioModelAction.java +++ b/activiti-cycle/src/main/java/org/activiti/cycle/impl/connector/signavio/action/CopySignavioModelAction.java @@ -12,6 +12,7 @@ import org.activiti.cycle.annotations.ExcludesCycleComponents; import org.activiti.cycle.context.CycleApplicationContext; import org.activiti.cycle.context.CycleContextType; import org.activiti.cycle.impl.action.AbstractCopyBaseAction; +import org.activiti.cycle.impl.action.DefaultCopyArtifactAction; import org.activiti.cycle.impl.connector.signavio.provider.JsonProvider; import org.activiti.cycle.impl.connector.signavio.repositoryartifacttype.SignavioBpmn20ArtifactType; @@ -22,7 +23,7 @@ import org.activiti.cycle.impl.connector.signavio.repositoryartifacttype.Signavi * @author bernd.ruecker@camunda.com */ @CycleComponent(context = CycleContextType.APPLICATION) -@ExcludesCycleComponents("org.activiti.cycle.impl.action.DefaultCopyArtifactAction") +@ExcludesCycleComponents(classes = { DefaultCopyArtifactAction.class }) public class CopySignavioModelAction extends AbstractCopyBaseAction { private static final long serialVersionUID = 1L;
Activiti Cycle: added support for referencing classes in the @ExcludesCycleComponents annotation.
camunda_camunda-bpm-platform
train
fae52f2541715847ece0acbb9e1c0d02e15e0ec1
diff --git a/lib/AV.js b/lib/AV.js index <HASH>..<HASH> 100644 --- a/lib/AV.js +++ b/lib/AV.js @@ -635,7 +635,7 @@ Foscam.prototype.snapPicture = function() { * @returns {Promise<Object>} A promise to the response. jpeg image data directly. */ Foscam.prototype.snapPicture2 = function() { - return this.getRaw(this.url, {qs: {cmd: 'snapPicture2'}}); + return this.get('snapPicture2'); }; /** diff --git a/test/AV.spec.js b/test/AV.spec.js index <HASH>..<HASH> 100644 --- a/test/AV.spec.js +++ b/test/AV.spec.js @@ -282,7 +282,7 @@ describe('Foscam: AV', function() { it('snapPicture2', function() { cam.snapPicture2(); - assertCalledWith(cam.getRaw, cam.url, {qs: {cmd: 'snapPicture2'}}); + assertCalledWith(cam.get, 'snapPicture2'); }); describe('config', function() {
snapPicture2 should call this.get instead of this.getRaw, in order to return the raw JPEG data
lightswitch05_foscam-client
train
a993b8e6f715e1e419623768e897dfdeefed46ba
diff --git a/src/frontend/org/voltdb/SystemProcedureCatalog.java b/src/frontend/org/voltdb/SystemProcedureCatalog.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/SystemProcedureCatalog.java +++ b/src/frontend/org/voltdb/SystemProcedureCatalog.java @@ -435,9 +435,9 @@ public class SystemProcedureCatalog { false, false, Restartability.NOT_APPLICABLE)); builder.put("@ValidatePartitioning", new Config("org.voltdb.sysprocs.ValidatePartitioning", - false, true, false, 0, VoltType.INVALID, + false, false, false, 0, VoltType.INVALID, false, false, true, Durability.NOT_DURABLE, - false, true, Restartability.NOT_RESTARTABLE)); + false, true, Restartability.RESTARTABLE)); builder.put("@GetHashinatorConfig", new Config("org.voltdb.sysprocs.GetHashinatorConfig", false, true, false, 0, VoltType.INVALID, @@ -630,7 +630,7 @@ public class SystemProcedureCatalog { new Config("org.voltdb.sysprocs.ExportControl", false, false, false, 0, VoltType.INVALID, false, false, true, Durability.NOT_DURABLE, - false, true, Restartability.NOT_RESTARTABLE)); + false, true, Restartability.RESTARTABLE)); builder.put("@MigrateRowsAcked_SP", new Config("org.voltdb.sysprocs.MigrateRowsAcked_SP", true, false, false, 0, VoltType.INVALID, diff --git a/src/frontend/org/voltdb/export/ExportDataSource.java b/src/frontend/org/voltdb/export/ExportDataSource.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/export/ExportDataSource.java +++ b/src/frontend/org/voltdb/export/ExportDataSource.java @@ -1652,6 +1652,11 @@ public class ExportDataSource implements Comparable<ExportDataSource> { @Override public void run() { try { + // Check again in case of multiple export release tasks are queued + // because restarted @ExportControl transaction + if (m_status != StreamStatus.BLOCKED) { + return; + } if (isMaster() && m_pollTask != null) { long firstUnpolledSeqNo = m_firstUnpolledSeqNo; Pair<Long, Long> gap = m_gapTracker.getFirstGap(m_firstUnpolledSeqNo);
ENG-<I>, make @ValidatePartitioning and @ExportControl restartable.. (#<I>) As read-write MP system procedure, @ValidatePartitioning needs to be restartable to avoid corruptting task scoreboard, so does @ExportControl. Change-Id: I0f<I>eba<I>a2fc6d5d<I>f3e0bf<I>b
VoltDB_voltdb
train
6a7dbdf5313234fd9bf7a2ebe5f4285bdc191372
diff --git a/bridge.js b/bridge.js index <HASH>..<HASH> 100644 --- a/bridge.js +++ b/bridge.js @@ -638,7 +638,7 @@ function deployOraclize () { logger.info('successfully deployed all contracts') oraclizeConfiguration.connector = activeOracleInstance.connector oraclizeConfiguration.account = activeOracleInstance.account - var oraclizeInstanceNewName = 'oracle_instance_' + moment().format('YYYYMMDDZZHHmmss') + '.json' + var oraclizeInstanceNewName = 'oracle_instance_' + moment().format('YYYYMMDDTHHmmss') + '.json' configFilePath = toFullPath('./config/instance/' + oraclizeInstanceNewName) currentInstance = oraclizeInstanceNewName try { @@ -930,7 +930,7 @@ function queryComplete (gasLimit, myid, result, proof, contractAddr, proofType) updateQuery(callbackObj, null, err) return logger.error('callback tx error, contract myid: ' + myid, err) } - logger.info('contract ' + contractAddr + ' __callback tx confirmed, transaction hash:', contract.transactionHash, callbackObj) + logger.info('contract ' + contractAddr + ' __callback tx sent, transaction hash:', contract.transactionHash, callbackObj) updateQuery(callbackObj, contract, null) }) }) diff --git a/lib/bridge-core.js b/lib/bridge-core.js index <HASH>..<HASH> 100644 --- a/lib/bridge-core.js +++ b/lib/bridge-core.js @@ -224,7 +224,7 @@ OracleInstance.prototype.changeOwner = function (newOwner, oar, callback) { OracleInstance.prototype.__callback = function (callbackObj, callback) { var callbackData = bridgeUtil.callbackTxEncode(callbackObj.myid, callbackObj.result, callbackObj.proof, callbackObj.proof_type) - BridgeTxManager().sendTx({'from': this.account, 'to': callbackObj.contract_address, 'data': callbackData, 'gas': callbackObj.gas_limit}, callback) + BridgeTxManager().sendTx({'from': this.account, 'to': callbackObj.contract_address, 'data': callbackData, 'gas': callbackObj.gas_limit, '$skip_confirmation': true}, callback) } OracleInstance.prototype.deployConnector = function (callback) { diff --git a/lib/bridge-tx-manager.js b/lib/bridge-tx-manager.js index <HASH>..<HASH> 100644 --- a/lib/bridge-tx-manager.js +++ b/lib/bridge-tx-manager.js @@ -44,7 +44,7 @@ BridgeTxManager.prototype.sendRawTx = function (txData, callback) { const self = this BlockchainInterface().inter.sendRawTransaction(this.buildLocalTx(txData), function (err, hash) { if (err) return callback(err, null) - else return self.checkTransaction(hash, callback) + else return self.checkTransaction(hash, txData, callback) }) } @@ -52,13 +52,16 @@ BridgeTxManager.prototype.sendActiveTx = function (txData, callback) { const self = this BlockchainInterface().inter.sendTransaction(txData, function (err, hash) { if (err) return callback(err, null) - else return self.checkTransaction(hash, callback) + else return self.checkTransaction(hash, txData, callback) }) } -BridgeTxManager.prototype.checkTransaction = function (hash, callback) { +BridgeTxManager.prototype.checkTransaction = function (hash, txData, callback) { var counter = 0 if (typeof hash === 'undefined') return callback(new Error('hash not found'), null) + if (typeof txData !== 'undefined' && + typeof txData['$skip_confirmation'] !== 'undefined' && + txData['$skip_confirmation'] === true) return BlockchainInterface().inter.getTransactionReceipt(hash, callback) var txConfirmedInterval = setInterval(function () { try { const contract = BlockchainInterface().inter.getTransactionReceipt(hash) diff --git a/lib/bridge-util.js b/lib/bridge-util.js index <HASH>..<HASH> 100644 --- a/lib/bridge-util.js +++ b/lib/bridge-util.js @@ -251,7 +251,7 @@ const getQueryUnixTime = function (time, unixTime) { const isValidTime = function (time, now) { var queryTime = getQueryUnixTime(time) - if (time != 0 && time > now && (time - now) >= 5184000) return false + if (queryTime !== 0 && queryTime > now && (queryTime - now) >= 5184000) return false else return true }
Skip transaction confirmation on __callback transactions
oraclize_ethereum-bridge
train
c89186f856aaa84dc1af8bd3252d1887191b67a6
diff --git a/core/src/main/java/com/graphhopper/routing/ch/CHAlgoFactoryDecorator.java b/core/src/main/java/com/graphhopper/routing/ch/CHAlgoFactoryDecorator.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/graphhopper/routing/ch/CHAlgoFactoryDecorator.java +++ b/core/src/main/java/com/graphhopper/routing/ch/CHAlgoFactoryDecorator.java @@ -23,7 +23,8 @@ import com.graphhopper.routing.util.HintsMap; import com.graphhopper.routing.util.TraversalMode; import com.graphhopper.routing.weighting.AbstractWeighting; import com.graphhopper.routing.weighting.Weighting; -import com.graphhopper.storage.*; +import com.graphhopper.storage.GraphHopperStorage; +import com.graphhopper.storage.StorableProperties; import com.graphhopper.util.CmdArgs; import com.graphhopper.util.PMap; import com.graphhopper.util.Parameters; @@ -32,7 +33,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; -import java.util.concurrent.*; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; import static com.graphhopper.util.Helper.*; import static com.graphhopper.util.Parameters.CH.DISABLE; @@ -90,8 +92,9 @@ public class CHAlgoFactoryDecorator implements RoutingAlgorithmFactoryDecorator if (enableThis) setDisablingAllowed(args.getBool(CH.INIT_DISABLING_ALLOWED, isDisablingAllowed())); - String edgeBasedCHStr = args.get(CH.PREPARE + "edge_based", "off"); - edgeBasedCHMode = EdgeBasedCHMode.valueOf(edgeBasedCHStr.trim().toUpperCase(Locale.ROOT)); + String edgeBasedCHStr = args.get(CH.PREPARE + "edge_based", "off").trim(); + edgeBasedCHStr = edgeBasedCHStr.equals("false") ? "off" : edgeBasedCHStr; + edgeBasedCHMode = EdgeBasedCHMode.valueOf(edgeBasedCHStr.toUpperCase(Locale.ROOT)); pMap = args; }
avoid exception for disabling edge based CH config, fixes #<I>
graphhopper_graphhopper
train
e01a631d8c7e52683102f60d964621d355eb554b
diff --git a/shapes.py b/shapes.py index <HASH>..<HASH> 100644 --- a/shapes.py +++ b/shapes.py @@ -2,58 +2,89 @@ import math """ Functions to generate different shapes to be used as sprite images. """ -def vector(angle, length): - """ - angle in degrees - length in pixels - """ - xLength = length * math.sin(math.radians(angle)) - yLength = length * math.cos(math.radians(angle)) - image = [[False for x in range(abs(int(xLength))+1)] for y in range(abs(int(yLength))+1)] - - if (angle-45) % 180 < 90: - - if xLength <= 0: # If -ve length --> go backwards - for xOff in range(0, int(xLength), -1): - image[int((xLength - xOff) / math.tan(math.radians(angle)))]\ - [int(xLength - xOff)] = True - - else: - - for xOff in range(0, int(xLength), 1): - image[int((xLength - xOff) / math.tan(math.radians(angle)))]\ - [int(xLength - xOff)] = True +def vector_p(y, x): + image = [[False for xPos in range(abs(x)+1)] + for yPos in range(abs(y)+1)] + yMirror = False + xMirror = False + if y < 0: + yMirror = True + if x < 0: + xMirror = True + + y0 = 0 + x0 = 0 + y1 = abs(y) + x1 = abs(x) + + dy = abs(y1-y0) + dx = abs(x1-x0) + + if y0 < y1: + sy = 1 else: + sy = -1 + if x0 < x1: + sx = 1 + else: + sx = -1 + + err = dx-dy + while not (y0 == y1 and x0 == x1): + image[y0][x0] = True + e2 = 2*err + + if e2 > -dy: + err -= dy + x0 += sx + + if x0 == x1 and y0 == y1: + image[y0][x0] = True + break + + if e2 < dx: + err += dx + y0 += sy + + if yMirror: + image.reverse() + if xMirror: + for row in image: + row.reverse() - if yLength <= 0: # If -ve length --> go backwards - for yOff in range(0, int(yLength), -1): - image[int(yLength - yOff)]\ - [int((yLength - yOff) * math.tan(math.radians(angle)))] = True - - else: - for yOff in range(0, int(yLength), 1): - image[int(yLength - yOff)]\ - [int((yLength - yOff) * math.tan(math.radians(angle)))] = True - return image +def vector(angle, length): + xLength = int(length * math.sin(math.radians(angle))) + yLength = int(length * math.cos(math.radians(angle))) + + return vector_p(yLength, xLength) + def square(size): """ size = (width, height) in pixels - the char to use """ - image = [[False for x in range(size[0])] for y in range(size[1])] + return [[False for x in range(size[0])] for y in range(size[1])] +def box(size): + """ + size = (width, height) in pixels + """ + image = [[False for x in range(size[0])] for y in range(size[1])] for xPos in range(0, size[0]): - for yPos in range(0, size[1]): - image[yPos][xPos] = True + image[0][xPos] = True + image[size[1]][xPos] = True + + for yPos in range(0, size[1]): + image[yPos][0] = True + image[yPos][size[1]] = True + return image def circle(radius): """ radius in pixels - the char to use """ image = [[False for x in range(radius*2+1)] for y in range(radius*2+1)]
Rewritten vector and square functions, created box and vector_p functions
olls_graphics
train
1a50512d06c2b0d444fcfc7d424cfe5529fdea46
diff --git a/logback-core/src/test/java/ch/qos/logback/core/appender/FileAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/appender/FileAppenderTest.java index <HASH>..<HASH> 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/appender/FileAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/appender/FileAppenderTest.java @@ -16,15 +16,19 @@ package ch.qos.logback.core.appender; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; +import static org.junit.Assert.assertNull; import java.io.File; import java.util.List; +import ch.qos.logback.core.recovery.ResilientFileOutputStream; import ch.qos.logback.core.status.StatusChecker; + import org.junit.Test; import ch.qos.logback.core.Appender; import ch.qos.logback.core.FileAppender; +import ch.qos.logback.core.NOPOutputStream; import ch.qos.logback.core.encoder.DummyEncoder; import ch.qos.logback.core.encoder.NopEncoder; import ch.qos.logback.core.status.Status; @@ -120,7 +124,7 @@ public class FileAppenderTest extends AbstractAppenderTest<Object> { assertTrue("Got message [" + msg1 + "]", msg1 .startsWith("Setting \"Append\" property")); - + appender.doAppend(new Object()); appender.stop(); assertTrue(file.exists()); @@ -147,10 +151,10 @@ public class FileAppenderTest extends AbstractAppenderTest<Object> { FileAppender<Object> fa = getFileAppender(filename); fa.setLazy(false); - assertFalse(fa.getOutputStream() != null); + assertNull("stream is not null", fa.getOutputStream()); fa.start(); - assertTrue(fa.getOutputStream() != null); - assertTrue(file.exists()); + assertTrue("expected ResilientFileOutputStream; actual " + fa.getOutputStream().getClass().getSimpleName(), fa.getOutputStream() instanceof ResilientFileOutputStream); + assertTrue("file does not exist", file.exists()); } @Test @@ -161,10 +165,10 @@ public class FileAppenderTest extends AbstractAppenderTest<Object> { FileAppender<Object> fa = getFileAppender(filename); fa.setLazy(true); - assertFalse(fa.getOutputStream() != null); + assertNull("stream is not null", fa.getOutputStream()); fa.start(); - assertFalse(fa.getOutputStream() != null); - assertFalse(file.exists()); + assertTrue("expected NOPOutputStream; actual " + fa.getOutputStream().getClass().getSimpleName(), fa.getOutputStream() instanceof NOPOutputStream); + assertFalse("file does not exist", file.exists()); } @Test @@ -176,10 +180,10 @@ public class FileAppenderTest extends AbstractAppenderTest<Object> { fa.setLazy(true); fa.start(); - assertFalse(fa.getOutputStream() != null); + assertTrue("expected NOPOutputStream; actual " + fa.getOutputStream().getClass().getSimpleName(), fa.getOutputStream() instanceof NOPOutputStream); fa.append(new Object()); - assertTrue(fa.getOutputStream() != null); - assertTrue(file.exists()); + assertTrue("expected ResilientFileOutputStream; actual " + fa.getOutputStream().getClass().getSimpleName(), fa.getOutputStream() instanceof ResilientFileOutputStream); + assertTrue("file does not exist", file.exists()); } // helper class used to access protected fields
Fix FileAppenderTest Check for NOPOutputStream after FileAppender is started with lazy flag
tony19_logback-android
train
bbccbacf3db8c1d481dc1e01111e7d402e6f9867
diff --git a/lib/strong_migrations/migration.rb b/lib/strong_migrations/migration.rb index <HASH>..<HASH> 100644 --- a/lib/strong_migrations/migration.rb +++ b/lib/strong_migrations/migration.rb @@ -31,14 +31,14 @@ module StrongMigrations if columns.is_a?(Array) && columns.size > 3 raise_error :add_index_columns end - options = args[2] - if postgresql? && !(options && options[:algorithm] == :concurrently) && !@new_tables.to_a.include?(args[0].to_s) + options = args[2] || {} + if postgresql? && options[:algorithm] != :concurrently && !@new_tables.to_a.include?(args[0].to_s) raise_error :add_index end when :add_column type = args[2] - options = args[3] - raise_error :add_column_default if options && !options[:default].nil? + options = args[3] || {} + raise_error :add_column_default if !options[:default].nil? raise_error :add_column_json if type.to_s == "json" when :change_column raise_error :change_column
Added consistency for options [skip ci]
ankane_strong_migrations
train
fa2eaa9e4ea5bc1048dba12f5b3093d384a4a5b4
diff --git a/src/Router.php b/src/Router.php index <HASH>..<HASH> 100644 --- a/src/Router.php +++ b/src/Router.php @@ -90,26 +90,29 @@ class Router implements StageInterface */ public function pipe(callable $stage) { - $this->pipeline->add(new Pipe(function ($payload) use ($stage) { - $reflection = $stage instanceof Closure ? - new ReflectionFunction($stage) : - new ReflectionMethod($stage, '__invoke'); - $parameters = $reflection->getParameters(); - $args = []; - foreach ($parameters as $key => $param) { - if (!$key) { - $args[] = $payload; - } elseif (isset(self::$matchedArguments[$param->name])) { - $args[] = self::$matchedArguments[$param->name]; - } else { - throw new InvalidArgumentException( - "Pipe expects variable {$param->name}, but it is not ". - "present in the URL being resolved." - ); + if (!($stage instanceof StageInterface)) { + $stage = new Pipe(function ($payload) use ($stage) { + $reflection = $stage instanceof Closure ? + new ReflectionFunction($stage) : + new ReflectionMethod($stage, '__invoke'); + $parameters = $reflection->getParameters(); + $args = []; + foreach ($parameters as $key => $param) { + if (!$key) { + $args[] = $payload; + } elseif (isset(self::$matchedArguments[$param->name])) { + $args[] = self::$matchedArguments[$param->name]; + } else { + throw new InvalidArgumentException( + "Pipe expects variable {$param->name}, but it is ". + "not present in the URL being resolved." + ); + } } - } - return call_user_func_array($stage, $args); - })); + return call_user_func_array($stage, $args); + }); + } + $this->pipeline->add($stage); return $this; } @@ -148,7 +151,7 @@ class Router implements StageInterface ); $url = preg_replace("@(?<!:)/{2,}@", '/', $url); if (!isset($this->routes[$url])) { - $this->routes[$url] = new Router($url, $this->pipeline->build()); + $this->routes[$url] = new Router($url); } if (isset($callback)) { $callback($this->routes[$url]); @@ -173,6 +176,21 @@ class Router implements StageInterface } $this->name = $name; $this->state = new State($name, $state); + $this->pipe(new Pipe(function ($request) { + if ($request instanceof RequestInterface) { + return $this->state->__invoke( + self::$matchedArguments, + $request + ); + } elseif ($request instanceof ResponseInterface) { + return $request; + } + throw new DomainException( + "The pipeline must resolve either with a custom " + ."Psr\Http\Message\ResponseInterface, or with the original " + ."request." + ); + })); return $this; } @@ -291,41 +309,23 @@ class Router implements StageInterface unset($parts['query'], $parts['fragment']); $parts += parse_url($this->host); $url = http_build_url('', $parts); + $response = $this->pipeline->build()->process($request); + if (preg_match("@^{$this->url}$@", $url, $matches) + and $response instanceof ResponseInterface + ) { + unset($matches[0]); + self::$matchedArguments += $matches; + return $response; + } foreach ($this->routes as $match => $router) { if (preg_match("@^$match(.*)$@", $url, $matches)) { - $last = array_pop($matches); + array_pop($matches); unset($matches[0]); self::$matchedArguments += $matches; - $pipeline = $router->pipeline->build(); - if (!strlen($last)) { - $pipeline = $pipeline->pipe(new Pipe( - function ($request) use ($matches, $router) { - if ($request instanceof RequestInterface) { - return $router->state->__invoke( - $matches, - $request - ); - } elseif ($request instanceof ResponseInterface) { - return $request; - } - throw new DomainException( - "The pipeline must resolve either with a " - ."custom Psr\Http\Message\ResponseInterface," - ." or with the original request." - ); - } - )); - $response = $pipeline->process($this->request); - if (!($response instanceof RequestInterface)) { - return $response; - } - } - if (strlen($last) and $response = $router($request)) { - return $response; - } + return $router($request); } } - return null; + return $response; } /**
fix pipeline logic, is now much better
monolyth-php_reroute
train
f4b0c80bd1ce9cc5d0c99c877195f9b759ce9825
diff --git a/model/Document.js b/model/Document.js index <HASH>..<HASH> 100644 --- a/model/Document.js +++ b/model/Document.js @@ -124,6 +124,23 @@ export default class Document extends EventEmitter { getAnnotations (path) { return this.getIndex('annotations').get(path) } + /** + * Retrieve the NodeProperty for a given path + * + * @param {string[]} path + */ + getProperty (path) { + if (path.length !== 2) { + throw new Error('path must have length=2') + } + let [nodeId, propName] = path + let node = this.get(nodeId) + if (node) { + return node.getSchema().getProperty(propName) + } else { + throw new Error('Invalid path.') + } + } /** Creates a context like a transaction for importing nodes. diff --git a/model/EditingInterface.js b/model/EditingInterface.js index <HASH>..<HASH> 100644 --- a/model/EditingInterface.js +++ b/model/EditingInterface.js @@ -33,6 +33,10 @@ export default class EditingInterface { return this._document.get(...args) } + getProperty (...args) { + return this._document.getProperty(...args) + } + contains (id) { return this._document.contains(id) }
Introduce Document.getProperty(path) Provides the specification for a property.
substance_substance
train
40b7eb3363ce5a5e82eb91ce5b71c2430b8f5273
diff --git a/src/jssocials.js b/src/jssocials.js index <HASH>..<HASH> 100644 --- a/src/jssocials.js +++ b/src/jssocials.js @@ -10,7 +10,7 @@ return value; }; - var IMG_SRC_REGEX = /(\.(jpeg|png|gif|bmp|svg\+xml)$|^data:image\/(jpeg|png|gif|bmp|svg\+xml);base64)/i; + var IMG_SRC_REGEX = /(\.(jpeg|png|gif|bmp|svg)$|^data:image\/(jpeg|png|gif|bmp|svg\+xml);base64)/i; var URL_PARAMS_REGEX = /(&?[a-zA-Z0-9]+=)?\{([a-zA-Z0-9]+)\}/g; var MEASURES = { diff --git a/src/jssocials.shares.js b/src/jssocials.shares.js index <HASH>..<HASH> 100644 --- a/src/jssocials.shares.js +++ b/src/jssocials.shares.js @@ -109,7 +109,7 @@ label: "Pocket", logo: "fa fa-get-pocket", shareUrl: "https://getpocket.com/save?url={url}&title={title}", - countUrl: "", + countUrl: "" }, messenger: { diff --git a/test/jssocials.tests.js b/test/jssocials.tests.js index <HASH>..<HASH> 100644 --- a/test/jssocials.tests.js +++ b/test/jssocials.tests.js @@ -277,6 +277,23 @@ assert.equal($shareLogo.attr("src"), imgBase64, "img has base64 src"); }); + QUnit.test("logo as svg image", function(assert) { + jsSocials.shares.testshare = { + shareUrl: "http://test.com/share" + }; + + var $element = $("#share").jsSocials({ + shares: [{ + share: "testshare", + logo: "test.svg" + }] + }); + + var $shareLogo = $element.find(".jssocials-share-logo"); + assert.equal($shareLogo.get(0).tagName, "IMG", "<img> tag is rendered"); + assert.equal($shareLogo.attr("src"), "test.svg", "img has svg image path"); + }); + QUnit.test("share should get sharing url and text", function(assert) { jsSocials.shares.testshare = { shareUrl: "http://test.com/share/?url={url}&text={text}"
Core: Fix *.svg image support Fixes #<I>
tabalinas_jssocials
train
fe62d9a3941e8a944ba3d8e5eb782b19aa73af95
diff --git a/core/lib/refinery/menu_item.rb b/core/lib/refinery/menu_item.rb index <HASH>..<HASH> 100644 --- a/core/lib/refinery/menu_item.rb +++ b/core/lib/refinery/menu_item.rb @@ -15,19 +15,17 @@ module Refinery def children @children ||= if has_children? - menu.class.new(menu.select{|item| item.type == type && item.parent_id == id}) + menu.select{|item| item.type == type && item.parent_id == id} else - menu.class.new + [] end end def descendants @descendants ||= if has_descendants? - menu.class.new(menu.select{|item| - item.type == type && item.lft > lft && item.rgt < rgt - }) + menu.select{|item| item.type == type && item.lft > lft && item.rgt < rgt} else - menu.class.new + [] end end @@ -60,7 +58,7 @@ module Refinery end def siblings - @siblings ||= menu.class.new((has_parent? ? children : menu.roots) - [self]) + @siblings ||= ((has_parent? ? children : menu.roots) - [self]) end alias_method :shown_siblings, :siblings
Creating a new menu instance ruined the way that it was supposed to work and I don't think we even need to do it (should be faster).
refinery_refinerycms
train
ab8325f965123b72b2f0525d6671012037787280
diff --git a/src/Model/BlogController.php b/src/Model/BlogController.php index <HASH>..<HASH> 100644 --- a/src/Model/BlogController.php +++ b/src/Model/BlogController.php @@ -12,6 +12,7 @@ use SilverStripe\ORM\FieldType\DBDatetime; use SilverStripe\ORM\PaginatedList; use SilverStripe\Security\Member; use SilverStripe\View\Parsers\URLSegmentFilter; +use SilverStripe\Control\HTTPRequest; class BlogController extends PageController { @@ -62,7 +63,7 @@ class BlogController extends PageController /** * @return string */ - public function index() + public function index(HTTPRequest $request) { /** * @var Blog $dataRecord
Compatibility issues with core index (#<I>) Making index function compatible with SilverStripe\CMS\Model\RedirectorPageController, this stops issues when module installed and also creating a custom index function in PageController
silverstripe_silverstripe-blog
train
916e19996c3fac06802cdf26d2c82e017e5b39f6
diff --git a/lib/svtplay_dl/service/svt.py b/lib/svtplay_dl/service/svt.py index <HASH>..<HASH> 100644 --- a/lib/svtplay_dl/service/svt.py +++ b/lib/svtplay_dl/service/svt.py @@ -1,4 +1,5 @@ import copy +import json import re from svtplay_dl.error import ServiceError @@ -12,16 +13,14 @@ class Svt(Svtplay): def get(self): data = self.get_urldata() - match_data_video_id = re.search('data-video-id="(.+?)"', data) - - if match_data_video_id: - id = match_data_video_id.group(1) - - else: + match = re.search("n.reduxState=(.*);", data) + if not match: yield ServiceError("Cant find video info.") return - res = self.http.get("http://api.svt.se/videoplayer-api/video/{}".format(id)) + janson = json.loads(match.group(1)) + vid = janson["areaData"]["articles"][list(janson["areaData"]["articles"].keys())[0]]["media"][0]["image"]["svtId"] + res = self.http.get("https://api.svt.se/video/{}".format(vid)) janson = res.json() if "subtitleReferences" in janson: for i in janson["subtitleReferences"]:
svt: fix so we can download videos again
spaam_svtplay-dl
train
32698e7b67e3e086eccea7fbb69d8f02adc23a78
diff --git a/facade/instance.go b/facade/instance.go index <HASH>..<HASH> 100644 --- a/facade/instance.go +++ b/facade/instance.go @@ -414,28 +414,16 @@ func (f *Facade) getInstanceHealth(svch *service.ServiceHealth, instanceID int) // GetHostStrategyInstances returns the strategy objects of all the instances // running on a host. -func (f *Facade) GetHostStrategyInstances(ctx datastore.Context, hostIDs ...string) ([]service.StrategyInstance, error) { +func (f *Facade) GetHostStrategyInstances(ctx datastore.Context, hosts []host.Host) ([]*service.StrategyInstance, error) { defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.GetHostStrategyInstances")) - svcMap := make(map[string]service.StrategyInstance) - insts := make([]service.StrategyInstance, 0) + svcMap := make(map[string]*service.StrategyInstance) + insts := make([]*service.StrategyInstance, 0) - for _, hostID := range hostIDs { - logger := plog.WithField("hostid", hostID) + for _, host := range hosts { + logger := plog.WithField("hostid", host.ID) - var hst host.Host - err := f.hostStore.Get(ctx, host.HostKey(hostID), &hst) - if err != nil { - - logger.WithError(err).Debug("Could not look up host") - - // TODO: expecting wrapped error here - return nil, err - } - - logger.Debug("Loaded host") - - states, err := f.zzk.GetHostStates(ctx, hst.PoolID, hst.ID) + states, err := f.zzk.GetHostStates(ctx, host.PoolID, host.ID) if err != nil { logger.WithError(err).Debug("Could not look up running instances") @@ -461,7 +449,7 @@ func (f *Facade) GetHostStrategyInstances(ctx datastore.Context, hostIDs ...stri return nil, err } - inst = service.StrategyInstance{ + inst = &service.StrategyInstance{ ServiceID: s.ID, CPUCommitment: int(s.CPUCommitment), RAMCommitment: s.RAMCommitment.Value, diff --git a/scheduler/strategy.go b/scheduler/strategy.go index <HASH>..<HASH> 100644 --- a/scheduler/strategy.go +++ b/scheduler/strategy.go @@ -60,14 +60,14 @@ func StrategySelectHost(sn *zkservice.ServiceNode, hosts []host.Host, strat stra // Look up all running services for the hosts glog.V(2).Infof("Looking up instances for hosts: %+v", hostids) - svcs, err := facade.GetHostStrategyInstances(datastore.Get(), hostids...) + svcs, err := facade.GetHostStrategyInstances(datastore.Get(), hosts) if err != nil { return "", err } // Assign the services to the StrategyHosts for _, s := range svcs { if h, ok := hostmap[s.HostID]; ok { - h.services = append(h.services, &StrategyRunningService{s}) + h.services = append(h.services, &StrategyRunningService{*s}) } } shosts := []strategy.Host{}
Remove unnecessary call to hostStore for scheduler
control-center_serviced
train
37c4ff0189783055f3c5db395751b16fe7802006
diff --git a/lib/sprockets-derailleur/manifest.rb b/lib/sprockets-derailleur/manifest.rb index <HASH>..<HASH> 100644 --- a/lib/sprockets-derailleur/manifest.rb +++ b/lib/sprockets-derailleur/manifest.rb @@ -115,6 +115,7 @@ module Sprockets else logger.debug "Writing #{target}" asset.write_to target + asset.write_to "#{target}.gz" if asset.is_a?(BundledAsset) end Marshal.dump(data, child_write)
Create gzipped versions of bundled assets
steel_sprockets-derailleur
train
8542f4f48129db5b410b7db7e30f05fa011f05f5
diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java index <HASH>..<HASH> 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java @@ -99,7 +99,13 @@ public class UserInfoTokenServices implements ResourceServerTokenServices { return new OAuth2Authentication(request, token); } - private Object getPrincipal(Map<String, Object> map) { + /** + * Return the principal that should be used for the token. The default implementation + * looks for well know {@code user*} keys in the map. + * @param map the source map + * @return the principal or {@literal "unknown"} + */ + protected Object getPrincipal(Map<String, Object> map) { for (String key : PRINCIPAL_KEYS) { if (map.containsKey(key)) { return map.get(key);
Make UserInfoTokenServices.getPrincipal protected Update UserInfoTokenServices.getPrincipal() so that it can be overridden by subclasses to allow a custom authenticated principal to be returned from the authorized request parameters. Fixes gh-<I>
spring-projects_spring-boot
train
48db88991801a453139b2a946acf9a1ab169e8be
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,17 @@ from setuptools import setup setup(name='jackal', - version='0.3.6', + version='0.3.7', description='Jackal provides a way to store results from hacking tools in a single place.', author='Matthijs Gielen', author_email='github@mwgielen.com', + license='MIT', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 3 :: Only' + ], + requires_python='>=3', url='https://github.com/mwgielen/jackal/', packages=['jackal', 'jackal.scripts'], install_requires=['elasticsearch_dsl', 'python-libnmap', 'future', 'gevent', 'grequests', 'requests'],
Added license, classifiers and requires python to the setup.py
mwgielen_jackal
train
f12f7d8db811caddcbae2fa4546313c0432b3a29
diff --git a/src/HMACAuth.php b/src/HMACAuth.php index <HASH>..<HASH> 100644 --- a/src/HMACAuth.php +++ b/src/HMACAuth.php @@ -76,7 +76,7 @@ class HMACAuth // to get the same signature every time ksort($headers); - return empty(implode('|', array_keys($headers))) ? - '(none)' : implode('|', array_keys($headers)); + return empty(implode(',', array_keys($headers))) ? + '(none)' : implode(',', array_keys($headers)); } }
According to <URL> is a legal header character, whereas the comma (,) is not.
1ma_Psr7Hmac
train
6c87679e7e776203ce1d9df12e5d13ff0ac77c34
diff --git a/gnupg/tests/test_gnupg.py b/gnupg/tests/test_gnupg.py index <HASH>..<HASH> 100644 --- a/gnupg/tests/test_gnupg.py +++ b/gnupg/tests/test_gnupg.py @@ -421,7 +421,7 @@ class GPGTestCase(unittest.TestCase): def test_import_and_export(self): """Test that key import and export works.""" logger.debug("test_import_and_export begins") - self.test_list_keys_initial() + self.test_list_keys_initial_public() gpg = self.gpg result = gpg.import_keys(KEYS_TO_IMPORT) self.assertEqual(result.summary(), '2 imported') @@ -450,7 +450,7 @@ class GPGTestCase(unittest.TestCase): def test_import_only(self): """Test that key import works.""" logger.debug("test_import_only begins") - self.test_list_keys_initial() + self.test_list_keys_initial_public() self.gpg.import_keys(KEYS_TO_IMPORT) public_keys = self.gpg.list_keys() self.assertTrue(is_list_with_len(public_keys, 2),
Fix a bug in two unittests caused by a method not having been renamed.
isislovecruft_python-gnupg
train
f498459ad2934a46578e97f4d96bd92d68eed5a2
diff --git a/core/corehttp/gateway_test.go b/core/corehttp/gateway_test.go index <HASH>..<HASH> 100644 --- a/core/corehttp/gateway_test.go +++ b/core/corehttp/gateway_test.go @@ -157,7 +157,9 @@ func TestGatewayGet(t *testing.T) { // 1. It's a valid TLD. // 2. Go treats it as the file extension for "man" files (even though // nobody actually *uses* this extension, AFAIK). - // 3. Go accepts "fnord" (the test value) as a valid man file. + // + // Unfortunately, this may not work on all platforms as file type + // detection is platform dependent. ns["/ipns/example.man"] = path.FromString("/ipfs/" + k) t.Log(ts.URL)
gateway_test: comment on platform dependence License: MIT
ipfs_go-ipfs
train
cf114b9c913fa537ab2262cee83529edd852940e
diff --git a/typedload/typechecks.py b/typedload/typechecks.py index <HASH>..<HASH> 100644 --- a/typedload/typechecks.py +++ b/typedload/typechecks.py @@ -15,7 +15,7 @@ protects the user from the ever changing internal representation used in different versions of Python. """ -# Copyright (C) 2019-2021 Salvo "LtWorf" Tomaselli +# Copyright (C) 2019-2022 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -54,6 +54,7 @@ __all__ = [ 'is_typeddict', 'is_newtype', 'is_optional', + 'is_notrequired', 'uniontypes', 'literalvalues', 'NONETYPE', @@ -85,6 +86,13 @@ except: pass +try: + # Since 3.11 + from typing import NotRequired # type: ignore +except ImportError: + NotRequired = None + + def _issubclass(t1, t2) -> bool: """ Wrapper around _issubclass to circumvent python 3.7 changing API @@ -278,3 +286,10 @@ def is_any(type_: Type[Any]) -> bool: Check if it is a typing.Any ''' return type_ == Any + + +def is_notrequired(type_: Type[Any]) -> bool: + ''' + Check if it's typing.NotRequired or typing_extensions.NotRequired + ''' + return getattr(type_, '__origin__', None) == NotRequired and NotRequired is not None
Add check for NotRequired type
ltworf_typedload
train
71e7cf60f174734788b8fb81d79c48254ee0e6e0
diff --git a/jodd-core/src/main/java/jodd/util/ThreadUtil.java b/jodd-core/src/main/java/jodd/util/ThreadUtil.java index <HASH>..<HASH> 100644 --- a/jodd-core/src/main/java/jodd/util/ThreadUtil.java +++ b/jodd-core/src/main/java/jodd/util/ThreadUtil.java @@ -25,11 +25,7 @@ package jodd.util; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** @@ -164,42 +160,4 @@ public class ThreadUtil { }; } - /** - * Creates new core thread pool. - * @see #newCoreThreadPool(String, int, int, int) - */ - public static ExecutorService newCoreThreadPool(String name) { - final int cpus = Runtime.getRuntime().availableProcessors(); - return newCoreThreadPool(name, 5 * cpus, 15 * cpus, 60); - } - - /** - * Creates core thread pool. Uses direct hand-off (<code>SynchronousQueue</code>) - * and <code>CallerRunsPolicy</code> to avoid deadlocks since tasks may have - * internal dependencies. - * <p> - * <code>Executors.newCachedThreadPool()</code> isn't a great choice for server - * code that's servicing multiple clients and concurrent requests. - * 1) It's unbounded, and 2) The unbounded problem is exacerbated by the fact that - * the Executor is fronted by a SynchronousQueue which means there's a direct - * handoff between the task-giver and the thread pool. Each new task will create - * a new thread if all existing threads are busy. This is generally a bad strategy - * for server code. When the CPU gets saturated, existing tasks take longer to finish. - * Yet more tasks are being submitted and more threads created, so tasks take longer and - * longer to complete. When the CPU is saturated, more threads is definitely not what the server needs. - */ - public static ExecutorService newCoreThreadPool(String name, int coreSize, int maxSize, int idleTimeoutInSeconds) { - return newCoreThreadPool(daemonThreadFactory(name), coreSize, maxSize, idleTimeoutInSeconds); - } - public static ExecutorService newCoreThreadPool(ThreadFactory threadFactory, int coreSize, int maxSize, int idleTimeoutInSeconds) { - return new ThreadPoolExecutor( - coreSize, - maxSize, - idleTimeoutInSeconds, TimeUnit.SECONDS, - new SynchronousQueue<>(), - threadFactory, - new ThreadPoolExecutor.CallerRunsPolicy() - ); - } - } \ No newline at end of file
Removed utility that made no improvements.
oblac_jodd
train
9ddaadca274177cecbe9652ba1bdabc924ba7b8a
diff --git a/src/main/java/gwt/material/design/client/data/AbstractDataView.java b/src/main/java/gwt/material/design/client/data/AbstractDataView.java index <HASH>..<HASH> 100644 --- a/src/main/java/gwt/material/design/client/data/AbstractDataView.java +++ b/src/main/java/gwt/material/design/client/data/AbstractDataView.java @@ -2697,10 +2697,10 @@ public abstract class AbstractDataView<T> implements DataView<T> { } @Override - public void enableHelp(Boolean enabled) { + public void showHelp(Boolean enabled) { List<TableHeader> headers = getHeaders(); for (TableHeader header : headers) { - header.enableHelp(enabled); + header.showHelp(enabled); } } diff --git a/src/main/java/gwt/material/design/client/data/HasColumns.java b/src/main/java/gwt/material/design/client/data/HasColumns.java index <HASH>..<HASH> 100644 --- a/src/main/java/gwt/material/design/client/data/HasColumns.java +++ b/src/main/java/gwt/material/design/client/data/HasColumns.java @@ -137,7 +137,7 @@ public interface HasColumns<T> { */ void setHelpEnabled(Boolean enabled); - void enableHelp(Boolean enabled); + void showHelp(Boolean enabled); Boolean isHelpEnabled(); } diff --git a/src/main/java/gwt/material/design/client/ui/table/AbstractDataTable.java b/src/main/java/gwt/material/design/client/ui/table/AbstractDataTable.java index <HASH>..<HASH> 100644 --- a/src/main/java/gwt/material/design/client/ui/table/AbstractDataTable.java +++ b/src/main/java/gwt/material/design/client/ui/table/AbstractDataTable.java @@ -720,8 +720,8 @@ public abstract class AbstractDataTable<T> extends MaterialWidget implements Dat } @Override - public void enableHelp(Boolean enabled) { - view.enableHelp(enabled); + public void showHelp(Boolean enabled) { + view.showHelp(enabled); } protected void onFocus() { diff --git a/src/main/java/gwt/material/design/client/ui/table/TableHeader.java b/src/main/java/gwt/material/design/client/ui/table/TableHeader.java index <HASH>..<HASH> 100644 --- a/src/main/java/gwt/material/design/client/ui/table/TableHeader.java +++ b/src/main/java/gwt/material/design/client/ui/table/TableHeader.java @@ -84,7 +84,7 @@ public class TableHeader extends TableData { } } - public void enableHelp(Boolean enabled) { + public void showHelp(Boolean enabled) { if (helpWidget.isAttached()) { helpWidget.setVisible(enabled); }
Refactor enableHelp - showHelp.
GwtMaterialDesign_gwt-material-table
train
445e48305353412483819acabe531a4facad187f
diff --git a/src/com/google/javascript/rhino/Node.java b/src/com/google/javascript/rhino/Node.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/rhino/Node.java +++ b/src/com/google/javascript/rhino/Node.java @@ -173,8 +173,16 @@ public class Node implements Cloneable, Serializable { @Override boolean isEquivalentTo(Node node, boolean compareJsType, boolean recurse) { - return (super.isEquivalentTo(node, compareJsType, recurse) - && getDouble() == ((NumberNode) node).getDouble()); + boolean equivalent = super.isEquivalentTo(node, compareJsType, recurse); + if (equivalent) { + double thisValue = getDouble(); + double thatValue = ((NumberNode) node).getDouble(); + if (thisValue == thatValue) { + // detect the difference between 0.0 and -0.0. + return (thisValue != 0.0) || (1/thisValue == 1/thatValue); + } + } + return false; } private double number; diff --git a/test/com/google/javascript/jscomp/IntegrationTest.java b/test/com/google/javascript/jscomp/IntegrationTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/IntegrationTest.java +++ b/test/com/google/javascript/jscomp/IntegrationTest.java @@ -1904,6 +1904,18 @@ public class IntegrationTest extends TestCase { test(options, code, result); } + public void testNegativeZero() { + CompilerOptions options = createCompilerOptions(); + CompilationLevel.ADVANCED_OPTIMIZATIONS + .setOptionsForCompilationLevel(options); + test(options, + "function bar(x) { return x; }\n" + + "function foo(x) { print(x / bar(0));\n" + + " print(x / bar(-0)); }\n" + + "foo(3);", + "print(3/0);print(3/-0);"); + } + private void testSame(CompilerOptions options, String original) { testSame(options, new String[] { original }); } diff --git a/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java b/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java +++ b/test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java @@ -312,7 +312,8 @@ public class PeepholeFoldConstantsTest extends CompilerTestCase { fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); - fold("a=-0", "a=0"); + fold("a=-0", "a=-0.0"); + fold("a=-(0)", "a=-0.0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()");
Fix Node equivalence checks for -<I>. Completes fix started with r<I>. Fixes issue <I>. R=nicksantos DELTA=<I> (<I> added, 0 deleted, 3 changed) Revision created by MOE tool push_codebase. MOE_MIGRATION=<I> git-svn-id: <URL>
google_closure-compiler
train
58186b73064627ece9782eab582222ef3c064a37
diff --git a/h2o-core/src/main/java/water/rapids/Rapids.java b/h2o-core/src/main/java/water/rapids/Rapids.java index <HASH>..<HASH> 100644 --- a/h2o-core/src/main/java/water/rapids/Rapids.java +++ b/h2o-core/src/main/java/water/rapids/Rapids.java @@ -107,8 +107,7 @@ public class Rapids { case '(': return new ASTExec(this); // function application case '{': return new ASTFun(this); // function definition case '#': _x++; // Skip before double, FALL THRU - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': + case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return new ASTNum(this); case '\"': return new ASTStr(this,'\"'); case '\'': return new ASTStr(this,'\''); @@ -181,7 +180,7 @@ public class Rapids { } static boolean isWS(char c) { - return c == ' '; + return c == ' ' || c == '\t' || c == '\n'; } static boolean isQuote(char c) {
Rapids: allow tabs and newlines to count as whitespace
h2oai_h2o-3
train
40b3a72498b458fe9feaeb075b0ff6ffdf28a903
diff --git a/namesys/republisher/repub.go b/namesys/republisher/repub.go index <HASH>..<HASH> 100644 --- a/namesys/republisher/repub.go +++ b/namesys/republisher/repub.go @@ -28,6 +28,7 @@ var log = logging.Logger("ipns-repub") var DefaultRebroadcastInterval = time.Hour * 4 var InitialRebroadcastDelay = time.Minute * 1 +var FailureRetryInterval = time.Minute * 5 const DefaultRecordLifetime = time.Hour * 24 @@ -56,17 +57,17 @@ func NewRepublisher(r routing.ValueStore, ds ds.Datastore, self ic.PrivKey, ks k } func (rp *Republisher) Run(proc goprocess.Process) { - tick := time.NewTicker(rp.Interval) - defer tick.Stop() - delayCh := time.After(InitialRebroadcastDelay) + timer := time.NewTimer(InitialRebroadcastDelay) + defer timer.Stop() for { select { - case <-delayCh: - delayCh = tick.C + case <-timer.C: + timer.Reset(rp.Interval) err := rp.republishEntries(proc) if err != nil { log.Error("Republisher failed to republish: ", err) + timer.Reset(FailureRetryInterval) } case <-proc.Closing(): return
retry publishing IPNS records every 5 minutes on failure This way, if we *happen* to be offline while attempting a publish, we don't wait the full interval. License: MIT
ipfs_go-ipfs
train
8752582c924c8583d089b12bfbfa72d3b5a71bd9
diff --git a/glue/ligolw/lsctables.py b/glue/ligolw/lsctables.py index <HASH>..<HASH> 100644 --- a/glue/ligolw/lsctables.py +++ b/glue/ligolw/lsctables.py @@ -568,7 +568,7 @@ class SnglInspiralTable(table.Table): "Gamma9": "real_4", "event_id": "int_8s" # FIXME: column should be ilwd } - # FIXME: event_id column needs to be changed to ilwd + # FIXME: inspiral pipeline needs to not encode data in event_id #ids = SnglInspiralIDs() def get_column(self,column): @@ -671,14 +671,17 @@ class SnglRingDownTable(table.Table): "start_time_gmst": "real_8", "frequency": "real_4", "quality": "real_4", + "phase": "real_4", "mass": "real_4", "spin": "real_4", + "epsilon": "real_4", + "amplitude": "real_4", "snr": "real_4", "eff_distance": "real_4", "sigma_sq": "real_8", - "event_id": "int_8s" # FIXME: column should be ilwd + "event_id": "ilwd:char" } - # FIXME: event_id column needs to be changed to ilwd + # FIXME: ringdown pipeline needs to not encode data in event_id #ids = SnglRingDownIDs()
Fix PR<I>: In sngl_ringdown talbe, add "phase", "epsilon", and "amplitude" columns, change "event_id" to "ilwd:char".
gwastro_pycbc-glue
train
9a3c74d3bd597546f3b81a00bd7056b5a012ec94
diff --git a/src/iterator.js b/src/iterator.js index <HASH>..<HASH> 100644 --- a/src/iterator.js +++ b/src/iterator.js @@ -120,7 +120,12 @@ export default class Iterator { this.descendLeft() } } else { - this.descendRight() + if (this.currentNode) { + this.descendRight() + } else { + if (comparePoints(outputPosition, INFINITY_POINT) !== 0) throw new Error('Unexpected iterator state') + return + } } } }
Allow seeking the iterator to Infinity,Infinity in the output
atom_superstring
train
609361a7803eadf20ca580d14a3337459b0e9fd3
diff --git a/lib/versatile_rjs/proxy.rb b/lib/versatile_rjs/proxy.rb index <HASH>..<HASH> 100644 --- a/lib/versatile_rjs/proxy.rb +++ b/lib/versatile_rjs/proxy.rb @@ -15,14 +15,14 @@ module VersatileRJS end def call(method, *arguments) - method = method.to_s.camelcase - statement = + method = method.to_s.camelcase(:lower) + script = if method =~ /(.*)=$/ "#{statement}.#{$1} = #{arguments.first.to_json}" else "#{statement}.#{method}(#{arguments.map(&:to_json).join(', ')})" end - ActiveSupport::JSON::Variable.new statement + ActiveSupport::JSON::Variable.new script end def to_json
method name conversion should be camelize with first letter lower.
condor_versatile_rjs
train
18062dd4162d4889608ab67416e2b434b56a609e
diff --git a/i3pystatus/updates/yaourt.py b/i3pystatus/updates/yaourt.py index <HASH>..<HASH> 100644 --- a/i3pystatus/updates/yaourt.py +++ b/i3pystatus/updates/yaourt.py @@ -1,15 +1,25 @@ -""" -This module counts the available updates using yaourt. -By default it will only count aur packages. -If you want to count both pacman and aur packages set the variable -count_only_aur = False -""" import re from i3pystatus.core.command import run_through_shell from i3pystatus.updates import Backend class Yaourt(Backend): + """ + This module counts the available updates using yaourt. + By default it will only count aur packages. Thus it can be used with the pacman backend like this: + + from i3pystatus.updates import pacman, yaourt + status.register("updates", + backends = [pacman.Pacman(), yaourt.Yaourt()]) + + If you want to count both pacman and aur packages with this module you can set the variable + count_only_aur = False like this: + + from i3pystatus.updates import yaourt + status.register("updates", + backends = [yaourt.Yaourt(False)]) + """ + def __init__(self, aur_only=True): self.aur_only = aur_only
Moved the docstring and added usage examples.
enkore_i3pystatus
train
544e75c6b357e22cc825035262e037ea66074ed6
diff --git a/pyspectral/tests/test_reflectance.py b/pyspectral/tests/test_reflectance.py index <HASH>..<HASH> 100644 --- a/pyspectral/tests/test_reflectance.py +++ b/pyspectral/tests/test_reflectance.py @@ -156,8 +156,9 @@ class TestReflectance(unittest.TestCase): refl37 = Calculator('EOS-Aqua', 'modis', '20') - refl37_sz88 = Calculator('EOS-Aqua', 'modis', '20', sunz_threshold=88.0) + refl37_sz88 = Calculator('EOS-Aqua', 'modis', '20', sunz_threshold=88.0, masking_limit=None) self.assertEqual(refl37_sz88.sunz_threshold, 88.0) + self.assertIsNone(refl37_sz88.masking_limit) self.assertAlmostEqual(refl37_sz88.bandwavelength, 3.780282, 5) self.assertEqual(refl37_sz88.bandname, '20')
Test that masking_limit is set to Calculator
pytroll_pyspectral
train
f345c5d456516817d4c021572dc80e759072d602
diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncHandler.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncHandler.java @@ -30,7 +30,7 @@ import net.jcip.annotations.ThreadSafe; public class CqlPrepareAsyncHandler extends CqlPrepareHandlerBase implements RequestHandler<PrepareRequest, CompletionStage<PreparedStatement>> { - CqlPrepareAsyncHandler( + public CqlPrepareAsyncHandler( PrepareRequest request, ConcurrentMap<ByteBuffer, DefaultPreparedStatement> preparedStatementsCache, DefaultSession session, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareSyncHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareSyncHandler.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareSyncHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareSyncHandler.java @@ -30,7 +30,7 @@ import net.jcip.annotations.ThreadSafe; public class CqlPrepareSyncHandler extends CqlPrepareHandlerBase implements RequestHandler<PrepareRequest, PreparedStatement> { - CqlPrepareSyncHandler( + public CqlPrepareSyncHandler( PrepareRequest request, ConcurrentMap<ByteBuffer, DefaultPreparedStatement> preparedStatementsCache, DefaultSession session, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestAsyncHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestAsyncHandler.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestAsyncHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestAsyncHandler.java @@ -27,7 +27,7 @@ import net.jcip.annotations.ThreadSafe; public class CqlRequestAsyncHandler extends CqlRequestHandlerBase implements RequestHandler<Statement<?>, CompletionStage<AsyncResultSet>> { - CqlRequestAsyncHandler( + public CqlRequestAsyncHandler( Statement<?> statement, DefaultSession session, InternalDriverContext context, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestSyncHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestSyncHandler.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestSyncHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestSyncHandler.java @@ -29,7 +29,7 @@ import net.jcip.annotations.ThreadSafe; public class CqlRequestSyncHandler extends CqlRequestHandlerBase implements RequestHandler<Statement<?>, ResultSet> { - CqlRequestSyncHandler( + public CqlRequestSyncHandler( Statement<?> statement, DefaultSession session, InternalDriverContext context,
Make constructors public for built-in implementations of RequestHandler
datastax_java-driver
train
2e23689c1687c5a0e1dd01304c88c68c81cad7bc
diff --git a/src/Abstract_/FormFieldDefault.php b/src/Abstract_/FormFieldDefault.php index <HASH>..<HASH> 100644 --- a/src/Abstract_/FormFieldDefault.php +++ b/src/Abstract_/FormFieldDefault.php @@ -76,7 +76,7 @@ abstract class FormFieldDefault extends FormField implements form_\Focusable $this->title = $title; $this->control = $control; if (strlen($title) > 0) - $this->setAccessKey($title[0]); + $this->setAccessKey(mb_substr($title, 0, 1)); } public function getValueToUse() @@ -167,7 +167,7 @@ abstract class FormFieldDefault extends FormField implements form_\Focusable return new html\String($this->title); } else { $matches = []; - if (preg_match('/^(.*?)('.$accessKey.')(.*)$/i', $this->title, + if (preg_match('/^(.*?)('.$accessKey.')(.*)$/iu', $this->title, $matches)) { $container = new form_\Container;
Fixes bugs based on missing utf8 support
hemio-ev_form
train
75def177a64f6b998470eaaf7d14696490af30a0
diff --git a/.travis.yml b/.travis.yml index <HASH>..<HASH> 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,7 @@ before_install: - sudo apt-get install -y acl lxc lxc-dev sqlite3 jq busybox-static protobuf-compiler install: - - go get -v code.google.com/p/goprotobuf/... + - go get -v github.com/golang/protobuf/... - go get golang.org/x/tools/cmd/vet - mkdir -p $GOPATH/github.com/lxc - go get -v -d ./... diff --git a/lxd/migration/migrate.go b/lxd/migration/migrate.go index <HASH>..<HASH> 100644 --- a/lxd/migration/migrate.go +++ b/lxd/migration/migrate.go @@ -24,7 +24,7 @@ import ( * generating a github.com import, and then we can switch this back * too. */ - "code.google.com/p/goprotobuf/proto" + "github.com/golang/protobuf/proto" "github.com/gorilla/websocket" "github.com/lxc/lxd" "github.com/lxc/lxd/shared" diff --git a/lxd/migration/migrate.pb.go b/lxd/migration/migrate.pb.go index <HASH>..<HASH> 100644 --- a/lxd/migration/migrate.pb.go +++ b/lxd/migration/migrate.pb.go @@ -4,7 +4,7 @@ package migration -import proto "code.google.com/p/goprotobuf/proto" +import proto "github.com/golang/protobuf/proto" import json "encoding/json" import math "math"
go-protobuf is now on github
lxc_lxd
train
67183ff9e8f4d16340a00975355f418fe03e2a0e
diff --git a/readthedocs/conf.py b/readthedocs/conf.py index <HASH>..<HASH> 100644 --- a/readthedocs/conf.py +++ b/readthedocs/conf.py @@ -106,7 +106,8 @@ def skip(app, what, name, obj, would_skip, options): '__init__', '__abstractmethods__', '__module__', - '__doc__' + '__doc__', + '__dict__' } return would_skip diff --git a/telethon/client/chats.py b/telethon/client/chats.py index <HASH>..<HASH> 100644 --- a/telethon/client/chats.py +++ b/telethon/client/chats.py @@ -1,4 +1,5 @@ import asyncio +import inspect import itertools import string import typing @@ -447,6 +448,8 @@ class ChatMethods: """ return await self.iter_participants(*args, **kwargs).collect() + get_participants.__signature__ = inspect.signature(iter_participants) + def iter_admin_log( self: 'TelegramClient', entity: 'hints.EntityLike', @@ -608,6 +611,8 @@ class ChatMethods: """ return await self.iter_admin_log(*args, **kwargs).collect() + get_admin_log.__signature__ = inspect.signature(iter_admin_log) + def iter_profile_photos( self: 'TelegramClient', entity: 'hints.EntityLike', @@ -673,6 +678,8 @@ class ChatMethods: """ return await self.iter_profile_photos(*args, **kwargs).collect() + get_profile_photos.__signature__ = inspect.signature(iter_profile_photos) + def action( self: 'TelegramClient', entity: 'hints.EntityLike', diff --git a/telethon/client/dialogs.py b/telethon/client/dialogs.py index <HASH>..<HASH> 100644 --- a/telethon/client/dialogs.py +++ b/telethon/client/dialogs.py @@ -1,4 +1,5 @@ import asyncio +import inspect import itertools import typing @@ -248,6 +249,8 @@ class DialogMethods: """ return await self.iter_dialogs(*args, **kwargs).collect() + get_dialogs.__signature__ = inspect.signature(iter_dialogs) + def iter_drafts( self: 'TelegramClient', entity: 'hints.EntitiesLike' = None diff --git a/telethon/client/messages.py b/telethon/client/messages.py index <HASH>..<HASH> 100644 --- a/telethon/client/messages.py +++ b/telethon/client/messages.py @@ -1,3 +1,4 @@ +import inspect import itertools import typing @@ -520,6 +521,8 @@ class MessageMethods: return await it.collect() + get_messages.__signature__ = inspect.signature(iter_messages) + # endregion # region Message sending/editing/deleting
Improve method signatures in the docs
LonamiWebs_Telethon
train
7a6a9371be3b7ea352c9b87b2c319f2dc1889471
diff --git a/parler/forms.py b/parler/forms.py index <HASH>..<HASH> 100644 --- a/parler/forms.py +++ b/parler/forms.py @@ -116,8 +116,10 @@ class BaseTranslatableModelForm(forms.BaseModelForm): UPGRADED_CLASSES = {} def _upgrade_boundfield_class(cls): - if cls is BoundField or cls is TranslatableBoundField: + if cls is BoundField: return TranslatableBoundField + elif issubclass(cls, TranslatableBoundField): + return cls # When some other package also performs this same trick, # combine both classes on the fly. Avoid having to do that each time.
Better fix for upgrading BoundField
django-parler_django-parler
train
b2b60c4aeb64dbe5f704b3bca58347c843913b21
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,12 @@ # -*- coding: utf-8 -*- from setuptools import setup +import sys + +extra = {} +if sys.version_info >= (3,): + extra['use_2to3'] = True + setup( name='funcparserlib', @@ -12,4 +18,4 @@ setup( 'combinators', license='MIT', url='http://code.google.com/p/funcparserlib/', - use_2to3=True) + **extra)
Compatibility with setuptools instead of distribute for Python 2
vlasovskikh_funcparserlib
train
5d36a7797e4feffb79ddbaaa4a62f87695fc44f0
diff --git a/server/auth.go b/server/auth.go index <HASH>..<HASH> 100644 --- a/server/auth.go +++ b/server/auth.go @@ -40,12 +40,15 @@ func (p *Permissions) clone() *Permissions { if p == nil { return nil } - clone := &Permissions{ - Publish: make([]string, len(p.Publish)), - Subscribe: make([]string, len(p.Subscribe)), + clone := &Permissions{} + if p.Publish != nil { + clone.Publish = make([]string, len(p.Publish)) + copy(clone.Publish, p.Publish) + } + if p.Subscribe != nil { + clone.Subscribe = make([]string, len(p.Subscribe)) + copy(clone.Subscribe, p.Subscribe) } - copy(clone.Publish, p.Publish) - copy(clone.Subscribe, p.Subscribe) return clone } diff --git a/server/auth_test.go b/server/auth_test.go index <HASH>..<HASH> 100644 --- a/server/auth_test.go +++ b/server/auth_test.go @@ -49,6 +49,23 @@ func TestUserClone(t *testing.T) { } } +func TestUserClonePermissionsNoLists(t *testing.T) { + user := &User{ + Username: "foo", + Password: "bar", + Permissions: &Permissions{}, + } + + clone := user.clone() + + if clone.Permissions.Publish != nil { + t.Fatalf("Expected Publish to be nil, got: %v", clone.Permissions.Publish) + } + if clone.Permissions.Subscribe != nil { + t.Fatalf("Expected Subscribe to be nil, got: %v", clone.Permissions.Subscribe) + } +} + func TestUserCloneNil(t *testing.T) { user := (*User)(nil) clone := user.clone() diff --git a/server/opts.go b/server/opts.go index <HASH>..<HASH> 100644 --- a/server/opts.go +++ b/server/opts.go @@ -80,15 +80,19 @@ func (o *Options) Clone() *Options { } clone := &Options{} *clone = *o - clone.Users = make([]*User, len(o.Users)) - for i, user := range o.Users { - clone.Users[i] = user.clone() - } - clone.Routes = make([]*url.URL, len(o.Routes)) - for i, route := range o.Routes { - routeCopy := &url.URL{} - *routeCopy = *route - clone.Routes[i] = routeCopy + if o.Users != nil { + clone.Users = make([]*User, len(o.Users)) + for i, user := range o.Users { + clone.Users[i] = user.clone() + } + } + if o.Routes != nil { + clone.Routes = make([]*url.URL, len(o.Routes)) + for i, route := range o.Routes { + routeCopy := &url.URL{} + *routeCopy = *route + clone.Routes[i] = routeCopy + } } return clone } diff --git a/server/opts_test.go b/server/opts_test.go index <HASH>..<HASH> 100644 --- a/server/opts_test.go +++ b/server/opts_test.go @@ -739,6 +739,19 @@ func TestOptionsClone(t *testing.T) { } } +func TestOptionsCloneNilLists(t *testing.T) { + opts := &Options{} + + clone := opts.Clone() + + if clone.Routes != nil { + t.Fatalf("Expected Routes to be nil, got: %v", clone.Routes) + } + if clone.Users != nil { + t.Fatalf("Expected Users to be nil, got: %v", clone.Users) + } +} + func TestOptionsCloneNil(t *testing.T) { opts := (*Options)(nil) clone := opts.Clone()
Fix Options Clone Ensure Options.Clone() only initializes Users and Routes when the Options it's cloning has them initialized.
nats-io_gnatsd
train
75b78170edf21f723bcf4a200327abfaf3804dde
diff --git a/features/support/env.rb b/features/support/env.rb index <HASH>..<HASH> 100644 --- a/features/support/env.rb +++ b/features/support/env.rb @@ -1,5 +1,7 @@ -require 'coveralls' -Coveralls.wear! +if ENV['CI'] + require 'coveralls' + Coveralls.wear! +end require 'active_record' require 'sqlite3'
Run Coveralls only on CI
kevgo_active_cucumber
train
7137ac1bbd41f6e93d36c921e171df112069c71b
diff --git a/clickoutside.directive.js b/clickoutside.directive.js index <HASH>..<HASH> 100644 --- a/clickoutside.directive.js +++ b/clickoutside.directive.js @@ -38,6 +38,11 @@ classNames = element.className, l = classList.length; + // Unwrap SVGAnimatedString + if (classNames && classNames.baseVal !== undefined) { + classNames = classNames.baseVal; + } + // loop through the elements id's and classnames looking for exceptions for (i = 0; i < l; i++) { // check for id's or classes, but only if they exist in the first place
Handle case where element is SVG This causes the 'className' property to be an instanceof SVGAnimatedString instead of simply a string. This can be handled by unwrapping the SVGAnimatedString.
IamAdamJowett_angular-click-outside
train
a45163c3c411693213514991720fa8f5bfba75dc
diff --git a/src/instrumentation/traceBuffer.js b/src/instrumentation/traceBuffer.js index <HASH>..<HASH> 100644 --- a/src/instrumentation/traceBuffer.js +++ b/src/instrumentation/traceBuffer.js @@ -9,6 +9,8 @@ var TraceBuffer = function (name) { } TraceBuffer.prototype.startTrace = function (signature, type) { + logger.log('opbeat.instrumentation.TraceBuffer.startTrace', signature) + var trace = new Trace(this.traceTransactionReference, signature, type) if (this._isLocked) { @@ -17,25 +19,24 @@ TraceBuffer.prototype.startTrace = function (signature, type) { this.activetraces.push(trace) - logger.log('opbeat.instrumentation.TraceBuffer.startTrace', signature) - return trace } TraceBuffer.prototype._onTraceEnd = function (trace) { + logger.log('opbeat.instrumentation.TraceBuffer._endTrace', this.name, trace.signature) this.traces.push(trace) var index = this.activetraces.indexOf(trace) if (index > -1) { this.activetraces.splice(index, 1) } - // TODO: Buffer should probably be flushed at somepoint to save memory - - logger.log('opbeat.instrumentation.TraceBuffer._endTrace', this.name, trace.signature) } TraceBuffer.prototype.setTransactionReference = function (transaction) { + + logger.log('opbeat.instrumentation.TraceBuffer.setTransactionReference', transaction) + if (this._isLocked) { return }
Add additional logging in TraceBuffer
opbeat_opbeat-js-core
train
7ac5f2b1e0d34b2670e92b9a3f88d7bed4dc074c
diff --git a/lib/bullet/active_record41.rb b/lib/bullet/active_record41.rb index <HASH>..<HASH> 100644 --- a/lib/bullet/active_record41.rb +++ b/lib/bullet/active_record41.rb @@ -125,7 +125,7 @@ module Bullet # call one to many associations alias_method :origin_load_target, :load_target def load_target - Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) unless @inversed if Bullet.start? + Bullet::Detector::NPlusOneQuery.call_association(@owner, @reflection.name) if Bullet.start? && !@inversed origin_load_target end
Auto corrected by following Lint Ruby Style/NestedModifier
flyerhzm_bullet
train
7fde792685756233acd0237c6abdb0cdfc97417c
diff --git a/doc/rules.md b/doc/rules.md index <HASH>..<HASH> 100644 --- a/doc/rules.md +++ b/doc/rules.md @@ -1171,6 +1171,8 @@ Options: `boolean`, default: `false`. Warn when the horizontal rules violate a given or detected style. + Note that horizontal rules are also called “thematic break”. + Options: `string`, either a valid markdown rule, or `consistent`, default: `'consistent'`. diff --git a/lib/rules/no-literal-urls.js b/lib/rules/no-literal-urls.js index <HASH>..<HASH> 100644 --- a/lib/rules/no-literal-urls.js +++ b/lib/rules/no-literal-urls.js @@ -61,7 +61,7 @@ function noLiteralURLs(ast, file, preferred, done) { if ( initial === head && final === tail && - (value === node.href || value == MAILTO + node.href) + (value === node.url || value == MAILTO + node.url) ) { file.warn('Don’t use literal URLs without angle brackets', node); } diff --git a/lib/rules/no-missing-blank-lines.js b/lib/rules/no-missing-blank-lines.js index <HASH>..<HASH> 100644 --- a/lib/rules/no-missing-blank-lines.js +++ b/lib/rules/no-missing-blank-lines.js @@ -43,7 +43,7 @@ function isApplicable(node) { 'html', 'list', 'table', - 'horizontalRule' + 'thematicBreak' ].indexOf(node.type) !== -1; } diff --git a/lib/rules/rule-style.js b/lib/rules/rule-style.js index <HASH>..<HASH> 100644 --- a/lib/rules/rule-style.js +++ b/lib/rules/rule-style.js @@ -6,6 +6,8 @@ * @fileoverview * Warn when the horizontal rules violate a given or detected style. * + * Note that horizontal rules are also called “thematic break”. + * * Options: `string`, either a valid markdown rule, or `consistent`, * default: `'consistent'`. * @example @@ -71,7 +73,7 @@ function ruleStyle(ast, file, preferred, done) { return; } - visit(ast, 'horizontalRule', function (node) { + visit(ast, 'thematicBreak', function (node) { var initial = start(node).offset; var final = end(node).offset; var hr; @@ -84,7 +86,7 @@ function ruleStyle(ast, file, preferred, done) { if (preferred) { if (hr !== preferred) { - file.warn('Horizontal rules should use `' + preferred + '`', node); + file.warn('Rules should use `' + preferred + '`', node); } } else { preferred = hr; diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -39,10 +39,10 @@ "istanbul": "^0.4.0", "jscs": "^2.0.0", "jscs-jsdoc": "^1.0.0", - "remark": "^3.0.0", - "remark-comment-config": "^2.0.0", - "remark-github": "^4.0.0", - "remark-toc": "^2.0.0", + "remark": "^4.0.0-alpha.4", + "remark-comment-config": "^3.0.0", + "remark-github": "^4.0.1", + "remark-toc": "^3.0.0", "remark-validate-links": "^2.0.0", "mocha": "^2.0.0", "vfile": "^1.0.0" diff --git a/script/build-rule-documentation.js b/script/build-rule-documentation.js index <HASH>..<HASH> 100755 --- a/script/build-rule-documentation.js +++ b/script/build-rule-documentation.js @@ -89,7 +89,7 @@ children.push( }, { 'type': 'link', - 'href': 'https://github.com/wooorm/remark-lint#list-of-external-rules', + 'url': 'https://github.com/wooorm/remark-lint#list-of-external-rules', 'children': [{ 'type': 'text', 'value': 'list of external rules' diff --git a/test/index.js b/test/index.js index <HASH>..<HASH> 100644 --- a/test/index.js +++ b/test/index.js @@ -1658,9 +1658,9 @@ describe('Rules', function () { describeSetting(true, function () { assertFile('rule-style-invalid.md', [ - 'rule-style-invalid.md:7:1-7:10: Horizontal rules should use `* * * *`', - 'rule-style-invalid.md:11:1-11:6: Horizontal rules should use `* * * *`', - 'rule-style-invalid.md:15:1-15:5: Horizontal rules should use `* * * *`' + 'rule-style-invalid.md:7:1-7:10: Rules should use `* * * *`', + 'rule-style-invalid.md:11:1-11:6: Rules should use `* * * *`', + 'rule-style-invalid.md:15:1-15:5: Rules should use `* * * *`' ]); assertFile('rule-style-valid.md', []);
Update for changes in remark@<I>
remarkjs_remark-lint
train
a129b832398a335182a39f67b135b8c9955e5ffc
diff --git a/dev/com.ibm.ws.jaxrs.2.0.common/src/com/ibm/ws/jaxrs20/injection/InjectionRuntimeContextHelper.java b/dev/com.ibm.ws.jaxrs.2.0.common/src/com/ibm/ws/jaxrs20/injection/InjectionRuntimeContextHelper.java index <HASH>..<HASH> 100644 --- a/dev/com.ibm.ws.jaxrs.2.0.common/src/com/ibm/ws/jaxrs20/injection/InjectionRuntimeContextHelper.java +++ b/dev/com.ibm.ws.jaxrs.2.0.common/src/com/ibm/ws/jaxrs20/injection/InjectionRuntimeContextHelper.java @@ -127,7 +127,8 @@ public abstract class InjectionRuntimeContextHelper { * then the intersection is only default constructor. * so if ConstructorProxies!=null means there are some other invalid constructors to EJB or CDI container */ - if ((!(resource instanceof ProviderInfo)) || (resource instanceof ApplicationInfo) || resource.getConstructorProxies() != null) { + if ((!(resource instanceof ProviderInfo)) || (resource instanceof ApplicationInfo) + || (resource.getConstructorProxies() != null && !(resource.getConstructorProxies().isEmpty()))) { return; } diff --git a/dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/com/ibm/ws/jaxrs20/injection/InjectionRuntimeContextHelper.java b/dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/com/ibm/ws/jaxrs20/injection/InjectionRuntimeContextHelper.java index <HASH>..<HASH> 100644 --- a/dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/com/ibm/ws/jaxrs20/injection/InjectionRuntimeContextHelper.java +++ b/dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/com/ibm/ws/jaxrs20/injection/InjectionRuntimeContextHelper.java @@ -126,7 +126,8 @@ public abstract class InjectionRuntimeContextHelper { * then the intersection is only default constructor. * so if ConstructorProxies!=null means there are some other invalid constructors to EJB or CDI container */ - if ((!(resource instanceof ProviderInfo)) || (resource instanceof ApplicationInfo) || resource.getConstructorProxies() != null) { + if ((!(resource instanceof ProviderInfo)) || (resource instanceof ApplicationInfo) + || (resource.getConstructorProxies() != null && !(resource.getConstructorProxies().isEmpty()))) { return; }
Issue #<I>: Fix CL Issue #<I> NPE in ThreadLocalHttpServletRequest
OpenLiberty_open-liberty
train
0a4a41841354e698c1b651d3facd3267a2b4456e
diff --git a/tests/test_mycroft_skills_manager.py b/tests/test_mycroft_skills_manager.py index <HASH>..<HASH> 100644 --- a/tests/test_mycroft_skills_manager.py +++ b/tests/test_mycroft_skills_manager.py @@ -160,7 +160,7 @@ class TestMycroftSkillsManager(TestCase): ] self.assertTrue(self.skills_json_path.exists()) - with open(self.skills_json_path) as skills_json: + with open(str(self.skills_json_path)) as skills_json: device_skill_state = json.load(skills_json) self.assertListEqual(initial_state, state['skills']) self.assertListEqual(initial_state, device_skill_state['skills']) @@ -227,7 +227,7 @@ class TestMycroftSkillsManager(TestCase): time_mock.time.return_value = 100 self.msm.install(skill_to_install, origin='voice') - with open(self.skills_json_path) as skills_json: + with open(str(self.skills_json_path)) as skills_json: device_skill_state = json.load(skills_json) skill_test_state = dict( @@ -288,7 +288,7 @@ class TestMycroftSkillsManager(TestCase): isinstance_mock.return_value = True self.msm.install(skill_to_install, origin='cli') - with open(self.skills_json_path) as skills_json: + with open(str(self.skills_json_path)) as skills_json: device_skill_state = json.load(skills_json) skill_test_state = dict( @@ -324,7 +324,7 @@ class TestMycroftSkillsManager(TestCase): isinstance_mock.return_value = True self.msm.remove(skill_to_remove) - with open(self.skills_json_path) as skills_json: + with open(str(self.skills_json_path)) as skills_json: device_skill_state = json.load(skills_json) skill_names = [skill['name'] for skill in device_skill_state['skills']] @@ -409,7 +409,7 @@ class TestMycroftSkillsManager(TestCase): time_mock.time.return_value = 100 self.msm.update(skill_to_update) - with open(self.skills_json_path) as skills_json: + with open(str(self.skills_json_path)) as skills_json: device_skill_state = json.load(skills_json) skill_names = [skill['name'] for skill in device_skill_state['skills']]
Convert Paths to str for python <I> compatibility
MycroftAI_mycroft-skills-manager
train
09c1d7389c9ebfa613cba24368db9e4f38a25a23
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/ResourceManagerRuntimeServices.java b/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/ResourceManagerRuntimeServices.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/ResourceManagerRuntimeServices.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/ResourceManagerRuntimeServices.java @@ -92,9 +92,8 @@ public class ResourceManagerRuntimeServices { new DefaultSlotStatusSyncer( slotManagerConfiguration.getTaskManagerRequestTimeout()), new DefaultResourceAllocationStrategy( - SlotManagerUtils.generateDefaultSlotResourceProfile( - slotManagerConfiguration.getDefaultWorkerResourceSpec(), - slotManagerConfiguration.getNumSlotsPerWorker()), + SlotManagerUtils.generateTaskManagerTotalResourceProfile( + slotManagerConfiguration.getDefaultWorkerResourceSpec()), slotManagerConfiguration.getNumSlotsPerWorker()), Time.milliseconds(REQUIREMENTS_CHECK_DELAY_MS)); } else if (configuration.isDeclarativeResourceManagementEnabled()) { diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategy.java b/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategy.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategy.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategy.java @@ -57,10 +57,12 @@ public class DefaultResourceAllocationStrategy implements ResourceAllocationStra private final int numSlotsPerWorker; public DefaultResourceAllocationStrategy( - ResourceProfile defaultSlotResourceProfile, int numSlotsPerWorker) { - this.defaultSlotResourceProfile = defaultSlotResourceProfile; - this.totalResourceProfile = defaultSlotResourceProfile.multiply(numSlotsPerWorker); + ResourceProfile totalResourceProfile, int numSlotsPerWorker) { + this.totalResourceProfile = totalResourceProfile; this.numSlotsPerWorker = numSlotsPerWorker; + this.defaultSlotResourceProfile = + SlotManagerUtils.generateDefaultSlotResourceProfile( + totalResourceProfile, numSlotsPerWorker); } @Override diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategyTest.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/DefaultResourceAllocationStrategyTest.java @@ -42,7 +42,8 @@ public class DefaultResourceAllocationStrategyTest extends TestLogger { ResourceProfile.fromResources(1, 100); private static final int NUM_OF_SLOTS = 5; private static final DefaultResourceAllocationStrategy STRATEGY = - new DefaultResourceAllocationStrategy(DEFAULT_SLOT_RESOURCE, NUM_OF_SLOTS); + new DefaultResourceAllocationStrategy( + DEFAULT_SLOT_RESOURCE.multiply(NUM_OF_SLOTS), NUM_OF_SLOTS); @Test public void testFulfillRequirementWithRegisteredResources() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/FineGrainedSlotManagerDefaultResourceAllocationStrategyITCase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/FineGrainedSlotManagerDefaultResourceAllocationStrategyITCase.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/FineGrainedSlotManagerDefaultResourceAllocationStrategyITCase.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/FineGrainedSlotManagerDefaultResourceAllocationStrategyITCase.java @@ -40,7 +40,7 @@ public class FineGrainedSlotManagerDefaultResourceAllocationStrategyITCase protected Optional<ResourceAllocationStrategy> getResourceAllocationStrategy() { return Optional.of( new DefaultResourceAllocationStrategy( - DEFAULT_SLOT_RESOURCE_PROFILE, DEFAULT_NUM_SLOTS_PER_WORKER)); + DEFAULT_TOTAL_RESOURCE_PROFILE, DEFAULT_NUM_SLOTS_PER_WORKER)); } /**
[hotfix][runtime] Pass total resource profile instead of default slot profile to DefaultResourceAllocationStrategy The total resource profile will contain the entire information of external resources
apache_flink
train
d0a8e5ff0ead3ea5de09e8d95b7a62d83c5f53f2
diff --git a/lib/hub/commands.rb b/lib/hub/commands.rb index <HASH>..<HASH> 100644 --- a/lib/hub/commands.rb +++ b/lib/hub/commands.rb @@ -368,10 +368,12 @@ module Hub if url = args.find { |a| a =~ %r{^https?://(gist\.)?github\.com/} } idx = args.index(url) gist = $1 == 'gist.' + # strip the fragment part of the url + url.sub!(/#.+/, '') # strip extra path from "pull/42/files", "pull/42/commits" - url = url.sub(%r{(/pull/\d+)/\w*$}, '\1') unless gist + url.sub!(%r{(/pull/\d+)/\w*$}, '\1') unless gist ext = gist ? '.txt' : '.patch' - url += ext unless File.extname(url) == ext + url << ext unless File.extname(url) == ext patch_file = File.join(ENV['TMPDIR'] || '/tmp', "#{gist ? 'gist-' : ''}#{File.basename(url)}") args.before 'curl', ['-#LA', "hub #{Hub::Version}", url, '-o', patch_file] args[idx] = patch_file diff --git a/test/hub_test.rb b/test/hub_test.rb index <HASH>..<HASH> 100644 --- a/test/hub_test.rb +++ b/test/hub_test.rb @@ -461,7 +461,7 @@ class HubTest < Test::Unit::TestCase with_tmpdir('/tmp/') do assert_commands "curl -#LA 'hub #{Hub::Version}' https://github.com/defunkt/hub/pull/55.patch -o /tmp/55.patch", "git am --signoff /tmp/55.patch -p2", - "am --signoff https://github.com/defunkt/hub/pull/55 -p2" + "am --signoff https://github.com/defunkt/hub/pull/55#comment_123 -p2" cmd = Hub("am https://github.com/defunkt/hub/pull/55/files").command assert_includes '/pull/55.patch', cmd
fix `am` command when given URLs that include the fragment
github_hub
train
5d02bba25e58a18eeeba7899ba27e701d274834c
diff --git a/autofit/graphical/__init__.py b/autofit/graphical/__init__.py index <HASH>..<HASH> 100644 --- a/autofit/graphical/__init__.py +++ b/autofit/graphical/__init__.py @@ -2,7 +2,7 @@ from .declarative import ModelFactor, ModelFactorCollection from .factor_graphs import \ Factor, FactorJacobian, FactorGraph, AbstractFactor, FactorValue, \ DiagonalTransform, CholeskyTransform, VariableTransform, \ - FullCholeskyTransform + FullCholeskyTransform , CovarianceTransform, identity_transform from .mean_field import FactorApproximation, MeanField from .expectation_propagation import EPMeanField, EPOptimiser from .messages import FixedMessage, NormalMessage, GammaMessage, AbstractMessage diff --git a/autofit/graphical/factor_graphs/__init__.py b/autofit/graphical/factor_graphs/__init__.py index <HASH>..<HASH> 100644 --- a/autofit/graphical/factor_graphs/__init__.py +++ b/autofit/graphical/factor_graphs/__init__.py @@ -9,7 +9,8 @@ from .jacobians import \ from .graph import FactorGraph from .transform import \ DiagonalTransform, CholeskyTransform, VariableTransform, \ - FullCholeskyTransform, identity_transform, TransformedNode + FullCholeskyTransform, identity_transform, TransformedNode, \ + CovarianceTransform FactorNode = Union[ Factor,
including CovarianceTransform and identity_transform in graph
rhayes777_PyAutoFit
train
ea227913dacaab01a8cbb4ed3ee54d8d7394eb6f
diff --git a/system/src/Grav/Common/Assets.php b/system/src/Grav/Common/Assets.php index <HASH>..<HASH> 100644 --- a/system/src/Grav/Common/Assets.php +++ b/system/src/Grav/Common/Assets.php @@ -24,9 +24,6 @@ class Assets { use GravTrait; - /** @const Regex to match grav asset shortcodes */ - const GRAV_ASSET_REGEX = '/@(plugin|theme)\/(.*?):(.*)/i'; - /** @const Regex to match CSS and JavaScript files */ const DEFAULT_REGEX = '/.\.(css|js)$/i'; @@ -70,7 +67,6 @@ class Assets // Some configuration variables protected $config; - protected $theme_url; protected $base_url; // Default values for pipeline settings @@ -103,8 +99,6 @@ class Assets $this->config($asset_config); $this->base_url = $base_url . '/'; - $this->theme_url = $base_url . '/' . USER_PATH . basename(THEMES_DIR) .'/'. $theme; - } /** @@ -548,45 +542,13 @@ class Assets protected function buildLocalLink($asset) { try { - return self::$grav['uri']->rootUrl() . '/' . self::$grav['locator']->findResource($asset, false); + return $this->base_url . self::$grav['locator']->findResource($asset, false); } catch (\Exception $e) {} - $matches = $this->assetIsGravPackage($asset); - $base_url = $this->base_url; - - - if($matches === false) - return $base_url . $asset; - - if($matches[1] == 'theme') { - return $this->theme_url . '/' . $matches[2] . '/' . $matches[3]; - } elseif ($matches[1] == 'plugin') { - return $base_url . 'user/plugins/' . $matches[2] . '/' . $matches[3]; - } else { - return $base_url . $asset; - } - - - } - - /** - * Determines if an asset contains a valid grav asset shortcode - * Currently supported formats are: - * @plugin/plugin_name/directories:assetname.js|css - * @theme/directories:assetname.js|css - * - * @param string $asset the asset string reference - * @return array|bool if there are matches, those regex matches are returned, else return false - */ - protected function assetIsGravPackage($asset) - { - if(preg_match(self::GRAV_ASSET_REGEX, $asset, $matches)) - return $matches; - return false; + return $this->base_url . $asset; } - /** * Determine whether a link is local or remote. *
switched assets to use new php stream locators
getgrav_grav
train
7ae85c2106942a7ab6cbc7875df6bac95e5398fb
diff --git a/asteval/asteval.py b/asteval/asteval.py index <HASH>..<HASH> 100644 --- a/asteval/asteval.py +++ b/asteval/asteval.py @@ -13,6 +13,7 @@ later, using the current values in the symboltable. from __future__ import division, print_function import ast +import inspect import six from sys import exc_info, stdout, stderr, version_info @@ -32,7 +33,6 @@ ALL_NODES = ['arg', 'assert', 'assign', 'attribute', 'augassign', 'binop', 'pass', 'print', 'raise', 'repr', 'return', 'slice', 'str', 'subscript', 'try', 'tuple', 'unaryop', 'while'] -# noinspection PyIncorrectDocstring class Interpreter(object): """Mathematical expression compiler and interpreter. @@ -167,7 +167,8 @@ class Interpreter(object): self.no_deepcopy = [key for key, val in symtable.items() if (callable(val) - or 'numpy.lib.index_tricks' in repr(val))] + or 'numpy.lib.index_tricks' in repr(val) + or inspect.ismodule(val))] def remove_nodehandler(self, node): """remove support for a node @@ -181,6 +182,7 @@ class Interpreter(object): """set node handler""" self.node_handlers[node] = handler + def user_defined_symbols(self): """Return a set of symbols that have been added to symtable after construction. @@ -467,20 +469,18 @@ class Interpreter(object): return delattr(sym, node.attr) # ctx is ast.Load - errfmt = "'%s' object has not attribute '%s'" - - if (node.attr in UNSAFE_ATTRS or - (isinstance(sym, six.string_types) and 'format' in node.attr) or - (isinstance(sym, Procedure) and node.attr not in dir(sym))): - self.raise_exception(node, exc=AttributeError, - msg=errfmt % (sym, node.attr)) - - try: - return getattr(sym, node.attr) - except AttributeError: - self.raise_exception(node, exc=AttributeError, - msg=errfmt % (sym, node.attr)) + fmt = "cannnot access attribute '%s' for %s" + if node.attr not in UNSAFE_ATTRS: + fmt = "no attribute '%s' for %s" + try: + return getattr(sym, node.attr) + except AttributeError: + pass + # AttributeError or accessed unsafe attribute + obj = self.run(node.value) + msg = fmt % (node.attr, obj) + self.raise_exception(node, exc=AttributeError, msg=msg) def on_assign(self, node): # ('targets', 'value') """Simple assignment.""" @@ -725,10 +725,7 @@ class Interpreter(object): if not isinstance(key, ast.keyword): msg = "keyword error in function call '%s'" % (func) self.raise_exception(node, msg=msg) - if key.arg is None: # Py3 **kwargs ! - keywords.update(self.run(key.value)) - else: - keywords[key.arg] = self.run(key.value) + keywords[key.arg] = self.run(key.value) kwargs = getattr(node, 'kwargs', None) if kwargs is not None: @@ -780,7 +777,7 @@ class Interpreter(object): args=args, kwargs=kwargs, vararg=vararg, varkws=varkws) if node.name in self.no_deepcopy: - self.no_deepcopy.pop(node.name) + self.no_deepcopy.remove(node.name) class Procedure(object):
several more fixes, notable add inspect.ismodule for no_deepcopy
newville_asteval
train
c0150ed669a33d6002db59ca726e914d3853f869
diff --git a/eth_utils/logging.py b/eth_utils/logging.py index <HASH>..<HASH> 100644 --- a/eth_utils/logging.py +++ b/eth_utils/logging.py @@ -1,19 +1,43 @@ import contextlib +import functools import logging -from typing import Any, Iterator, Type, TypeVar +from typing import Any, Callable, Iterator, Optional, Type, TypeVar from .toolz import assoc DEBUG2_LEVEL_NUM = 8 +class cached_show_debug2_property: + def __init__(self, func: Callable[[logging.Logger], bool]): + functools.update_wrapper(self, func) + self._func = func + + def __get__(self, obj: Optional[logging.Logger], cls: Type[logging.Logger]) -> bool: + if obj is None: + return self + + result = self._func(obj) + obj.__dict__[self._func.__name__] = result + return result + + class ExtendedDebugLogger(logging.Logger): """ Logging class that can be used for lower level debug logging. """ + @cached_show_debug2_property + def show_debug2(self) -> bool: + return self.isEnabledFor(DEBUG2_LEVEL_NUM) def debug2(self, message: str, *args: Any, **kwargs: Any) -> None: - self.log(DEBUG2_LEVEL_NUM, message, *args, **kwargs) + if self.show_debug2: + self.log(DEBUG2_LEVEL_NUM, message, *args, **kwargs) + else: + # When we find that `DEBUG2` isn't enabled we completely replace + # the `debug2` function in this instance of the logger with a noop + # lambda to further speed up + self.__dict__['debug2'] = lambda message, *args, **kwargs: None def setup_DEBUG2_logging() -> None: diff --git a/tests/logging-utils/test_DEBUG2_logging.py b/tests/logging-utils/test_DEBUG2_logging.py index <HASH>..<HASH> 100644 --- a/tests/logging-utils/test_DEBUG2_logging.py +++ b/tests/logging-utils/test_DEBUG2_logging.py @@ -1,4 +1,5 @@ import logging +import uuid import pytest @@ -7,7 +8,7 @@ from eth_utils.logging import DEBUG2_LEVEL_NUM @pytest.fixture -def DEBUG2_enabled(): +def DEBUG2_installed(): # caplog only works on loggers retrieved from `logging.getLogger` so we # have to use that mechanism to instantiate our logger. original_logger = logging.getLoggerClass() @@ -19,7 +20,7 @@ def DEBUG2_enabled(): logging.setLoggerClass(original_logger) -def test_extended_debug_logger(caplog, DEBUG2_enabled): +def test_extended_debug_logger(caplog, DEBUG2_installed): caplog.set_level(DEBUG2_LEVEL_NUM, "testing") logger = logging.getLogger("testing") @@ -32,3 +33,47 @@ def test_extended_debug_logger(caplog, DEBUG2_enabled): assert record.levelno == 8 assert record.args == (1,) assert record.message == "message 1" + + +def test_caching_of_debug2_when_disabled(DEBUG2_installed): + # we need a unique logger because loggers are cached + logger = logging.getLogger("testing-{}".format(uuid.uuid4())) + + assert logger.isEnabledFor(DEBUG2_LEVEL_NUM) is False + + assert 'show_debug2' not in logger.__dict__ + assert logger.show_debug2 is False + # cached property should have inserted it into the dict + assert 'show_debug2' in logger.__dict__ + + assert 'debug2' not in logger.__dict__ + assert logger.debug2('this should actually call the function') is None + assert 'debug2' in logger.__dict__ + assert logger.debug2('should not do anything but hit the lambda') is None + + # now see that it always returns the value from `__dict__` + logger.__dict__['show_debug2'] = 100 + assert logger.show_debug2 == 100 + + +def test_caching_of_debug2_when_enabled(DEBUG2_installed): + # we need a unique logger because loggers are cached + logger = logging.getLogger("testing-{}".format(uuid.uuid4())) + + assert logger.isEnabledFor(DEBUG2_LEVEL_NUM) is False + logger.setLevel(DEBUG2_LEVEL_NUM) + assert logger.isEnabledFor(DEBUG2_LEVEL_NUM) is True + + assert 'show_debug2' not in logger.__dict__ + assert logger.show_debug2 is True + # cached property should have inserted it into the dict + assert 'show_debug2' in logger.__dict__ + + assert 'debug2' not in logger.__dict__ + assert logger.debug2('this should actually call the function') is None + assert 'debug2' not in logger.__dict__ + assert logger.debug2('this should still call the function') is None + + # now see that it always returns the value from `__dict__` + logger.__dict__['show_debug2'] = 100 + assert logger.show_debug2 == 100
caching of checks for whether to log at DEBUG2 levels
ethereum_eth-utils
train
46378e4b56e3ec815bd47a818f41c2815dae5fee
diff --git a/spec/lib/endpoints/insurance_packages_spec.rb b/spec/lib/endpoints/insurance_packages_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/endpoints/insurance_packages_spec.rb +++ b/spec/lib/endpoints/insurance_packages_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' describe AthenaHealth::Endpoints::InsurancePackages do let(:attributes) { { practice_id: 195900 } } describe '#top_insurance_packages' do - it 'returns instance of InsutancePackageCollection' do + it 'returns instance of InsurancePackageCollection' do VCR.use_cassette('top_insurance_packages') do expect(client.top_insurance_packages(attributes)) .to be_an_instance_of AthenaHealth::InsurancePackageCollection @@ -12,7 +12,7 @@ describe AthenaHealth::Endpoints::InsurancePackages do end describe '#common_insurance_packages' do - it 'returns instance of InsutancePackageCollection' do + it 'returns instance of InsurancePackageCollection' do VCR.use_cassette('common_insurance_packages') do expect(client.common_insurance_packages(practice_id: 195900, params: {departmentid: 1})) .to be_an_instance_of AthenaHealth::InsurancePackageCollection
Fix Spelling Typo in Spec
HealthTechDevelopers_athena_health
train
fef05d77d28e4d00f1e4407851877266bad430d6
diff --git a/expression/builtin_cast.go b/expression/builtin_cast.go index <HASH>..<HASH> 100644 --- a/expression/builtin_cast.go +++ b/expression/builtin_cast.go @@ -1915,17 +1915,17 @@ func WrapWithCastAsString(ctx sessionctx.Context, expr Expression) Expression { return expr } argLen := exprTp.Flen - // If expr is decimal, we should take the decimal point and negative sign - // into consideration, so we set `expr.GetType().Flen + 2` as the `argLen`. + // If expr is decimal, we should take the decimal point ,negative sign and the leading zero(0.xxx) + // into consideration, so we set `expr.GetType().Flen + 3` as the `argLen`. // Since the length of float and double is not accurate, we do not handle // them. if exprTp.Tp == mysql.TypeNewDecimal && argLen != int(types.UnspecifiedFsp) { - argLen += 2 + argLen += 3 } if exprTp.EvalType() == types.ETInt { argLen = mysql.MaxIntWidth } - // because we can't control the length of cast(float as char) for now, we can't determine the argLen + // Because we can't control the length of cast(float as char) for now, we can't determine the argLen. if exprTp.Tp == mysql.TypeFloat || exprTp.Tp == mysql.TypeDouble { argLen = -1 } diff --git a/expression/integration_test.go b/expression/integration_test.go index <HASH>..<HASH> 100644 --- a/expression/integration_test.go +++ b/expression/integration_test.go @@ -10568,6 +10568,15 @@ func (s *testIntegrationSuite) TestIssue29434(c *C) { tk.MustQuery("select least(c1, '99999999999999') from t1;").Check(testkit.Rows("2021-12-12 10:10:10")) } +func (s *testIntegrationSuite) TestIssue29417(c *C) { + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t1;") + tk.MustExec("create table t1 (f1 decimal(5,5));") + tk.MustExec("insert into t1 values (-0.12345);") + tk.MustQuery("select concat(f1) from t1;").Check(testkit.Rows("-0.12345")) +} + func (s *testIntegrationSuite) TestIssue29244(c *C) { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test") diff --git a/expression/typeinfer_test.go b/expression/typeinfer_test.go index <HASH>..<HASH> 100644 --- a/expression/typeinfer_test.go +++ b/expression/typeinfer_test.go @@ -329,7 +329,7 @@ func (s *InferTypeSuite) createTestCase4StrFuncs() []typeInferTestCase { {"from_base64(c_bigint_d )", mysql.TypeVarString, charset.CharsetBin, mysql.BinaryFlag, 60, types.UnspecifiedLength}, {"from_base64(c_float_d )", mysql.TypeVarString, charset.CharsetBin, mysql.BinaryFlag, types.UnspecifiedLength, types.UnspecifiedLength}, {"from_base64(c_double_d )", mysql.TypeVarString, charset.CharsetBin, mysql.BinaryFlag, types.UnspecifiedLength, types.UnspecifiedLength}, - {"from_base64(c_decimal )", mysql.TypeVarString, charset.CharsetBin, mysql.BinaryFlag, 24, types.UnspecifiedLength}, + {"from_base64(c_decimal )", mysql.TypeVarString, charset.CharsetBin, mysql.BinaryFlag, 27, types.UnspecifiedLength}, {"from_base64(c_datetime )", mysql.TypeVarString, charset.CharsetBin, mysql.BinaryFlag, 66, types.UnspecifiedLength}, {"from_base64(c_time_d )", mysql.TypeVarString, charset.CharsetBin, mysql.BinaryFlag, 30, types.UnspecifiedLength}, {"from_base64(c_timestamp_d)", mysql.TypeVarString, charset.CharsetBin, mysql.BinaryFlag, 57, types.UnspecifiedLength}, @@ -432,7 +432,7 @@ func (s *InferTypeSuite) createTestCase4StrFuncs() []typeInferTestCase { {"reverse(c_bigint_d )", mysql.TypeVarString, charset.CharsetUTF8MB4, 0, 20, types.UnspecifiedLength}, {"reverse(c_float_d )", mysql.TypeVarString, charset.CharsetUTF8MB4, 0, -1, types.UnspecifiedLength}, {"reverse(c_double_d )", mysql.TypeVarString, charset.CharsetUTF8MB4, 0, -1, types.UnspecifiedLength}, - {"reverse(c_decimal )", mysql.TypeVarString, charset.CharsetUTF8MB4, 0, 8, types.UnspecifiedLength}, + {"reverse(c_decimal )", mysql.TypeVarString, charset.CharsetUTF8MB4, 0, 9, types.UnspecifiedLength}, {"reverse(c_char )", mysql.TypeVarString, charset.CharsetUTF8MB4, 0, 20, types.UnspecifiedLength}, {"reverse(c_varchar )", mysql.TypeVarString, charset.CharsetUTF8MB4, 0, 20, types.UnspecifiedLength}, {"reverse(c_text_d )", mysql.TypeVarString, charset.CharsetUTF8MB4, 0, 65535, types.UnspecifiedLength},
expression: fix wrong flen when cast decimal to string (#<I>)
pingcap_tidb
train
734fac97a6747051c0aff17332954fcba1d5baec
diff --git a/lib/listings/base.rb b/lib/listings/base.rb index <HASH>..<HASH> 100644 --- a/lib/listings/base.rb +++ b/lib/listings/base.rb @@ -50,7 +50,7 @@ module Listings end if paginated? - items = paginatable(items).page(page).per(page_size) + items = items.page(page).per(page_size) end if items.is_a?(Class) diff --git a/test/dummy/app/listings/array_listing.rb b/test/dummy/app/listings/array_listing.rb index <HASH>..<HASH> 100644 --- a/test/dummy/app/listings/array_listing.rb +++ b/test/dummy/app/listings/array_listing.rb @@ -1,6 +1,6 @@ class ArrayListing < Listings::Base - model { (1..30).to_a } + model { (1..50).to_a } scope 'Todos', :all, default: true scope 'Impares', :impares, lambda { |items| items.select{|i| i % 2 == 1} }
fix double paginatable to array been applied.
manastech_listings
train
cda584a51039693a239cab1f73711423fdb2f88b
diff --git a/pkg/image/trigger/deploymentconfigs/deploymentconfigs.go b/pkg/image/trigger/deploymentconfigs/deploymentconfigs.go index <HASH>..<HASH> 100644 --- a/pkg/image/trigger/deploymentconfigs/deploymentconfigs.go +++ b/pkg/image/trigger/deploymentconfigs/deploymentconfigs.go @@ -128,13 +128,19 @@ func (i deploymentConfigTriggerIndexer) Index(obj, old interface{}) (string, *tr default: // updated dc = obj.(*appsapi.DeploymentConfig) + oldDC := old.(*appsapi.DeploymentConfig) triggers = calculateDeploymentConfigTriggers(dc) - oldTriggers := calculateDeploymentConfigTriggers(old.(*appsapi.DeploymentConfig)) + oldTriggers := calculateDeploymentConfigTriggers(oldDC) switch { case len(oldTriggers) == 0: change = cache.Added case !reflect.DeepEqual(oldTriggers, triggers): change = cache.Updated + // We need to react on image changes as well. Image names could change, + // images could be set to different value or resetted to "" e.g. by oc apply + // and we need to make sure those changes get reconciled by re-resolving images + case !reflect.DeepEqual(dc.Spec.Template.Spec.Containers, oldDC.Spec.Template.Spec.Containers): + change = cache.Updated } } @@ -187,9 +193,6 @@ func UpdateDeploymentConfigImages(dc *appsapi.DeploymentConfig, tagRetriever tri glog.V(4).Infof("trigger %#v in deployment %s is not resolveable", p, dc.Name) return nil, false, nil } - if ref == p.LastTriggeredImage { - continue - } if len(ref) == 0 { ref = p.LastTriggeredImage
Fix DC image reactor to reconcile on DC dc.Spec.Template.Spec.Containers changes
openshift_origin
train
144e606971b63a9271c48e2048a6372a912321a7
diff --git a/lib/attributor/attribute.rb b/lib/attributor/attribute.rb index <HASH>..<HASH> 100644 --- a/lib/attributor/attribute.rb +++ b/lib/attributor/attribute.rb @@ -14,10 +14,7 @@ module Attributor # @block: code definition for struct attributes (nil for predefined types or leaf/simple types) def initialize(type, options={}, &block) @type = Attributor.resolve_type(type, options, block) - @options = options - @saved_block = block - # @inherit_from = @options.delete(:inherit_from) # AttributeType object to inherit options/subdefinitions from check_options! end @@ -126,7 +123,6 @@ module Attributor # Lazy compilation def compiled_definition unless @compiled_definition - #@compiled_definition = type.definition( @options, @saved_block ) @compiled_definition = type.definition @compiled_options = @compiled_definition.options.merge(@options) end
remove @saved_block from Attribute acu<I>
praxis_attributor
train
de1601921b1df695296c0c1ba716acf58f46fc28
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index <HASH>..<HASH> 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -173,9 +173,9 @@ module Rails if options[:asset_pipeline] == "sprockets" GemfileEntry.version "sprockets-rails", ">= 2.0.0", - "The traditional bundling and transpiling asset pipeline for Rails." + "The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]" elsif options[:asset_pipeline] == "propshaft" - GemfileEntry.version "propshaft", ">= 0.1.7", "The modern asset pipeline for Rails." + GemfileEntry.version "propshaft", ">= 0.1.7", "The modern asset pipeline for Rails [https://github.com/rails/propshaft/]" else [] end
Use same comment format as other gems, including links to learn more
rails_rails
train
7411761b8076d291093896d7bacd4d0b3bf42ff4
diff --git a/match/lib/match/storage/google_cloud_storage.rb b/match/lib/match/storage/google_cloud_storage.rb index <HASH>..<HASH> 100644 --- a/match/lib/match/storage/google_cloud_storage.rb +++ b/match/lib/match/storage/google_cloud_storage.rb @@ -293,6 +293,9 @@ module Match end def ensure_bucket_is_selected + # Skip the instructions if the user provided a bucket name + return unless self.bucket_name.to_s.length == 0 + created_bucket = UI.confirm("Did you already create a Google Cloud Storage bucket?") while self.bucket_name.to_s.length == 0 unless created_bucket
Check if the bucket name was already specified (#<I>)
fastlane_fastlane
train
4c104dddd1f9bf9d5d006c2e1ac7fe1a2b5ca606
diff --git a/src/SectionField/Api/Controller/RestController.php b/src/SectionField/Api/Controller/RestController.php index <HASH>..<HASH> 100644 --- a/src/SectionField/Api/Controller/RestController.php +++ b/src/SectionField/Api/Controller/RestController.php @@ -706,7 +706,9 @@ class RestController implements RestControllerInterface private function preFlightOptions(Request $request, string $allowMethods = 'OPTIONS'): ?JsonResponse { if (strtolower($request->getMethod()) === self::OPTIONS_CALL) { + $origin = $request->headers->get('Origin'); return new JsonResponse([], JsonResponse::HTTP_OK, [ + 'Access-Control-Allow-Origin' => $origin ?: '*', 'Access-Control-Allow-Methods' => $allowMethods, 'Access-Control-Allow-Credentials' => 'true' ]); diff --git a/test/unit/SectionField/Api/Controller/RestControllerTest.php b/test/unit/SectionField/Api/Controller/RestControllerTest.php index <HASH>..<HASH> 100644 --- a/test/unit/SectionField/Api/Controller/RestControllerTest.php +++ b/test/unit/SectionField/Api/Controller/RestControllerTest.php @@ -133,7 +133,15 @@ class RestControllerTest extends TestCase $this->requestStack->shouldReceive('getCurrentRequest') ->once() ->andReturn($request); + + $request->headers = Mockery::mock(HeaderCollection::class); + $request->headers->shouldReceive('get') + ->with('Origin') + ->once() + ->andReturn('someorigin.com'); + $response = new JsonResponse([], JsonResponse::HTTP_OK, [ + 'Access-Control-Allow-Origin' => 'someorigin.com', 'Access-Control-Allow-Methods' => $allowMethods, 'Access-Control-Allow-Credentials' => 'true' ]);
Return Origin on OPTIONS calls
dionsnoeijen_sexy-field-api
train
c7a59e10a17deafc069de3156970024cd7613a74
diff --git a/cmsplugin_cascade/bootstrap4/fields.py b/cmsplugin_cascade/bootstrap4/fields.py index <HASH>..<HASH> 100644 --- a/cmsplugin_cascade/bootstrap4/fields.py +++ b/cmsplugin_cascade/bootstrap4/fields.py @@ -9,4 +9,5 @@ class BootstrapMultiSizeField(MultiSizeField): """ def __init__(self, *args, **kwargs): properties = [bp.name for bp in Breakpoint] + kwargs['sublabels'] = [bp.label for bp in Breakpoint] super().__init__(properties, *args, **kwargs) diff --git a/cmsplugin_cascade/bootstrap4/jumbotron.py b/cmsplugin_cascade/bootstrap4/jumbotron.py index <HASH>..<HASH> 100644 --- a/cmsplugin_cascade/bootstrap4/jumbotron.py +++ b/cmsplugin_cascade/bootstrap4/jumbotron.py @@ -150,6 +150,7 @@ class JumbotronFormMixin(EntangledModelFormMixin): background_width_height = MultiSizeField( ['width', 'height'], label=_("Background width/height"), + sublabels=[_("Width"), _("Height")], allowed_units=['px', '%'], required=False, help_text=_("This property specifies the width and height of a background image in px or %."), diff --git a/cmsplugin_cascade/fields.py b/cmsplugin_cascade/fields.py index <HASH>..<HASH> 100644 --- a/cmsplugin_cascade/fields.py +++ b/cmsplugin_cascade/fields.py @@ -235,7 +235,7 @@ class MultiSizeField(MultiValueField): Some size input fields must be specified per Bootstrap breakpoint. Use this multiple input field to handle this. """ - def __init__(self, properties, *args, **kwargs): + def __init__(self, properties, sublabels=None, *args, **kwargs): required = kwargs.pop('required', False) require_all_fields = kwargs.pop('require_all_fields', required) initial = kwargs.pop('initial', None) @@ -247,7 +247,9 @@ class MultiSizeField(MultiValueField): initial = {prop: initial for prop in properties} allowed_units = kwargs.pop('allowed_units', None) fields = [SizeField(required=required, allowed_units=allowed_units)] * len(properties) - widget = MultipleTextInputWidget(properties) + if sublabels is None: + sublabels = properties + widget = MultipleTextInputWidget(sublabels) super().__init__(fields=fields, widget=widget, required=required, require_all_fields=require_all_fields, initial=initial, *args, **kwargs) self.properties = list(properties) diff --git a/cmsplugin_cascade/leaflet/map.py b/cmsplugin_cascade/leaflet/map.py index <HASH>..<HASH> 100644 --- a/cmsplugin_cascade/leaflet/map.py +++ b/cmsplugin_cascade/leaflet/map.py @@ -63,6 +63,7 @@ class MarkerForm(CascadeModelForm): marker_anchor = MultiSizeField( ['left', 'top'], label=_("Marker Anchor"), + sublabels=[_("Left"), _("Top")], allowed_units=['px', '%'], required=False, help_text=_("Coordinates of the icon's anchor relative to its top left corner."),
MultiSizeField accepts sublabels for all of its fields
jrief_djangocms-cascade
train
c594317337457a7f19166244f6acc66b476be856
diff --git a/src/main/java/io/pivotal/spring/cloud/IssuerCheckConfiguration.java b/src/main/java/io/pivotal/spring/cloud/IssuerCheckConfiguration.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/pivotal/spring/cloud/IssuerCheckConfiguration.java +++ b/src/main/java/io/pivotal/spring/cloud/IssuerCheckConfiguration.java @@ -13,7 +13,7 @@ import org.springframework.security.oauth2.provider.token.store.jwk.JwkTokenStor import java.net.MalformedURLException; @Configuration -@ConditionalOnProperty({"ssoServiceUrl", "security.oauth2.resource.jwk.key-set-uri"}) +@ConditionalOnProperty({"sso.connector.cloud.available"}) public class IssuerCheckConfiguration { @Value("${ssoServiceUrl}") private String ssoServiceUrl; diff --git a/src/main/java/io/pivotal/spring/cloud/SsoServiceCredentialsListener.java b/src/main/java/io/pivotal/spring/cloud/SsoServiceCredentialsListener.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/pivotal/spring/cloud/SsoServiceCredentialsListener.java +++ b/src/main/java/io/pivotal/spring/cloud/SsoServiceCredentialsListener.java @@ -35,6 +35,7 @@ public class SsoServiceCredentialsListener implements ApplicationListener<Applic map.put("security.oauth2.resource.userInfoUri", ssoServiceInfo.getAuthDomain() + "/userinfo"); map.put("security.oauth2.resource.tokenInfoUri", ssoServiceInfo.getAuthDomain() + "/check_token"); map.put("security.oauth2.resource.jwk.key-set-uri", ssoServiceInfo.getAuthDomain() + "/token_keys"); + map.put("sso.connector.cloud.available", "success"); MapPropertySource mapPropertySource = new MapPropertySource("vcapPivotalSso", map); event.getEnvironment().getPropertySources().addFirst(mapPropertySource); diff --git a/src/test/java/io/pivotal/spring/cloud/IssuerCheckConfigurationTest.java b/src/test/java/io/pivotal/spring/cloud/IssuerCheckConfigurationTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/pivotal/spring/cloud/IssuerCheckConfigurationTest.java +++ b/src/test/java/io/pivotal/spring/cloud/IssuerCheckConfigurationTest.java @@ -19,7 +19,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @EnableAutoConfiguration @TestPropertySource(properties = { "ssoServiceUrl=https://cf-identity-eng-test1.login.run.pivotal.io", - "security.oauth2.resource.jwk.key-set-uri=https://cf-identity-eng-test1.login.run.pivotal.io/token_keys" + "security.oauth2.resource.jwk.key-set-uri=https://cf-identity-eng-test1.login.run.pivotal.io/token_keys", + "sso.connector.cloud.available=success" }) public class IssuerCheckConfigurationTest { @ClassRule diff --git a/src/test/java/io/pivotal/spring/cloud/SsoServiceCredentialsListenerTest.java b/src/test/java/io/pivotal/spring/cloud/SsoServiceCredentialsListenerTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/pivotal/spring/cloud/SsoServiceCredentialsListenerTest.java +++ b/src/test/java/io/pivotal/spring/cloud/SsoServiceCredentialsListenerTest.java @@ -48,5 +48,6 @@ public class SsoServiceCredentialsListenerTest { assertEquals("test-auth-domain/userinfo", environment.getProperty("security.oauth2.resource.userInfoUri")); assertEquals("test-auth-domain/check_token", environment.getProperty("security.oauth2.resource.tokenInfoUri")); assertEquals("test-auth-domain", environment.getProperty("ssoServiceUrl")); + assertEquals("success", environment.getProperty("sso.connector.cloud.available")); } }
Do not attempt to create token store if not running in cloud environment [#<I>] <URL>
pivotal-cf_spring-cloud-sso-connector
train
0731baaf050aa1c507baa020db9ae0bed7560cea
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -9,6 +9,7 @@ // * Source: <https://github.com/niftylettuce/express-paginate> var querystring = require('querystring') +var url = require('url'); var _ = require('lodash') exports = module.exports @@ -19,7 +20,7 @@ exports.href = function paginate(req) { prev = (typeof prev === 'boolean') ? prev : false query.page = prev ? query.page-= 1 : query.page += 1 query.page = (query.page < 1) ? 1 : query.page - return req.originalUrl + '?' + querystring.stringify(query) + return url.parse(req.originalUrl).pathname + '?' + querystring.stringify(query) } }
removing query parameters from the url, so it won't duplicate when reappended
expressjs_express-paginate
train
3fa521574f8a8107a758042cc22fd5b892e74006
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # VisiData version history -# 2.8 (2021-12-XX) +# 2.8 (2021-12-15) ## Improvements diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -# VisiData v2.7.1 [![twitter @VisiData][1.1]][1] [![CircleCI](https://circleci.com/gh/saulpw/visidata/tree/stable.svg?style=svg)](https://circleci.com/gh/saulpw/visidata/tree/stable) [![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/saulpw/visidata) +# VisiData v2.8 [![twitter @VisiData][1.1]][1] [![CircleCI](https://circleci.com/gh/saulpw/visidata/tree/stable.svg?style=svg)](https://circleci.com/gh/saulpw/visidata/tree/stable) [![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/saulpw/visidata) A terminal interface for exploring and arranging tabular data. diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ from setuptools import setup # tox can't actually run python3 setup.py: https://github.com/tox-dev/tox/issues/96 #from visidata import __version__ -__version__ = '2.8dev' +__version__ = '2.8' setup(name='visidata', version=__version__, diff --git a/visidata/__init__.py b/visidata/__init__.py index <HASH>..<HASH> 100644 --- a/visidata/__init__.py +++ b/visidata/__init__.py @@ -1,6 +1,6 @@ 'VisiData: a curses interface for exploring and arranging tabular data' -__version__ = '2.8dev' +__version__ = '2.8' __version_info__ = 'VisiData v' + __version__ __author__ = 'Saul Pwanson <vd@saul.pw>' __status__ = 'Production/Stable' diff --git a/visidata/main.py b/visidata/main.py index <HASH>..<HASH> 100755 --- a/visidata/main.py +++ b/visidata/main.py @@ -2,7 +2,7 @@ # Usage: $0 [<options>] [<input> ...] # $0 [<options>] --play <cmdlog> [--batch] [-w <waitsecs>] [-o <output>] [field=value ...] -__version__ = '2.8dev' +__version__ = '2.8' __version_info__ = 'saul.pw/VisiData v' + __version__ from copy import copy
[dev] bump to <I>
saulpw_visidata
train
b6f08e746d29a10f73c9e37ea828f093d68a89bd
diff --git a/sonar-channel/src/main/java/org/sonar/channel/CodeBuffer.java b/sonar-channel/src/main/java/org/sonar/channel/CodeBuffer.java index <HASH>..<HASH> 100644 --- a/sonar-channel/src/main/java/org/sonar/channel/CodeBuffer.java +++ b/sonar-channel/src/main/java/org/sonar/channel/CodeBuffer.java @@ -94,11 +94,9 @@ public class CodeBuffer implements CharSequence { } private void updateCursorPosition(int character) { - //see Java Language Specification : http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.4 - if (character == LF || character == CR) { - if ((lastChar != LF && lastChar != CR) || lastChar == character || lastChar == LF) { - cursor.line++; - } + // see Java Language Specification : http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.4 + if (character == LF || (character == CR && peek() != LF)) { + cursor.line++; cursor.column = 0; } else if (character == '\t') { cursor.column += tabWidth; diff --git a/sonar-channel/src/test/java/org/sonar/channel/CodeBufferTest.java b/sonar-channel/src/test/java/org/sonar/channel/CodeBufferTest.java index <HASH>..<HASH> 100644 --- a/sonar-channel/src/test/java/org/sonar/channel/CodeBufferTest.java +++ b/sonar-channel/src/test/java/org/sonar/channel/CodeBufferTest.java @@ -84,8 +84,8 @@ public class CodeBufferTest { assertThat(reader.getLinePosition(), is(3)); assertThat((char) reader.pop(), is('s')); reader.pop(); // \r - assertThat(reader.getColumnPosition(), is(0)); - assertThat(reader.getLinePosition(), is(4)); + assertThat(reader.getColumnPosition(), is(2)); + assertThat(reader.getLinePosition(), is(3)); reader.pop(); // \n assertThat(reader.getColumnPosition(), is(0)); assertThat(reader.getLinePosition(), is(4));
Sonar Channel : Slightly improve the readability of the source code in charge to increment the line number
SonarSource_sonarqube
train
bb215a48c4c2ef592410c5bd1425ed57a53c78f6
diff --git a/tests/unit/AssetTest.php b/tests/unit/AssetTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/AssetTest.php +++ b/tests/unit/AssetTest.php @@ -2,6 +2,9 @@ namespace WeiTest; +/** + * @property \Wei\Asset asset + */ class AssetTest extends TestCase { /** @@ -52,4 +55,13 @@ class AssetTest extends TestCase $this->asset->setBaseUrl('abc'); $this->assertEquals('abc', $this->asset->getBaseUrl()); } + + public function testConcat() + { + $this->asset->setBaseUrl('abc'); + $this->asset->setOption('concatUrl', '/c/'); + $this->assertEquals('/c/?b=abc&f=a.js,b/b.js,c/c/c.js', $this->asset->concat(array( + 'a.js', 'b/b.js', 'c/c/c.js' + ))); + } }
added test for asset service concat method
twinh_wei
train
497e1c27d2f911a2311b84f3c5976d7f3e0f9fe7
diff --git a/src/browser/rollbar.js b/src/browser/rollbar.js index <HASH>..<HASH> 100644 --- a/src/browser/rollbar.js +++ b/src/browser/rollbar.js @@ -123,7 +123,7 @@ Rollbar.prototype.handleUnhandledRejection = function(reason, promise) { if (_.isError(reason)) { item = this._createItem([message, reason, context]); } else { - item = this._createItem([message, context]); + item = this._createItem([message, reason, context]); item.stackInfo = _.makeUnhandledStackInfo( message, '', @@ -138,7 +138,7 @@ Rollbar.prototype.handleUnhandledRejection = function(reason, promise) { item.level = this.options.uncaughtErrorLevel; item._isUncaught = true; item._originalArgs = item._originalArgs || []; - item._originalArgs.push(reason, promise); + item._originalArgs.push(promise); this.client.log(item); };
include the reason in the item even if it is not an error, even though this duplicates information that is already in message
rollbar_rollbar.js
train
be38d2519c84da1bd26f5e681bfe3331d0b86ac1
diff --git a/bokeh/io/webdriver.py b/bokeh/io/webdriver.py index <HASH>..<HASH> 100644 --- a/bokeh/io/webdriver.py +++ b/bokeh/io/webdriver.py @@ -22,6 +22,7 @@ log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Standard library imports +import atexit import signal import warnings from os.path import devnull @@ -125,3 +126,5 @@ class _WebdriverState(object): webdriver_control = _WebdriverState() + +atexit.register(lambda: webdriver_control.reset())
Always kill phantomjs at process exit (#<I>)
bokeh_bokeh
train
7dd76c234c5b9c1c43176bf2ac73b339c2e6323f
diff --git a/aeron-system-tests/src/test/java/io/aeron/archive/ArchiveDeleteAndRestartTest.java b/aeron-system-tests/src/test/java/io/aeron/archive/ArchiveDeleteAndRestartTest.java index <HASH>..<HASH> 100644 --- a/aeron-system-tests/src/test/java/io/aeron/archive/ArchiveDeleteAndRestartTest.java +++ b/aeron-system-tests/src/test/java/io/aeron/archive/ArchiveDeleteAndRestartTest.java @@ -120,7 +120,7 @@ public class ArchiveDeleteAndRestartTest final String uri = "aeron:ipc?term-length=16m|init-term-id=502090867|term-offset=0|term-id=502090867"; final ExclusivePublication recordedPublication1 = client.addExclusivePublication(uri, STREAM_ID); - aeronArchive.startRecording(uri, STREAM_ID, SourceLocation.LOCAL); + final long subscriptionId = aeronArchive.startRecording(uri, STREAM_ID, SourceLocation.LOCAL); for (int i = 0; i < 10; i++) { @@ -144,6 +144,7 @@ public class ArchiveDeleteAndRestartTest } recordedPublication1.close(); + aeronArchive.stopRecording(subscriptionId); while (position1 != aeronArchive.getStopPosition(collector.descriptors.get(0).recordingId)) {
[Java] Stop recording before shutting down archive with separate media driver.
real-logic_aeron
train