hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
dc5c31fedbb9661562bb4994469567fcd04f39b3
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -18,6 +18,7 @@ setup(
author_email='jeongyoon.lee1@gmail.com',
packages=['kaggler',
+ 'kaggler.feature_selection',
'kaggler.model',
'kaggler.metrics',
'kaggler.online_model',
|
add feature_selection to setup.py
|
jeongyoonlee_Kaggler
|
train
|
621653732336511ca4f370e87b87dc5cb21ace46
|
diff --git a/bundles/org.eclipse.orion.client.core/web/orion/searchExplorer.js b/bundles/org.eclipse.orion.client.core/web/orion/searchExplorer.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.core/web/orion/searchExplorer.js
+++ b/bundles/org.eclipse.orion.client.core/web/orion/searchExplorer.js
@@ -122,6 +122,10 @@ define(['require', 'dojo', 'dijit','orion/explorer', 'orion/treeModelIterator',
onItem(this._listRoot);
};
+ SearchResultModel.prototype.getTopIterationNodes = function(){
+ return this.indexedFileItems;
+ };
+
SearchResultModel.prototype.buildResultModel = function(){
this.restoreGlobalStatus();
this.buildFlatModel();
@@ -1218,7 +1222,6 @@ define(['require', 'dojo', 'dijit','orion/explorer', 'orion/treeModelIterator',
that.reportStatus("");
});
};
-
SearchResultExplorer.prototype.replacePreview = function(replaceStr) {
this._state = "replace_preview";
@@ -1231,11 +1234,6 @@ define(['require', 'dojo', 'dijit','orion/explorer', 'orion/treeModelIterator',
parentDivID: this.getParentDivId()
});
this._uiFactory.buildUI();
- // FIXME shouldn't know this id, should be passed in
- var parentPane = dijit.byId("orion.searchResults");
- if(parentPane.isLeftPaneOpen()){
- parentPane.toggle();
- }
this.reportStatus("Preparing preview...");
var that = this;
|
Bug <I> - "auto collapse" of left hand pane on search results preview is disrupting.
|
eclipse_orion.client
|
train
|
453b3ed33d85f36bd8aa0b697a4700141c2eca8c
|
diff --git a/drools-examples/drools-examples-drl/src/main/java/org/drools/examples/cdss/CDSSExample.java b/drools-examples/drools-examples-drl/src/main/java/org/drools/examples/cdss/CDSSExample.java
index <HASH>..<HASH> 100644
--- a/drools-examples/drools-examples-drl/src/main/java/org/drools/examples/cdss/CDSSExample.java
+++ b/drools-examples/drools-examples-drl/src/main/java/org/drools/examples/cdss/CDSSExample.java
@@ -34,7 +34,7 @@ public class CDSSExample {
RecommendationService recommendationService = new RecommendationService();
ksession.setGlobal( "recommendationService",
recommendationService );
-
+
// create patient
Patient patient = new Patient();
patient.setName( "John Doe" );
@@ -89,12 +89,16 @@ public class CDSSExample {
kbuilder.add( ResourceFactory.newClassPathResource( "/org/drools/examples/cdss/ClinicalPathwayX.rf", CDSSExample.class ),
ResourceType.DRF );
+ kbuilder.add( ResourceFactory.newClassPathResource( "/org/drools/examples/cdss/ClinicalPathwayX.drl", CDSSExample.class ),
+ ResourceType.DRL );
+
kbuilder.add( ResourceFactory.newClassPathResource( "/org/drools/examples/cdss/TreatmentX.rf", CDSSExample.class ),
ResourceType.DRF );
kbuilder.add( ResourceFactory.newClassPathResource( "/org/drools/examples/cdss/TreatmentY.rf", CDSSExample.class ) ,
ResourceType.DRF );
+
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
|
CDSSExample was not working because ClinicalPathwayX.drl was not added in to the knowledge builder.
git-svn-id: <URL>
|
kiegroup_drools
|
train
|
4f69ec128b8466260ebb941dd44234feb6c8a66b
|
diff --git a/src/Black/Component/User/Infrastructure/CQRS/Handler/ActiveUserHandler.php b/src/Black/Component/User/Infrastructure/CQRS/Handler/ActiveUserHandler.php
index <HASH>..<HASH> 100644
--- a/src/Black/Component/User/Infrastructure/CQRS/Handler/ActiveUserHandler.php
+++ b/src/Black/Component/User/Infrastructure/CQRS/Handler/ActiveUserHandler.php
@@ -19,7 +19,7 @@ use Black\Component\User\Infrastructure\DomainEvent\UserActivateSubscriber;
use Black\Component\User\Infrastructure\Service\UserStatusService;
use Black\Component\User\UserEvents;
use Black\DDD\CQRSinPHP\Infrastructure\CQRS\CommandHandler;
-use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
+use Symfony\Component\EventDispatcher\EventDispatcher;
/**
* Class ActiveUserHandler
@@ -40,7 +40,7 @@ class ActiveUserHandler implements CommandHandler
protected $service;
/**
- * @var TraceableEventDispatcher
+ * @var EventDispatcher
*/
protected $dispatcher;
@@ -52,13 +52,13 @@ class ActiveUserHandler implements CommandHandler
/**
* @param UserManager $userManager
* @param UserStatusService $service
- * @param TraceableEventDispatcher $dispatcher
+ * @param EventDispatcher $dispatcher
* @param UserActivateSubscriber $subscriber
*/
public function __construct(
UserManager $userManager,
UserStatusService $service,
- TraceableEventDispatcher $dispatcher,
+ EventDispatcher $dispatcher,
UserActivateSubscriber $subscriber
) {
$this->manager = $userManager;
diff --git a/src/Black/Component/User/Infrastructure/CQRS/Handler/RemoveUserHandler.php b/src/Black/Component/User/Infrastructure/CQRS/Handler/RemoveUserHandler.php
index <HASH>..<HASH> 100644
--- a/src/Black/Component/User/Infrastructure/CQRS/Handler/RemoveUserHandler.php
+++ b/src/Black/Component/User/Infrastructure/CQRS/Handler/RemoveUserHandler.php
@@ -17,7 +17,7 @@ use Black\Component\User\Infrastructure\DomainEvent\UserRemovedEvent;
use Black\Component\User\Infrastructure\DomainEvent\UserRemovedSubscriber;
use Black\Component\User\UserEvents;
use Black\DDD\CQRSinPHP\Infrastructure\CQRS\CommandHandler;
-use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
+use Symfony\Component\EventDispatcher\EventDispatcher;
/**
* Class RemoveUserHandler
@@ -33,7 +33,7 @@ class RemoveUserHandler implements CommandHandler
protected $manager;
/**
- * @var TraceableEventDispatcher
+ * @var EventDispatcher
*/
protected $dispatcher;
@@ -47,7 +47,7 @@ class RemoveUserHandler implements CommandHandler
*/
public function __construct(
UserManager $userManager,
- TraceableEventDispatcher $dispatcher,
+ EventDispatcher $dispatcher,
UserRemovedSubscriber $subscriber
) {
$this->manager = $userManager;
|
Move from TraceableEventDispatcher to EventDispatcher
|
pocky_user
|
train
|
5a5766c21d9783a19e7be76ef01a943aca47b7e8
|
diff --git a/src/tests/testRenderer/snapshot.spec.js b/src/tests/testRenderer/snapshot.spec.js
index <HASH>..<HASH> 100644
--- a/src/tests/testRenderer/snapshot.spec.js
+++ b/src/tests/testRenderer/snapshot.spec.js
@@ -175,7 +175,8 @@ describe('snapshots', function () {
expect(fs.writeFileSync, 'to have a call satisfying', [
snapshotPath,
expect.it('to match', /\/\/ <button onClick={/)
- .and('to match', /\/\/ <\/button>/)
+ .and('to match', /\/\/ <\/button>/)
+ .and('not to match', /\/\/\s*children:/)
]);
});
@@ -415,6 +416,7 @@ describe('snapshots', function () {
snapshotPath,
expect.it('to match', /\/\/ <button onClick={/)
.and('to match', /\/\/ <\/button>/)
+ .and('not to match', /\/\/\s*children:/)
]
]);
});
|
Add negative check for `children:`
The comments contain a correct snapshot comment, and a failed snapshot
comment, therefore we need to check for both positive and negative
examples.
|
bruderstein_unexpected-react
|
train
|
144b31d52729a945f0def9df1d08e109d731f50b
|
diff --git a/tests/src/test/java/alluxio/underfs/UnderStorageSystemInterfaceIntegrationTest.java b/tests/src/test/java/alluxio/underfs/UnderStorageSystemInterfaceIntegrationTest.java
index <HASH>..<HASH> 100644
--- a/tests/src/test/java/alluxio/underfs/UnderStorageSystemInterfaceIntegrationTest.java
+++ b/tests/src/test/java/alluxio/underfs/UnderStorageSystemInterfaceIntegrationTest.java
@@ -22,9 +22,6 @@ import alluxio.client.file.options.CreateFileOptions;
import alluxio.client.file.options.ListStatusOptions;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.FileAlreadyExistsException;
-import alluxio.security.authorization.Mode;
-import alluxio.security.authorization.Permission;
-import alluxio.underfs.options.CreateOptions;
import alluxio.util.CommonUtils;
import alluxio.util.io.PathUtils;
import alluxio.wire.LoadMetadataType;
@@ -71,21 +68,6 @@ public final class UnderStorageSystemInterfaceIntegrationTest {
}
/**
- * Tests that an empty file can be created with correct permission.
- */
- @Test
- public void createEmptyWithPermission() throws IOException {
- String testFile = PathUtils.concatPath(mUnderfsAddress, "testFile");
- String user = "User";
- String group = "Group";
- Permission perm = new Permission(user, group, Mode.createFullAccess());
- createEmptyFileWithPermission(testFile, perm);
- Assert.assertTrue(mUfs.exists(testFile));
- Assert.assertEquals(user, mUfs.getOwner(testFile));
- Assert.assertEquals(group, mUfs.getGroup(testFile));
- }
-
- /**
* Tests that a file can be created and validates the data written to it.
*/
@Test
@@ -482,13 +464,6 @@ public final class UnderStorageSystemInterfaceIntegrationTest {
o.close();
}
- private void createEmptyFileWithPermission(String path, Permission perm) throws IOException {
- CreateOptions options = new CreateOptions();
- options.setPermission(perm);
- OutputStream o = mUfs.create(path, options);
- o.close();
- }
-
private void createTestBytesFile(String path) throws IOException {
OutputStream o = mUfs.create(path);
o.write(TEST_BYTES);
|
Rever UFS permission test as user is required on system
|
Alluxio_alluxio
|
train
|
9262982ae9422b04b2f15f07406d12f89acfe10e
|
diff --git a/command/v2/restart_command_test.go b/command/v2/restart_command_test.go
index <HASH>..<HASH> 100644
--- a/command/v2/restart_command_test.go
+++ b/command/v2/restart_command_test.go
@@ -7,10 +7,9 @@ import (
"code.cloudfoundry.org/cli/actor/sharedaction"
"code.cloudfoundry.org/cli/actor/v2action"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv2"
- "code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/commandfakes"
+ "code.cloudfoundry.org/cli/command/translatableerror"
. "code.cloudfoundry.org/cli/command/v2"
- "code.cloudfoundry.org/cli/command/v2/shared"
"code.cloudfoundry.org/cli/command/v2/v2fakes"
"code.cloudfoundry.org/cli/util/configv3"
"code.cloudfoundry.org/cli/util/ui"
@@ -85,7 +84,7 @@ var _ = Describe("Restart Command", func() {
})
It("returns an error if the check fails", func() {
- Expect(executeErr).To(MatchError(command.NotLoggedInError{BinaryName: "faceman"}))
+ Expect(executeErr).To(MatchError(translatableerror.NotLoggedInError{BinaryName: "faceman"}))
Expect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))
_, checkTargetedOrg, checkTargetedSpace := fakeSharedActor.CheckTargetArgsForCall(0)
@@ -448,7 +447,7 @@ var _ = Describe("Restart Command", func() {
})
It("stops logging and returns StagingFailedError", func() {
- Expect(executeErr).To(MatchError(shared.StagingFailedError{Message: "Something, but not nothing"}))
+ Expect(executeErr).To(MatchError(translatableerror.StagingFailedError{Message: "Something, but not nothing"}))
})
})
@@ -458,7 +457,7 @@ var _ = Describe("Restart Command", func() {
})
It("stops logging and returns StagingTimeoutError", func() {
- Expect(executeErr).To(MatchError(shared.StagingTimeoutError{AppName: "some-app", Timeout: time.Nanosecond}))
+ Expect(executeErr).To(MatchError(translatableerror.StagingTimeoutError{AppName: "some-app", Timeout: time.Nanosecond}))
})
})
@@ -468,7 +467,7 @@ var _ = Describe("Restart Command", func() {
})
It("stops logging and returns UnsuccessfulStartError", func() {
- Expect(executeErr).To(MatchError(shared.UnsuccessfulStartError{AppName: "some-app", BinaryName: "faceman"}))
+ Expect(executeErr).To(MatchError(translatableerror.UnsuccessfulStartError{AppName: "some-app", BinaryName: "faceman"}))
})
})
@@ -478,7 +477,7 @@ var _ = Describe("Restart Command", func() {
})
It("stops logging and returns UnsuccessfulStartError", func() {
- Expect(executeErr).To(MatchError(shared.UnsuccessfulStartError{AppName: "some-app", BinaryName: "faceman"}))
+ Expect(executeErr).To(MatchError(translatableerror.UnsuccessfulStartError{AppName: "some-app", BinaryName: "faceman"}))
})
})
@@ -488,7 +487,7 @@ var _ = Describe("Restart Command", func() {
})
It("stops logging and returns StartupTimeoutError", func() {
- Expect(executeErr).To(MatchError(shared.StartupTimeoutError{AppName: "some-app", BinaryName: "faceman"}))
+ Expect(executeErr).To(MatchError(translatableerror.StartupTimeoutError{AppName: "some-app", BinaryName: "faceman"}))
})
})
})
@@ -619,7 +618,7 @@ var _ = Describe("Restart Command", func() {
})
It("returns back an error", func() {
- Expect(executeErr).To(MatchError(command.ApplicationNotFoundError{Name: "some-app"}))
+ Expect(executeErr).To(MatchError(translatableerror.ApplicationNotFoundError{Name: "some-app"}))
Expect(testUI.Err).To(Say("warning-1"))
Expect(testUI.Err).To(Say("warning-2"))
|
edited errors in tests
[#<I>]
|
cloudfoundry_cli
|
train
|
f4c706b5640690fff39846ee940a2729fb51c218
|
diff --git a/tests/HumusPHPUnitModuleTest/VersionTest.php b/tests/HumusPHPUnitModuleTest/VersionTest.php
index <HASH>..<HASH> 100644
--- a/tests/HumusPHPUnitModuleTest/VersionTest.php
+++ b/tests/HumusPHPUnitModuleTest/VersionTest.php
@@ -28,11 +28,14 @@ class VersionTest extends \PHPUnit_Framework_TestCase
*/
public function testVersionCompare()
{
+ $prefixes = array(
+ 'dev', 'pr', 'PR', 'alpha', 'a1', 'a2', 'beta', 'b1', 'b2', 'RC', 'RC1', 'RC2', 'RC3', '', 'pl1', 'PL1'
+ );
$expect = -1;
for ($i=0; $i < 2; $i++) {
for ($j=0; $j < 12; $j++) {
for ($k=0; $k < 20; $k++) {
- foreach (array('dev', 'pr', 'PR', 'alpha', 'a1', 'a2', 'beta', 'b1', 'b2', 'RC', 'RC1', 'RC2', 'RC3', '', 'pl1', 'PL1') as $rel) {
+ foreach ($prefixes as $rel) {
$ver = "$i.$j.$k$rel";
$normalizedVersion = strtolower(Version::VERSION);
if (strtolower($ver) === $normalizedVersion
@@ -49,7 +52,8 @@ class VersionTest extends \PHPUnit_Framework_TestCase
$expect,
"For version '$ver' and HumusPHPUnitModule\\Version::VERSION = '"
. Version::VERSION . "': result=" . (Version::compareVersion($ver))
- . ', but expected ' . $expect);
+ . ', but expected ' . $expect
+ );
}
}
}
|
fix phpcs in version test
|
prolic_HumusPHPUnitModule
|
train
|
e2be3fee02acafce02a8872c9a9340f304eed830
|
diff --git a/integration-cli/docker_cli_import_test.go b/integration-cli/docker_cli_import_test.go
index <HASH>..<HASH> 100644
--- a/integration-cli/docker_cli_import_test.go
+++ b/integration-cli/docker_cli_import_test.go
@@ -37,6 +37,7 @@ func (s *DockerSuite) TestImportBadURL(c *check.C) {
c.Assert(err, checker.NotNil, check.Commentf("import was supposed to fail but didn't"))
// Depending on your system you can get either of these errors
if !strings.Contains(out, "dial tcp") &&
+ !strings.Contains(out, "ApplyLayer exit status 1 stdout: stderr: archive/tar: invalid tar header") &&
!strings.Contains(out, "Error processing tar file") {
c.Fatalf("expected an error msg but didn't get one.\nErr: %v\nOut: %v", err, out)
}
|
integration-cli: fix TestImportBadURL w/o network
As explained in the test comment itself, the error message may vary on
different platform.
This patch adds another condition found while testing w/o network
access on RHEL based distros (Fedora, RHEL, CentOS).
|
moby_moby
|
train
|
155bfe62939e4688de7c6e21502784fa6d2aeae8
|
diff --git a/cake/tests/cases/libs/cache/memcache.test.php b/cake/tests/cases/libs/cache/memcache.test.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/libs/cache/memcache.test.php
+++ b/cake/tests/cases/libs/cache/memcache.test.php
@@ -240,7 +240,7 @@ class MemcacheEngineTest extends CakeTestCase {
$result = Cache::read('other_test');
$this->assertFalse($result);
- Cache::config('memcache', array('duration' => '+30 day'));
+ Cache::config('memcache', array('duration' => '+29 days'));
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('long_expiry_test', $data);
$this->assertTrue($result);
|
Fixing failing test caused by setting an expiry value outside of the PECL extensions limits.
|
cakephp_cakephp
|
train
|
7db9a92f2324d0bbea461df1cb731efd49812fff
|
diff --git a/src/Sylius/Bundle/CoreBundle/Application/Kernel.php b/src/Sylius/Bundle/CoreBundle/Application/Kernel.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/CoreBundle/Application/Kernel.php
+++ b/src/Sylius/Bundle/CoreBundle/Application/Kernel.php
@@ -31,7 +31,7 @@ use Webmozart\Assert\Assert;
class Kernel extends HttpKernel
{
- public const VERSION = '1.9.0-DEV';
+ public const VERSION = '1.9.0-ALPHA.1';
public const VERSION_ID = '10900';
@@ -41,7 +41,7 @@ class Kernel extends HttpKernel
public const RELEASE_VERSION = '0';
- public const EXTRA_VERSION = 'DEV';
+ public const EXTRA_VERSION = 'ALPHA.1';
public function __construct(string $environment, bool $debug)
{
|
Change application's version to <I>-ALPHA<I>
|
Sylius_Sylius
|
train
|
35accefb20200a463b8f0feedb4a93b9ae6e3ed1
|
diff --git a/wandb/board/ui/src/components/DashboardView.js b/wandb/board/ui/src/components/DashboardView.js
index <HASH>..<HASH> 100644
--- a/wandb/board/ui/src/components/DashboardView.js
+++ b/wandb/board/ui/src/components/DashboardView.js
@@ -108,6 +108,7 @@ class DashboardView extends Component {
w: 3,
h: 2,
},
+ query: {strategy: 'merge'},
});
}}>
<Icon name="plus" />
|
Default to merge strategy for dashboard panels.
|
wandb_client
|
train
|
aef7d3e9ac58f4d191d8a993093b13cc198c8038
|
diff --git a/php/Toolbar_Theme_Switcher.php b/php/Toolbar_Theme_Switcher.php
index <HASH>..<HASH> 100644
--- a/php/Toolbar_Theme_Switcher.php
+++ b/php/Toolbar_Theme_Switcher.php
@@ -28,7 +28,7 @@ class Toolbar_Theme_Switcher {
return;
}
- if ( isset( $_GET['tts_reset'] ) ) {
+ if ( ! empty( filter_input( INPUT_GET, 'tts_reset' ) ) ) {
setcookie( self::get_cookie_name(), '', 1 );
nocache_headers();
wp_safe_redirect( home_url() );
@@ -66,17 +66,17 @@ class Toolbar_Theme_Switcher {
*/
public static function load_cookie() {
- $cookie_name = self::get_cookie_name();
+ $theme_name = filter_input( INPUT_COOKIE, self::get_cookie_name() );
- if ( empty( $_COOKIE[ $cookie_name ] ) ) {
+ if ( ! $theme_name ) {
return;
}
- $theme = wp_get_theme( $_COOKIE[ $cookie_name ] );
+ $theme = wp_get_theme( $theme_name );
if (
$theme->exists()
- && $theme->get( 'Name' ) != get_option( 'current_theme' )
+ && $theme->get( 'Name' ) !== get_option( 'current_theme' )
&& $theme->is_allowed()
) {
self::$theme = $theme;
@@ -218,7 +218,7 @@ class Toolbar_Theme_Switcher {
*/
public static function set_theme() {
- $stylesheet = $_REQUEST['theme'];
+ $stylesheet = filter_input( INPUT_GET, 'theme' );
$theme = wp_get_theme( $stylesheet );
if ( $theme->exists() && $theme->is_allowed() ) {
|
Changed superglobals access to filters.
|
Rarst_toolbar-theme-switcher
|
train
|
1f94f2118f963ddd570712a31b4cd70d3bc54472
|
diff --git a/test/remote/gateways/remote_finansbank_test.rb b/test/remote/gateways/remote_finansbank_test.rb
index <HASH>..<HASH> 100644
--- a/test/remote/gateways/remote_finansbank_test.rb
+++ b/test/remote/gateways/remote_finansbank_test.rb
@@ -2,8 +2,8 @@ require 'test_helper'
class RemoteFinansbankTest < Test::Unit::TestCase
def setup
- @original_kcode = $KCODE
if RUBY_VERSION < '1.9' && $KCODE == "NONE"
+ @original_kcode = $KCODE
$KCODE = 'u'
end
@@ -23,7 +23,7 @@ class RemoteFinansbankTest < Test::Unit::TestCase
end
def teardown
- $KCODE = @original_kcode
+ $KCODE = @original_kcode if @original_kcode
end
def test_successful_purchase
diff --git a/test/remote/gateways/remote_garanti_test.rb b/test/remote/gateways/remote_garanti_test.rb
index <HASH>..<HASH> 100644
--- a/test/remote/gateways/remote_garanti_test.rb
+++ b/test/remote/gateways/remote_garanti_test.rb
@@ -4,8 +4,8 @@ require 'test_helper'
class RemoteGarantiTest < Test::Unit::TestCase
def setup
- @original_kcode = $KCODE
if RUBY_VERSION < '1.9' && $KCODE == "NONE"
+ @original_kcode = $KCODE
$KCODE = 'u'
end
@@ -23,7 +23,7 @@ class RemoteGarantiTest < Test::Unit::TestCase
end
def teardown
- $KCODE = @original_kcode
+ $KCODE = @original_kcode if @original_kcode
end
def test_successful_purchase
diff --git a/test/unit/gateways/finansbank_test.rb b/test/unit/gateways/finansbank_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/gateways/finansbank_test.rb
+++ b/test/unit/gateways/finansbank_test.rb
@@ -2,8 +2,8 @@ require 'test_helper'
class FinansbankTest < Test::Unit::TestCase
def setup
- @original_kcode = $KCODE
if RUBY_VERSION < '1.9' && $KCODE == "NONE"
+ @original_kcode = $KCODE
$KCODE = 'u'
end
@@ -24,7 +24,7 @@ class FinansbankTest < Test::Unit::TestCase
end
def teardown
- $KCODE = @original_kcode
+ $KCODE = @original_kcode if @original_kcode
end
def test_successful_purchase
diff --git a/test/unit/gateways/garanti_test.rb b/test/unit/gateways/garanti_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/gateways/garanti_test.rb
+++ b/test/unit/gateways/garanti_test.rb
@@ -4,8 +4,8 @@ require 'test_helper'
class GarantiTest < Test::Unit::TestCase
def setup
- @original_kcode = $KCODE
if RUBY_VERSION < '1.9' && $KCODE == "NONE"
+ @original_kcode = $KCODE
$KCODE = 'u'
end
@@ -23,7 +23,7 @@ class GarantiTest < Test::Unit::TestCase
end
def teardown
- $KCODE = @original_kcode
+ $KCODE = @original_kcode if @original_kcode
end
def test_successful_purchase
|
Refactor of my last PR to remove warnings for ruby >= <I>
|
activemerchant_active_merchant
|
train
|
eeecfc31b6396e695c86db37c8c0b8ffe7378f68
|
diff --git a/packages/webiny-app-i18n/src/admin/components/I18NInput.js b/packages/webiny-app-i18n/src/admin/components/I18NInput.js
index <HASH>..<HASH> 100644
--- a/packages/webiny-app-i18n/src/admin/components/I18NInput.js
+++ b/packages/webiny-app-i18n/src/admin/components/I18NInput.js
@@ -20,6 +20,10 @@ const style = {
cursor: "pointer",
zIndex: 1
}
+ }),
+ i18nRichEditorDialogIconButton: css({
+ position: "absolute",
+ right: 10
})
};
@@ -90,7 +94,11 @@ const I18NInput = ({ richText, value, onChange, ...inputProps }) => {
render({ MenuButton }: Object) {
return (
// eslint-disable-next-line react/jsx-no-bind
- <MenuButton onClick={openDialog}>
+ <MenuButton
+ right
+ onClick={openDialog}
+ className={style.i18nRichEditorDialogIconButton}
+ >
<I18NIcon />
</MenuButton>
);
diff --git a/packages/webiny-ui/src/RichTextEditor/Menu.js b/packages/webiny-ui/src/RichTextEditor/Menu.js
index <HASH>..<HASH> 100644
--- a/packages/webiny-ui/src/RichTextEditor/Menu.js
+++ b/packages/webiny-ui/src/RichTextEditor/Menu.js
@@ -3,6 +3,7 @@ import React from "react";
import styled from "react-emotion";
import { css } from "emotion";
import type { FormComponentProps } from "./../types";
+import classNames from "classnames";
const MenuContainer = styled("div")({
position: "relative",
@@ -25,7 +26,13 @@ const MenuContainer = styled("div")({
}
});
-const MenuButton = ({ onClick, active, children, onMouseDown = e => e.preventDefault() }) => {
+const MenuButton = ({
+ className,
+ onClick,
+ active,
+ children,
+ onMouseDown = e => e.preventDefault()
+}) => {
const buttonStyle = css({
cursor: "pointer",
color: active
@@ -37,7 +44,11 @@ const MenuButton = ({ onClick, active, children, onMouseDown = e => e.preventDef
});
return (
- <span onClick={onClick} className={buttonStyle} onMouseDown={onMouseDown}>
+ <span
+ onClick={onClick}
+ className={classNames(className, buttonStyle)}
+ onMouseDown={onMouseDown}
+ >
{children}
</span>
);
|
fix: I<I>N - move icon to the right side of the rich text editor toolbar
|
Webiny_webiny-js
|
train
|
26ef70f3b324d7b8f4bb87204eec574862c5bad9
|
diff --git a/addons/koji/jaxrs/src/main/java/org/commonjava/indy/koji/bind/jaxrs/KojiRepairResource.java b/addons/koji/jaxrs/src/main/java/org/commonjava/indy/koji/bind/jaxrs/KojiRepairResource.java
index <HASH>..<HASH> 100644
--- a/addons/koji/jaxrs/src/main/java/org/commonjava/indy/koji/bind/jaxrs/KojiRepairResource.java
+++ b/addons/koji/jaxrs/src/main/java/org/commonjava/indy/koji/bind/jaxrs/KojiRepairResource.java
@@ -43,6 +43,7 @@ import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import static org.commonjava.indy.bind.jaxrs.util.ResponseUtils.throwError;
+import static org.commonjava.indy.koji.model.IndyKojiConstants.MASK;
import static org.commonjava.indy.koji.model.IndyKojiConstants.REPAIR_KOJI;
import static org.commonjava.indy.koji.model.IndyKojiConstants.VOL;
import static org.commonjava.indy.util.ApplicationContent.application_json;
@@ -105,7 +106,7 @@ public class KojiRepairResource
value = "JSON request specifying source and other configuration options",
required = true, dataType = "org.commonjava.indy.koji.model.KojiRepairRequest" )
@POST
- @Path( "/" + VOL )
+ @Path( "/" + MASK )
@Consumes( ApplicationContent.application_json )
public KojiRepairResult repairPathMasks( final KojiRepairRequest request, final @Context HttpServletRequest servletRequest,
final @Context SecurityContext securityContext, final @Context UriInfo uriInfo )
|
fix REST resource endpoint path for koji pathMask repair
|
Commonjava_indy
|
train
|
696e55c6b27da080d7dda380f94ef4d5e4015a3a
|
diff --git a/src/Fish/Logger/LoggerServiceProvider.php b/src/Fish/Logger/LoggerServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/Fish/Logger/LoggerServiceProvider.php
+++ b/src/Fish/Logger/LoggerServiceProvider.php
@@ -34,8 +34,7 @@ class LoggerServiceProvider extends ServiceProvider
*/
public function registerCommands()
{
- $this->app['logger.init'] = $this->app->share(function ($app) {
-
+ $this->app->singleton('logger.init', function ($app) {
return new InitLoggerCommand(new FileSystem);
});
|
Update to support singleton
The share method was deprecated a while ago, replaced by singleton
|
matfish2_eloquent-logger
|
train
|
14d3a98742a7c92e5bebc4aa4cd493c57c24c764
|
diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt
index <HASH>..<HASH> 100644
--- a/doc/source/whatsnew/v0.20.0.txt
+++ b/doc/source/whatsnew/v0.20.0.txt
@@ -392,7 +392,7 @@ Bug Fixes
-
+- Bug in ``.groupby(...).rolling(...)`` when ``on`` is specified and using a ``DatetimeIndex`` (:issue:`15130`)
diff --git a/pandas/core/window.py b/pandas/core/window.py
index <HASH>..<HASH> 100644
--- a/pandas/core/window.py
+++ b/pandas/core/window.py
@@ -1025,19 +1025,8 @@ class Rolling(_Rolling_and_Expanding):
if (self.is_datetimelike and
isinstance(self.window, (compat.string_types, DateOffset))):
- # must be monotonic for on
- if not self._on.is_monotonic:
- formatted = self.on or 'index'
- raise ValueError("{0} must be "
- "monotonic".format(formatted))
-
- from pandas.tseries.frequencies import to_offset
- try:
- freq = to_offset(self.window)
- except (TypeError, ValueError):
- raise ValueError("passed window {0} in not "
- "compat with a datetimelike "
- "index".format(self.window))
+ self._validate_monotonic()
+ freq = self._validate_freq()
# we don't allow center
if self.center:
@@ -1058,6 +1047,23 @@ class Rolling(_Rolling_and_Expanding):
elif self.window < 0:
raise ValueError("window must be non-negative")
+ def _validate_monotonic(self):
+ """ validate on is monotonic """
+ if not self._on.is_monotonic:
+ formatted = self.on or 'index'
+ raise ValueError("{0} must be "
+ "monotonic".format(formatted))
+
+ def _validate_freq(self):
+ """ validate & return our freq """
+ from pandas.tseries.frequencies import to_offset
+ try:
+ return to_offset(self.window)
+ except (TypeError, ValueError):
+ raise ValueError("passed window {0} in not "
+ "compat with a datetimelike "
+ "index".format(self.window))
+
@Substitution(name='rolling')
@Appender(SelectionMixin._see_also_template)
@Appender(SelectionMixin._agg_doc)
@@ -1175,6 +1181,25 @@ class RollingGroupby(_GroupByMixin, Rolling):
def _constructor(self):
return Rolling
+ def _gotitem(self, key, ndim, subset=None):
+
+ # we are setting the index on the actual object
+ # here so our index is carried thru to the selected obj
+ # when we do the splitting for the groupby
+ if self.on is not None:
+ self._groupby.obj = self._groupby.obj.set_index(self._on)
+ self.on = None
+ return super(RollingGroupby, self)._gotitem(key, ndim, subset=subset)
+
+ def _validate_monotonic(self):
+ """
+ validate that on is monotonic;
+ we don't care for groupby.rolling
+ because we have already validated at a higher
+ level
+ """
+ pass
+
class Expanding(_Rolling_and_Expanding):
"""
diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/test_window.py
+++ b/pandas/tests/test_window.py
@@ -3616,3 +3616,23 @@ class TestRollingTS(tm.TestCase):
agg_by_day).reset_index(level=0, drop=True)
tm.assert_frame_equal(result, expected)
+
+ def test_groupby_monotonic(self):
+
+ # GH 15130
+ # we don't need to validate monotonicity when grouping
+
+ data = [
+ ['David', '1/1/2015', 100], ['David', '1/5/2015', 500],
+ ['David', '5/30/2015', 50], ['David', '7/25/2015', 50],
+ ['Ryan', '1/4/2014', 100], ['Ryan', '1/19/2015', 500],
+ ['Ryan', '3/31/2016', 50], ['Joe', '7/1/2015', 100],
+ ['Joe', '9/9/2015', 500], ['Joe', '10/15/2015', 50]]
+
+ df = pd.DataFrame(data=data, columns=['name', 'date', 'amount'])
+ df['date'] = pd.to_datetime(df['date'])
+
+ expected = df.set_index('date').groupby('name').apply(
+ lambda x: x.rolling('180D')['amount'].sum())
+ result = df.groupby('name').rolling('180D', on='date')['amount'].sum()
+ tm.assert_series_equal(result, expected)
|
BUG: no need to validate monotonicity when groupby-rolling
closes #<I>
|
pandas-dev_pandas
|
train
|
c08c29bd4a5f6b8dde785e7a9df1645fae3220c7
|
diff --git a/conversation.html b/conversation.html
index <HASH>..<HASH> 100644
--- a/conversation.html
+++ b/conversation.html
@@ -102,11 +102,13 @@
<td>
<div class='contacts'>
{{ #contacts }}
- <img class='avatar' src='{{ avatar }}'>
- <span class='name'>{{ name }}</div>
- {{ #conflict }}
- <button class='resolve'>Key Conflict</button>
- {{ /conflict }}
+ <div>
+ <img class='avatar' src='{{ avatar }}'>
+ <span class='name'>{{ name }}</div>
+ {{ #conflict }}
+ <button class='resolve'>Key Conflict</button>
+ {{ /conflict }}
+ </div>
{{ /contacts }}
</div>
</td>
diff --git a/js/models/conversations.js b/js/models/conversations.js
index <HASH>..<HASH> 100644
--- a/js/models/conversations.js
+++ b/js/models/conversations.js
@@ -34,6 +34,7 @@
initialize: function() {
this.messageCollection = new Whisper.MessageCollection();
+ this.contactCollection = new Whisper.ConversationCollection();
},
validate: function(attributes, options) {
@@ -143,6 +144,20 @@
return this.messageCollection.fetchConversation(this.id, options);
},
+ fetchContacts: function(options) {
+ if (this.isPrivate()) {
+ this.contactCollection.reset([this]);
+ } else {
+ this.contactCollection.reset(
+ this.get('members').map(function(number) {
+ var c = this.collection.add({id: number, type: 'private'});
+ c.fetch();
+ return c;
+ }.bind(this))
+ );
+ }
+ },
+
archive: function() {
this.unset('active_at');
},
@@ -165,6 +180,9 @@
} else {
return '';
}
+ },
+ isPrivate: function() {
+ return this.get('type') === 'private';
}
});
diff --git a/js/models/messages.js b/js/models/messages.js
index <HASH>..<HASH> 100644
--- a/js/models/messages.js
+++ b/js/models/messages.js
@@ -40,6 +40,9 @@
},
isGroupUpdate: function() {
return !!(this.get('group_update'));
+ },
+ isIncoming: function() {
+ return this.get('type') === 'incoming';
}
});
diff --git a/js/panel_controller.js b/js/panel_controller.js
index <HASH>..<HASH> 100644
--- a/js/panel_controller.js
+++ b/js/panel_controller.js
@@ -43,7 +43,9 @@
window.openConversation = function openConversation (modelId) {
var conversation = conversations.add({id: modelId});
- conversation.fetch();
+ conversation.fetch().then(function() {
+ conversation.fetchContacts();
+ });
conversation.fetchMessages();
var windowId = windowMap.windowIdFrom(modelId);
diff --git a/js/views/message_detail_view.js b/js/views/message_detail_view.js
index <HASH>..<HASH> 100644
--- a/js/views/message_detail_view.js
+++ b/js/views/message_detail_view.js
@@ -37,10 +37,12 @@
sent_at: moment(this.model.get('sent_at')).toString(),
received_at: moment(this.model.get('received_at')).toString(),
tofrom: this.model.isIncoming() ? 'From' : 'To',
- contacts: {
- name : this.conversation.getTitle(),
- avatar : this.conversation.get('avatar')
- }
+ contacts: this.conversation.contactCollection.map(function(contact) {
+ return {
+ name : contact.getTitle(),
+ avatar : contact.get('avatar'),
+ };
+ }.bind(this))
}));
this.view.render().$el.prependTo(this.$el.find('.message-container'));
}
|
Render group members in the message detail view
This requires that we fetch contact info when opening a conversation
so that's available for rendering contact names and avatars.
|
ForstaLabs_librelay-node
|
train
|
ab35a6a1f7cbc3f98fb365e97d07220f0008b7d3
|
diff --git a/connection.js b/connection.js
index <HASH>..<HASH> 100644
--- a/connection.js
+++ b/connection.js
@@ -603,7 +603,11 @@ InitOperation.prototype.onTimeout = function onTimeout(now) {
elapsed: elapsed,
timeout: self.timeout
});
- self.connection.timedOutEvent.emit(self.connection, err);
+
+ self.connection.logger.warn('destroying due to init timeout', self.connection.extendLogInfo({
+ error: err
+ }));
+ self.connection.resetAll(err);
};
module.exports = TChannelConnection;
|
TChannelConnection: clarify init timeout log
|
uber_tchannel-node
|
train
|
4f1e64adc3454ee401d80c146ace17cda9cbaf57
|
diff --git a/grib/src/main/java/ucar/nc2/grib/grib2/table/NwsMetDevTables.java b/grib/src/main/java/ucar/nc2/grib/grib2/table/NwsMetDevTables.java
index <HASH>..<HASH> 100644
--- a/grib/src/main/java/ucar/nc2/grib/grib2/table/NwsMetDevTables.java
+++ b/grib/src/main/java/ucar/nc2/grib/grib2/table/NwsMetDevTables.java
@@ -33,7 +33,6 @@
*/
package ucar.nc2.grib.grib2.table;
-import ucar.nc2.grib.GribNumbers;
import ucar.nc2.grib.TimeCoord;
import ucar.nc2.grib.grib2.Grib2Pds;
import ucar.nc2.grib.grib2.Grib2Record;
@@ -69,10 +68,16 @@ public class NwsMetDevTables extends NcepLocalTables {
if (!pds.isTimeInterval()) return null;
Grib2Pds.PdsInterval pdsIntv = (Grib2Pds.PdsInterval) gr.getPDS();
- CalendarDate intvEnd = pdsIntv.getIntervalTimeEnd();
+ // override here only if timeRangeUnit = 255
+ boolean needOverride = false;
+ for (Grib2Pds.TimeInterval ti : pdsIntv.getTimeIntervals()) {
+ needOverride = (ti.timeRangeUnit == 255);
+ }
+ if (!needOverride)
+ return super.getForecastTimeInterval(gr);
+ CalendarDate intvEnd = pdsIntv.getIntervalTimeEnd();
int ftime = pdsIntv.getForecastTime();
-
int timeUnitOrg = pds.getTimeUnit();
int timeUnitConvert = convertTimeUnit(timeUnitOrg);
CalendarPeriod unitPeriod = Grib2Utils.getCalendarPeriod(timeUnitConvert);
@@ -94,6 +99,17 @@ public class NwsMetDevTables extends NcepLocalTables {
*/
@Override
public double getForecastTimeIntervalSizeInHours(Grib2Pds pds) {
+ Grib2Pds.PdsInterval pdsIntv = (Grib2Pds.PdsInterval) pds;
+
+ // override here only if timeRangeUnit = 255
+ boolean needOverride = false;
+ for (Grib2Pds.TimeInterval ti : pdsIntv.getTimeIntervals()) {
+ needOverride = (ti.timeRangeUnit == 255);
+ }
+ if (!needOverride)
+ return super.getForecastTimeIntervalSizeInHours(pds);
+
+
return 12.0;
}
|
CdmrCoverage: add call to read coordinate values that have been defferred.
|
Unidata_thredds
|
train
|
f082838a0a01de6416b363ac03fe86dcbea1ad84
|
diff --git a/itests/standalone/basic/src/test/java/org/wildfly/camel/test/slack/SlackIntegrationTest.java b/itests/standalone/basic/src/test/java/org/wildfly/camel/test/slack/SlackIntegrationTest.java
index <HASH>..<HASH> 100644
--- a/itests/standalone/basic/src/test/java/org/wildfly/camel/test/slack/SlackIntegrationTest.java
+++ b/itests/standalone/basic/src/test/java/org/wildfly/camel/test/slack/SlackIntegrationTest.java
@@ -25,7 +25,7 @@ import org.apache.camel.impl.DefaultCamelContext;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.spec.JavaArchive;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extension.camel.CamelAware;
@@ -35,9 +35,8 @@ import org.wildfly.extension.camel.CamelAware;
public class SlackIntegrationTest {
@Deployment
- public static JavaArchive deployment() {
- final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "camel-slack-tests");
- return archive;
+ public static WebArchive deployment() {
+ return ShrinkWrap.create(WebArchive.class, "camel-slack-tests.war");
}
@Test
@@ -47,32 +46,24 @@ public class SlackIntegrationTest {
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
- onException(Exception.class).handled(true).to("mock:errors");
- from("direct:test").to("slack:#general?iconEmoji=:camel:&username=CamelTest");
- from("direct:error").to("slack:#badchannel?iconEmoji=:camel:&username=CamelTest");
+ from("direct:test").to("slack:#general?iconEmoji=:camel:&username=CamelTest").to("mock:result");
+ from("undertow:http://localhost/slack/webhook").setBody(constant("{\"ok\": true}"));
}
});
SlackComponent comp = camelctx.getComponent("slack", SlackComponent.class);
- comp.setWebhookUrl("https://hooks.slack.com/services/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");
+ comp.setWebhookUrl("http://localhost:8080/slack/webhook");
- MockEndpoint mockErrors = camelctx.getEndpoint("mock:errors", MockEndpoint.class);
- mockErrors.expectedMessageCount(0);
+ MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
+ mockEndpoint.expectedMessageCount(1);
camelctx.start();
try {
ProducerTemplate producer = camelctx.createProducerTemplate();
producer.sendBody("direct:test", "Hello from Camel!");
- mockErrors.assertIsSatisfied();
-
- mockErrors.reset();
- mockErrors.expectedMessageCount(1);
-
- producer.sendBody("direct:error", "Error from Camel!");
- mockErrors.assertIsSatisfied();
+ mockEndpoint.assertIsSatisfied();
} finally {
camelctx.stop();
}
-
}
}
|
[resolves #<I>] SlackIntegrationTest fails to trigger onException handler
|
wildfly-extras_wildfly-camel
|
train
|
94617d7da1e76daeae3a05c61b42321163f93d62
|
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -10,6 +10,10 @@ module ActiveSupport
true
end
+ def with_indifferent_access
+ self
+ end
+
def initialize(constructor = {})
if constructor.is_a?(Hash)
super()
@@ -58,8 +62,12 @@ module ActiveSupport
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
#
def update(other_hash)
- other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
- self
+ if other_hash.is_a? HashWithIndifferentAccess
+ super(other_hash)
+ else
+ other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
+ self
+ end
end
alias_method :merge!, :update
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index <HASH>..<HASH> 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -971,6 +971,11 @@ class HashToXmlTest < Test::Unit::TestCase
assert_nil hash_wia.default
end
+ def test_should_return_self_for_with_indifferent_access
+ hash_wia = HashWithIndifferentAccess.new
+ assert_equal hash_wia, hash_wia.with_indifferent_access
+ end
+
def test_should_copy_the_default_value_when_converting_to_hash_with_indifferent_access
hash = Hash.new(3)
hash_wia = hash.with_indifferent_access
|
Optimize parts of HashWithIndifferentAccess
|
rails_rails
|
train
|
21eb1badb8ee3fc97279b7d07ffef560dc3ac32b
|
diff --git a/scss.inc.php b/scss.inc.php
index <HASH>..<HASH> 100644
--- a/scss.inc.php
+++ b/scss.inc.php
@@ -1329,8 +1329,12 @@ class scssc {
protected static $lib_alpha = array("color");
protected function lib_alpha($args) {
- list($color) = $args;
- return isset($color[4]) ? $color[4] : 1;
+ if ($color = $this->coerceColor($args[0])) {
+ return isset($color[4]) ? $color[4] : 1;
+ }
+
+ // this might be the IE function, so return value unchanged
+ return array("function", "alpha", array("list", ",", $args));
}
protected static $lib_opacity = array("color");
|
let unknown alpha() args pass through
|
leafo_scssphp
|
train
|
03450f000716d28430eb67668011c8c4b32b4c76
|
diff --git a/lib/simple_form/components/errors.rb b/lib/simple_form/components/errors.rb
index <HASH>..<HASH> 100644
--- a/lib/simple_form/components/errors.rb
+++ b/lib/simple_form/components/errors.rb
@@ -32,7 +32,11 @@ module SimpleForm
end
def errors_on_attribute
- object.errors[attribute_name]
+ if object.respond_to?(:errors)
+ object.errors[attribute_name]
+ else
+ []
+ end
end
def errors_on_association
diff --git a/test/components/error_test.rb b/test/components/error_test.rb
index <HASH>..<HASH> 100644
--- a/test/components/error_test.rb
+++ b/test/components/error_test.rb
@@ -23,6 +23,13 @@ class ErrorTest < ActionView::TestCase
assert_no_select 'span.error'
end
+ test "error should not generate messages when object doesn't respond to errors method" do
+ @user.instance_eval {undef errors}
+ with_error_for @user, :name, :string
+ assert_no_select 'span.error'
+ end
+
+
test 'error should generate messages for attribute with single error' do
with_error_for @user, :name, :string
assert_select 'span.error', "can't be blank"
|
Allow forms for objects that don't respond to the "errors" method.
Useful for non-model forms, such as search forms.
|
plataformatec_simple_form
|
train
|
3e9f9f3c6c574c2f17d7c361e00fdf3cc609ea52
|
diff --git a/lib/jsonapi/path_segment.rb b/lib/jsonapi/path_segment.rb
index <HASH>..<HASH> 100644
--- a/lib/jsonapi/path_segment.rb
+++ b/lib/jsonapi/path_segment.rb
@@ -30,7 +30,7 @@ module JSONAPI
end
def eql?(other)
- relationship == other.relationship && resource_klass == other.resource_klass
+ other.is_a?(self.class) && relationship == other.relationship && resource_klass == other.resource_klass
end
def hash
@@ -59,7 +59,7 @@ module JSONAPI
end
def eql?(other)
- field_name == other.field_name && resource_klass == other.resource_klass
+ other.is_a?(self.class) && field_name == other.field_name && resource_klass == other.resource_klass
end
def delegated_field_name
|
Fix JSONAPI::PathSegment::Relationship#eql?
Relationship objects are used as key in @join_details in JoinManager.
This hash contains two types of objects: String and Relationship
In case of hash collisions in @join_details the method Relationship#eql? is called.
It currently fails when comparing with a string key.
Fixes #<I>
|
cerebris_jsonapi-resources
|
train
|
fc7fff3b24a9534c0bb49197fb3a5346b3411291
|
diff --git a/greycat/src/main/java/greycat/internal/MWResolver.java b/greycat/src/main/java/greycat/internal/MWResolver.java
index <HASH>..<HASH> 100644
--- a/greycat/src/main/java/greycat/internal/MWResolver.java
+++ b/greycat/src/main/java/greycat/internal/MWResolver.java
@@ -1004,7 +1004,7 @@ final class MWResolver implements Resolver {
if (timeTree != null) {
long currentDivergenceTime = objectWorldOrder.get(worldCollector.get(i));
int finalI = i;
- timeTree.range(currentDivergenceTime, previousDivergenceTime, CoreConstants.END_OF_TIME, new SuperTreeWalker() {
+ timeTree.range(from, previousDivergenceTime, CoreConstants.END_OF_TIME, new SuperTreeWalker() {
@Override
public void elem(final long superTime, final long superCapacity) {
if (!tempSuperTimeCollector.contains(superTime)) {
|
Changing _currentDivergenceTime_ to _from_ in the resolution of superTimeTrees. This could break the many world.
|
datathings_greycat
|
train
|
3deeeafd210913addf632bee8eb5308f415830fe
|
diff --git a/drools-scenario-simulation/drools-scenario-simulation-backend/src/main/java/org/drools/scenariosimulation/backend/runner/AbstractRunnerHelper.java b/drools-scenario-simulation/drools-scenario-simulation-backend/src/main/java/org/drools/scenariosimulation/backend/runner/AbstractRunnerHelper.java
index <HASH>..<HASH> 100644
--- a/drools-scenario-simulation/drools-scenario-simulation-backend/src/main/java/org/drools/scenariosimulation/backend/runner/AbstractRunnerHelper.java
+++ b/drools-scenario-simulation/drools-scenario-simulation-backend/src/main/java/org/drools/scenariosimulation/backend/runner/AbstractRunnerHelper.java
@@ -292,8 +292,8 @@ public abstract class AbstractRunnerHelper {
private String determineExceptionMessage(FactMappingValue factMappingValue, String factName) {
if (factMappingValue.getCollectionPathToValue() == null) {
return ScenarioSimulationServerMessages.getFactWithWrongValueExceptionMessage(factName,
- factMappingValue.getErrorValue(),
- factMappingValue.getRawValue());
+ factMappingValue.getRawValue(),
+ factMappingValue.getErrorValue());
}
return ScenarioSimulationServerMessages.getCollectionFactExceptionMessage(factName,
factMappingValue.getCollectionPathToValue(),
diff --git a/drools-scenario-simulation/drools-scenario-simulation-backend/src/test/java/org/drools/scenariosimulation/backend/runner/RuleScenarioRunnerHelperTest.java b/drools-scenario-simulation/drools-scenario-simulation-backend/src/test/java/org/drools/scenariosimulation/backend/runner/RuleScenarioRunnerHelperTest.java
index <HASH>..<HASH> 100644
--- a/drools-scenario-simulation/drools-scenario-simulation-backend/src/test/java/org/drools/scenariosimulation/backend/runner/RuleScenarioRunnerHelperTest.java
+++ b/drools-scenario-simulation/drools-scenario-simulation-backend/src/test/java/org/drools/scenariosimulation/backend/runner/RuleScenarioRunnerHelperTest.java
@@ -358,8 +358,8 @@ public class RuleScenarioRunnerHelperTest extends AbstractRuleCoverageTest {
} catch (ScenarioException exception) {
assertTrue(exception.isFailedAssertion());
assertEquals(ScenarioSimulationServerMessages.getFactWithWrongValueExceptionMessage("Fact 2.amount",
- amountNameExpectedFactMappingValue.getErrorValue(),
- amountNameExpectedFactMappingValue.getRawValue()),
+ amountNameExpectedFactMappingValue.getRawValue(),
+ amountNameExpectedFactMappingValue.getErrorValue()),
exception.getMessage());
}
|
DROOLS-<I>: Test Scenario - expected vs actual alert is misleading (#<I>)
|
kiegroup_drools
|
train
|
24950d239ef4c69f3ac0479ad0b7b53512cfd76d
|
diff --git a/lib/splash.js b/lib/splash.js
index <HASH>..<HASH> 100644
--- a/lib/splash.js
+++ b/lib/splash.js
@@ -34,7 +34,7 @@ export default function splash({ name, org, logo, active, total, channels, ifram
),
!iframe && dom('p.signin',
'or ',
- dom(`a href=https://${org}.slack.com`, 'sign in'),
+ dom(`a href=https://${org}.slack.com target=_top`, 'sign in'),
'.'
),
!iframe && dom('footer',
|
For new signin link, use target=_top so iframes work
Currently, no target set in the iframe can rain on some parades. This makes sure no rain happens, only _Slackshine_.
Couldn't resist..
|
rauchg_slackin
|
train
|
4b89cd26840a656247e381ae8e0d260e30a4d920
|
diff --git a/iktomi/unstable/db/files.py b/iktomi/unstable/db/files.py
index <HASH>..<HASH> 100644
--- a/iktomi/unstable/db/files.py
+++ b/iktomi/unstable/db/files.py
@@ -27,7 +27,7 @@ class BaseFile(object):
@cached_property
def size(self):
try:
- return os.path.getsize(self.full_path)
+ return os.path.getsize(self.path)
# Return None for non-existing file.
# There can be OSError or IOError (depending on Python version?), both
# are derived from EnvironmentError having errno property.
@@ -103,7 +103,7 @@ class FileManager(BaseFileManager):
# places, I think...
if os.path.isfile(file_obj.path):
try:
- os.unlink(file_obj.full_path)
+ os.unlink(file_obj.path)
except OSError:
pass
|
BaseFile.full_path => BaseFile.path
|
SmartTeleMax_iktomi
|
train
|
53ce3833fcf8a9dfd54ef3fa62497ac85ad60af5
|
diff --git a/core/src/main/java/tachyon/worker/WorkerStorage.java b/core/src/main/java/tachyon/worker/WorkerStorage.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/tachyon/worker/WorkerStorage.java
+++ b/core/src/main/java/tachyon/worker/WorkerStorage.java
@@ -27,6 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Throwables;
+import com.google.common.io.Closer;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import tachyon.Constants;
@@ -186,30 +187,34 @@ public class WorkerStorage {
for (int k = 0; k < fileInfo.blockIds.size(); k ++) {
lockBlock(fileInfo.blockIds.get(k), Users.CHECKPOINT_USER_ID);
}
- OutputStream os = mCheckpointUfs.create(midPath, (int) fileInfo.getBlockSizeByte());
+ Closer closer = Closer.create();
long fileSizeByte = 0;
- for (int k = 0; k < fileInfo.blockIds.size(); k ++) {
- File tempFile =
- new File(CommonUtils.concat(mLocalDataFolder.toString(), fileInfo.blockIds.get(k)));
- fileSizeByte += tempFile.length();
- InputStream is = new FileInputStream(tempFile);
- byte[] buf = new byte[16 * Constants.KB];
- int got = is.read(buf);
- while (got != -1) {
- os.write(buf, 0, got);
- got = is.read(buf);
+ try {
+ OutputStream os =
+ closer.register(mCheckpointUfs.create(midPath, (int) fileInfo.getBlockSizeByte()));
+ for (int k = 0; k < fileInfo.blockIds.size(); k ++) {
+ File tempFile =
+ new File(CommonUtils.concat(mLocalDataFolder.toString(),
+ fileInfo.blockIds.get(k)));
+ fileSizeByte += tempFile.length();
+ InputStream is = closer.register(new FileInputStream(tempFile));
+ byte[] buf = new byte[16 * Constants.KB];
+ int got = is.read(buf);
+ while (got != -1) {
+ os.write(buf, 0, got);
+ got = is.read(buf);
+ }
+ }
+ if (!mCheckpointUfs.rename(midPath, dstPath)) {
+ LOG.error("Failed to rename from " + midPath + " to " + dstPath);
+ }
+ } finally {
+ closer.close();
+ for (int k = 0; k < fileInfo.blockIds.size(); k ++) {
+ unlockBlock(fileInfo.blockIds.get(k), Users.CHECKPOINT_USER_ID);
}
- is.close();
- }
- os.close();
- if (!mCheckpointUfs.rename(midPath, dstPath)) {
- LOG.error("Failed to rename from " + midPath + " to " + dstPath);
}
mMasterClient.addCheckpoint(mWorkerId, fileId, fileSizeByte, dstPath);
- for (int k = 0; k < fileInfo.blockIds.size(); k ++) {
- unlockBlock(fileInfo.blockIds.get(k), Users.CHECKPOINT_USER_ID);
- }
-
long shouldTakeMs = (long) (1000.0 * fileSizeByte / Constants.MB
/ WorkerConf.get().WORKER_PER_THREAD_CHECKPOINT_CAP_MB_SEC);
long currentTimeMs = System.currentTimeMillis();
|
fix lockblock bug in checkpoint thread in workerstorage
|
Alluxio_alluxio
|
train
|
6534f63f62857f03f94d38dfcc77a7a98bcab67b
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -32,6 +32,7 @@ import glob, os, sys
if sys.version[0:1] == '1':
raise RuntimeError, ("pyscard requires Python 2.x to build.")
+print get_platform()
if 'win32'==get_platform():
platform__cc_defines=[('WIN32', '100')]
platform_swig_opts=['-DWIN32']
@@ -48,7 +49,7 @@ elif 'linux-i586'==get_platform() or 'linux-i686'==get_platform():
platform_include_dirs=['/usr/include/PCSC']
platform_extra_compile_args=[]#['-ggdb', '-O0']
platform_extra_link_args=[]#['-ggdb']
-elif 'macosx-10.3-fat'==get_platform():
+elif 'macosx-10.3-fat'==get_platform() or 'darwin-8.9.1-i386'==get_platform():
platform__cc_defines=[('PCSCLITE', '1'),('__APPLE__','1')]
platform_swig_opts=['-DPCSCLITE', '-D__APPLE__']
platform_sources=[]
|
alternate platform string for mac os x darwin
|
LudovicRousseau_pyscard
|
train
|
dcdc518f39aa3f70a65762e87129b856a2416055
|
diff --git a/es5-autogenerated/index.js b/es5-autogenerated/index.js
index <HASH>..<HASH> 100644
--- a/es5-autogenerated/index.js
+++ b/es5-autogenerated/index.js
@@ -1,8 +1,6 @@
'use strict';
-var fs = require('fs');
var path = require('path');
-var mkdirp = require('mkdirp-promise');
var Prerenderer = require('@prerenderer/prerenderer');
var PuppeteerRenderer = require('@prerenderer/renderer-puppeteer');
@@ -12,6 +10,7 @@ var _require = require('html-minifier'),
function PrerenderSPAPlugin() {
var _this = this;
+ console.log('BUILDING');
var rendererOptions = {}; // Primarily for backwards-compatibility.
this._options = {};
@@ -66,7 +65,18 @@ function PrerenderSPAPlugin() {
PrerenderSPAPlugin.prototype.apply = function (compiler) {
var _this2 = this;
- compiler.plugin('after-emit', function (compilation, done) {
+ var compilerFS = compiler.outputFileSystem;
+
+ // From https://github.com/ahmadnassri/mkdirp-promise/blob/master/lib/index.js
+ var mkdirp = function mkdirp(dir, opts) {
+ return new Promise(function (resolve, reject) {
+ compilerFS.mkdirp(dir, opts, function (err, made) {
+ return err === null ? resolve(made) : reject(err);
+ });
+ });
+ };
+
+ var afterEmit = function afterEmit(compilation, done) {
var PrerendererInstance = new Prerenderer(_this2._options);
PrerendererInstance.initialize().then(function () {
@@ -123,7 +133,7 @@ PrerenderSPAPlugin.prototype.apply = function (compiler) {
var promises = Promise.all(processedRoutes.map(function (processedRoute) {
return mkdirp(path.dirname(processedRoute.outputPath)).then(function () {
return new Promise(function (resolve, reject) {
- fs.writeFile(processedRoute.outputPath, processedRoute.html.trim(), function (err) {
+ compilerFS.writeFile(processedRoute.outputPath, processedRoute.html.trim(), function (err) {
if (err) reject(`[prerender-spa-plugin] Unable to write rendered route to file "${processedRoute.outputPath}" \n ${err}.`);
});
@@ -147,7 +157,14 @@ PrerenderSPAPlugin.prototype.apply = function (compiler) {
console.error('[prerender-spa-plugin] Unable to prerender all routes!');
throw err;
});
- });
+ };
+
+ if (compiler.hooks) {
+ var plugin = { name: 'PrerenderSPAPlugin' };
+ compiler.hooks.afterEmit.tapAsync(plugin, afterEmit);
+ } else {
+ compiler.plugin('after-emit', afterEmit);
+ }
};
PrerenderSPAPlugin.PuppeteerRenderer = PuppeteerRenderer;
diff --git a/es6/index.js b/es6/index.js
index <HASH>..<HASH> 100644
--- a/es6/index.js
+++ b/es6/index.js
@@ -1,11 +1,10 @@
-const fs = require('fs')
const path = require('path')
-const mkdirp = require('mkdirp-promise')
const Prerenderer = require('@prerenderer/prerenderer')
const PuppeteerRenderer = require('@prerenderer/renderer-puppeteer')
const { minify } = require('html-minifier')
function PrerenderSPAPlugin (...args) {
+ console.log('BUILDING')
const rendererOptions = {} // Primarily for backwards-compatibility.
this._options = {}
@@ -54,6 +53,15 @@ function PrerenderSPAPlugin (...args) {
}
PrerenderSPAPlugin.prototype.apply = function (compiler) {
+ const compilerFS = compiler.outputFileSystem
+
+ // From https://github.com/ahmadnassri/mkdirp-promise/blob/master/lib/index.js
+ const mkdirp = function (dir, opts) {
+ return new Promise((resolve, reject) => {
+ compilerFS.mkdirp(dir, opts, (err, made) => err === null ? resolve(made) : reject(err))
+ })
+ }
+
const afterEmit = (compilation, done) => {
const PrerendererInstance = new Prerenderer(this._options)
@@ -112,7 +120,7 @@ PrerenderSPAPlugin.prototype.apply = function (compiler) {
return mkdirp(path.dirname(processedRoute.outputPath))
.then(() => {
return new Promise((resolve, reject) => {
- fs.writeFile(processedRoute.outputPath, processedRoute.html.trim(), err => {
+ compilerFS.writeFile(processedRoute.outputPath, processedRoute.html.trim(), err => {
if (err) reject(`[prerender-spa-plugin] Unable to write rendered route to file "${processedRoute.outputPath}" \n ${err}.`)
})
|
Switch to using compiler.outputFileSystem instead of built-in Node FS.
|
chrisvfritz_prerender-spa-plugin
|
train
|
aa2e956d72c57f07f5b238e838e96147aed66676
|
diff --git a/bin/install.js b/bin/install.js
index <HASH>..<HASH> 100644
--- a/bin/install.js
+++ b/bin/install.js
@@ -60,38 +60,31 @@ if(hasMissingBinary){
}
function validateJava(){
+ var potentialLibJvmLocations=[
+ 'jre\\bin\\server\\jvm.dll',
+ 'jre/lib/amd64/server/libjvm.so',
+ 'jre/lib/i386/server/libjvm.so',
+ 'jre/lib/server/libjvm.dylib'
+ ];
+ var proposedPathToLibJvm;
var pathToLibJvm;
+
if(!javaHome){
err("JAVA_HOME isn't set! The java module can't build without it.");
err("You must set this first before installing.");
err("Exiting...");
exit();
}
- if(isWin){
- pathToLibJvm=path.resolve(
- javaHome, 'jre', 'bin', 'server', 'jvm.dll'
- );
- } else {
- switch(arch){
- //TODO add other archs here as need requires.
- case "64":
- pathToLibJvm=path.resolve(
- javaHome, 'jre', 'lib', 'amd64', 'server', 'libjvm.so'
- );
- break;
- case "32":
- pathToLibJvm=path.resolve(
- javaHome, 'jre', 'lib', 'i386', 'server', 'libjvm.so'
- );
+
+ while(potentialLibJvmLocations.length){
+ proposedPathToLibJvm=path.resolve(javaHome, potentialLibJvmLocations.shift());
+ if(fs.existsSync(proposedPathToLibJvm)){
+ pathToLibJvm=proposedPathToLibJvm;
break;
- default:
- err("Your architecture isn't supported yet by this module!");
- err("The architecture was listed as: "+arch);
- showForkItToFixAndExit();
}
}
- if(!fs.existsSync(pathToLibJvm)){
+ if(!pathToLibJvm || !fs.existsSync(pathToLibJvm)){
err("libjvm.so wasn't found using '"+pathToLibJvm+"'.");
err("Verify that $JAVA_HOME is set correctly and try again.");
exit();
|
closes #<I>: libjvm.so not found on OSX bug.
|
jsdevel_webdriver-sync
|
train
|
c415a158aafe1ae46e84b901b41c90a49c7507be
|
diff --git a/sampler/influxdb/influxdb.go b/sampler/influxdb/influxdb.go
index <HASH>..<HASH> 100644
--- a/sampler/influxdb/influxdb.go
+++ b/sampler/influxdb/influxdb.go
@@ -88,6 +88,10 @@ func (o *Output) Commit() error {
o.batchMutex.Lock()
defer o.batchMutex.Unlock()
+ if o.currentBatch == nil {
+ return nil
+ }
+
err := o.Client.Write(o.currentBatch)
o.currentBatch = nil
return err
|
[fix] Prevent crashes when no batch is prepared
|
loadimpact_k6
|
train
|
f937f036a45d87dfd140f34892339c457d5aca10
|
diff --git a/src/main/java/com/github/rholder/retry/RetryerBuilder.java b/src/main/java/com/github/rholder/retry/RetryerBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/rholder/retry/RetryerBuilder.java
+++ b/src/main/java/com/github/rholder/retry/RetryerBuilder.java
@@ -61,9 +61,9 @@ public class RetryerBuilder<V> {
}
/**
- * Sets the wait strategy used to decide . The default strategy
- * is to not sleep at all between attempts.
- * @param stopStrategy the strategy used to sleep between failed attempts
+ * Sets the stop strategy used to decide when to stop retrying. The default strategy
+ * is to not stop at all ({@link StopStrategies.NeverStopStrategy}) .
+ * @param stopStrategy the strategy used to decide when to stop retrying
* @return <code>this</code>
* @throws IllegalStateException if a stop strategy has already been set.
*/
|
Updated javadoc to reflect the real purpose of defining a stop strategy.
|
rholder_guava-retrying
|
train
|
2c8809cc09b7671ef084b3df24c01add2c1bd328
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -4,12 +4,12 @@ from setuptools import setup
setup(
name='lavalink',
packages=['lavalink'],
- version='2.1.6',
+ version='2.1.7',
description='A lavalink interface built for discord.py',
author='Devoxin',
author_email='luke@serux.pro',
url='https://github.com/Devoxin/Lavalink.py',
- download_url='https://github.com/Devoxin/Lavalink.py/archive/2.1.6.tar.gz',
+ download_url='https://github.com/Devoxin/Lavalink.py/archive/2.1.7.tar.gz',
keywords=['lavalink'],
include_package_data=True,
install_requires=['websockets!=5.0.0', 'aiohttp']
|
Didn't cd to correct folder, missed a file
|
Devoxin_Lavalink.py
|
train
|
5174bb2bd8d14ba1af4476e8ece759f287dbc6b1
|
diff --git a/src/runtime/directives/model.js b/src/runtime/directives/model.js
index <HASH>..<HASH> 100644
--- a/src/runtime/directives/model.js
+++ b/src/runtime/directives/model.js
@@ -1,5 +1,15 @@
import { isAndroid, isIE9 } from '../util/env'
+if (isIE9) {
+ // http://www.matts411.com/post/internet-explorer-9-oninput/
+ document.addEventListener('selectionchange', () => {
+ const el = document.activeElement
+ if (el && el.vmodel) {
+ trigger(el)
+ }
+ })
+}
+
export default {
bind (el, value) {
if (!isAndroid) {
@@ -7,8 +17,7 @@ export default {
el.addEventListener('compositionend', onCompositionEnd)
}
if (isIE9) {
- el.addEventListener('cut', trigger)
- el.addEventListener('keyup', triggerOnDelOrBackspace)
+ el.vmodel = true
}
},
unbind (el) {
@@ -16,10 +25,6 @@ export default {
el.removeEventListener('compositionstart', onCompositionStart)
el.removeEventListener('compositionend', onCompositionEnd)
}
- if (isIE9) {
- el.removeEventListener('cut', trigger)
- el.removeEventListener('keyup', triggerOnDelOrBackspace)
- }
}
}
@@ -29,17 +34,11 @@ function onCompositionStart (e) {
function onCompositionEnd (e) {
e.target.composing = false
- trigger(e)
-}
-
-function trigger (e) {
- const ev = document.createEvent('HTMLEvents')
- ev.initEvent('input', true, true)
- e.target.dispatchEvent(ev)
+ trigger(e.target)
}
-function triggerOnDelOrBackspace (e) {
- if (e.keyCode === 46 || e.keyCode === 8) {
- trigger(e)
- }
+function trigger (el) {
+ const e = document.createEvent('HTMLEvents')
+ e.initEvent('input', true, true)
+ el.dispatchEvent(e)
}
|
better IE9 v-model support
|
IOriens_wxml-transpiler
|
train
|
4a617b8153b064f30e2cb6336e4a4b7b6d216e13
|
diff --git a/lib/context.js b/lib/context.js
index <HASH>..<HASH> 100644
--- a/lib/context.js
+++ b/lib/context.js
@@ -1,8 +1,9 @@
const Response = require('./response');
module.exports = class {
- constructor(call) {
+ constructor(call, methodName) {
this.call = call;
+ this.methodName = methodName;
this.request = this.call.request;
this.metadata = this.call.metadata;
this.write = this.call.write;
diff --git a/lib/context.spec.js b/lib/context.spec.js
index <HASH>..<HASH> 100644
--- a/lib/context.spec.js
+++ b/lib/context.spec.js
@@ -3,7 +3,7 @@ const Context = require('./context');
const Response = require('./response');
describe('Context:', () => {
- let call, context;
+ let call, context, methodName;
const expectedResponse = new Response('message');
const response = new Response('message');
const metadata = new grpc.Metadata();
@@ -23,7 +23,8 @@ describe('Context:', () => {
return object;
},
};
- context = new Context(call);
+ methodName = 'myapp.MyService.methodName';
+ context = new Context(call, methodName);
});
describe('constructor', () => {
@@ -35,6 +36,10 @@ describe('Context:', () => {
expect(context.call).toBe(call);
});
+ it('should create a Context with the methodName', () => {
+ expect(context.methodName).toEqual(methodName);
+ });
+
it('should have a send method', () => {
expect(context.send).toEqual(jasmine.any(Function));
});
diff --git a/lib/proxy.js b/lib/proxy.js
index <HASH>..<HASH> 100644
--- a/lib/proxy.js
+++ b/lib/proxy.js
@@ -83,8 +83,9 @@ module.exports = class {
const implementation = {
'instance': this._serviceDefinition.implementation, 'name': propertyName,
};
+ const methodName = `${this._serviceDefinition.serviceFullName}.${propertyName}`;
return (call, callback) => {
- const context = new Context(call);
+ const context = new Context(call, methodName);
const elements = {middleware, errorHandlers};
const functionIterator = new FunctionIterator(elements, context, implementation);
return functionIterator.next().then((result) => {
diff --git a/lib/proxy.spec.js b/lib/proxy.spec.js
index <HASH>..<HASH> 100644
--- a/lib/proxy.spec.js
+++ b/lib/proxy.spec.js
@@ -1,12 +1,13 @@
const Proxy = require('./proxy');
const Response = require('./response');
+const Context = require('./context');
const Mocks = require('../spec/util/mocks');
const Spy = require('../spec/util/spy');
/* eslint max-lines: "off" */
describe('Proxy:', () => {
let serviceDefinition, proxy, personServiceMock, middlewareMock, middleware, errorHandlerMock,
- errorHandlers, call, expectedError, expectedResponse, error;
+ errorHandlers, call, methodName, expectedError, expectedResponse, error;
beforeEach(() => {
middlewareMock = Mocks.getMiddleware();
@@ -21,6 +22,7 @@ describe('Proxy:', () => {
errorHandlers = errorHandlerMock.errorHandlers;
proxy = new Proxy(serviceDefinition, middleware, errorHandlers);
call = {'a': 1};
+ methodName = `${serviceDefinition.serviceFullName}.list`;
});
it('should return an object', () => {
@@ -230,6 +232,17 @@ describe('Proxy:', () => {
done();
});
});
+
+ it('should call middlewares with context and next', (done) => {
+ proxy.list(call, () => {
+ const args = middlewareMock.globalMiddleware.method.calls.argsFor(0);
+ expect(args[0] instanceof Context).toBeTruthy();
+ expect(args[0].call).toEqual(call);
+ expect(args[0].methodName).toEqual(methodName);
+ expect(args[1]).toEqual(jasmine.any(Function));
+ done();
+ });
+ });
});
describe('when error handlers are added', () => {
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "condor-framework",
- "version": "1.0.1",
+ "version": "1.1.0",
"description": "Framework for building GRPC services in Node JS.",
"main": "index.js",
"scripts": {
|
add methodName to the context, so it can be used from the condor-auth middleware
|
devsu_condor-framework
|
train
|
82547ca01ec8cb0961f6b3c0cbae4fc7e2f6e997
|
diff --git a/src/DOIServiceProvider.php b/src/DOIServiceProvider.php
index <HASH>..<HASH> 100755
--- a/src/DOIServiceProvider.php
+++ b/src/DOIServiceProvider.php
@@ -290,8 +290,18 @@ class DOIServiceProvider
$this->setResponse("responsecode", "MT014");
return false;
}
- $result = $this->dataciteClient->updateURL($doiValue, $url);
+ }
+
+ if(isset($xml) && $xml!="") {
+ // Validate xml
+ if ($this->validateXML($xml) === false) {
+ $this->setResponse('responsecode', 'MT007');
+ return false;
+ }
+ }
+ if (isset($url) && $url!="") {
+ $result = $this->dataciteClient->updateURL($doiValue, $url);
if ($result === true) {
$this->setResponse('responsecode', 'MT002');
//update the database DOIRepository
@@ -301,16 +311,10 @@ class DOIServiceProvider
$this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors()));
return false;
}
-
-
}
+
if(isset($xml) && $xml!="") {
- // Validate xml
- if ($this->validateXML($xml) === false) {
- $this->setResponse('responsecode', 'MT007');
- return false;
- }
$result = $this->dataciteClient->update($xml);
if ($result === true) {
$this->setResponse('responsecode', 'MT002');
@@ -321,10 +325,7 @@ class DOIServiceProvider
$this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors()));
return false;
}
-
-
}
-
return true;
}
|
check validity of any provided xml and url and ensure both are valid prior to performing either update CC-<I>
|
au-research_ANDS-DOI-Service
|
train
|
e487e81e0fc1c105105b532ca9383bc673feb0af
|
diff --git a/lib/tocer/cli.rb b/lib/tocer/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/tocer/cli.rb
+++ b/lib/tocer/cli.rb
@@ -42,7 +42,6 @@ module Tocer
files = runner.files
runner.run
-
return if files.empty?
say "Processed table of contents for:"
@@ -84,6 +83,7 @@ module Tocer
def build_configuration path, label, whitelist
if Pathname(path).file?
+ warn "[DEPRECATION]: File paths are deprecated, use directory paths instead."
self.class.configuration.merge label: label, whitelist: [path]
else
self.class.configuration.merge label: label, whitelist: whitelist
diff --git a/spec/lib/tocer/cli_spec.rb b/spec/lib/tocer/cli_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/tocer/cli_spec.rb
+++ b/spec/lib/tocer/cli_spec.rb
@@ -130,6 +130,14 @@ RSpec.describe Tocer::CLI do
context "with file path", :temp_dir do
let(:options) { ["test.md"] }
+ it "prints deprecation warning" do
+ ClimateControl.modify HOME: temp_dir do
+ Dir.chdir temp_dir do
+ expect(&cli).to output(/DEPRECATION/).to_stdout
+ end
+ end
+ end
+
it "generates table of contents" do
ClimateControl.modify HOME: temp_dir do
Dir.chdir temp_dir do
|
Added `--generate` deprecation warning when using file paths.
- The use of file paths will be removed in the next major version
release. Use directory paths instead.
|
bkuhlmann_tocer
|
train
|
a90d37d420cbe2978c546662f0d835837546cc46
|
diff --git a/test/unexpected-with-plugins.js b/test/unexpected-with-plugins.js
index <HASH>..<HASH> 100644
--- a/test/unexpected-with-plugins.js
+++ b/test/unexpected-with-plugins.js
@@ -64,8 +64,12 @@ function toAst(stringOrAssetOrFunctionOrAst) {
}
}
-expect.addAssertion('to have the same AST as', function (expect, subject, value) {
- expect(toAst(subject).print_to_string(), 'to equal', toAst(value).print_to_string());
+expect.addAssertion('[not] to have the same AST as', function (expect, subject, value) {
+ if (this.flags.not) {
+ expect(toAst(subject).print_to_string(), 'not to equal', toAst(value).print_to_string());
+ } else {
+ expect(toAst(subject).print_to_string(), 'to equal', toAst(value).print_to_string());
+ }
});
expect.addType({
|
Add a negation flag on 'to have the same AST as'-assertion in unexpected plugins
|
assetgraph_assetgraph
|
train
|
7896264edf6a3ea94a2f7ae396da1f1db152311e
|
diff --git a/gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/process/FeatureCoverageTest.java b/gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/process/FeatureCoverageTest.java
index <HASH>..<HASH> 100644
--- a/gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/process/FeatureCoverageTest.java
+++ b/gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/process/FeatureCoverageTest.java
@@ -35,6 +35,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.AggregateT
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupCountTest;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.InjectTest;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.StoreTest;
+import org.junit.Ignore;
import org.junit.Test;
import java.io.BufferedReader;
@@ -65,6 +66,7 @@ public class FeatureCoverageTest {
private static Pattern scenarioName = Pattern.compile("^\\s*Scenario:\\s*(.*)$");
@Test
+ @Ignore("As it stands we won't have all of these tests migrated initially so there is no point to running this in full - it can be flipped on later")
public void shouldImplementAllProcessTestsAsFeatures() throws Exception {
// TEMPORARY while test framework is under development - all tests should ultimately be included
|
TINKERPOP-<I> Disabled coverage test for features
No point to enabling at this time since all tests aren't really targetted for migration with this initial body of work. It will be turned on later when all test are intended for migration.
|
apache_tinkerpop
|
train
|
52b7f254e72ed482ee2dd9a4df86fc859668ea3b
|
diff --git a/app/controllers/blogr/posts_controller.rb b/app/controllers/blogr/posts_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/blogr/posts_controller.rb
+++ b/app/controllers/blogr/posts_controller.rb
@@ -1,89 +1,64 @@
require_dependency "blogr/application_controller"
module Blogr
- class PostsController < ApplicationController
- before_action :set_post, only: [:show, :edit, :update, :destroy]
-
- def index
- @posts = Post.order id: :desc
- @title = "Posts"
- end
-
- def show
- @title = @post.title
- end
-
- def new
- @post = Post.new
- @title = "New Post"
- end
-
- def edit
- if params[:delete_image]
- Image.find(params[:delete_image]).try :destroy
- end
- @title = "Editing '#{@post.title}'"
- end
-
- def create
- @post = Post.new(post_params)
-
- if @post.save
- # image_upload
- # params[:post][:categories] ||= []
- # params[:post][:categories].reject! {|c| c.to_s.blank? }
-
- # params[:post][:categories].each do |category_id|
- # @post.categories << Category.find(category_id)
- # end
-
- redirect_to @post, notice: "Post was successfully created"
- else
- render action: 'new'
- end
- end
-
- def update
-
- # image_upload
- if @post.update(post_params)
- # params[:post][:categories] ||= []
- # params[:post][:categories].reject! {|c| c.to_s.blank? }
-
- # @post.categories.delete_all
- # params[:post][:categories].each do |category_id|
- # @post.categories << Category.find(category_id)
- # end
- redirect_to @post, notice: "Post was successfully updated"
- else
- render action: 'edit'
- end
- end
-
- def destroy
- @post.destroy
- redirect_to posts_url, notice: "Post was successfully destroyed"
- end
-
- private
-
- # Use callbacks to share common setup or constraints between actions.
- def set_post
- @post = Post.find_by_permalink!(params[:id])
- end
-
- # Only allow a trusted parameter "white list" through.
- def post_params
- params.require(:post).permit(:title, :category_id, :permalink, :content, :tag_list, :published, :published_at)
- end
-
- def image_params
- params.require(:image).permit!
- end
-
- # def image_upload
- # Image.create image_params.merge(post_id: @post.id) if params[:image]
- # end
-
- end
+ class PostsController < ApplicationController
+
+ before_action :set_post, only: [:show, :edit, :update, :destroy]
+
+ def index
+ @posts = Post.order(published_at: :desc)
+ @title = "Posts"
+ end
+
+ def show
+ @title = @post.title
+ end
+
+ def new
+ @post = Post.new
+ @title = "New Post"
+ end
+
+ def edit
+ if params[:delete_image]
+ Image.find(params[:delete_image]).try :destroy
+ end
+ @title = "Editing '#{@post.title}'"
+ end
+
+ def create
+ @post = Post.new(post_params)
+
+ if @post.save
+ redirect_to @post, notice: "Post was successfully created"
+ else
+ render action: "new"
+ end
+ end
+
+ def update
+
+ if @post.update(post_params)
+ redirect_to @post, notice: "Post was successfully updated"
+ else
+ render action: "edit"
+ end
+ end
+
+ def destroy
+ @post.destroy
+ redirect_to posts_url, notice: "Post was successfully destroyed"
+ end
+
+ private
+
+ def set_post
+ @post = Post.find_by_permalink!(params[:id])
+ end
+
+ def post_params
+ params.require(:post).permit(:title, :category_id, :permalink, :content, :tag_list, :published, :published_at)
+ end
+
+ end
end
\ No newline at end of file
|
cleanup of posts controller and sort posts by published_at desc
|
deanpcmad_blogr
|
train
|
5a511cbef040c5fabbc23553083d1f14a8e33ab9
|
diff --git a/server/src/main/java/com/metamx/druid/db/DatabaseRuleManager.java b/server/src/main/java/com/metamx/druid/db/DatabaseRuleManager.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/com/metamx/druid/db/DatabaseRuleManager.java
+++ b/server/src/main/java/com/metamx/druid/db/DatabaseRuleManager.java
@@ -69,7 +69,7 @@ public class DatabaseRuleManager
{
List<Map<String, Object>> existing = handle.select(
String.format(
- "SELECT id from %s where datasource=%s;",
+ "SELECT id from %s where datasource='%s';",
ruleTable,
defaultDatasource
)
|
bug fix for missing quotations creating default datasource
|
apache_incubator-druid
|
train
|
59e9bc571a3b4cd6e9841573b15818013fed2df6
|
diff --git a/core/src/main/java/com/automation/remarks/video/recorder/FFMpegRecorder.java b/core/src/main/java/com/automation/remarks/video/recorder/FFMpegRecorder.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/automation/remarks/video/recorder/FFMpegRecorder.java
+++ b/core/src/main/java/com/automation/remarks/video/recorder/FFMpegRecorder.java
@@ -53,7 +53,8 @@ public class FFMpegRecorder extends VideoRecorder {
@Override
public File stopAndSave(final String filename) {
- killFFmpeg();
+ String killLog = killFFmpeg();
+ log.info("Process kill output: " + killLog);
File destFile = getDestinationFile(filename);
this.future.whenCompleteAsync((out, errors) -> {
|
kill log added to ffmpeg
|
SergeyPirogov_video-recorder-java
|
train
|
283bf5dcae1cc3ae5e7184807ecefda6f68da655
|
diff --git a/rah_flat.php b/rah_flat.php
index <HASH>..<HASH> 100644
--- a/rah_flat.php
+++ b/rah_flat.php
@@ -46,6 +46,13 @@ class rah_flat
register_callback(array($this, 'importForms'), 'textpattern');
register_callback(array($this, 'importPages'), 'textpattern');
}
+
+ if (txpinterface === 'admin')
+ {
+ register_callback(array($this, 'importSections'), 'admin_side', 'body_end');
+ register_callback(array($this, 'importForms'), 'admin_side', 'body_end');
+ register_callback(array($this, 'importPages'), 'admin_side', 'body_end');
+ }
}
}
|
Run on every admin-side request.
|
gocom_rah_flat
|
train
|
5383bd80222c0efc5f3278e187400b6fc1ed3440
|
diff --git a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
+++ b/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
@@ -78,6 +78,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@@ -186,7 +187,7 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
private Supplier<List<JSChunk>> modulesSupplierForTesting = null;
@GwtIncompatible("Unnecessary")
- private Function<Integer, Void> exitCodeReceiver = SystemExitCodeReceiver.INSTANCE;
+ private Consumer<Integer> exitCodeReceiver = SystemExitCodeReceiver.INSTANCE;
@Nullable
@GwtIncompatible("Unnecessary")
@@ -244,13 +245,13 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
Supplier<List<SourceFile>> externsSupplier,
Supplier<List<SourceFile>> inputsSupplier,
Supplier<List<JSChunk>> modulesSupplier,
- Function<Integer, Void> exitCodeReceiver) {
+ Consumer<Integer> exitCodeReceiver) {
checkArgument(inputsSupplier == null != (modulesSupplier == null));
testMode = true;
this.externsSupplierForTesting = externsSupplier;
this.inputsSupplierForTesting = inputsSupplier;
this.modulesSupplierForTesting = modulesSupplier;
- this.exitCodeReceiver = exitCodeReceiver;
+ setExitCodeReceiver(exitCodeReceiver);
}
/**
@@ -258,7 +259,7 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
* or 0i to indicate success.
*/
@GwtIncompatible("Unnecessary")
- public void setExitCodeReceiver(Function<Integer, Void> newExitCodeReceiver) {
+ public void setExitCodeReceiver(Consumer<Integer> newExitCodeReceiver) {
this.exitCodeReceiver = checkNotNull(newExitCodeReceiver);
}
@@ -564,7 +565,7 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
result = -2;
}
- exitCodeReceiver.apply(result);
+ exitCodeReceiver.accept(result);
}
/** Returns the PrintStream for writing errors associated with this AbstractCommandLineRunner. */
@@ -3328,7 +3329,7 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
}
@GwtIncompatible("Unnecessary")
- static final class SystemExitCodeReceiver implements Function<Integer, Void> {
+ static final class SystemExitCodeReceiver implements Consumer<Integer> {
static final SystemExitCodeReceiver INSTANCE = new SystemExitCodeReceiver();
private SystemExitCodeReceiver() {
@@ -3336,7 +3337,7 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
}
@Override
- public Void apply(Integer exitCode) {
+ public void accept(Integer exitCode) {
int exitCodeValue = checkNotNull(exitCode);
// Don't spuriously report success.
// Posix conventions only guarantee that 8b are significant.
@@ -3345,7 +3346,6 @@ public abstract class AbstractCommandLineRunner<A extends Compiler, B extends Co
exitCodeByte = (byte) -1;
}
System.exit(exitCodeByte);
- return null;
}
}
}
diff --git a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
+++ b/test/com/google/javascript/jscomp/CommandLineRunnerTest.java
@@ -3319,7 +3319,6 @@ public final class CommandLineRunnerTest {
modulesSupplier,
exitCode -> {
exitCodes.add(exitCode);
- return null;
});
runner.run();
lastCompiler = runner.getCompiler();
|
Change the JSCompilerRunner setExitCodeReceiver method to accept a Consumer, not a Function, as the return type is always unused.
PiperOrigin-RevId: <I>
|
google_closure-compiler
|
train
|
a6a2d2e7d5f77c4ffd75e49601bb15376d476aaf
|
diff --git a/django_geckoboard/decorators.py b/django_geckoboard/decorators.py
index <HASH>..<HASH> 100644
--- a/django_geckoboard/decorators.py
+++ b/django_geckoboard/decorators.py
@@ -431,14 +431,13 @@ def _is_api_key_correct(request):
def _render(request, data, format=None):
+ """Render the data to Geckoboard based on the format request parameter or the format argument supplied to the decorator. Default to XML"""
if format:
if format == "json":
return _render_json(data)
else:
- """Just default to XML"""
return _render_xml(data)
else:
- """Render the data to Geckoboard based on the format request parameter."""
format = request.POST.get('format', '')
if not format:
format = request.GET.get('format', '')
|
Doc strings should be after the function definition
|
jcassee_django-geckoboard
|
train
|
b7ac9bee8916e5a0438acee8823008af4094134a
|
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index <HASH>..<HASH> 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1102,7 +1102,7 @@ class DataFrame(NDFrame, OpsMixin):
...
@Substitution(
- header_type="bool or sequence of strings",
+ header_type="bool or sequence of str",
header="Write out the column names. If a list of strings "
"is given, it is assumed to be aliases for the "
"column names",
|
fix PR<I> failing CI (#<I>)
|
pandas-dev_pandas
|
train
|
42cf5f8511f10b69528e9a9febc99b9bd99ce044
|
diff --git a/examples/igc.js b/examples/igc.js
index <HASH>..<HASH> 100644
--- a/examples/igc.js
+++ b/examples/igc.js
@@ -7,7 +7,7 @@ import LineString from '../src/ol/geom/LineString.js';
import Point from '../src/ol/geom/Point.js';
import TileLayer from '../src/ol/layer/Tile.js';
import VectorLayer from '../src/ol/layer/Vector.js';
-import OSM from '../src/ol/source/OSM.js';
+import OSM, {ATTRIBUTION} from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js';
import CircleStyle from '../src/ol/style/Circle.js';
import Fill from '../src/ol/style/Fill.js';
@@ -86,7 +86,7 @@ const map = new Map({
source: new OSM({
attributions: [
'All maps © <a href="https://www.opencyclemap.org/">OpenCycleMap</a>',
- OSM.ATTRIBUTION
+ ATTRIBUTION
],
url: 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' +
'?apikey=0e6fc415256d4fbb9b5166a718591d71'
diff --git a/examples/localized-openstreetmap.js b/examples/localized-openstreetmap.js
index <HASH>..<HASH> 100644
--- a/examples/localized-openstreetmap.js
+++ b/examples/localized-openstreetmap.js
@@ -2,14 +2,14 @@ import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls} from '../src/ol/control.js';
import TileLayer from '../src/ol/layer/Tile.js';
-import OSM from '../src/ol/source/OSM.js';
+import OSM, {ATTRIBUTION} from '../src/ol/source/OSM.js';
const openCycleMapLayer = new TileLayer({
source: new OSM({
attributions: [
'All maps © <a href="https://www.opencyclemap.org/">OpenCycleMap</a>',
- OSM.ATTRIBUTION
+ ATTRIBUTION
],
url: 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' +
'?apikey=0e6fc415256d4fbb9b5166a718591d71'
@@ -20,7 +20,7 @@ const openSeaMapLayer = new TileLayer({
source: new OSM({
attributions: [
'All maps © <a href="http://www.openseamap.org/">OpenSeaMap</a>',
- OSM.ATTRIBUTION
+ ATTRIBUTION
],
opaque: false,
url: 'https://tiles.openseamap.org/seamark/{z}/{x}/{y}.png'
diff --git a/src/ol/source/OSM.js b/src/ol/source/OSM.js
index <HASH>..<HASH> 100644
--- a/src/ol/source/OSM.js
+++ b/src/ol/source/OSM.js
@@ -4,6 +4,19 @@
import {inherits} from '../index.js';
import XYZ from '../source/XYZ.js';
+
+/**
+ * The attribution containing a link to the OpenStreetMap Copyright and License
+ * page.
+ * @const
+ * @type {string}
+ * @api
+ */
+export const ATTRIBUTION = '© ' +
+ '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> ' +
+ 'contributors.';
+
+
/**
* @classdesc
* Layer source for the OpenStreetMap tile server.
@@ -21,7 +34,7 @@ const OSM = function(opt_options) {
if (options.attributions !== undefined) {
attributions = options.attributions;
} else {
- attributions = [OSM.ATTRIBUTION];
+ attributions = [ATTRIBUTION];
}
const crossOrigin = options.crossOrigin !== undefined ?
@@ -46,15 +59,4 @@ const OSM = function(opt_options) {
inherits(OSM, XYZ);
-
-/**
- * The attribution containing a link to the OpenStreetMap Copyright and License
- * page.
- * @const
- * @type {string}
- * @api
- */
-OSM.ATTRIBUTION = '© ' +
- '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> ' +
- 'contributors.';
export default OSM;
diff --git a/src/ol/source/Stamen.js b/src/ol/source/Stamen.js
index <HASH>..<HASH> 100644
--- a/src/ol/source/Stamen.js
+++ b/src/ol/source/Stamen.js
@@ -2,7 +2,7 @@
* @module ol/source/Stamen
*/
import {inherits} from '../index.js';
-import OSM from '../source/OSM.js';
+import {ATTRIBUTION as OSM_ATTRIBUTION} from '../source/OSM.js';
import XYZ from '../source/XYZ.js';
@@ -14,7 +14,7 @@ const ATTRIBUTIONS = [
'Map tiles by <a href="https://stamen.com/">Stamen Design</a>, ' +
'under <a href="https://creativecommons.org/licenses/by/3.0/">CC BY' +
' 3.0</a>.',
- OSM.ATTRIBUTION
+ OSM_ATTRIBUTION
];
|
Named exports from ol/source/OSM
|
openlayers_openlayers
|
train
|
cc8ee9ae6fbbc23b3ba2bd1ad18b805ebc918ee5
|
diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/type/Type.java b/presto-spi/src/main/java/com/facebook/presto/spi/type/Type.java
index <HASH>..<HASH> 100644
--- a/presto-spi/src/main/java/com/facebook/presto/spi/type/Type.java
+++ b/presto-spi/src/main/java/com/facebook/presto/spi/type/Type.java
@@ -52,7 +52,7 @@ public interface Type
* be called on Cursor, RecordSet or RandomAccessBlock to fetch a value of
* this type.
* <p>
- * Currently, this must be boolean, long, double, or Slice.
+ * Currently, this must be boolean, long, double, Slice or Block.
*/
Class<?> getJavaType();
|
Document Type can use Block as the representation
|
prestodb_presto
|
train
|
af62b77f4f2ee7b85efdb74f5d9635da0ac490d9
|
diff --git a/core-bundle/src/Resources/contao/library/Contao/Input.php b/core-bundle/src/Resources/contao/library/Contao/Input.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/library/Contao/Input.php
+++ b/core-bundle/src/Resources/contao/library/Contao/Input.php
@@ -462,6 +462,12 @@ class Input
$varValue = strip_tags($varValue, $strAllowedTags);
$varValue = str_replace(array('<!--', '<![', '-->'), array('<!--', '<![', '-->'), $varValue);
+ // Recheck for encoded null bytes
+ while (strpos($varValue, '\\0') !== false)
+ {
+ $varValue = str_replace('\\0', '', $varValue);
+ }
+
return $varValue;
}
|
[Core] Fix another weakness in the `Input` class and further harden the `deserialize()` function
Fix another weakness in the `Input` class and further harden the `deserialize()` function. Thanks to Martin Auswöger for his input.
|
contao_contao
|
train
|
74eed6290e63111d1aad2b181692a84f4f040aea
|
diff --git a/actionpack/lib/action_controller/flash.rb b/actionpack/lib/action_controller/flash.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_controller/flash.rb
+++ b/actionpack/lib/action_controller/flash.rb
@@ -28,7 +28,6 @@ module ActionController #:nodoc:
base.class_eval do
include InstanceMethods
alias_method_chain :assign_shortcuts, :flash
- alias_method_chain :process_cleanup, :flash
alias_method_chain :reset_session, :flash
end
end
@@ -166,11 +165,7 @@ module ActionController #:nodoc:
def assign_shortcuts_with_flash(request, response) #:nodoc:
assign_shortcuts_without_flash(request, response)
flash(:refresh)
- end
-
- def process_cleanup_with_flash
- flash.sweep if @_session
- process_cleanup_without_flash
+ flash.sweep if @_session && !component_request?
end
end
end
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index <HASH>..<HASH> 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -12,6 +12,11 @@ class TestTest < Test::Unit::TestCase
render :text => 'ignore me'
end
+ def set_flash_now
+ flash.now["test_now"] = ">#{flash["test_now"]}<"
+ render :text => 'ignore me'
+ end
+
def set_session
session['string'] = 'A wonder'
session[:symbol] = 'it works'
@@ -145,6 +150,11 @@ XML
assert_equal '>value<', flash['test']
end
+ def test_process_with_flash_now
+ process :set_flash_now, nil, nil, { "test_now" => "value_now" }
+ assert_equal '>value_now<', flash['test_now']
+ end
+
def test_process_with_session
process :set_session
assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key"
|
Fixed flash.now not being accessible in tests. Flash sweeping is now done before action processing instead after
|
rails_rails
|
train
|
8c7f97eb73a6a21cf606d4273acc16844e22dff5
|
diff --git a/lib/custom/src/MW/View/Helper/Response/Symfony2.php b/lib/custom/src/MW/View/Helper/Response/Symfony2.php
index <HASH>..<HASH> 100644
--- a/lib/custom/src/MW/View/Helper/Response/Symfony2.php
+++ b/lib/custom/src/MW/View/Helper/Response/Symfony2.php
@@ -25,13 +25,9 @@ class Symfony2
* Initializes the URL view helper.
*
* @param \Aimeos\MW\View\Iface $view View instance with registered view helpers
- * @param \Symfony\Component\HttpFoundation\Response $response Symfony2 response object
*/
- public function __construct( $view, \Symfony\Component\HttpFoundation\Response $response )
+ public function __construct( \Aimeos\MW\View\Iface $view )
{
- $factory = new \Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory();
- $psr7response = $factory->createResponse( $response );
-
- parent::__construct( $view, $psr7response );
+ parent::__construct( $view, new \Zend\Diactoros\Response() );
}
}
diff --git a/lib/custom/tests/MW/View/Helper/Response/Symfony2Test.php b/lib/custom/tests/MW/View/Helper/Response/Symfony2Test.php
index <HASH>..<HASH> 100644
--- a/lib/custom/tests/MW/View/Helper/Response/Symfony2Test.php
+++ b/lib/custom/tests/MW/View/Helper/Response/Symfony2Test.php
@@ -17,17 +17,12 @@ class Symfony2Test extends \PHPUnit_Framework_TestCase
protected function setUp()
{
- if( !class_exists( '\Symfony\Component\HttpFoundation\Response' ) ) {
- $this->markTestSkipped( '\Symfony\Component\HttpFoundation\Response is not available' );
- }
-
- if( !class_exists( '\Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory' ) ) {
- $this->markTestSkipped( '\Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory is not available' );
+ if( !class_exists( '\Zend\Diactoros\Response' ) ) {
+ $this->markTestSkipped( '\Zend\Diactoros\Response is not available' );
}
$view = new \Aimeos\MW\View\Standard();
- $request = new \Symfony\Component\HttpFoundation\Response( 'Content' );
- $this->object = new \Aimeos\MW\View\Helper\Response\Symfony2( $view, $request );
+ $this->object = new \Aimeos\MW\View\Helper\Response\Symfony2( $view );
}
|
Symfony response object isn't required
|
aimeos_ai-symfony
|
train
|
e9be40c289f5f4bb1cf730609c42dfae116eee14
|
diff --git a/packages/core/logger/src/index.js b/packages/core/logger/src/index.js
index <HASH>..<HASH> 100644
--- a/packages/core/logger/src/index.js
+++ b/packages/core/logger/src/index.js
@@ -204,16 +204,6 @@ export class Logger {
this.events.emit("log", "dir", obj);
this.logFunction(obj, null);
-
- let origin;
- if (this.isDebugOrTrace) {
- try {
- const stack = new Error().stack;
- origin = stack.split('\n')[2].trim();
- // eslint-disable-next-line no-empty
- } catch (e) {}
- }
- this.writeToFile({ args: obj, origin, prefix: "[dir]" });
}
shouldLog(level) {
|
fix(@embark/logger): Remove `writeToFile` for logger `dir`
When using `dir` in the logger, do not write this value to the log file, and instead only print the output to the screen
|
embark-framework_embark
|
train
|
044c29f0ec41963e4342631f19c55fa6b8e9d616
|
diff --git a/manifest.php b/manifest.php
index <HASH>..<HASH> 100755
--- a/manifest.php
+++ b/manifest.php
@@ -39,7 +39,7 @@ return array(
'label' => 'QTI test model',
'description' => 'TAO QTI test implementation',
'license' => 'GPL-2.0',
- 'version' => '33.1.0',
+ 'version' => '33.2.2',
'author' => 'Open Assessment Technologies',
'requires' => array(
'taoQtiItem' => '>=19.5.0',
|
TAO-<I> valid version of the component itself
|
oat-sa_extension-tao-testqti
|
train
|
9729b283b5f69a13d830dc26aaff2fc6edba06a9
|
diff --git a/src/main/java/com/couchbase/cblite/CBLQueryRow.java b/src/main/java/com/couchbase/cblite/CBLQueryRow.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/couchbase/cblite/CBLQueryRow.java
+++ b/src/main/java/com/couchbase/cblite/CBLQueryRow.java
@@ -2,6 +2,7 @@ package com.couchbase.cblite;
import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
/**
@@ -151,8 +152,18 @@ public class CBLQueryRow {
* If the index is out of range, returns nil.
*/
public Object getKeyAtIndex(int index) {
- // TODO: implement
- throw new RuntimeException("TODO: implement");
+ if (key instanceof List) {
+ List keyList = (List)key;
+ if (index < keyList.size()) {
+ return keyList.get(index);
+ }
+ }
+ else {
+ if (index == 0) {
+ return key;
+ }
+ }
+ return null;
}
/**
@@ -175,8 +186,7 @@ public class CBLQueryRow {
* The local sequence number of the associated doc/revision.
*/
public long getLocalSequence() {
- // TODO: implement
- throw new RuntimeException("TODO: implement");
+ return sequence;
}
|
CBLQueryRow all methods implemented
|
couchbase_couchbase-lite-java-core
|
train
|
f2164fc9ae27544c1337dd5999adc170f1264688
|
diff --git a/app/controllers/leaf/tinymce_assets_controller.rb b/app/controllers/leaf/tinymce_assets_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/leaf/tinymce_assets_controller.rb
+++ b/app/controllers/leaf/tinymce_assets_controller.rb
@@ -1,5 +1,6 @@
module Leaf
class TinymceAssetsController < BaseController
+ skip_authorization_check, :only => [:create]
def create
asset = TinymceAsset.new
diff --git a/app/controllers/leaf/translations_controller.rb b/app/controllers/leaf/translations_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/leaf/translations_controller.rb
+++ b/app/controllers/leaf/translations_controller.rb
@@ -22,7 +22,7 @@ module Leaf
end
def index
- # authorize! :manage, Translation
+ authorize! :manage, I18n::Backend::Leaf::Translation
@list = @object_class = I18n::Backend::Leaf::Translation.includes(:translation_data).filter(:search => params[:search])
if !params[:ajax].blank?
render :layout => false
@@ -30,17 +30,17 @@ module Leaf
end
def edit
- # authorize! :manage, Translation
+ authorize! :manage, I18n::Backend::Leaf::Translation
@item = current_object_class.find(params[:id])
end
def show
- # authorize! :manage, Translation
+ authorize! :manage, I18n::Backend::Leaf::Translation
redirect_to url_for( :action => "edit", :id => params[:id] )
end
def create
- # authorize! :manage, Translation
+ authorize! :manage, I18n::Backend::Leaf::Translation
@item = current_object_class.new(item_params)
respond_to do |format|
@@ -55,7 +55,7 @@ module Leaf
end
def update
- # authorize! :manage, Translation
+ authorize! :manage, I18n::Backend::Leaf::Translation
@item = current_object_class.find(params[:id])
unless params[:translations].blank?
|
Update code for permissios
|
cubesystems_releaf
|
train
|
d725a654eaa26ef1b7071960f9d495b1386b5808
|
diff --git a/instana/version.py b/instana/version.py
index <HASH>..<HASH> 100644
--- a/instana/version.py
+++ b/instana/version.py
@@ -3,4 +3,4 @@
# Module version file. Used by setup.py and snapshot reporting.
-VERSION = '1.33.2'
+VERSION = '1.33.3'
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -64,7 +64,7 @@ setup(name='instana',
'certifi>=2018.4.16',
'fysom>=2.1.2',
'opentracing>=2.3.0',
- 'requests>=2.8.0',
+ 'requests>=2.6.0',
'six>=1.12.0',
'urllib3<1.26,>=1.21.1'],
entry_points={
|
lowering the requests version dependency for supporting air-gapped environment of customer ZD:<I> (#<I>)
|
instana_python-sensor
|
train
|
c4535fc2615f75f11acbc870cc79fe502c8c0950
|
diff --git a/go/test/endtoend/vtgate/lookup_test.go b/go/test/endtoend/vtgate/lookup_test.go
index <HASH>..<HASH> 100644
--- a/go/test/endtoend/vtgate/lookup_test.go
+++ b/go/test/endtoend/vtgate/lookup_test.go
@@ -77,6 +77,20 @@ func TestUnownedLookupInsertChecksKeyspaceIdsAreMatching(t *testing.T) {
utils.Exec(t, conn, "delete from t9 WHERE parent_id = 1")
}
+func TestUnownedLookupSelectNull(t *testing.T) {
+ defer cluster.PanicHandler(t)
+
+ ctx := context.Background()
+ conn, err := mysql.Connect(ctx, &vtParams)
+ require.Nil(t, err)
+ defer conn.Close()
+
+ utils.Exec(t, conn, "select * from t8 WHERE t9_id IS NULL")
+
+ // Cleanup
+ utils.Exec(t, conn, "delete from t9 WHERE parent_id = 1")
+}
+
func TestConsistentLookup(t *testing.T) {
defer cluster.PanicHandler(t)
ctx := context.Background()
diff --git a/go/vt/sqlparser/ast_funcs.go b/go/vt/sqlparser/ast_funcs.go
index <HASH>..<HASH> 100644
--- a/go/vt/sqlparser/ast_funcs.go
+++ b/go/vt/sqlparser/ast_funcs.go
@@ -1830,6 +1830,16 @@ func (ae *AliasedExpr) ColumnName() string {
return String(ae.Expr)
}
+// AllAggregation returns true if all the expressions contain aggregation
+func (s SelectExprs) AllAggregation() bool {
+ for _, k := range s {
+ if !ContainsAggregation(k) {
+ return false
+ }
+ }
+ return true
+}
+
func isExprLiteral(expr Expr) bool {
switch expr := expr.(type) {
case *Literal:
diff --git a/go/vt/sqlparser/ast_rewriting.go b/go/vt/sqlparser/ast_rewriting.go
index <HASH>..<HASH> 100644
--- a/go/vt/sqlparser/ast_rewriting.go
+++ b/go/vt/sqlparser/ast_rewriting.go
@@ -575,10 +575,7 @@ func (er *astRewriter) existsRewrite(cursor *Cursor, node *ExistsExpr) {
return
}
- allAggregation := forAll(node.SelectExprs, func(s SelectExpr) bool {
- return ContainsAggregation(s)
- })
- if allAggregation && len(node.GroupBy) == 0 {
+ if len(node.GroupBy) == 0 && node.SelectExprs.AllAggregation() {
// in these situations, we are guaranteed to always get a non-empty result,
// so we can replace the EXISTS with a literal true
cursor.Replace(BoolVal(true))
@@ -593,15 +590,6 @@ func (er *astRewriter) existsRewrite(cursor *Cursor, node *ExistsExpr) {
}
}
-func forAll(coll SelectExprs, test func(SelectExpr) bool) bool {
- for _, k := range coll {
- if !test(k) {
- return false
- }
- }
- return true
-}
-
func bindVarExpression(name string) Expr {
return NewArgument(name)
}
diff --git a/go/vt/vtgate/planbuilder/gen4_planner.go b/go/vt/vtgate/planbuilder/gen4_planner.go
index <HASH>..<HASH> 100644
--- a/go/vt/vtgate/planbuilder/gen4_planner.go
+++ b/go/vt/vtgate/planbuilder/gen4_planner.go
@@ -95,12 +95,14 @@ func gen4SelectStmtPlanner(
}
primitive := plan.Primitive()
- if rb, ok := primitive.(*engine.Route); ok {
+ if rb, ok := primitive.(*engine.Route); ok && isSel {
// this is done because engine.Route doesn't handle the empty result well
// if it doesn't find a shard to send the query to.
// All other engine primitives can handle this, so we only need it when
// Route is the last (and only) instruction before the user sees a result
- rb.NoRoutesSpecialHandling = true
+ if isOnlyDual(sel) || (len(sel.GroupBy) == 0 && sel.SelectExprs.AllAggregation()) {
+ rb.NoRoutesSpecialHandling = true
+ }
}
return primitive, nil
|
Fix failure when Unowned lookup IS NULL (#<I>)
* Add a failing test case showing Gen4 planner failure.
This test case shows a regression in the query planner for queries that use `IS NULL` condition on an unowned lookup vindex column.
|
vitessio_vitess
|
train
|
c24d36a73163f769940db1970a0e904f91d007c7
|
diff --git a/openquake/baselib/parallel.py b/openquake/baselib/parallel.py
index <HASH>..<HASH> 100644
--- a/openquake/baselib/parallel.py
+++ b/openquake/baselib/parallel.py
@@ -225,8 +225,8 @@ def safely_call(func, args):
:param args: the arguments
"""
with Monitor('total ' + func.__name__, measuremem=True) as child:
- pickle = args and hasattr(args[0], 'unpickle')
- if pickle: # measure the unpickling time too
+ if args and hasattr(args[0], 'unpickle'):
+ # args is a list of Pickled objects
args = [a.unpickle() for a in args]
if args and isinstance(args[-1], Monitor):
mon = args[-1]
@@ -365,7 +365,7 @@ class IterResult(object):
next(self.log_percent)
if sent:
self.progress('Sent %s of data in %s task(s)',
- humansize(sum(sent.values())), num_tasks or '?')
+ humansize(sum(sent.values())), num_tasks)
def _log_percent(self):
yield 0
@@ -697,6 +697,7 @@ def wakeup_pool():
executor.pids = list(pids)
+# TODO: remove this?
class BaseStarmap(object):
poolfactory = staticmethod(lambda size: multiprocessing.Pool(size))
add_task_no = Starmap.__dict__['add_task_no']
diff --git a/openquake/calculators/event_based_risk.py b/openquake/calculators/event_based_risk.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/event_based_risk.py
+++ b/openquake/calculators/event_based_risk.py
@@ -284,9 +284,7 @@ class EbrPostCalculator(base.RiskCalculator):
cr, oq.conditional_loss_poes, oq.insured_losses)
cb_inputs = self.cb_inputs('agg_loss_table')
R = len(weights)
- # NB: using the Processmap since celery is hanging; the computation
- # is fast anyway and this part will likely be removed in the future
- result = parallel.Processmap.apply(
+ result = parallel.Starmap.apply(
build_agg_curve, (cb_inputs, self.monitor('')),
concurrent_tasks=self.oqparam.concurrent_tasks).reduce()
agg_curve = numpy.zeros(R, loss_curve_dt)
|
Removed usage of Processmap.apply [skip hazardlib] [demos]
|
gem_oq-engine
|
train
|
be3414294c1cd707525d55486895a52af4c2d04b
|
diff --git a/DbalConsumerHelperTrait.php b/DbalConsumerHelperTrait.php
index <HASH>..<HASH> 100644
--- a/DbalConsumerHelperTrait.php
+++ b/DbalConsumerHelperTrait.php
@@ -32,7 +32,7 @@ trait DbalConsumerHelperTrait
->andWhere('delivery_id IS NULL')
->andWhere('delayed_until IS NULL OR delayed_until <= :delayedUntil')
->andWhere('queue IN (:queues)')
- ->addOrderBy('priority', 'desc')
+ ->addOrderBy('priority', 'asc')
->addOrderBy('published_at', 'asc')
->setParameter('delayedUntil', $now, ParameterType::INTEGER)
->setParameter('queues', array_values($queues), Connection::PARAM_STR_ARRAY)
diff --git a/DbalContext.php b/DbalContext.php
index <HASH>..<HASH> 100644
--- a/DbalContext.php
+++ b/DbalContext.php
@@ -154,7 +154,7 @@ class DbalContext implements Context
$dbalMessageObj->setRedelivered((bool) $dbalMessage['redelivered']);
}
if (isset($dbalMessage['priority'])) {
- $dbalMessageObj->setPriority((int) $dbalMessage['priority']);
+ $dbalMessageObj->setPriority((int) (-1 * $dbalMessage['priority']));
}
if (isset($dbalMessage['published_at'])) {
$dbalMessageObj->setPublishedAt((int) $dbalMessage['published_at']);
@@ -233,14 +233,18 @@ class DbalContext implements Context
$table->addColumn('redeliver_after', Type::BIGINT, ['notnull' => false]);
$table->setPrimaryKey(['id']);
- $table->addIndex(['published_at']);
- $table->addIndex(['queue']);
- $table->addIndex(['priority']);
- $table->addIndex(['delayed_until']);
- $table->addIndex(['priority', 'published_at']);
- $table->addIndex(['redeliver_after']);
$table->addUniqueIndex(['delivery_id']);
+ // try to select a message index
+ $table->addIndex(['delivery_id, delayed_until, queue']);
+ $table->addIndex(['priority', 'published_at']);
+
+ // redeliver failed messages
+ $table->addIndex(['delivery_id', 'redeliver_after']);
+
+ // remove expired messages
+ $table->addIndex(['time_to_live', 'delivery_id']);
+
$sm->createTable($table);
}
}
diff --git a/DbalProducer.php b/DbalProducer.php
index <HASH>..<HASH> 100644
--- a/DbalProducer.php
+++ b/DbalProducer.php
@@ -85,7 +85,7 @@ class DbalProducer implements Producer
'body' => $body,
'headers' => JSON::encode($message->getHeaders()),
'properties' => JSON::encode($message->getProperties()),
- 'priority' => $message->getPriority(),
+ 'priority' => -1 * $message->getPriority(),
'queue' => $destination->getQueueName(),
'redelivered' => false,
'delivery_id' => null,
|
[dbal] Optimize query so an index is used, not filesort.
|
php-enqueue_dbal
|
train
|
fbc689363ae348801d62a19e04d99f72a6311fcf
|
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
@@ -1450,6 +1450,10 @@ class FrameworkExtension extends Extension
->setArgument(2, $config['not_compromised_password']['enabled'])
->setArgument(3, $config['not_compromised_password']['endpoint'])
;
+
+ if (!class_exists(ExpressionLanguage::class)) {
+ $container->removeDefinition('validator.expression_language');
+ }
}
private function registerValidatorMapping(ContainerBuilder $container, array $config, array &$files)
|
remove service if its class doesn't exist
|
symfony_symfony
|
train
|
a87f13cd2bffaa7c228907727c116798a94692e9
|
diff --git a/src/BEAR/Resource/Invoker.php b/src/BEAR/Resource/Invoker.php
index <HASH>..<HASH> 100644
--- a/src/BEAR/Resource/Invoker.php
+++ b/src/BEAR/Resource/Invoker.php
@@ -11,15 +11,16 @@ use Aura\Di\ConfigInterface;
use Aura\Signal\Manager as Signal;
use BEAR\Resource\AbstractObject as ResourceObject;
use BEAR\Resource\Annotation\ParamSignal;
+use BEAR\Resource\Exception\MethodNotAllowed;
use Ray\Aop\Weave;
use Ray\Aop\ReflectiveMethodInvocation;
use ReflectionParameter;
use Ray\Di\Di\Scope;
use Ray\Di\Config;
use Ray\Di\Definition;
+use ReflectionException;
use Ray\Di\Di\Inject;
use Ray\Di\Di\Named;
-
/**
* Resource request invoker
*
@@ -203,7 +204,11 @@ class Invoker implements InvokerInterface
*/
public function getParams($object, $method, array $args)
{
- $parameters = (new \ReflectionMethod($object, $method))->getParameters();
+ try {
+ $parameters = (new \ReflectionMethod($object, $method))->getParameters();
+ } catch (ReflectionException $e) {
+ throw new MethodNotAllowed;
+ }
if ($parameters === []) {
return [];
}
diff --git a/tests/InvokerTest.php b/tests/InvokerTest.php
index <HASH>..<HASH> 100644
--- a/tests/InvokerTest.php
+++ b/tests/InvokerTest.php
@@ -231,4 +231,45 @@ class InvokerTest extends \PHPUnit_Framework_TestCase
$actual = $this->invoker->getConfig();
$this->assertInstanceOf('Ray\Di\Config', $actual);
}
+
+ public function test_getParams()
+ {
+ $ro = new \testworld\ResourceObject\RestBucks\Order;
+ $query = ['id' => 1];
+ $actual = $this->invoker->getParams($ro, 'onGet', $query);
+ $expected = [1];
+ $this->assertSame($expected, $actual);
+ }
+
+ public function test_getParamsInRandomOrder()
+ {
+ $ro = new \testworld\ResourceObject\RestBucks\Payment;
+ // in any order
+ $query = [
+ 'credit_card_number' => '12345678',
+ 'order_id' => 1,
+ 'name' => 'koriym',
+ 'expires' => "20130214",
+ 'amount' => 1
+ ];
+ $actual = $this->invoker->getParams($ro, 'onPut', $query);
+ $expected = [
+ 1,
+ '12345678',
+ '20130214',
+ 'koriym',
+ 1
+ ];
+ $this->assertSame($expected, $actual);
+ }
+
+ /**
+ * @expectedException \BEAR\Resource\Exception\MethodNotAllowed
+ */
+ public function test_getParamsMethodNotExists()
+ {
+ $ro = new \testworld\ResourceObject\RestBucks\Order;
+ $query = ['id' => 1];
+ $actual = $this->invoker->getParams($ro, 'onDelete', $query);
+ }
}
|
[#6] fix to throw MethodNotAllowed exception
|
bearsunday_BEAR.Resource
|
train
|
97f1daa043581e76cdf420c873a6748fa39c6b64
|
diff --git a/lib/torigoya_kit/client.rb b/lib/torigoya_kit/client.rb
index <HASH>..<HASH> 100644
--- a/lib/torigoya_kit/client.rb
+++ b/lib/torigoya_kit/client.rb
@@ -8,33 +8,21 @@ module TorigoyaKit
def initialize(host, port)
@host = host
@port = port
+ @session = new_session()
end
####
def exec_ticket(ticket)
- return new_session().exec_ticket(ticket)
+ return @session.exec_ticket(ticket)
end
def exec_ticket_with_stream(ticket, &block)
- return new_session().exec_ticket_with_stream(ticket, &block)
+ return @session.exec_ticket_with_stream(ticket, &block)
end
####
def update_packages()
- return new_session().update_packages()
- end
-
- ####
- def reload_proc_table()
- return new_session().reload_proc_table()
- end
-
- def update_proc_table()
- return new_session().update_proc_table()
- end
-
- def get_proc_table()
- return new_session().get_proc_table()
+ return @session.update_packages()
end
private
diff --git a/lib/torigoya_kit/session.rb b/lib/torigoya_kit/session.rb
index <HASH>..<HASH> 100644
--- a/lib/torigoya_kit/session.rb
+++ b/lib/torigoya_kit/session.rb
@@ -73,8 +73,13 @@ module TorigoyaKit
elsif res.is_a?(StreamSystemError)
raise res.message
+
+ elsif res.is_a?(StreamExit)
+ break
+
else
raise "Unexpected error: unknown message was recieved (#{res.class})"
+
end
end
return result
@@ -141,8 +146,9 @@ module TorigoyaKit
obj = recv_frame_object()
raise "object is empty" if obj.nil?
- break if obj.is_a?(StreamExit)
+ will_terminate = obj.is_a?(StreamExit)
block.call(obj) unless block.nil?
+ break if will_terminate
end
end
diff --git a/lib/torigoya_kit/stream_result.rb b/lib/torigoya_kit/stream_result.rb
index <HASH>..<HASH> 100644
--- a/lib/torigoya_kit/stream_result.rb
+++ b/lib/torigoya_kit/stream_result.rb
@@ -12,8 +12,8 @@ module TorigoyaKit
#
class StreamOutput
- StdoutFd = 0
- StderrFd = 1
+ StdoutFd = 1
+ StderrFd = 2
def initialize(fd, buffer)
@fd = fd
diff --git a/lib/torigoya_kit/version.rb b/lib/torigoya_kit/version.rb
index <HASH>..<HASH> 100644
--- a/lib/torigoya_kit/version.rb
+++ b/lib/torigoya_kit/version.rb
@@ -1,3 +1,3 @@
module TorigoyaKit
- VERSION = "0.2.0"
+ VERSION = "0.3.0"
end
diff --git a/spec/cases/session_spec.rb b/spec/cases/session_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cases/session_spec.rb
+++ b/spec/cases/session_spec.rb
@@ -3,7 +3,7 @@
require_relative '../spec_helper'
describe :session do
- port = 23432
+ port = 23456
it "session proc exec_ticket" do
s = TorigoyaKit::Session.new("localhost", port)
@@ -18,8 +18,10 @@ describe :session do
expect(t.link.result.exit_status).to eq 0
expect(t.run[0].result.system_error_status).to eq 0
- expect(t.run[0].result.exited).to eq true
- expect(t.run[0].result.exit_status).to eq 0
+ expect(t.run[0].result.exited).to eq false
+ expect(t.run[0].result.signaled).to eq true
+ expect(t.run[0].result.signal).to eq 9
+ #expect(t.run[0].result.exit_status).to eq 0
end
it "session proc update_packages" do
|
fix test. send terminate message. etc
|
yutopp_torigoya_kit
|
train
|
cea56d9b9ca68e35752e1c92cd32c618a5b44c15
|
diff --git a/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MulticastJoiner.java b/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MulticastJoiner.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MulticastJoiner.java
+++ b/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MulticastJoiner.java
@@ -109,37 +109,40 @@ public class MulticastJoiner extends AbstractJoiner {
@Override
public void searchForOtherClusters() {
node.multicastService.send(node.createSplitBrainJoinMessage());
- SplitBrainJoinMessage joinInfo;
+ SplitBrainJoinMessage splitBrainMsg;
try {
- while ((joinInfo = splitBrainJoinMessages.poll(3, TimeUnit.SECONDS)) != null) {
- try {
- if (node.clusterService.getMember(joinInfo.getAddress()) != null) {
- if (logger.isFineEnabled()) {
- logger.fine("Ignoring merge join response, since " + joinInfo.getAddress()
- + " is already a member.");
- }
- continue;
+ while ((splitBrainMsg = splitBrainJoinMessages.poll(3, TimeUnit.SECONDS)) != null) {
+ if (logger.isFineEnabled()) {
+ logger.fine("Received " + splitBrainMsg);
+ }
+ Address targetAddress = splitBrainMsg.getAddress();
+ if (node.clusterService.getMember(targetAddress) != null) {
+ if (logger.isFineEnabled()) {
+ logger.fine("Ignoring merge join response, since " + targetAddress + " is already a member.");
}
+ continue;
+ }
- if (joinInfo.getMemberCount() == 1) {
- // if the other cluster has just single member, that may be a newly starting node instead of a split node
- // wait 2 times 'WAIT_SECONDS_BEFORE_JOIN' seconds before processing merge JoinRequest
- Thread.sleep(2 * node.getProperties().getMillis(GroupProperty.WAIT_SECONDS_BEFORE_JOIN));
- }
+ if (splitBrainMsg.getMemberCount() == 1) {
+ // if the other cluster has just single member, that may be a newly starting node instead of a split node
+ // wait 2 times 'WAIT_SECONDS_BEFORE_JOIN' seconds before processing merge JoinRequest
+ Thread.sleep(2 * node.getProperties().getMillis(GroupProperty.WAIT_SECONDS_BEFORE_JOIN));
+ }
- SplitBrainJoinMessage response = sendSplitBrainJoinMessage(joinInfo.getAddress());
- if (shouldMerge(response)) {
- logger.warning(node.getThisAddress() + " is merging [multicast] to " + joinInfo.getAddress());
- startClusterMerge(joinInfo.getAddress());
- }
- } catch (Exception e) {
- if (logger != null) {
- logger.warning(e);
- }
+ SplitBrainJoinMessage response = sendSplitBrainJoinMessage(targetAddress);
+ if (shouldMerge(response)) {
+ logger.warning(node.getThisAddress() + " is merging [multicast] to " + targetAddress);
+ startClusterMerge(targetAddress);
+ return;
}
+
+ // other side should join to us. broadcast a new SplitBrainJoinMessage.
+ node.multicastService.send(node.createSplitBrainJoinMessage());
}
- } catch (InterruptedException ignored) {
- EmptyStatement.ignore(ignored);
+ } catch (InterruptedException e) {
+ logger.fine("Interrupted: " + e.getMessage());
+ } catch (Exception e) {
+ logger.warning(e);
}
}
|
MulticastJoiner split handler broadcasts message on every round
MulticastJoiner split handler should broadcast a new split brain message
on every round, when it detects other side should join.
Otherwise a live-lock can happen, on every poll, a new message is received but
`shouldMerge()` decides that other side should join to this side. Node cannot
break the message poll loop and as a result cannot broadcast split brain message.
|
hazelcast_hazelcast
|
train
|
1c40d9a47f857c6d797618a4c88fbe499718cb62
|
diff --git a/lib/vlc-client/connection.rb b/lib/vlc-client/connection.rb
index <HASH>..<HASH> 100644
--- a/lib/vlc-client/connection.rb
+++ b/lib/vlc-client/connection.rb
@@ -1,4 +1,5 @@
require 'socket'
+require 'timeout'
module VLC
#
@@ -15,7 +16,7 @@ module VLC
# Connects to VLC RC interface on Client#host and Client#port
def connect
@socket = TCPSocket.new(@host, @port)
- 2.times { read } #Clean the reading channel
+ 2.times { read(0.4) } #Clean the reading channel
true
rescue Errno::ECONNREFUSED => e
raise VLC::ConnectionRefused, "Could not connect to #{@host}:#{@port}: #{e}"
@@ -61,9 +62,20 @@ module VLC
#
# @return [String] the data
#
- def read
- #TODO: Timeouts
- raw_data = @socket.gets.chomp
+ def read(timeout = nil)
+ raw_data = nil
+ if (timeout)
+ begin
+ Timeout.timeout(timeout) do
+ raw_data = @socket.gets.chomp
+ end
+ rescue Timeout::Error
+ return nil #Timed out
+ end
+ else
+ raw_data = @socket.gets.chomp
+ end
+
if (data = process_data(raw_data))
data[1]
else
diff --git a/lib/vlc-client/server.rb b/lib/vlc-client/server.rb
index <HASH>..<HASH> 100644
--- a/lib/vlc-client/server.rb
+++ b/lib/vlc-client/server.rb
@@ -91,12 +91,20 @@ module VLC
private
def process_spawn(detached)
- Process.spawn(headless? ? 'cvlc' : 'vlc',
- '--extraintf', 'rc', '--rc-host', "#{@host}:#{@port}",
- :pgroup => detached,
- :in => '/dev/null',
- :out => '/dev/null',
- :err => '/dev/null')
+ if (ENV['OS'] == 'Windows_NT') # We don't have pgroup, and should write to NUL in case the env doesn't simulate /dev/null
+ Process.spawn(headless? ? 'cvlc' : 'vlc',
+ '--extraintf', 'rc', '--rc-host', "#{@host}:#{@port}",
+ :in => 'NUL',
+ :out => 'NUL',
+ :err => 'NUL')
+ else
+ Process.spawn(headless? ? 'cvlc' : 'vlc',
+ '--extraintf', 'rc', '--rc-host', "#{@host}:#{@port}",
+ :pgroup => detached,
+ :in => '/dev/null',
+ :out => '/dev/null',
+ :err => '/dev/null')
+ end
end
# For ruby 1.8
@@ -134,9 +142,11 @@ module VLC
exit
end
- trap("CLD") do
- @pid = NullObject.new
- @deamon = false
+ if Signal.list["CLD"] # Windows does not support this signal. Or daemons.
+ trap("CLD") do
+ @pid = NullObject.new
+ @deamon = false
+ end
end
end
|
Ruby on Windows (<I>) compatibility
Added Timeout on read, needed to actually start on Windows
-1 TODO
|
mguinada_vlc-client
|
train
|
986b8f55615df073fd190e7dfd19c605dc4a3587
|
diff --git a/guava/src/com/google/common/base/Equivalence.java b/guava/src/com/google/common/base/Equivalence.java
index <HASH>..<HASH> 100644
--- a/guava/src/com/google/common/base/Equivalence.java
+++ b/guava/src/com/google/common/base/Equivalence.java
@@ -90,9 +90,9 @@ public abstract class Equivalence<T> {
* {@code hash(x}} consistently return the same value provided {@code x} remains unchanged
* according to the definition of the equivalence. The hash need not remain consistent from
* one execution of an application to another execution of the same application.
- * <li>It is <i>distributable accross equivalence</i>: for any references {@code x} and {@code y},
+ * <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code y},
* if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary
- * that the hash be distributable accorss <i>inequivalence</i>. If {@code equivalence(x, y)}
+ * that the hash be distributable across <i>inequivalence</i>. If {@code equivalence(x, y)}
* is false, {@code hash(x) == hash(y)} may still be true.
* <li>{@code hash(null)} is {@code 0}.
* </ul>
|
Fix some typos in Equivalence.
-------------
Created by MOE: <URL>
|
google_guava
|
train
|
888718622d9090cd68b072d3cdf69e4004a6087f
|
diff --git a/src/com/google/javascript/jscomp/TypeInference.java b/src/com/google/javascript/jscomp/TypeInference.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/TypeInference.java
+++ b/src/com/google/javascript/jscomp/TypeInference.java
@@ -728,7 +728,9 @@ class TypeInference
// See CodingConvention#getObjectLiteralCase and goog.object.reflect.
// Ignore these types of literals.
ObjectType objectType = ObjectType.cast(type);
- if (objectType == null || n.getBooleanProp(Node.REFLECTED_OBJECT)) {
+ if (objectType == null
+ || n.getBooleanProp(Node.REFLECTED_OBJECT)
+ || objectType.isEnumType()) {
return scope;
}
@@ -1117,7 +1119,7 @@ class TypeInference
}
}
- private void resolvedTemplateType(
+ private static void resolvedTemplateType(
Map<TemplateType, JSType> map, TemplateType template, JSType resolved) {
JSType previous = map.get(template);
if (!resolved.isUnknownType()) {
@@ -1266,7 +1268,7 @@ class TypeInference
* If we give the anonymous object an inferred property of (number|undefined),
* then this code will type-check appropriately.
*/
- private void inferPropertyTypesToMatchConstraint(
+ private static void inferPropertyTypesToMatchConstraint(
JSType type, JSType constraint) {
if (type == null || constraint == null) {
return;
diff --git a/test/com/google/javascript/jscomp/TypeCheckTest.java b/test/com/google/javascript/jscomp/TypeCheckTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/TypeCheckTest.java
+++ b/test/com/google/javascript/jscomp/TypeCheckTest.java
@@ -6810,6 +6810,18 @@ public class TypeCheckTest extends CompilerTypeTestCase {
"required: string");
}
+ public void testEnums() throws Exception {
+ testTypes(
+ "var outer = function() {" +
+ " /** @enum {number} */" +
+ " var Level = {" +
+ " NONE: 0," +
+ " };" +
+ " /** @type {!Level} */" +
+ " var l = Level.NONE;" +
+ "}");
+ }
+
/**
* Tests that the || operator is type checked correctly, that is of
* the type of the first argument or of the second argument. See
|
Fix issue with reflected objects and enums.
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
f50b7da1f3d4a8af6d0d6afd5af9e6431ba1160c
|
diff --git a/lib/em-stathat.rb b/lib/em-stathat.rb
index <HASH>..<HASH> 100644
--- a/lib/em-stathat.rb
+++ b/lib/em-stathat.rb
@@ -97,4 +97,6 @@ module EventMachine
EventMachine::HttpRequest.new(@base_uri + endpoint).post(:body => opts)
end
end
+
+ Stathat = StatHat
end
diff --git a/spec/em-stathat_spec.rb b/spec/em-stathat_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/em-stathat_spec.rb
+++ b/spec/em-stathat_spec.rb
@@ -1,5 +1,10 @@
require 'spec_helper'
+describe EM::Stathat do
+ subject { EM::Stathat }
+ it { should == EM::StatHat }
+end
+
describe EM::StatHat, '.config' do
before do
EM::StatHat.config { } # reset the config
|
add EM::Stathat alias
|
ajsharp_em-stathat
|
train
|
1aaa82f8ebe0825cae66b6a03ec41a8aef229627
|
diff --git a/datadog_checks_dev/datadog_checks/dev/plugin/pytest.py b/datadog_checks_dev/datadog_checks/dev/plugin/pytest.py
index <HASH>..<HASH> 100644
--- a/datadog_checks_dev/datadog_checks/dev/plugin/pytest.py
+++ b/datadog_checks_dev/datadog_checks/dev/plugin/pytest.py
@@ -163,7 +163,9 @@ def dd_agent_check(request, aggregator):
result = run_command(check_command, capture=True)
if AGENT_COLLECTOR_SEPARATOR not in result.stdout:
raise ValueError(
- '{}{}\nCould find `{}` in the output'.format(result.stdout, result.stderr, AGENT_COLLECTOR_SEPARATOR)
+ '{}{}\nCould not find `{}` in the output'.format(
+ result.stdout, result.stderr, AGENT_COLLECTOR_SEPARATOR
+ )
)
_, _, collector_output = result.stdout.partition(AGENT_COLLECTOR_SEPARATOR)
diff --git a/network/README.md b/network/README.md
index <HASH>..<HASH> 100644
--- a/network/README.md
+++ b/network/README.md
@@ -34,6 +34,8 @@ sudo modprobe nf_conntrack_ipv6
## @param collect_connection_state - boolean - required
## Set to true to collect connection states for your interfaces
+ ## Note: this will require either the command `ss` from system package `iproute2` or
+ ## the command `netstat` from the system package `net-tools` to be installed
#
- collect_connection_state: false
```
diff --git a/network/datadog_checks/network/data/conf.yaml.default b/network/datadog_checks/network/data/conf.yaml.default
index <HASH>..<HASH> 100644
--- a/network/datadog_checks/network/data/conf.yaml.default
+++ b/network/datadog_checks/network/data/conf.yaml.default
@@ -10,6 +10,8 @@ instances:
## @param collect_connection_state - boolean - required
## Set to true to collect connection states for your interfaces
+ ## Note: this will require either the command `ss` from system package `iproute2` or
+ ## the command `netstat` from the system package `net-tools` to be installed
#
- collect_connection_state: false
diff --git a/network/tests/common.py b/network/tests/common.py
index <HASH>..<HASH> 100644
--- a/network/tests/common.py
+++ b/network/tests/common.py
@@ -10,6 +10,10 @@ INSTANCE = {"collect_connection_state": True}
INSTANCE_BLACKLIST = {"collect_connection_state": True, "blacklist_conntrack_metrics": ["count"]}
+
+# In order to collect connection state we need `ss` command included in `iproute2` package
+E2E_METADATA = {'start_commands': ['apt-get update', 'apt-get install iproute2 -y']}
+
EXPECTED_METRICS = [
'system.net.bytes_rcvd',
'system.net.bytes_sent',
@@ -19,6 +23,21 @@ EXPECTED_METRICS = [
'system.net.packets_out.error',
]
+E2E_EXPECTED_METRICS = EXPECTED_METRICS + [
+ "system.net.tcp4.closing",
+ "system.net.tcp4.established",
+ "system.net.tcp4.listening",
+ "system.net.tcp4.opening",
+ "system.net.tcp4.time_wait",
+ "system.net.tcp6.closing",
+ "system.net.tcp6.established",
+ "system.net.tcp6.listening",
+ "system.net.tcp6.opening",
+ "system.net.tcp6.time_wait",
+ "system.net.udp4.connections",
+ "system.net.udp6.connections",
+]
+
CONNTRACK_METRICS = [
'system.net.conntrack.acct',
'system.net.conntrack.buckets',
diff --git a/network/tests/conftest.py b/network/tests/conftest.py
index <HASH>..<HASH> 100644
--- a/network/tests/conftest.py
+++ b/network/tests/conftest.py
@@ -12,7 +12,7 @@ from . import common
@pytest.fixture(scope='session')
def dd_environment():
- yield common.INSTANCE
+ yield common.INSTANCE, common.E2E_METADATA
@pytest.fixture
diff --git a/network/tests/test_e2e.py b/network/tests/test_e2e.py
index <HASH>..<HASH> 100644
--- a/network/tests/test_e2e.py
+++ b/network/tests/test_e2e.py
@@ -7,5 +7,5 @@ from . import common
def test_check_e2e(dd_agent_check, instance):
aggregator = dd_agent_check(instance, rate=True)
- for metric in common.EXPECTED_METRICS:
+ for metric in common.E2E_EXPECTED_METRICS:
aggregator.assert_metric(metric)
|
Include iproute2 in network e2e environment (#<I>)
* Include iproute2 in network e2e environment
* Update README
* Clarify either ss or netstat are required
* Fix ValueError reporting
* Fix error message
|
DataDog_integrations-core
|
train
|
257ad9c40c7dbc122c724f1b1479a627673f748d
|
diff --git a/codenerix/context.py b/codenerix/context.py
index <HASH>..<HASH> 100644
--- a/codenerix/context.py
+++ b/codenerix/context.py
@@ -59,6 +59,7 @@ def codenerix_js( request ):
if ALARMS_QUICKLOOP is not None: cnf['alarms_quickloop'] = ALARMS_QUICKLOOP
if ALARMS_ERRORLOOP is not None: cnf['alarms_errorloop'] = ALARMS_ERRORLOOP
cnf['debug'] = str(DEBUG).lower()
+ cnf['session_cookie_age'] = getattr(settings,'SESSION_COOKIE_AGE', None)
cnf['codenerix_css'] = getattr(settings,'CODENERIX_CSS', _('WARNING: CODENERIX_CSS is not set in your configuration!!!'))
cnf['codenerix_js'] = getattr(settings,'CODENERIX_JS', _('WARNING: CODENERIX_JS is not set in your configuration!!!'))
|
New session cookie age passed to all templates so they can logout the user automatically
|
codenerix_django-codenerix
|
train
|
e05e2c15b09726b5fb7e622e30729bd4ac62efa1
|
diff --git a/src/Server/Application.php b/src/Server/Application.php
index <HASH>..<HASH> 100644
--- a/src/Server/Application.php
+++ b/src/Server/Application.php
@@ -69,7 +69,7 @@ class Application
*/
protected $resolves = [
'view', 'files', 'session', 'session.store', 'routes',
- 'db', 'db.factory', 'cache', 'cache.store', 'config',
+ 'db', 'db.factory', 'cache', 'cache.store', 'config', 'cookie',
'encrypter', 'hash', 'router', 'translator', 'url', 'log'
];
|
add cookie to pre-resolved list in sandbox
|
swooletw_laravel-swoole
|
train
|
12a153535b43870364de5b3816eb616f303e7973
|
diff --git a/tinkergraph-gremlin/src/main/java/com/tinkerpop/gremlin/tinkergraph/process/computer/TinkerWorkerPool.java b/tinkergraph-gremlin/src/main/java/com/tinkerpop/gremlin/tinkergraph/process/computer/TinkerWorkerPool.java
index <HASH>..<HASH> 100644
--- a/tinkergraph-gremlin/src/main/java/com/tinkerpop/gremlin/tinkergraph/process/computer/TinkerWorkerPool.java
+++ b/tinkergraph-gremlin/src/main/java/com/tinkerpop/gremlin/tinkergraph/process/computer/TinkerWorkerPool.java
@@ -13,19 +13,17 @@ import java.util.function.Consumer;
*/
public class TinkerWorkerPool {
- private final int numberOfWorkers;
private final List<MapReduce> mapReducers;
public TinkerWorkerPool(final int numberOfWorkers, final Configuration configuration) {
- this.numberOfWorkers = numberOfWorkers;
- this.mapReducers = new ArrayList<>(this.numberOfWorkers);
- for (int i = 0; i < this.numberOfWorkers; i++) {
+ this.mapReducers = new ArrayList<>(numberOfWorkers);
+ for (int i = 0; i < numberOfWorkers; i++) {
this.mapReducers.add(MapReduce.createMapReduce(configuration));
}
}
public void executeMapReduce(final Consumer<MapReduce> worker) {
- final CountDownLatch activeWorkers = new CountDownLatch(this.numberOfWorkers);
+ final CountDownLatch activeWorkers = new CountDownLatch(this.mapReducers.size());
for (final MapReduce mapReduce : this.mapReducers) {
final Thread thread = new Thread(() -> {
worker.accept(mapReduce);
|
minor optimization to TinkerWorkerPool.
|
apache_tinkerpop
|
train
|
7e704c0e815f6b51c39451dcee16458e6edf320b
|
diff --git a/salt/grains/core.py b/salt/grains/core.py
index <HASH>..<HASH> 100644
--- a/salt/grains/core.py
+++ b/salt/grains/core.py
@@ -763,6 +763,7 @@ def _virtual(osdata):
# If a Dom0 or DomU was detected, obviously this is xen
if 'dom' in grains.get('virtual_subtype', '').lower():
grains['virtual'] = 'xen'
+ # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile('/proc/1/cgroup'):
try:
with salt.utils.fopen('/proc/1/cgroup', 'r') as fhr:
|
Moved down container check code below hypervisors to validate containers type running in virtual environment.
Fixes #<I> & #<I>
|
saltstack_salt
|
train
|
de87c649327dd07274ffc669123ac6621added0a
|
diff --git a/lib/vcr/cassette.rb b/lib/vcr/cassette.rb
index <HASH>..<HASH> 100644
--- a/lib/vcr/cassette.rb
+++ b/lib/vcr/cassette.rb
@@ -46,7 +46,21 @@ module VCR
end
def previously_recorded_interactions
- @previously_recorded_interactions ||= []
+ @previously_recorded_interactions ||= if file && File.size?(file)
+ @serializer.deserialize(raw_yaml_content)['http_interactions'].map { |h| HTTPInteraction.from_hash(h) }.tap do |interactions|
+ invoke_hook(:before_playback, interactions)
+
+ interactions.reject! do |i|
+ i.request.uri.is_a?(String) && VCR.request_ignorer.ignore?(i.request)
+ end
+
+ if update_content_length_header?
+ interactions.each { |i| i.response.update_content_length_header }
+ end
+ end
+ else
+ []
+ end
end
def record_http_interaction(interaction)
@@ -109,22 +123,6 @@ module VCR
end
def load_previously_recorded_interactions
- if file && File.size?(file)
- interactions = @serializer.deserialize(raw_yaml_content)['http_interactions'].map { |h| HTTPInteraction.from_hash(h) }
-
- invoke_hook(:before_playback, interactions)
-
- interactions.reject! do |i|
- i.request.uri.is_a?(String) && VCR.request_ignorer.ignore?(i.request)
- end
-
- if update_content_length_header?
- interactions.each { |i| i.response.update_content_length_header }
- end
-
- previously_recorded_interactions.replace(interactions)
- end
-
interactions = should_stub_requests? ? previously_recorded_interactions : []
@http_interactions = HTTPInteractionList.new(
|
Extract logic into accessor method for previously_recorded_interactions.
|
vcr_vcr
|
train
|
949b1b0eb99705c1a5645a5c2b40deeace3d3845
|
diff --git a/Controller/CRUDController.php b/Controller/CRUDController.php
index <HASH>..<HASH> 100644
--- a/Controller/CRUDController.php
+++ b/Controller/CRUDController.php
@@ -283,7 +283,7 @@ class CRUDController extends Controller
if ($this->getRestMethod() == 'DELETE') {
// check the csrf token
- $this->validateCsrfToken('sonata.delete', $request);
+ $this->validateCsrfToken('sonata.delete');
try {
$this->admin->delete($object);
@@ -317,7 +317,7 @@ class CRUDController extends Controller
);
}
- return $this->redirectTo($object, $request);
+ return $this->redirectTo($object);
}
return $this->render($this->admin->getTemplate('delete'), array(
@@ -388,7 +388,7 @@ class CRUDController extends Controller
);
// redirect to edit mode
- return $this->redirectTo($object, $request);
+ return $this->redirectTo($object);
} catch (ModelManagerException $e) {
$this->logModelManagerException($e);
@@ -487,7 +487,7 @@ class CRUDController extends Controller
}
// check the csrf token
- $this->validateCsrfToken('sonata.batch', $request);
+ $this->validateCsrfToken('sonata.batch');
$confirmation = $request->get('confirmation', false);
@@ -517,7 +517,7 @@ class CRUDController extends Controller
$isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
if (method_exists($this, $isRelevantAction)) {
- $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements, $request);
+ $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements);
} else {
$nonRelevantMessage = count($idx) != 0 || $allElements; // at least one item is selected
}
@@ -578,7 +578,7 @@ class CRUDController extends Controller
$query = null;
}
- return call_user_func(array($this, $finalAction), $query, $request);
+ return call_user_func(array($this, $finalAction), $query);
}
/**
@@ -639,7 +639,7 @@ class CRUDController extends Controller
);
// redirect to edit mode
- return $this->redirectTo($object, $request);
+ return $this->redirectTo($object);
} catch (ModelManagerException $e) {
$this->logModelManagerException($e);
|
remove unneeded request argument
This was overlooked in a previous refactoring.
|
sonata-project_SonataAdminBundle
|
train
|
3dcd8bde6f1307b802ac5c5c3f11de135f24d5dd
|
diff --git a/src/Form/Field/Select.php b/src/Form/Field/Select.php
index <HASH>..<HASH> 100644
--- a/src/Form/Field/Select.php
+++ b/src/Form/Field/Select.php
@@ -120,6 +120,8 @@ class Select extends Field
'text' => trans('admin.choose'),
]);
+ $strAllowClear = var_export($allowClear, true);
+
$script = <<<EOT
$(document).off('change', "{$this->getElementClassSelector()}");
$(document).on('change', "{$this->getElementClassSelector()}", function () {
@@ -128,7 +130,7 @@ $(document).on('change', "{$this->getElementClassSelector()}", function () {
target.find("option").remove();
$(target).select2({
placeholder: $placeholder,
- allowClear: $allowClear,
+ allowClear: $strAllowClear,
data: $.map(data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
@@ -164,6 +166,8 @@ EOT;
'text' => trans('admin.choose'),
]);
+ $strAllowClear = var_export($allowClear, true);
+
$script = <<<EOT
var fields = '$fieldsStr'.split('.');
var urls = '$urlsStr'.split('^');
@@ -173,7 +177,7 @@ var refreshOptions = function(url, target) {
target.find("option").remove();
$(target).select2({
placeholder: $placeholder,
- allowClear: $allowClear,
+ allowClear: $strAllowClear,
data: $.map(data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
@@ -211,8 +215,7 @@ EOT;
*/
public function model($model, $idField = 'id', $textField = 'name')
{
- if (
- !class_exists($model)
+ if (!class_exists($model)
|| !in_array(Model::class, class_parents($model))
) {
throw new \InvalidArgumentException("[$model] must be a valid model class");
|
fixed the problem that (bool) false is interpreted to '' in text
|
z-song_laravel-admin
|
train
|
0c449811e16a210a7c6a92ce33aafc6386b5e0c2
|
diff --git a/miflora/miflora_poller.py b/miflora/miflora_poller.py
index <HASH>..<HASH> 100644
--- a/miflora/miflora_poller.py
+++ b/miflora/miflora_poller.py
@@ -28,7 +28,7 @@ class MiFloraPoller(object):
A class to read data from Mi Flora plant sensors.
"""
- def __init__(self, mac, backend, cache_timeout=600, retries=3, adapter='hci0'):
+ def __init__(self, mac, backend, cache_timeout=600, adapter='hci0'):
"""
Initialize a Mi Flora Poller for the given MAC address.
"""
@@ -39,8 +39,6 @@ class MiFloraPoller(object):
self._cache_timeout = timedelta(seconds=cache_timeout)
self._last_read = None
self._fw_last_read = None
- self.retries = retries
- self.ble_timeout = 10
self.lock = Lock()
self._firmware_version = None
self.battery = None
|
Removed unused "retries" and "ble_timeout"
|
open-homeautomation_miflora
|
train
|
98253d169dbbc6d2010cd120190a54900236459f
|
diff --git a/parsl/dataflow/dflow.py b/parsl/dataflow/dflow.py
index <HASH>..<HASH> 100644
--- a/parsl/dataflow/dflow.py
+++ b/parsl/dataflow/dflow.py
@@ -126,7 +126,7 @@ class DataFlowKernel(object):
checkpoint_period = (h * 3600) + (m * 60) + s
self._checkpoint_timer = Timer(self.checkpoint, interval=checkpoint_period)
except Exception as e:
- logger.error("invalid checkpoint_period provided:{0} expected HH:MM:SS".format(period))
+ logger.error("invalid checkpoint_period provided:{0} expected HH:MM:SS".format(config.checkpoint_period))
self._checkpoint_timer = Timer(self.checkpoint, interval=(30 * 60))
if any([x.managed for x in config.executors]):
|
Fix incorrect variable name logging checkpoint_period parsing problem
|
Parsl_parsl
|
train
|
f2289c8903eb126bb888b784116fa31d3691a244
|
diff --git a/example/client/main.go b/example/client/main.go
index <HASH>..<HASH> 100644
--- a/example/client/main.go
+++ b/example/client/main.go
@@ -16,6 +16,7 @@ import (
func main() {
verbose := flag.Bool("v", false, "verbose")
quiet := flag.Bool("q", false, "don't print the data")
+ insecure := flag.Bool("insecure", false, "skip certificate verification")
flag.Parse()
urls := flag.Args()
@@ -30,7 +31,8 @@ func main() {
roundTripper := &http3.RoundTripper{
TLSClientConfig: &tls.Config{
- RootCAs: testdata.GetRootCA(),
+ RootCAs: testdata.GetRootCA(),
+ InsecureSkipVerify: *insecure,
},
}
defer roundTripper.Close()
|
add a flag to skip certificate verification to the example client
|
lucas-clemente_quic-go
|
train
|
741f2f37900b4601896037eb2e4223707361f1b8
|
diff --git a/src/test/java/io/github/bonigarcia/wdm/test/CustomTargetTest.java b/src/test/java/io/github/bonigarcia/wdm/test/CustomTargetTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/io/github/bonigarcia/wdm/test/CustomTargetTest.java
+++ b/src/test/java/io/github/bonigarcia/wdm/test/CustomTargetTest.java
@@ -14,6 +14,7 @@
*/
package io.github.bonigarcia.wdm.test;
+import static java.lang.System.getProperty;
import static java.lang.System.setProperty;
import static java.lang.invoke.MethodHandles.lookup;
import static java.nio.file.Files.createTempDirectory;
@@ -47,19 +48,17 @@ public class CustomTargetTest {
@Before
public void setup() throws IOException {
tmpFolder = createTempDirectory("");
- log.info("Using temporal folder {} as cache", tmpFolder);
+ setProperty("wdm.targetPath", tmpFolder.toString());
+ log.info("Using temporal folder {} as cache [{}]", tmpFolder,
+ getProperty("wdm.targetPath"));
}
@Test
public void testTargetPath() {
- String cacheFolder = tmpFolder.toString();
- setProperty("wdm.targetPath", cacheFolder);
ChromeDriverManager.getInstance().setup();
-
String binaryPath = ChromeDriverManager.getInstance().getBinaryPath();
log.info("Binary path {}", binaryPath);
-
- assertThat(binaryPath, startsWith(cacheFolder));
+ assertThat(binaryPath, startsWith(tmpFolder.toString()));
}
@After
|
Include more logging traces in custom target test
|
bonigarcia_webdrivermanager
|
train
|
8412ea8ae10ef9bce48a94d770e6e5391f82a297
|
diff --git a/lib/amqp-spec/rspec.rb b/lib/amqp-spec/rspec.rb
index <HASH>..<HASH> 100644
--- a/lib/amqp-spec/rspec.rb
+++ b/lib/amqp-spec/rspec.rb
@@ -122,7 +122,8 @@ module AMQP
def amqp opts={}, &block
opts = self.class.default_options.merge opts
spec_timeout = opts.delete(:spec_timeout) || self.class.default_timeout
- @event_loop = EventLoop.new(:amqp, opts, spec_timeout, &block)
+ hooks = self.class.em_hooks
+ @event_loop = EventLoop.new(:amqp, opts, spec_timeout, hooks, &block)
@event_loop.run
end
@@ -131,7 +132,8 @@ module AMQP
#
def em(spec_timeout = self.class.default_timeout, &block)
spec_timeout = spec_timeout[:spec_timeout] || self.class.default_timeout if spec_timeout.is_a?(Hash)
- @event_loop = EventLoop.new(:em, spec_timeout, &block)
+ hooks = self.class.em_hooks
+ @event_loop = EventLoop.new(:em, spec_timeout, hooks, &block)
@event_loop.run
end
@@ -150,8 +152,8 @@ module AMQP
# Represents any type of spec supposed to run inside event loop
class EventLoop
- def initialize type, opts = {}, spec_timeout, &block
- @type, @spec_timeout, @opts, @block = type, spec_timeout, opts, block
+ def initialize type, opts = {}, spec_timeout, hooks, &block
+ @type, @opts, @spec_timeout, @hooks, @block = type, opts, spec_timeout, hooks, block
end
def run
@@ -265,7 +267,7 @@ module AMQP
# Stops EM loop, executes optional block, finishes off fiber and raises exception if any
#
def finish_em_spec_fiber
-# self.class.em_hooks[:after][:each].reverse.each { |hook| instance_eval_with_rescue(&hook) }
+@hooks[:after][:each].reverse.each { |hook| instance_eval_with_rescue(&hook) }
EM.stop_event_loop if EM.reactor_running?
yield if block_given?
@_em_spec_fiber.resume if @_em_spec_fiber.alive?
@@ -284,7 +286,7 @@ module AMQP
def run_em_spec_fiber spec_timeout, opts = {}, &block
EM.run do
# Running em_before hooks
-# self.class.em_hooks[:before][:each].each { |hook| instance_eval(&hook) }
+ @hooks[:before][:each].each { |hook| instance_eval(&hook) }
@_em_spec_exception = nil
timeout(spec_timeout) if spec_timeout
|
AMQPHelper reimplemented with EventLoop class, sync and hooks dropped for now
|
arvicco_amqp-spec
|
train
|
ff9a1f670905f42288253a554f12ab610f2d29cd
|
diff --git a/src/Support/Download/UrlDownloader.php b/src/Support/Download/UrlDownloader.php
index <HASH>..<HASH> 100644
--- a/src/Support/Download/UrlDownloader.php
+++ b/src/Support/Download/UrlDownloader.php
@@ -35,6 +35,8 @@ class UrlDownloader implements UrlDownloaderInterface
{
$localPath = $this->makeLocalTemporaryPath();
+ $url = $this->normalizeUrl($url);
+
$this->downloadToTempLocalPath($url, $localPath);
// Remove the query string if it exists, to make sure the extension is valid
@@ -162,4 +164,15 @@ class UrlDownloader implements UrlDownloaderInterface
return $newPath;
}
+ /**
+ * Normalizes URL for safe cURL use.
+ *
+ * @param string $url
+ * @return string
+ */
+ protected function normalizeUrl($url)
+ {
+ return str_replace(' ', '+', $url);
+ }
+
}
|
Fixed issue downloading URLs with spaces using cURL
|
czim_file-handling
|
train
|
2e37a7d02b09c75113a3f7f679299507786644f2
|
diff --git a/app/util/index.js b/app/util/index.js
index <HASH>..<HASH> 100644
--- a/app/util/index.js
+++ b/app/util/index.js
@@ -3,20 +3,108 @@ const uuid = require('uuid/v4');
const definitions = {};
-const replaceRef = obj => {
+const replaceRefForRequest = obj => {
if (!obj) return;
Object.keys(obj).forEach(item => {
- if (!obj[item]) return;
-
if (obj[item].$ref) {
obj[item] = definitions[obj[item].$ref];
} else if (typeof obj[item] === 'object') {
- replaceRef(obj[item]);
+ replaceRefForRequest(obj[item]);
}
});
};
+const replaceRefForResponse = obj => {
+ if (obj.$ref) {
+ obj.$ref = definitions[obj.$ref];
+ } else {
+ Object.keys(obj).forEach(item => {
+ if (typeof obj[item] === 'object') {
+ replaceRefForResponse(obj[item]);
+ }
+ });
+ }
+};
+
+// up object level when find '$ref'
+const repleceRefStringForResponse = obj => {
+ const jsonStr = JSON.stringify(obj);
+ const parseList = [];
+ const deleteIdxs = [];
+ const keyword = '"$ref":{';
+
+ /**
+ * '{"$ref":{"foo": "bar"}}' => ['{', '"$ref":{', '"foo": "bar"','}', '}']
+ */
+ const scan = () => {
+ let idx = 0;
+ let tmp = '';
+
+ function clearTmp() {
+ if (tmp) {
+ parseList.push(tmp);
+ tmp = '';
+ }
+ }
+
+ while (idx < jsonStr.length) {
+ const char = jsonStr[idx];
+ if (char === '{') {
+ if (tmp + char === keyword) {
+ parseList.push(tmp + char);
+ tmp = '';
+ } else {
+ clearTmp();
+ parseList.push(char);
+ }
+ } else if (char === '}') {
+ clearTmp();
+ parseList.push(char);
+ } else {
+ tmp += char;
+ }
+ idx++;
+ }
+ };
+
+ /**
+ * recursion parseList, collecte index
+ */
+ const find = () => {
+ let start = 0; // 第n个{
+ const list = [];
+ parseList.forEach((v, i) => {
+ if (v === '{') {
+ start += 1;
+ }
+ if (v === '}') {
+
+ // {{{}}}
+ if (list.indexOf(start) >= 0) {
+ deleteIdxs.push(i);
+ }
+ start -= 1;
+ }
+ if (v === keyword) {
+ deleteIdxs.push(i);
+ list.push(start); // key include '{'
+ }
+ });
+ };
+
+ scan();
+ find();
+
+ const result = parseList.map((v, i) => {
+ if (deleteIdxs.indexOf(i) >= 0) {
+ return '';
+ }
+ return v;
+ }).join('');
+ return JSON.parse(result);
+};
+
const handleParamRequestSchema = (param, paramRequestSchema) => {
if (param.schema) {
paramRequestSchema.properties[param.name] = {
@@ -40,7 +128,7 @@ const swaggerConvert = data => {
});
Object.keys(definitions).forEach(definition => {
- replaceRef(definitions[definition]);
+ replaceRefForRequest(definitions[definition]);
});
Object.keys(data.paths).forEach(pathname => {
@@ -51,14 +139,11 @@ const swaggerConvert = data => {
const info = data.paths[pathname][method];
const interfaceUniqId = uuid();
- const willHandleResponse = info.responses
+ const responseSchema = info.responses
&& info.responses['200']
&& info.responses['200'].schema;
- replaceRef(info.parameters);
- if (willHandleResponse) {
- replaceRef([ info.responses['200'].schema ]);
- }
+ replaceRefForRequest(info.parameters);
// handle Schema request param
const paramRequestSchema = {
@@ -77,8 +162,19 @@ const swaggerConvert = data => {
type: 'object',
properties: {},
};
- if (willHandleResponse) {
- paramReponseSchema = info.responses['200'].schema;
+ if (responseSchema) {
+ const needHandleRef = JSON.stringify(responseSchema).indexOf('$ref') !== -1;
+
+ // handle $ref
+ if (needHandleRef) {
+ replaceRefForResponse(responseSchema);
+ paramReponseSchema = repleceRefStringForResponse(responseSchema);
+ } else {
+ if (responseSchema.type === 'object') {
+ delete responseSchema.type;
+ paramReponseSchema.properties = responseSchema;
+ }
+ }
}
const interfaceData = {
|
fix: recover swagger response data (#<I>)
|
macacajs_macaca-datahub
|
train
|
8f256d28b6fa96f3e4d2a20f771198a18903eb17
|
diff --git a/ext/gsl/extconf.rb b/ext/gsl/extconf.rb
index <HASH>..<HASH> 100644
--- a/ext/gsl/extconf.rb
+++ b/ext/gsl/extconf.rb
@@ -21,8 +21,20 @@ def gsl_have_library(func)
have_func(func) if have_library('gsl', func)
end
-def gsl_dir_config(target)
- dir_config(target, $sitearchdir, $sitearchdir)
+def gsl_dir_config(target, idir = nil, ldir = idir)
+ dir_config(target, idir || $sitearchdir, ldir || $sitearchdir)
+end
+
+def gsl_gem_config(target, dir = 'ext')
+ path = begin
+ require 'rubygems'
+
+ spec = Gem::Specification.find_by_path("#{target}.h")
+ File.join(spec.full_gem_path, dir) if spec
+ rescue LoadError
+ end
+
+ gsl_dir_config(target, path)
end
$CFLAGS += ' -Wall -Iinclude'
@@ -94,22 +106,13 @@ gsl_have_library('gsl_poly_solve_quartic')
gsl_def(:HAVE_GNU_GRAPH) if find_executable('graph')
-narray = gsl_dir_config('narray')
-
-begin
- require 'rubygems'
-
- if spec = Gem::Specification.find_by_path('narray.h')
- $LOCAL_LIBS = "-L#{File.join(narray = spec.full_gem_path, 'src')} " + $LOCAL_LIBS
- $CPPFLAGS = "-I#{File.join(narray, spec.require_path)} " + $CPPFLAGS
- end
-rescue LoadError
-end
+gsl_gem_config('narray', 'src')
have_header('narray.h')
-have_library('narray') if narray && RUBY_PLATFORM =~ /cygwin|mingw/
+have_library('narray') if RUBY_PLATFORM =~ /cygwin|mingw/
-if !arg_config('--disable-tamu-anova') && gsl_dir_config('tamu_anova')
+unless arg_config('--disable-tamu-anova')
+ gsl_dir_config('tamu_anova')
gsl_have_header('tamuanova', 'tamu_anova/tamu_anova.h')
end
|
ext/gsl/extconf.rb: Refactored and extracted helper method gsl_gem_config.
|
SciRuby_rb-gsl
|
train
|
d73a63cbcb6e635a12aa427d753815fc389298a4
|
diff --git a/test/frontend/rest-adaptor.test.js b/test/frontend/rest-adaptor.test.js
index <HASH>..<HASH> 100644
--- a/test/frontend/rest-adaptor.test.js
+++ b/test/frontend/rest-adaptor.test.js
@@ -136,28 +136,21 @@ suite('REST API', function() {
plugins: [testPlugin]
});
- var mockedReceiver = nodemock
- .mock('receive')
- .takes('api OK');
+ backend.reserveResponse(function(request) {
+ return utils.createReplyPacket(request,
+ {
+ statusCode: 200,
+ body: 'API response',
+ });
+ });
utils.get('/path/to/droonga/path/to/api')
.next(function(response) {
- mockedReceiver.receive(response.body);
- });
-
- Deferred
- .wait(0.01)
- .next(function() {
backend.assertReceived([{ type: 'api',
body: 'api requested' }]);
-
- return backend.sendResponse(backend.getMessages()[0],
- 'api.result',
- 'api OK?');
- })
- .wait(0.01)
- .next(function() {
- mockedReceiver.assertThrows();
+ assert.deepEqual(response,
+ { statusCode: 200,
+ body: JSON.stringify('api OK') });
done();
})
.error(function(error) {
|
test: return response on receiving request instead of using wait()
wait() makes test fragile.
|
droonga_express-droonga
|
train
|
a85a3a0b492978a222366e73a5afbe55df2f4645
|
diff --git a/itests/common/src/main/java/org/wildfly/camel/test/common/rule/ExecutableResource.java b/itests/common/src/main/java/org/wildfly/camel/test/common/rule/ExecutableResource.java
index <HASH>..<HASH> 100644
--- a/itests/common/src/main/java/org/wildfly/camel/test/common/rule/ExecutableResource.java
+++ b/itests/common/src/main/java/org/wildfly/camel/test/common/rule/ExecutableResource.java
@@ -37,6 +37,7 @@ public class ExecutableResource extends ExternalResource {
private String downloadFrom;
private String args;
private int waitForPort;
+ private boolean managed = true;
private Process process;
public ExecutableResource() {
@@ -46,12 +47,17 @@ public class ExecutableResource extends ExternalResource {
protected void before() throws Throwable {
Assume.assumeFalse("Unknown environment: " + EnvironmentUtils.getOSName(), EnvironmentUtils.isUnknown());
downloadExecutable();
- startProcess();
+
+ if (isManaged()) {
+ startProcess();
+ }
}
@Override
protected void after() {
- stopProcess();
+ if (isManaged()) {
+ stopProcess();
+ }
}
private void downloadExecutable() throws IOException {
@@ -76,7 +82,7 @@ public class ExecutableResource extends ExternalResource {
}
}
- private void startProcess() throws Exception {
+ public void startProcess() throws Exception {
File file;
if (this.executable == "java") {
file = EnvironmentUtils.getJavaExecutablePath().toFile();
@@ -116,7 +122,7 @@ public class ExecutableResource extends ExternalResource {
}
}
- private void stopProcess() {
+ public void stopProcess() {
if (process != null) {
LOG.info("Terminating process");
process.destroy();
@@ -208,11 +214,20 @@ public class ExecutableResource extends ExternalResource {
this.executable = executable;
}
+ public boolean isManaged() {
+ return managed;
+ }
+
+ public void setManaged(boolean managed) {
+ this.managed = managed;
+ }
+
public class ExecutableResourceBuilder {
private String executable;
private String downloadFrom;
private String args;
private int waitForPort;
+ private boolean managed;
public ExecutableResourceBuilder executable(String executable) {
String fileSuffix = "";
@@ -238,12 +253,18 @@ public class ExecutableResource extends ExternalResource {
return this;
}
+ public ExecutableResourceBuilder managed(boolean managed) {
+ this.managed = managed;
+ return this;
+ }
+
public ExecutableResource build() {
ExecutableResource resource = new ExecutableResource();
resource.setExecutable(this.executable);
resource.setDownloadFrom(this.downloadFrom);
resource.setArgs(this.args);
resource.setWaitForPort(this.waitForPort);
+ resource.setManaged(this.managed);
return resource;
}
}
diff --git a/itests/standalone/extra/src/main/java/org/wildfly/camel/test/nats/NatsIntegrationTest.java b/itests/standalone/extra/src/main/java/org/wildfly/camel/test/nats/NatsIntegrationTest.java
index <HASH>..<HASH> 100644
--- a/itests/standalone/extra/src/main/java/org/wildfly/camel/test/nats/NatsIntegrationTest.java
+++ b/itests/standalone/extra/src/main/java/org/wildfly/camel/test/nats/NatsIntegrationTest.java
@@ -34,6 +34,7 @@ import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
+import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -54,6 +55,7 @@ public class NatsIntegrationTest {
.executable(String.format("%s/gnatsd", resolveExecutableName()))
.args("-DV -a 127.0.0.1")
.waitForPort(4222)
+ .managed(false)
.build();
@Deployment
@@ -72,8 +74,13 @@ public class NatsIntegrationTest {
@Test
public void testNatsRoutes() throws Exception {
+ // There is no gnatsd binary for AIX
+ Assume.assumeFalse("[#1684] NatsIntegrationTest fails on AIX", EnvironmentUtils.isAIX());
+
CamelContext camelctx = new DefaultCamelContext();
try {
+ nats.startProcess();
+
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
@@ -110,6 +117,7 @@ public class NatsIntegrationTest {
} finally {
camelctx.stop();
+ nats.stopProcess();
}
}
|
[resolves #<I>] NatsIntegrationTest fails on AIX
|
wildfly-extras_wildfly-camel
|
train
|
715d7f3240401912355d79616dc97d3e221d669e
|
diff --git a/routes/modelIndex.js b/routes/modelIndex.js
index <HASH>..<HASH> 100644
--- a/routes/modelIndex.js
+++ b/routes/modelIndex.js
@@ -3,8 +3,6 @@
/* GET /admin/model/:model/list */
var route = function (req, res) {
- console.log(req.body);
-
var total = Number(req.linz.records.total),
pageSize = Number(req.linz.records.pageSize),
page = Number(req.linz.records.page),
|
Removed a console.log that shouldn't be there.
|
linzjs_linz
|
train
|
4ac4fed4e28d787763e7229670ac28ace39e9032
|
diff --git a/mockserver-client-javascript/src/test/javascript/no_proxy/mockServerClientTest.js b/mockserver-client-javascript/src/test/javascript/no_proxy/mockServerClientTest.js
index <HASH>..<HASH> 100644
--- a/mockserver-client-javascript/src/test/javascript/no_proxy/mockServerClientTest.js
+++ b/mockserver-client-javascript/src/test/javascript/no_proxy/mockServerClientTest.js
@@ -1019,7 +1019,7 @@ describe("mockServerClient client:", function () {
// first request
expect(requests[0].path).toEqual('/somePathOne');
expect(requests[0].method).toEqual('POST');
- expect(requests[0].body.string).toEqual('someBody');
+ expect(requests[0].body).toEqual('someBody');
// second request
expect(requests[1].path).toEqual('/somePathOne');
expect(requests[1].method).toEqual('GET');
@@ -1052,7 +1052,7 @@ describe("mockServerClient client:", function () {
// first request
expect(requests[0].path).toEqual('/somePathOne');
expect(requests[0].method).toEqual('POST');
- expect(requests[0].body.string).toEqual('someBody');
+ expect(requests[0].body).toEqual('someBody');
// second request
expect(requests[1].path).toEqual('/somePathOne');
expect(requests[1].method).toEqual('GET');
@@ -1089,7 +1089,7 @@ describe("mockServerClient client:", function () {
// first request
expect(requests[0].path).toEqual('/somePathOne');
expect(requests[0].method).toEqual('POST');
- expect(requests[0].body.string).toEqual('someBody');
+ expect(requests[0].body).toEqual('someBody');
// second request
expect(requests[1].path).toEqual('/somePathOne');
expect(requests[1].method).toEqual('GET');
@@ -1129,7 +1129,7 @@ describe("mockServerClient client:", function () {
// first request
expect(requests[0].path).toEqual('/somePathOne');
expect(requests[0].method).toEqual('POST');
- expect(requests[0].body.string).toEqual('someBody');
+ expect(requests[0].body).toEqual('someBody');
// second request
expect(requests[1].path).toEqual('/somePathOne');
expect(requests[1].method).toEqual('GET');
diff --git a/mockserver-core/src/main/java/org/mockserver/mappers/ContentTypeMapper.java b/mockserver-core/src/main/java/org/mockserver/mappers/ContentTypeMapper.java
index <HASH>..<HASH> 100644
--- a/mockserver-core/src/main/java/org/mockserver/mappers/ContentTypeMapper.java
+++ b/mockserver-core/src/main/java/org/mockserver/mappers/ContentTypeMapper.java
@@ -47,6 +47,8 @@ public class ContentTypeMapper {
|| contentType.contains("csv")
|| contentType.contains("html")
|| contentType.contains("xhtml")
+ || contentType.contains("form")
+ || contentType.contains("urlencoded")
|| contentType.contains("xml");
if (!utf8Body) {
binary = contentType.contains("ogg")
diff --git a/mockserver-core/src/test/java/org/mockserver/mappers/ContentTypeMapperTest.java b/mockserver-core/src/test/java/org/mockserver/mappers/ContentTypeMapperTest.java
index <HASH>..<HASH> 100644
--- a/mockserver-core/src/test/java/org/mockserver/mappers/ContentTypeMapperTest.java
+++ b/mockserver-core/src/test/java/org/mockserver/mappers/ContentTypeMapperTest.java
@@ -34,6 +34,7 @@ public class ContentTypeMapperTest {
"application/xop+xml",
"application/xslt+xml",
"application/xspf+xml",
+ "application/x-www-form-urlencoded",
"image/svg+xml",
"text/css",
"text/csv",
|
adding missing content type for application/x-www-form-urlencoded which was incorrectly being treated as binary
|
jamesdbloom_mockserver
|
train
|
0bf1cfad8f69441a4d4091689fb0dd9876b0c1dc
|
diff --git a/lib/selenium_standalone_dsl/base.rb b/lib/selenium_standalone_dsl/base.rb
index <HASH>..<HASH> 100644
--- a/lib/selenium_standalone_dsl/base.rb
+++ b/lib/selenium_standalone_dsl/base.rb
@@ -64,12 +64,12 @@ module SeleniumStandaloneDSL
select.select_by :text, text
end
- def has_element?(method, selector)
- if method == :text
+ def has_element?(selector, find_by: :link_text)
+ if [:text, :link_text].include?(find_by)
@driver.page_source.match(selector) != nil
else
begin
- @driver.find_element(method, selector).is_a? Selenium::WebDriver::Element
+ @driver.find_element(find_by, selector).is_a? Selenium::WebDriver::Element
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
|
change the method has_element? for API usability
|
acro5piano_selenium_standalone_dsl
|
train
|
dd403f9926564c62135284ac61c31c39e95fba8d
|
diff --git a/test/class_methods_test.rb b/test/class_methods_test.rb
index <HASH>..<HASH> 100644
--- a/test/class_methods_test.rb
+++ b/test/class_methods_test.rb
@@ -148,7 +148,7 @@ class BelongsToErrorsTest < ActiveSupport::TestCase
assert_equal Library::Category, Library::SubcategoriesController.resources_configuration[:category][:parent_class]
end
- def test_belongs_to_without_namesoace_sets_parent_class_properly
+ def test_belongs_to_without_namespace_sets_parent_class_properly
FoldersController.send(:belongs_to, :book)
assert_equal Book, FoldersController.resources_configuration[:book][:parent_class]
end
|
typo in test/class_methods_test.rb
|
activeadmin_inherited_resources
|
train
|
147de861dfe55538600bcc20e41484f11d9c60d1
|
diff --git a/dropwizard-logging/src/main/java/io/dropwizard/logging/LoggingFactory.java b/dropwizard-logging/src/main/java/io/dropwizard/logging/LoggingFactory.java
index <HASH>..<HASH> 100644
--- a/dropwizard-logging/src/main/java/io/dropwizard/logging/LoggingFactory.java
+++ b/dropwizard-logging/src/main/java/io/dropwizard/logging/LoggingFactory.java
@@ -30,6 +30,7 @@ import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
+import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -37,6 +38,7 @@ public class LoggingFactory {
private static final Duration LOGGER_CONTEXT_AWAITING_TIMEOUT = Duration.seconds(10);
private static final Duration LOGGER_CONTEXT_AWAITING_SLEEP_TIME = Duration.milliseconds(100);
+ private static final ReentrantLock MBEAN_REGISTRATION_LOCK = new ReentrantLock();
// initially configure for WARN+ console logging
public static void bootstrap() {
@@ -181,6 +183,7 @@ public class LoggingFactory {
}
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+ MBEAN_REGISTRATION_LOCK.lock();
try {
final ObjectName objectName = new ObjectName("io.dropwizard:type=Logging");
if (!server.isRegistered(objectName)) {
@@ -192,6 +195,8 @@ public class LoggingFactory {
} catch (MalformedObjectNameException | InstanceAlreadyExistsException |
NotCompliantMBeanException | MBeanRegistrationException e) {
throw new RuntimeException(e);
+ } finally {
+ MBEAN_REGISTRATION_LOCK.unlock();
}
configureInstrumentation(root, metricRegistry);
|
Add MBean registration lock
We have a data race, if LoggerFactory is created in parallel.
Therefore we should guard the process of MBean registration
|
dropwizard_dropwizard
|
train
|
7ea8c0f548146381c1878cd1a678e6a322884868
|
diff --git a/lib/Client.js b/lib/Client.js
index <HASH>..<HASH> 100644
--- a/lib/Client.js
+++ b/lib/Client.js
@@ -117,7 +117,7 @@ Client.prototype.connect = function(config, cb) {
this.connecting = true;
- process.nextTick(function() {
+ setImmediate(function() {
// doing a manual resolve prevents libmariadbclient from doing a blocking
// DNS resolve
if (!isIP(cfg.host)) {
|
Client: Client: make sure connect()s get delayed appropriately
|
mscdex_node-mariasql
|
train
|
5e86379da4274303e53f5ec7b97c57fe27aa4634
|
diff --git a/Test/Case/Model/ImageStorageTest.php b/Test/Case/Model/ImageStorageTest.php
index <HASH>..<HASH> 100644
--- a/Test/Case/Model/ImageStorageTest.php
+++ b/Test/Case/Model/ImageStorageTest.php
@@ -88,6 +88,23 @@ class ImageStorageTest extends FileStorageTestCase {
$Folder = new Folder($path);
$folderResult = $Folder->read();
$this->assertEqual(count($folderResult[1]), 4);
+
+
+ $Event = new CakeEvent('ImageVersion.removeVersion', $this->Image, array(
+ 'record' => $result,
+ 'storage' => StorageManager::adapter('Local'),
+ 'operations' => array(
+ 't200' => array(
+ 'thumbnail' => array(
+ 'mode' => 'outbound',
+ 'width' => 200, 'height' => 200)))));
+
+ CakeEventManager::instance()->dispatch($Event);
+
+ $path = $this->testPath . $result['FileStorage']['path'];
+ $Folder = new Folder($path);
+ $folderResult = $Folder->read();
+ $this->assertEqual(count($folderResult[1]), 3);
}
}
\ No newline at end of file
|
Improving the ImageStorageTest.php
|
burzum_cakephp-file-storage
|
train
|
0765f0e6d5d4ca9156047f60e8635184dd14cbce
|
diff --git a/lib/detect-port.js b/lib/detect-port.js
index <HASH>..<HASH> 100644
--- a/lib/detect-port.js
+++ b/lib/detect-port.js
@@ -2,6 +2,7 @@
const debug = require('debug')('detect-port');
const net = require('net');
+const address = require('address');
module.exports = (port, callback) => {
if (typeof port === 'function') {
@@ -26,28 +27,58 @@ module.exports = (port, callback) => {
};
function tryListen(port, maxPort, callback) {
- const server = new net.Server();
-
- server.on('error', err => {
- debug('listen %s error: %s', port, err);
- if (port === 0) {
- return callback(err);
- }
-
+ function handleError() {
port++;
if (port >= maxPort) {
debug('port: %s >= maxPort: %s, give up and use random port', port, maxPort);
port = 0;
maxPort = 0;
}
+ tryListen(port, maxPort, callback);
+ }
+
+ // 1. check 0.0.0.0
+ listen(port, null, (err, realPort) => {
+ // ignore random listening
+ if (port === 0) {
+ return callback(err, realPort);
+ }
+
+ if (err) {
+ return handleError(err);
+ }
+
+ // 2. check localhost
+ listen(port, 'localhost', err => {
+ if (err) {
+ return handleError(err);
+ }
+
+ // 3. check current ip
+ listen(port, address.ip(), (err, realPort) => {
+ if (err) {
+ return handleError(err);
+ }
+
+ callback(null, realPort);
+ });
+ });
+ });
+}
+
+function listen(port, hostname, callback) {
+ const server = new net.Server();
+
+ server.on('error', err => {
+ debug('listen %s:%s error: %s', hostname, port, err);
server.close();
- return tryListen(port, maxPort, callback);
+ return callback(err);
});
- server.listen({ port }, () => {
+ server.listen(port, hostname, () => {
port = server.address().port;
server.close();
- debug('get free port: %s', port);
- callback(null, port);
+ debug('get free %s:%s', hostname, port);
+ return callback(null, port);
});
}
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"url": "git://github.com/node-modules/detect-port.git"
},
"dependencies": {
+ "address": "^1.0.1",
"debug": "^2.6.0"
},
"devDependencies": {
diff --git a/test/detect-port.test.js b/test/detect-port.test.js
index <HASH>..<HASH> 100644
--- a/test/detect-port.test.js
+++ b/test/detect-port.test.js
@@ -3,18 +3,30 @@
const assert = require('assert');
const net = require('net');
const pedding = require('pedding');
+const address = require('address');
const detectPort = require('..');
describe('detect port test', () => {
const servers = [];
before(done => {
- done = pedding(11, done);
+ done = pedding(12, done);
const server = new net.Server();
- server.listen(3000, done);
+ server.listen(3000, 'localhost', done);
servers.push(server);
+
+ const server2 = new net.Server();
+ server2.listen(4000, address.ip(), done);
+ servers.push(server2);
+
for (let port = 7000; port < 7010; port++) {
const server = new net.Server();
- server.listen(port, done);
+ if (port % 3 === 0) {
+ server.listen(port, done);
+ } else if (port % 3 === 1) {
+ server.listen(port, 'localhost', done);
+ } else {
+ server.listen(port, address.ip(), done);
+ }
servers.push(server);
}
});
@@ -37,7 +49,7 @@ describe('detect port test', () => {
});
});
- it('work with listening next port 3001', done => {
+ it('work with listening next port 3001 because 3000 was listen by localhost', done => {
const port = 3000;
detectPort(port, (_, realPort) => {
assert(realPort === 3001);
@@ -45,6 +57,14 @@ describe('detect port test', () => {
});
});
+ it('work with listening next port 4001 because 4000 was listen by ' + address.ip(), done => {
+ const port = 4000;
+ detectPort(port, (_, realPort) => {
+ assert(realPort === 4001);
+ done();
+ });
+ });
+
it('work with listening random port when try port hit maxPort', done => {
const port = 7000;
detectPort(port, (_, realPort) => {
|
fix: should double check <I> and localhost (#<I>)
should check current ip too
- closes <URL>
|
node-modules_detect-port
|
train
|
6fc420747f76f5a8a10b2c1afc4202b43c4695da
|
diff --git a/src/extensions/default/HoverPreview/main.js b/src/extensions/default/HoverPreview/main.js
index <HASH>..<HASH> 100644
--- a/src/extensions/default/HoverPreview/main.js
+++ b/src/extensions/default/HoverPreview/main.js
@@ -102,30 +102,6 @@ define(function (require, exports, module) {
event.clientY <= offset.top + $div.height());
}
- // Heuristic to detect common cases of newer syntax color stops that Chrome 25
- // does not yet support. This is supported in Chrome 26 which will be upgraded
- // to soon, so this code is quick (to write) and dirty (inefficient to run).
- function hasNewSyntaxColorStop(gradient) {
- // Old school webkit gradients are supported and don't fit this heuristic
- if (gradient.indexOf("-webkit-gradient") !== -1) {
- return false;
- }
-
- // To make code easier to parse remove optional whitespace
- // Whitespace around commas and opening parens is optional. Also before
- // (but not after) closing parens. This is common with colors specified as
- // functions such as rgb().
- var s = gradient
- .trim()
- .replace(/\s*,\s*/g, ",")
- .replace(/\s*\(\s*/g, "(")
- .replace(/\s*\)/g, ")");
-
- // Whitespace in first (optional) parameter is supported, but all subsequent
- // (i.e. after first comma) whitespace is from a color stop (<color> <length>).
- return s.match(/,\S+\s/);
- }
-
function colorAndGradientPreviewProvider(editor, pos, token, line) {
var cm = editor._codeMirror;
@@ -147,10 +123,6 @@ define(function (require, exports, module) {
// If the gradient match has "to " in it, it's most likely the new gradient
// syntax which is not supported until Chrome 26, so we can't yet preview it
gradientMatch = null;
-
- } else if (hasNewSyntaxColorStop(gradientMatch[0])) {
- // Ignore new gradient color stop syntax, for now
- gradientMatch = null;
}
}
|
remove misguided attempt to filter gradients for Chrome <I>
|
adobe_brackets
|
train
|
cba532c9b4878f14b3cea4ec84f979cc33d625a6
|
diff --git a/models/Brand.php b/models/Brand.php
index <HASH>..<HASH> 100644
--- a/models/Brand.php
+++ b/models/Brand.php
@@ -53,6 +53,12 @@ class Brand extends Model
use DataFileModel;
public $table = 'lovata_shopaholic_brands';
+
+ public $implement = [
+ '@RainLab.Translate.Behaviors.TranslatableModel',
+ ];
+
+ public $translatable = ['name', 'preview_text', 'description'];
public $rules = [
'name' => 'required',
diff --git a/models/Category.php b/models/Category.php
index <HASH>..<HASH> 100644
--- a/models/Category.php
+++ b/models/Category.php
@@ -72,6 +72,12 @@ class Category extends Model
use DataFileModel;
public $table = 'lovata_shopaholic_categories';
+
+ public $implement = [
+ '@RainLab.Translate.Behaviors.TranslatableModel',
+ ];
+
+ public $translatable = ['name', 'preview_text', 'description'];
public $rules = [
'name' => 'required',
diff --git a/models/Offer.php b/models/Offer.php
index <HASH>..<HASH> 100644
--- a/models/Offer.php
+++ b/models/Offer.php
@@ -64,6 +64,12 @@ class Offer extends Model
public $table = 'lovata_shopaholic_offers';
+ public $implement = [
+ '@RainLab.Translate.Behaviors.TranslatableModel',
+ ];
+
+ public $translatable = ['name', 'preview_text', 'description'];
+
public $rules = ['name' => 'required'];
public $attributeNames = [
diff --git a/models/Product.php b/models/Product.php
index <HASH>..<HASH> 100644
--- a/models/Product.php
+++ b/models/Product.php
@@ -69,7 +69,13 @@ class Product extends Model
use DataFileModel;
public $table = 'lovata_shopaholic_products';
-
+
+ public $implement = [
+ '@RainLab.Translate.Behaviors.TranslatableModel',
+ ];
+
+ public $translatable = ['name', 'preview_text', 'description'];
+
public $rules = [
'name' => 'required',
'slug' => 'required|unique:lovata_shopaholic_products',
|
#<I> Add integration with Translate plugin
|
lovata_oc-shopaholic-plugin
|
train
|
59be14de39cd3c4a488f2e770432a04b11c29536
|
diff --git a/lib/questionlib.php b/lib/questionlib.php
index <HASH>..<HASH> 100644
--- a/lib/questionlib.php
+++ b/lib/questionlib.php
@@ -1033,7 +1033,9 @@ function question_preload_states($attemptid) {
// The questionid field must be listed first so that it is used as the
// array index in the array returned by $DB->get_records_sql
- $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment, n.flagged, n.id as questionsessionid';
+ $statefields = 'n.questionid as question, s.id, s.attempt, ' .
+ 's.seq_number, s.answer, s.timestamp, s.event, s.grade, s.raw_grade, ' .
+ 's.penalty, n.sumpenalty, n.manualcomment, n.flagged, n.id as questionsessionid';
// Load the newest states for the questions
$sql = "SELECT $statefields
@@ -1101,8 +1103,11 @@ function question_load_states(&$questions, &$states, $cmoptions, $attempt, $last
// If the new attempt is to be based on this previous attempt.
// Find the responses from the previous attempt and save them to the new session
- // Load the last graded state for the question
- $statefields = 'n.questionid as question, s.*, n.sumpenalty';
+ // Load the last graded state for the question. Note, $statefields is
+ // the same as above, except that we don't want n.manualcomment.
+ $statefields = 'n.questionid as question, s.id, s.attempt, ' .
+ 's.seq_number, s.answer, s.timestamp, s.event, s.grade, s.raw_grade, ' .
+ 's.penalty, n.sumpenalty';
$sql = "SELECT $statefields
FROM {question_states} s, {question_sessions} n
WHERE s.id = n.newest
|
questionlib: MDL-<I> Fix database query that does not work in Oracle.
Bug report and fix thanks to David Binney.
|
moodle_moodle
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.