hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
83580f51e254c1269669035f0452f2fe0aef3ede
diff --git a/component/all/resource.go b/component/all/resource.go index <HASH>..<HASH> 100644 --- a/component/all/resource.go +++ b/component/all/resource.go @@ -210,9 +210,7 @@ func (r resources) registerHookContextFacade() { func (r resources) registerUnitDownloadEndpoint() { common.RegisterAPIModelEndpoint(privateapi.HTTPEndpointPattern, apihttp.HandlerSpec{ Constraints: apihttp.HandlerConstraints{ - // Machines are allowed too so that unit resources can be - // retrieved for model migrations. - AuthKinds: []string{names.UnitTagKind, names.MachineTagKind}, + AuthKinds: []string{names.UnitTagKind}, StrictValidation: true, ControllerModelOnly: false, },
Remove machine access to unit resource endpoint It turns out there's no need to pull unit resource binaries.
juju_juju
train
16bc03ff39dd16dadfae705726ab3e192c42c208
diff --git a/rsocket-examples/src/test/java/io/rsocket/resume/ResumeIntegrationTest.java b/rsocket-examples/src/test/java/io/rsocket/resume/ResumeIntegrationTest.java index <HASH>..<HASH> 100644 --- a/rsocket-examples/src/test/java/io/rsocket/resume/ResumeIntegrationTest.java +++ b/rsocket-examples/src/test/java/io/rsocket/resume/ResumeIntegrationTest.java @@ -40,6 +40,7 @@ import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.ReplayProcessor; +import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; @SlowTest @@ -83,7 +84,7 @@ public class ResumeIntegrationTest { StepVerifier.create( rSocket .requestChannel(testRequest()) - .take(Duration.ofSeconds(120)) + .take(Duration.ofSeconds(600)) .map(Payload::getDataUtf8) .timeout(Duration.ofSeconds(12)) .doOnNext(x -> throwOnNonContinuous(counter, x)) @@ -210,7 +211,8 @@ public class ResumeIntegrationTest { return RSocketFactory.connect() .resume() .resumeSessionDuration(Duration.ofSeconds(sessionDurationSeconds)) - .keepAliveTickPeriod(Duration.ofSeconds(1)) + .keepAliveTickPeriod(Duration.ofSeconds(30)) + .keepAliveAckTimeout(Duration.ofMinutes(5)) .errorConsumer(errConsumer) .resumeStrategy(() -> new PeriodicResumeStrategy(Duration.ofSeconds(1))) .transport(clientTransport) @@ -224,6 +226,7 @@ public class ResumeIntegrationTest { private static Mono<CloseableChannel> newServerRSocket(int sessionDurationSeconds) { return RSocketFactory.receive() .resume() + .resumeStore(t -> new InMemoryResumableFramesStore("server",100_000)) .resumeSessionDuration(Duration.ofSeconds(sessionDurationSeconds)) .acceptor((setupPayload, rSocket) -> Mono.just(new TestResponderRSocket())) .transport(serverTransport(SERVER_HOST, SERVER_PORT)) @@ -236,10 +239,18 @@ public class ResumeIntegrationTest { @Override public Flux<Payload> requestChannel(Publisher<Payload> payloads) { - return Flux.interval(Duration.ofMillis(1)) - .onBackpressureLatest() + return duplicate(Flux.interval(Duration.ofMillis(1)) + .onBackpressureLatest().publishOn(Schedulers.elastic()), 20) .map(v -> DefaultPayload.create(String.valueOf(counter.getAndIncrement()))) .takeUntilOther(Flux.from(payloads).then()); } + + private <T> Flux<T> duplicate(Flux<T> f, int n) { + Flux<T> r =Flux.empty(); + for (int i = 0; i < n; i++) { + r = r.mergeWith(f); + } + return r; + } } }
resumption: update long running test
rsocket_rsocket-java
train
a251c223b0a1c038c0f7598cd8ad24aa3b2ff231
diff --git a/skitai/server/http_server.py b/skitai/server/http_server.py index <HASH>..<HASH> 100644 --- a/skitai/server/http_server.py +++ b/skitai/server/http_server.py @@ -330,8 +330,8 @@ class http_server (asyncore.dispatcher): self.listen (os.name == "posix" and 65535 or 256) if os.name == "posix": - while SURVAIL: - try: + try: + while SURVAIL: if ACTIVE_WORKERS < numworker: pid = os.fork () if pid == 0: @@ -349,8 +349,8 @@ class http_server (asyncore.dispatcher): signal.signal (signal.SIGCHLD, hCHLD) time.sleep (1) - except KeyboardInterrupt: - pass + except KeyboardInterrupt: + pass if self.worker_ident == "master": return EXITCODE
handle KeyboardInterrupt on posix
hansroh_skitai
train
3db632732c95f4af4a374172195a8c151a42a005
diff --git a/lib/Cake/Controller/Component/AuthComponent.php b/lib/Cake/Controller/Component/AuthComponent.php index <HASH>..<HASH> 100644 --- a/lib/Cake/Controller/Component/AuthComponent.php +++ b/lib/Cake/Controller/Component/AuthComponent.php @@ -667,6 +667,12 @@ class AuthComponent extends Component { * @return boolean true if a user can be found, false if one cannot. */ protected function _getUser() { + $user = $this->user(); + if ($user) { + $this->Session->delete('Auth.redirect'); + return true; + } + if (empty($this->_authenticateObjects)) { $this->constructAuthenticate(); } @@ -678,11 +684,6 @@ class AuthComponent extends Component { } } - $user = $this->user(); - if ($user) { - $this->Session->delete('Auth.redirect'); - return true; - } return false; } diff --git a/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php b/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php index <HASH>..<HASH> 100644 --- a/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php +++ b/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php @@ -1368,6 +1368,7 @@ class AuthComponentTest extends CakeTestCase { $_SERVER['PHP_AUTH_USER'] = 'mariano'; $_SERVER['PHP_AUTH_PW'] = 'cake'; + AuthComponent::$sessionKey = false; $this->Auth->authenticate = array( 'Basic' => array('userModel' => 'AuthUser') );
Avoid unnecessary overhead if user record already available from session.
cakephp_cakephp
train
12faec329ea96d4fd51d1f23473aabf8cb4ad746
diff --git a/porespy/tools/__init__.py b/porespy/tools/__init__.py index <HASH>..<HASH> 100644 --- a/porespy/tools/__init__.py +++ b/porespy/tools/__init__.py @@ -55,5 +55,8 @@ from ._sphere_insertions import * def _get_version(): - from porespy.__version__ import __version__ - return __version__.removesuffix(".dev0") + from porespy.__version__ import __version__ as ver + suffix = ".dev0" + if ver.endswith(suffix): + ver = ver[:-len(suffix)] + return ver
Replaced usage of removesuffix since only available in py<I> [no ci]
PMEAL_porespy
train
c437f0504f06c99da51d618d3138d1c0427cb9d1
diff --git a/src/Hprose/Swoole/Client.php b/src/Hprose/Swoole/Client.php index <HASH>..<HASH> 100644 --- a/src/Hprose/Swoole/Client.php +++ b/src/Hprose/Swoole/Client.php @@ -56,7 +56,7 @@ namespace Hprose\Swoole { } return null; } - public function invoke($name, &$args = array(), $byref = false, $mode = ResultMode::Normal, $simple = null, $callback = null) { + public function invoke($name, &$args = array(), $byref = false, $mode = \Hprose\ResultMode::Normal, $simple = null, $callback = null) { if ($this->real_client) { return $this->real_client->invoke($name, $args, $byref, $mode, $simple, $callback); }
Update Client.php PHP Fatal error: Class 'Hprose\Swoole\ResultMode' not found
hprose_hprose-php
train
7e75e0ba2c1c007bf0fe81cc9efae5ed275df58a
diff --git a/presto-main/src/test/java/com/facebook/presto/TestQueries.java b/presto-main/src/test/java/com/facebook/presto/TestQueries.java index <HASH>..<HASH> 100644 --- a/presto-main/src/test/java/com/facebook/presto/TestQueries.java +++ b/presto-main/src/test/java/com/facebook/presto/TestQueries.java @@ -522,6 +522,21 @@ public class TestQueries assertEqualsIgnoreOrder(actual, expected); } + @Test(enabled = false) + public void testJoinAggregations() + throws Exception + { + List<Tuple> actual = computeActual("SELECT x + y FROM (" + + " SELECT orderdate, COUNT(*) x FROM orders GROUP BY orderdate) a JOIN (" + + " SELECT orderdate, COUNT(*) y FROM orders GROUP BY orderdate) b USING (orderdate)"); + + List<Tuple> expected = computeExpected("SELECT x + y FROM (" + + " SELECT orderdate, COUNT(*) x FROM orders GROUP BY orderdate) a JOIN (" + + " SELECT orderdate, COUNT(*) y FROM orders GROUP BY orderdate) b ON a.orderdate = b.orderdate", FIXED_INT_64); + + assertEqualsIgnoreOrder(actual, expected); + } + private List<Tuple> computeExpected(@Language("SQL") final String sql, TupleInfo.Type... types) { TupleInfo tupleInfo = new TupleInfo(types);
Add join test (temporarily disabled)
prestodb_presto
train
d3af473cda6b50b409f3e6f467c292d230c11c5a
diff --git a/src/test-tools.js b/src/test-tools.js index <HASH>..<HASH> 100644 --- a/src/test-tools.js +++ b/src/test-tools.js @@ -92,21 +92,30 @@ export class ParallelMessages { } next (foundMessage) { + let nextMessages; + if (this.notStarted) { this.notStarted = false; - return this.messages; + nextMessages = this.messages; } else { const index = this.messages.findIndex(msg => msg === foundMessage); const queue = this.queues[index]; if (queue.length) { this.messages[index] = queue.shift(); - return [this.messages[index]]; + nextMessages = [this.messages[index]]; } else { this.messages.splice(index, 1); this.queues.splice(index, 1); - return []; + nextMessages = []; } } + + if (getDebug()) { + console.info(`Current ${chalk.cyan('parallel')} messages '${ + chalk.green(JSON.stringify(this.messages))}'`); + } + + return nextMessages; } } export const parallel = (...queues) => new ParallelMessages(queues);
Added debug logs to ParallelMessages
jlenoble_test-gulp-process
train
2710cfe91a94deceda70a3639fe17063d9182787
diff --git a/src/Theme_Command.php b/src/Theme_Command.php index <HASH>..<HASH> 100644 --- a/src/Theme_Command.php +++ b/src/Theme_Command.php @@ -3,7 +3,9 @@ use WP_CLI\Utils; /** - * Manage themes. + * Manages site themes, including installs, activations, and updates. + * + * See the WordPress [Theme Handbook](https://developer.wordpress.org/themes/) developer resource. * * ## EXAMPLES *
Improve 'wp theme' command description
wp-cli_extension-command
train
e506275389ed3a35faffab44f0666fd532243007
diff --git a/spec/cb/responses/resumes/get_spec.rb b/spec/cb/responses/resumes/get_spec.rb index <HASH>..<HASH> 100644 --- a/spec/cb/responses/resumes/get_spec.rb +++ b/spec/cb/responses/resumes/get_spec.rb @@ -18,4 +18,4 @@ describe Cb::Responses::Resumes::Get do end end end -end \ No newline at end of file +end
blank line adding part 3: son of adding
careerbuilder_ruby-cb-api
train
1b338c61250475572cb182b75dd638c501dd5930
diff --git a/src/Components/BaseEngineAdapter.php b/src/Components/BaseEngineAdapter.php index <HASH>..<HASH> 100644 --- a/src/Components/BaseEngineAdapter.php +++ b/src/Components/BaseEngineAdapter.php @@ -10,11 +10,11 @@ use DreamFactory\Core\Exceptions\RestException; use DreamFactory\Core\Exceptions\ServiceUnavailableException; use DreamFactory\Core\Utility\ResponseFactory; use DreamFactory\Core\Utility\Session; -use DreamFactory\Library\Utility\ArrayUtils; -use DreamFactory\Library\Utility\Curl; -use DreamFactory\Library\Utility\Enums\Verbs; +use DreamFactory\Core\Utility\Curl; +use DreamFactory\Core\Enums\Verbs; use Cache; use Config; +use Illuminate\Support\Arr; use ServiceManager; /** @@ -326,7 +326,7 @@ abstract class BaseEngineAdapter implements ScriptingEngineInterface if (!empty($headers = (array)array_get($curlOptions, 'headers'))) { unset($curlOptions['headers']); $curlHeaders = []; - if (ArrayUtils::isArrayNumeric($headers)) { + if (!Arr::isAssoc($headers)) { $curlHeaders = $headers; } else { foreach ($headers as $key => $value) { diff --git a/src/Components/ScriptServiceRequest.php b/src/Components/ScriptServiceRequest.php index <HASH>..<HASH> 100644 --- a/src/Components/ScriptServiceRequest.php +++ b/src/Components/ScriptServiceRequest.php @@ -1,7 +1,7 @@ <?php namespace DreamFactory\Core\Script\Components; -use DreamFactory\Library\Utility\Enums\Verbs; +use DreamFactory\Core\Enums\Verbs; use DreamFactory\Core\Components\InternalServiceRequest; use DreamFactory\Core\Contracts\ServiceRequestInterface; use DreamFactory\Core\Enums\ServiceRequestorTypes; diff --git a/src/Engines/V8Js.php b/src/Engines/V8Js.php index <HASH>..<HASH> 100644 --- a/src/Engines/V8Js.php +++ b/src/Engines/V8Js.php @@ -5,7 +5,6 @@ use DreamFactory\Core\Contracts\ServiceResponseInterface; use DreamFactory\Core\Exceptions\InternalServerErrorException; use DreamFactory\Core\Exceptions\ServiceUnavailableException; use DreamFactory\Core\Script\Components\BaseEngineAdapter; -use DreamFactory\Library\Utility\Scalar; use DreamFactory\Core\Script\Components\ScriptSession; use DreamFactory\Core\Utility\Session; use Log; @@ -68,8 +67,8 @@ class V8Js extends BaseEngineAdapter $extensions = array_get($settings, 'extensions', []); // accept comma-delimited string $extensions = (is_string($extensions)) ? array_map('trim', explode(',', trim($extensions, ','))) : $extensions; - $reportUncaughtExceptions = Scalar::boolval(array_get($settings, 'report_uncaught_exceptions', false)); - $logMemoryUsage = Scalar::boolval(array_get($settings, 'log_memory_usage', false)); + $reportUncaughtExceptions = array_get_bool($settings, 'report_uncaught_exceptions'); + $logMemoryUsage = array_get_bool($settings, 'log_memory_usage'); static::startup($settings); diff --git a/src/Enums/ScriptLanguages.php b/src/Enums/ScriptLanguages.php index <HASH>..<HASH> 100644 --- a/src/Enums/ScriptLanguages.php +++ b/src/Enums/ScriptLanguages.php @@ -1,7 +1,7 @@ <?php namespace DreamFactory\Core\Script\Enums; -use DreamFactory\Library\Utility\Enums\FactoryEnum; +use DreamFactory\Core\Enums\FactoryEnum; /** * ScriptLanguages diff --git a/src/Services/Script.php b/src/Services/Script.php index <HASH>..<HASH> 100644 --- a/src/Services/Script.php +++ b/src/Services/Script.php @@ -10,8 +10,7 @@ use DreamFactory\Core\Services\BaseRestService; use DreamFactory\Core\Utility\ResourcesWrapper; use DreamFactory\Core\Utility\ResponseFactory; use DreamFactory\Core\Utility\Session; -use DreamFactory\Library\Utility\Enums\Verbs; -use DreamFactory\Library\Utility\Scalar; +use DreamFactory\Core\Enums\Verbs; use Illuminate\Foundation\Bus\DispatchesJobs; use Log; @@ -75,7 +74,7 @@ class Script extends BaseRestService $this->content = ''; } - $this->queued = Scalar::boolval(array_get($config, 'queued', false)); + $this->queued = array_get_bool($config, 'queued'); if (empty($this->engineType = array_get($config, 'type'))) { throw new \InvalidArgumentException('Script engine configuration can not be empty.'); @@ -86,7 +85,7 @@ class Script extends BaseRestService } $this->apiDoc = (array)array_get($settings, 'doc'); - $this->implementsAccessList = boolval(array_get($config, 'implements_access_list', false)); + $this->implementsAccessList = array_get_bool($config, 'implements_access_list'); } /**
cleanup - removal of php-utils dependency
dreamfactorysoftware_df-script
train
f41de10abb1079bfccefbcbef691c8a5388901f3
diff --git a/lib/kaminari/models/array_extension.rb b/lib/kaminari/models/array_extension.rb index <HASH>..<HASH> 100644 --- a/lib/kaminari/models/array_extension.rb +++ b/lib/kaminari/models/array_extension.rb @@ -9,7 +9,7 @@ module Kaminari # * <tt>:limit</tt> - limit # * <tt>:offset</tt> - offset # * <tt>:total_count</tt> - total_count - def initialize(original_array, options = {}) + def initialize(original_array = [], options = {}) @_original_array, @_limit_value, @_offset_value, @_total_count = original_array, (options[:limit] || default_per_page).to_i, options[:offset].to_i, options[:total_count] if options[:limit] && options[:offset] diff --git a/spec/models/array_spec.rb b/spec/models/array_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/array_spec.rb +++ b/spec/models/array_spec.rb @@ -1,6 +1,8 @@ require File.expand_path('../spec_helper', File.dirname(__FILE__)) describe Kaminari::PaginatableArray do + it { should have(0).items } + context 'specifying limit and offset when initializing' do subject { Kaminari::PaginatableArray.new((1..100).to_a, :limit => 10, :offset => 20) } its(:current_page) { should == 3 }
PaginatableArray can be instantiated without an argument
kaminari_kaminari
train
46eebfff014c187d3717a751da1e832eda7a19fb
diff --git a/src/PaginateRoute.php b/src/PaginateRoute.php index <HASH>..<HASH> 100644 --- a/src/PaginateRoute.php +++ b/src/PaginateRoute.php @@ -183,34 +183,58 @@ class PaginateRoute } $urls = []; + $left = $this->getLeftPoint($paginator); + $right = $this->getRightPoint($paginator); + for ($page = $left; $page <= $right; $page++) { + $urls[$page] = $this->pageUrl($page, $full); + } + + return $urls; + } + + + /** + * Get the left most point in the pagination element + * + * @param LengthAwarePaginator $paginator + * @return int + */ + public function getLeftPoint(LengthAwarePaginator $paginator) + { $side = $paginator->onEachSide; $current = $paginator->currentPage(); $last = $paginator->lastPage(); - + if (!empty($side)) { - $total = $current + $side; - $first = $current - $side; - if ($first < 1) { - $first = 1; - $total += $side; - } - if ($total > $last) { - $total = $last; - if ($first > $side + 1) { - $first -= $side; - } - } - } - else { - $first = 1; - $total = $last; + $x = $current + $side; + $offset = $x > $last ? $x - $last : 0; + $left = $current - $side - $offset; } - for ($page = $first; $page <= $total; $page++) { - $urls[$page] = $this->pageUrl($page, $full); + + return !isset($left) || $left < 1 ? 1 : $left; + } + + + /** + * Get the right or last point of the pagination element + * + * @param LengthAwarePaginator $paginator + * @return int + */ + public function getRightPoint(LengthAwarePaginator $paginator) + { + $side = $paginator->onEachSide; + $current = $paginator->currentPage(); + $last = $paginator->lastPage(); + + if (!empty($side)) { + $offset = $current < $side ? $side - $current + 1 : 0; + $right = $current + $side + $offset; } - return $urls; + return !isset($right) || $right > $last ? $last : $right; } + /** * Render a plain html list with previous, next and all urls. The current page gets a current class on the list item.
Refactoring left point and right point Refactor them into separate methods
spatie_laravel-paginateroute
train
31ca200d44ee10ef37482832d446d950dec48567
diff --git a/test/test_crypto.py b/test/test_crypto.py index <HASH>..<HASH> 100644 --- a/test/test_crypto.py +++ b/test/test_crypto.py @@ -917,6 +917,11 @@ class X509Tests(TestCase, _PKeyInteractionTestsMixin): # An invalid string results in a ValueError self.assertRaises(ValueError, set, "foo bar") + # The wrong number of arguments results in a TypeError. + self.assertRaises(TypeError, set) + self.assertRaises(TypeError, set, "20040203040506Z", "20040203040506Z") + self.assertRaises(TypeError, get, "foo bar") + def test_set_notBefore(self): """
Test wrong number of arguments to set_notBefore and friends
pyca_pyopenssl
train
9836d2008cd9ca8bc9a36287d2007d3fb15e98d2
diff --git a/lib/discordrb/commands/command_bot.rb b/lib/discordrb/commands/command_bot.rb index <HASH>..<HASH> 100644 --- a/lib/discordrb/commands/command_bot.rb +++ b/lib/discordrb/commands/command_bot.rb @@ -56,7 +56,8 @@ module Discordrb::Commands type: attributes[:type], name: attributes[:name], fancy_log: attributes[:fancy_log], - suppress_ready: attributes[:suppress_ready]) + suppress_ready: attributes[:suppress_ready], + parse_self: attributes[:parse_self]) @prefix = attributes[:prefix] @attributes = {
Make sure command bots pass through parse_self
meew0_discordrb
train
223a3a2dc4818ae7dce0723e703837fb196455c5
diff --git a/lib/multiple_mailers/version.rb b/lib/multiple_mailers/version.rb index <HASH>..<HASH> 100644 --- a/lib/multiple_mailers/version.rb +++ b/lib/multiple_mailers/version.rb @@ -1,3 +1,3 @@ module MultipleMailers - VERSION = "1.0.0" + VERSION = "1.1.0" end
Bumping version to <I>
flyerhzm_multiple_mailers
train
4e66a41565db4d3999dd54f664aae3b0515bb7f4
diff --git a/test/jade.test.js b/test/jade.test.js index <HASH>..<HASH> 100644 --- a/test/jade.test.js +++ b/test/jade.test.js @@ -881,6 +881,32 @@ describe('jade', function(){ assert.equal("<p>foo\u2028bar</p>", jade.render("p foo\u2028bar")); assert.equal("<p>foo\u2029bar</p>", jade.render("p foo\u2029bar")); }); + + it('should display error line number correctly up to token level', function() { + var str = [ + 'p.', + ' Lorem ipsum dolor sit amet, consectetur', + ' adipisicing elit, sed do eiusmod tempor', + ' incididunt ut labore et dolore magna aliqua.', + 'p.', + ' Ut enim ad minim veniam, quis nostrud', + ' exercitation ullamco laboris nisi ut aliquip', + ' ex ea commodo consequat.', + 'p.', + ' Duis aute irure dolor in reprehenderit', + ' in voluptate velit esse cillum dolore eu', + ' fugiat nulla pariatur.', + 'a(href="#" Next', + ].join('\n'); + var errorLocation = function(str) { + try { + jade.render(str); + } catch (err) { + return err.message.split('\n')[0]; + } + }; + assert.equal(errorLocation(str), "Jade:13"); + }); }); describe('.compileFile()', function () {
Added a test case for error line number
pugjs_then-pug
train
1a2ece6127bcadcd33d29d424e38066e5a4b6dff
diff --git a/fcrepo-server/src/main/java/org/fcrepo/server/utilities/rebuild/Rebuild.java b/fcrepo-server/src/main/java/org/fcrepo/server/utilities/rebuild/Rebuild.java index <HASH>..<HASH> 100755 --- a/fcrepo-server/src/main/java/org/fcrepo/server/utilities/rebuild/Rebuild.java +++ b/fcrepo-server/src/main/java/org/fcrepo/server/utilities/rebuild/Rebuild.java @@ -151,7 +151,6 @@ public class Rebuild implements Constants, Runnable { " objects failed to rebuild due to errors."); } } finally { - System.out.println("Exiting without rebuilding."); m_rebuilder.finish(); if (server != null) { server.shutdown(null); @@ -162,6 +161,7 @@ public class Rebuild implements Constants, Runnable { } return; } else { + System.out.println("Exiting without rebuilding."); if (server != null) { server.shutdown(null); server = null; @@ -284,11 +284,11 @@ public class Rebuild implements Constants, Runnable { } labels[i] = "Exit"; int choiceNum = i; - System.out.println("Getting rebuilder... " + - System.getProperty("rebuilder")); if (System.getProperty("rebuilder") == null) { choiceNum = getChoice("What do you want to do?", labels); } else { + System.out.println("Getting rebuilder... " + + System.getProperty("rebuilder")); for (int j = 0; j < rebuilders.length; j++) { if (rebuilders[j].equals(System.getProperty("rebuilder"))) { choiceNum = j;
relocate Sysout messaging in Rebuild to appropriate blocks
fcrepo3_fcrepo
train
239b860222928d28acb3b40b8cd956cf01709e04
diff --git a/findbugs/src/java/edu/umd/cs/findbugs/ba/ch/Subtypes2.java b/findbugs/src/java/edu/umd/cs/findbugs/ba/ch/Subtypes2.java index <HASH>..<HASH> 100644 --- a/findbugs/src/java/edu/umd/cs/findbugs/ba/ch/Subtypes2.java +++ b/findbugs/src/java/edu/umd/cs/findbugs/ba/ch/Subtypes2.java @@ -41,6 +41,7 @@ import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.XClass; +import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.internalAnnotations.DottedClassName; @@ -160,6 +161,10 @@ public class Subtypes2 { * @param appXClass application XClass to add to the inheritance graph */ public void addApplicationClass(XClass appXClass) { + for(XMethod m : appXClass.getXMethods()) { + if (m.isStub()) + return; + } ClassVertex vertex = addClassAndGetClassVertex(appXClass); vertex.markAsApplicationClass();
If a class has stub methods, it isn't treated as an application class git-svn-id: <URL>
spotbugs_spotbugs
train
eb87a988494f3c9de3ef004b7befe9b77d884bad
diff --git a/pax-logging-logback/src/main/java/org/ops4j/pax/logging/logback/internal/PaxLoggingServiceImpl.java b/pax-logging-logback/src/main/java/org/ops4j/pax/logging/logback/internal/PaxLoggingServiceImpl.java index <HASH>..<HASH> 100644 --- a/pax-logging-logback/src/main/java/org/ops4j/pax/logging/logback/internal/PaxLoggingServiceImpl.java +++ b/pax-logging-logback/src/main/java/org/ops4j/pax/logging/logback/internal/PaxLoggingServiceImpl.java @@ -500,6 +500,10 @@ public class PaxLoggingServiceImpl implements PaxLoggingService, org.knopflerfis { return LOG_WARNING; } + else if ( "OFF".equals( levelName ) || "NONE".equals( levelName ) ) + { + return 0; + } else { return LOG_DEBUG; diff --git a/pax-logging-service/src/main/java/org/ops4j/pax/logging/service/internal/PaxLoggingServiceImpl.java b/pax-logging-service/src/main/java/org/ops4j/pax/logging/service/internal/PaxLoggingServiceImpl.java index <HASH>..<HASH> 100644 --- a/pax-logging-service/src/main/java/org/ops4j/pax/logging/service/internal/PaxLoggingServiceImpl.java +++ b/pax-logging-service/src/main/java/org/ops4j/pax/logging/service/internal/PaxLoggingServiceImpl.java @@ -399,6 +399,10 @@ public class PaxLoggingServiceImpl { return LOG_WARNING; } + else if ( "OFF".equals( levelName ) || "NONE".equals( levelName ) ) + { + return 0; + } else { return LOG_DEBUG;
[PAXLOGGING-<I>] Support OFF/NONE level for the default logger
ops4j_org.ops4j.pax.logging
train
7c1886cf8751281e1b41e80341a045b46c2c38f5
diff --git a/querylist/betterdict.py b/querylist/betterdict.py index <HASH>..<HASH> 100644 --- a/querylist/betterdict.py +++ b/querylist/betterdict.py @@ -16,10 +16,6 @@ class BetterDict(dict): return super(BetterDict, self).__init__(*args, **kwargs) def __getattr__(self, attr): - # Don't attempt lookups for things that conflict with dict attrs - if attr in self.__dict_attrs: - raise AttributeError - # If the requested attribute is prefixed with self.__prefix, # we need to unprefix it and do a lookup for that key. if attr.startswith(self.__prefix) and attr != self.__prefix:
Remove unnecessary check for dict attr conflicts.
thomasw_querylist
train
3caf0ced1604de40be3148ed69f433408451e7f1
diff --git a/cmd/routing-api/main_test.go b/cmd/routing-api/main_test.go index <HASH>..<HASH> 100644 --- a/cmd/routing-api/main_test.go +++ b/cmd/routing-api/main_test.go @@ -156,7 +156,9 @@ var _ = Describe("Main", func() { Context("when etcd is unavailable", func() { AfterEach(func() { + peerPort := etcdPort + 3000 validatePort(uint16(etcdPort)) + validatePort(uint16(peerPort)) _, err := etcdAllocator.Create() Expect(err).NotTo(HaveOccurred()) })
Validate that etcd peer port is also available to bind
cloudfoundry_routing-api
train
84293ab6ea7c6f86c0895ce5df02b4d519b7e7b7
diff --git a/src/assertions/text.js b/src/assertions/text.js index <HASH>..<HASH> 100644 --- a/src/assertions/text.js +++ b/src/assertions/text.js @@ -21,8 +21,8 @@ export default function text(client, chai, utils) { this.assert( elementTextAsExpected, - `Expected element <${selector}> to contain text "${expected}", but only found [${textArray}].`, - `Expected element <${selector}> not to contain text "${expected}", but only found [${textArray}].` + `Expected element <${selector}> to contain text "${expected}", but only found: ${textArray}`, + `Expected element <${selector}> not to contain text "${expected}", but found: ${textArray}` ); }); } diff --git a/src/assertions/value.js b/src/assertions/value.js index <HASH>..<HASH> 100644 --- a/src/assertions/value.js +++ b/src/assertions/value.js @@ -10,18 +10,19 @@ export default function value(client, chai, utils) { } const elementValue = client.getValue(selector); + const valueArray = (elementValue instanceof Array) ? elementValue : [elementValue]; var elementValueAsExpected; if (typeof(expected) == "string") { - elementValueAsExpected = elementValue === expected; + elementValueAsExpected = valueArray.some(value => value === expected); } else { - elementValueAsExpected = elementValue.match(expected); + elementValueAsExpected = valueArray.some(value => value.match(expected)); } this.assert( elementValueAsExpected, - `Expected element <${selector}> to contain value "${expected}", but it contains "${elementValue}" instead.`, - `Expected element <${selector}> not to contain value "${expected}", but it contains "${elementValue}".` + `Expected an element matching <${selector}> to contain value "${expected}", but only found these values: ${valueArray}`, + `Expected an element matching <${selector}> not to contain value "${expected}", but found these values: ${valueArray}` ); }); } diff --git a/test/assertions/value-test.js b/test/assertions/value-test.js index <HASH>..<HASH> 100644 --- a/test/assertions/value-test.js +++ b/test/assertions/value-test.js @@ -35,7 +35,7 @@ describe('value', () => { expect(elementExists).to.have.been.calledOnce; }); - describe('When element exists', () => { + describe('When matching element exists', () => { let testResult = 'Never gonna give you up'; beforeEach(() => { elementExists.returns(); @@ -105,5 +105,61 @@ describe('value', () => { }); }); }); + + describe('When multiple elements match', () => { + let testResult = ['Never gonna give you up', 'Never gonna let you down']; + beforeEach(() => { + elementExists.returns(); + fakeClient.getValue.returns(testResult); + }); + + describe('When at least one element value matches string expectation', () => { + it('Should not throw an error', () => { + expect('.some-selector').to.have.value(testResult[0]); + }); + + describe('When negated', () => { + it('Should throw an error', () => { + expect(() => expect('.some-selector').to.not.have.value(testResult[0])).to.throw(); + }); + }); + }); + + describe('When at least one element value matches regex expectation', () => { + it('Should not throw an error', () => { + expect('.some-selector').to.have.value(/gon+a give/); + }); + + describe('When negated', () => { + it('Should throw an error', () => { + expect(() => expect('.some-selector').to.not.have.value(/gon+a give/)).to.throw(); + }); + }); + }); + + describe('When no element value matches string expectation', () => { + it('Should throw an error', () => { + expect(() => expect('.some-selector').to.have.value("dis don't match jack! 1#43@")).to.throw(); + }); + + describe('When negated', () => { + it('Should not throw an error', () => { + expect('.some-selector').to.not.have.value("dis don't match jack! 1#43@"); + }); + }); + }); + + describe('When no element value matches regex expectation', () => { + it('Should throw an error', () => { + expect(() => expect('.some-selector').to.have.value(/dis don't match jack! 1#43@/)).to.throw(); + }); + + describe('When negated', () => { + it('Should not throw an error', () => { + expect('.some-selector').to.not.have.value(/dis don't match jack! 1#43@/); + }); + }); + }); + }); }); });
Add multiple-match handling to value assertion.
marcodejongh_chai-webdriverio
train
fd360d8c2c2dbd2314ace81f0467bf36269b4ef2
diff --git a/lib/Adapter/Composer/ComposerClassToFile.php b/lib/Adapter/Composer/ComposerClassToFile.php index <HASH>..<HASH> 100644 --- a/lib/Adapter/Composer/ComposerClassToFile.php +++ b/lib/Adapter/Composer/ComposerClassToFile.php @@ -98,6 +98,19 @@ class ComposerClassToFile implements ClassToFile $candidates = []; foreach ($prefixes as $prefix => $paths) { + + if (is_int($prefix)) { + $prefix = ''; + } + + if ($prefix && false === $className->beginsWith($prefix)) { + continue; + } + + if (!isset($candidates[$prefix])) { + $candidates[$prefix] = []; + } + $paths = (array) $paths; $paths = array_map(function ($path) { if (!file_exists($path)) { @@ -112,18 +125,6 @@ class ComposerClassToFile implements ClassToFile return realpath($path); }, $paths); - if (is_int($prefix)) { - $prefix = ''; - } - - if ($prefix && false === $className->beginsWith($prefix)) { - continue; - } - - if (!isset($candidates[$prefix])) { - $candidates[$prefix] = []; - } - $candidates[$prefix] = array_merge($candidates[$prefix], $paths); }
Performance: Move existing path filter until after we know it's a valid ...prefix. This caused severe performance issues in long running processes.
phpactor_class-to-file
train
9863258c7942606fcd599ce80bd39457ecb2205e
diff --git a/packages/patternfly-3/patternfly-react/src/components/ListView/ListViewItem.js b/packages/patternfly-3/patternfly-react/src/components/ListView/ListViewItem.js index <HASH>..<HASH> 100644 --- a/packages/patternfly-3/patternfly-react/src/components/ListView/ListViewItem.js +++ b/packages/patternfly-3/patternfly-react/src/components/ListView/ListViewItem.js @@ -42,6 +42,7 @@ class ListViewItem extends React.Component { compoundExpand, compoundExpanded, onCloseCompoundExpand, + initExpanded, ...other } = this.props; const { expanded } = this.state;
fix(ListViewItem) - initExpanded being passed to children (#<I>)
patternfly_patternfly-react
train
4c4a1efe1c6074701e1b0b3fd3979c4accda4af5
diff --git a/lib/codechecksReport.js b/lib/codechecksReport.js index <HASH>..<HASH> 100644 --- a/lib/codechecksReport.js +++ b/lib/codechecksReport.js @@ -48,7 +48,7 @@ class CodeChecksReport { } stats.diff = this.getMethodDiff(methodId, stats.average); - stats.percentDiff = this.getMethodDiff(methodId, stats.average); + stats.percentDiff = this.getMethodPercentageDiff(methodId, stats.average); highlighting = this.getHighlighting(stats.diff); @@ -287,7 +287,7 @@ class CodeChecksReport { getPercentageDiff(previousVal, currentVal) { if (typeof previousVal === "number") { const diff = currentVal - previousVal; - return `${math.round((diff / previous) * 100)}%`; + return `${Math.round((diff / previousVal) * 100)}%`; } return "-"; }
Fix syntax error in diff % calc
cgewecke_eth-gas-reporter
train
491f627ab8673901d1d40b206cf1ae16f687a550
diff --git a/src/instrumentTest/java/com/couchbase/cblite/testapp/tests/Attachments.java b/src/instrumentTest/java/com/couchbase/cblite/testapp/tests/Attachments.java index <HASH>..<HASH> 100644 --- a/src/instrumentTest/java/com/couchbase/cblite/testapp/tests/Attachments.java +++ b/src/instrumentTest/java/com/couchbase/cblite/testapp/tests/Attachments.java @@ -76,7 +76,7 @@ public class Attachments extends CBLiteTestCase { Map<String,Object> attachmentDict = new HashMap<String,Object>(); attachmentDict.put("attach", innerDict); - Map<String,Object> attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), false); + Map<String,Object> attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), EnumSet.noneOf(CBLDatabase.TDContentOptions.class)); Assert.assertEquals(attachmentDict, attachmentDictForSequence); CBLRevision gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(), EnumSet.noneOf(CBLDatabase.TDContentOptions.class)); @@ -86,7 +86,7 @@ public class Attachments extends CBLiteTestCase { // Check the attachment dict, with attachments included: innerDict.remove("stub"); innerDict.put("data", Base64.encodeBytes(attach1)); - attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), true); + attachmentDictForSequence = database.getAttachmentsDictForSequenceWithContent(rev1.getSequence(), EnumSet.of(CBLDatabase.TDContentOptions.TDIncludeAttachments)); Assert.assertEquals(attachmentDict, attachmentDictForSequence); gotRev1 = database.getDocumentWithIDAndRev(rev1.getDocId(), rev1.getRevId(), EnumSet.of(CBLDatabase.TDContentOptions.TDIncludeAttachments)); diff --git a/src/main/java/com/couchbase/cblite/CBLDatabase.java b/src/main/java/com/couchbase/cblite/CBLDatabase.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/couchbase/cblite/CBLDatabase.java +++ b/src/main/java/com/couchbase/cblite/CBLDatabase.java @@ -70,7 +70,7 @@ public class CBLDatabase extends Observable { * Options for what metadata to include in document bodies */ public enum TDContentOptions { - TDIncludeAttachments, TDIncludeConflicts, TDIncludeRevs, TDIncludeRevsInfo, TDIncludeLocalSeq, TDNoBody + TDIncludeAttachments, TDIncludeConflicts, TDIncludeRevs, TDIncludeRevsInfo, TDIncludeLocalSeq, TDNoBody, TDBigAttachmentsFollow } private static final Set<String> KNOWN_SPECIAL_KEYS; @@ -1453,9 +1453,11 @@ public class CBLDatabase extends Observable { /** * Constructs an "_attachments" dictionary for a revision, to be inserted in its JSON body. */ - public Map<String,Object> getAttachmentsDictForSequenceWithContent(long sequence, boolean withContent) { + public Map<String,Object> getAttachmentsDictForSequenceWithContent(long sequence, EnumSet<TDContentOptions> contentOptions) { assert(sequence > 0); + boolean withContent = contentOptions.contains(TDContentOptions.TDIncludeAttachments); + Cursor cursor = null; String args[] = { Long.toString(sequence) }; @@ -1477,7 +1479,7 @@ public class CBLDatabase extends Observable { if(withContent) { byte[] data = attachments.blobForKey(key); if(data != null) { - dataBase64 = Base64.encodeBytes(data); + dataBase64 = Base64.encodeBytes(data); // <-- very expensive } else { Log.w(CBLDatabase.TAG, "Error loading attachment");
change method signature of getAttachmentsDictForSequenceWithContent to take TDContentOptions as parameter
couchbase_couchbase-lite-java-core
train
57b0ac887015a4f17413f6e8aac675ec96c9e796
diff --git a/responses.py b/responses.py index <HASH>..<HASH> 100644 --- a/responses.py +++ b/responses.py @@ -208,7 +208,8 @@ class RequestsMock(object): # TODO(dcramer): find the correct class for this if match is None: - error_msg = 'Connection refused: {0}'.format(request.url) + error_msg = 'Connection refused: {0} {1}'.format(request.method, + request.url) response = ConnectionError(error_msg) self._calls.add(request, response)
added method name to connection refused error to aid debugging
getsentry_responses
train
991c77a5d053cba7c5ba9113411ec3f576886b55
diff --git a/core/src/main/java/org/cache2k/impl/BaseCache.java b/core/src/main/java/org/cache2k/impl/BaseCache.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/cache2k/impl/BaseCache.java +++ b/core/src/main/java/org/cache2k/impl/BaseCache.java @@ -1387,6 +1387,7 @@ public abstract class BaseCache<E extends Entry, K, T> public T peekAndReplace(K key, T _value) { final int hc = modifiedHash(key.hashCode()); boolean _hasFreshData = false; + boolean _newEntry = false; E e; for (;;) { e = lookupEntryUnsynchronized(key, hc); @@ -1395,6 +1396,7 @@ public abstract class BaseCache<E extends Entry, K, T> e = lookupEntry(key, hc); if (e == null) { e = newEntry(key, hc); + _newEntry = true; } } } @@ -1421,9 +1423,13 @@ public abstract class BaseCache<E extends Entry, K, T> _finished = true; return _previousValue; } else { - synchronized (lock) { - putNewEntryCnt++; + if (_newEntry) { + synchronized (lock) { + putNewEntryCnt++; + } } + e.finishFetch(Entry.LOADED_NON_VALID); + _finished = true; return null; } } finally {
peekAndReplace, fix wrong statistics counting
cache2k_cache2k
train
430102d127c540a04b96f8fa9b18fef8ad4a98c7
diff --git a/src/ModelSearch.php b/src/ModelSearch.php index <HASH>..<HASH> 100755 --- a/src/ModelSearch.php +++ b/src/ModelSearch.php @@ -265,7 +265,7 @@ class ModelSearch $attributes = [$attributes]; } - // Is empty, so we base it off the key. + // Is empty, use the name of the table + name. if (empty($attributes)) { $attributes = [sprintf('%s.%s', $model->getTable(), $name)]; } @@ -982,10 +982,6 @@ class ModelSearch */ public static function getAllowedOperators($type) { - if (!in_array($type, self::$filter_types)) { - return []; - } - $data = self::getOperators($type); return array_keys($data);
Fixed comment; Removed code duplication
hnhdigital-os_laravel-model-search
train
962bfb30155e5547d9c475d2231efed43e60bcea
diff --git a/src/windows/EmailComposerProxy.js b/src/windows/EmailComposerProxy.js index <HASH>..<HASH> 100644 --- a/src/windows/EmailComposerProxy.js +++ b/src/windows/EmailComposerProxy.js @@ -31,7 +31,7 @@ * @param {Array} args * Interface arguments */ -exports.isAvailable = function (success, error, args) { +exports.isAvailable = function (success) { success(true); }; @@ -48,12 +48,22 @@ exports.isAvailable = function (success, error, args) { exports.open = function (success, error, args) { var props = args[0]; - try{ + try { var email = exports.getDraftWithProperties(props); Windows.ApplicationModel.Email.EmailManager .showComposeNewEmailAsync(email) - .done(success()); + .done(function () { + if (Debug.debuggerEnabled) { + success(); + console.log('degugmode'); + } else { + Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function () { + success(); + }, false); + } + + }); } catch (e) { var mailTo = exports.getMailTo(props); Windows.System.Launcher.launchUriAsync(mailTo).then( @@ -81,11 +91,11 @@ exports.getDraftWithProperties = function (props) { // body exports.setBody(props.body, props.isHtml, mail); // To recipients - exports.setRecipients(props.to, mail); + exports.setRecipients(props.to, mail.to); // CC recipients - exports.setCcRecipients(props.cc, mail); + exports.setRecipients(props.cc, mail.cc); // BCC recipients - exports.setBccRecipients(props.bcc, mail); + exports.setRecipients(props.bcc, mail.bcc); // attachments exports.setAttachments(props.attachments, mail); @@ -152,42 +162,12 @@ exports.setBody = function (body, isHTML, draft) { * * @param {String[]} recipients * List of mail addresses - * @param {Windows.ApplicationModel.Email.EmailMessage} draft - * The draft - */ -exports.setRecipients = function (recipients, draft) { - recipients.forEach(function (address) { - draft.to.push( - new Windows.ApplicationModel.Email.EmailRecipient(address)); - }); -}; - -/** - * Setter for the cc recipients. - * - * @param {String[]} recipients - * List of mail addresses - * @param {Windows.ApplicationModel.Email.EmailMessage} draft - * The draft - */ -exports.setCcRecipients = function (recipients, draft) { - recipients.forEach(function (address) { - draft.cc.push( - new Windows.ApplicationModel.Email.EmailRecipient(address)); - }); -}; - -/** - * Setter for the bcc recipients. - * - * @param {String[]} recipients - * List of mail addresses - * @param {Windows.ApplicationModel.Email.EmailMessage} draft - * The draft + * @param {Windows.ApplicationModel.Email.EmailMessage} draftAttribute + * The draft.to / *.cc / *.bcc */ -exports.setBccRecipients = function (recipients, draft) { +exports.setRecipients = function (recipients, draftAttribute) { recipients.forEach(function (address) { - draft.bcc.push( + draft.push( new Windows.ApplicationModel.Email.EmailRecipient(address)); }); }; @@ -260,12 +240,9 @@ exports.getUriForAbsolutePath = function (path) { * The URI pointing to the given path */ exports.getUriForAssetPath = function (path) { - var host = document.location.host, - protocol = document.location.protocol, - resPath = path.replace('file:/', '/www'), - rawUri = protocol + '//' + host + resPath; + var resPath = path.replace('file:/', '/www'); - return new Windows.Foundation.Uri(rawUri); + return exports.getUriForPathUtil(resPath); }; /** @@ -278,9 +255,23 @@ exports.getUriForAssetPath = function (path) { * The URI pointing to the given path */ exports.getUriForResourcePath = function (path) { + var resPath = path.replace('res:/', '/images'); + + return exports.getUriForPathUtil(resPath); +}; + +/** + * The URI for a path. + * + * @param {String} resPath + * The given relative path + * + * @return + * The URI pointing to the given path + */ +exports.getUriForPathUtil = function (resPath) { var host = document.location.host, protocol = document.location.protocol, - resPath = path.replace('res:/', '/images'), rawUri = protocol + '//' + host + resPath; return new Windows.Foundation.Uri(rawUri);
Callbacks are called after resuming now.
katzer_cordova-plugin-email-composer
train
7112532b233ae3cd48703b6e76cda0ae785ea004
diff --git a/system/View/Parser.php b/system/View/Parser.php index <HASH>..<HASH> 100644 --- a/system/View/Parser.php +++ b/system/View/Parser.php @@ -129,12 +129,13 @@ class Parser extends View $saveData = $this->config->saveData; } - $view = str_replace('.php', '', $view) . '.php'; + $template = str_replace('.php', '', $view); + $view = $template . '.php'; // Was it cached? if (isset($options['cache'])) { - $cacheName = $options['cache_name'] ?: str_replace('.php', '', $view); + $cacheName = $options['cache_name'] ?: $template; if ($output = cache($cacheName)) {
reduce str_replace in View/Parser::render()
codeigniter4_CodeIgniter4
train
44b53389c233daf96886303978678140cce09a73
diff --git a/lib/active_record_shards/connection_switcher.rb b/lib/active_record_shards/connection_switcher.rb index <HASH>..<HASH> 100644 --- a/lib/active_record_shards/connection_switcher.rb +++ b/lib/active_record_shards/connection_switcher.rb @@ -6,25 +6,25 @@ module ActiveRecordShards end def on_shard(shard, &block) - old_shard = current_shard_selection.shard + old_options = current_shard_selection.options switch_connection(:shard => shard) if supports_sharding? yield ensure - switch_connection(:shard => old_shard) + switch_connection(old_options) end def on_all_shards(&block) - old_shard = current_shard_selection.shard - if supports_sharding? - shard_names.each do |shard| - switch_connection(:shard => shard) - yield - end - else + old_options = current_shard_selection.options + if supports_sharding? + shard_names.each do |shard| + switch_connection(:shard => shard) yield end - ensure - switch_connection(:shard => old_shard) + else + yield + end + ensure + switch_connection(old_options) end def on_slave_if(condition, &block) @@ -58,21 +58,22 @@ module ActiveRecordShards alias_method :with_slave_unless, :on_slave_unless def on_slave_block(&block) - old_slave = current_shard_selection.on_slave? - begin - switch_connection(:slave => true) - rescue ActiveRecord::AdapterNotSpecified => e - switch_connection(:slave => old_slave) - logger.warn("Failed to establish shard connection: #{e.message} - defaulting to master") - end + old_options = current_shard_selection.options + switch_connection(:slave => true) with_scope({:find => {:readonly => current_shard_selection.on_slave?}}, :merge, &block) ensure - switch_connection(:slave => old_slave) + switch_connection(old_options) end # Name of the connection pool. Used by ConnectionHandler to retrieve the current connection pool. def connection_pool_name # :nodoc: - current_shard_selection.shard_name(self) + name = current_shard_selection.shard_name(self) + + if configurations[name].nil? && current_shard_selection.on_slave? + current_shard_selection.shard_name(self, false) + else + name + end end def supports_sharding? @@ -100,13 +101,17 @@ module ActiveRecordShards end def shard_names - env_name = defined?(Rails.env) ? Rails.env : RAILS_ENV - configurations[env_name]['shard_names'] || [] + configurations[shard_env]['shard_names'] || [] + end + + def shard_env + @shard_env = defined?(Rails.env) ? Rails.env : RAILS_ENV end def establish_shard_connection - name = current_shard_selection.shard_name(self) + name = connection_pool_name spec = configurations[name] + raise ActiveRecord::AdapterNotSpecified.new("No database defined by #{name} in database.yml") if spec.nil? connection_handler.establish_connection(connection_pool_name, ActiveRecord::Base::ConnectionSpecification.new(spec, "#{spec['adapter']}_connection")) diff --git a/lib/active_record_shards/shard_selection.rb b/lib/active_record_shards/shard_selection.rb index <HASH>..<HASH> 100644 --- a/lib/active_record_shards/shard_selection.rb +++ b/lib/active_record_shards/shard_selection.rb @@ -29,14 +29,20 @@ module ActiveRecordShards @on_slave = (new_slave == true) end - def shard_name(klass = nil) + def shard_name(klass = nil, try_slave = true) s = "#{RAILS_ENV}" if the_shard = shard(klass) s << '_shard_' s << the_shard end - s << "_slave" if @on_slave + if @on_slave && try_slave + s << "_slave" if @on_slave + end s end + + def options + {:shard => @shard, :slave => @on_slave} + end end end \ No newline at end of file
batter fallback when slaves are not present
zendesk_active_record_shards
train
ec500d119b8cc4758cc1fde21fa421853864e095
diff --git a/pattern/src/main/java/org/openbase/jul/pattern/AbstractObservable.java b/pattern/src/main/java/org/openbase/jul/pattern/AbstractObservable.java index <HASH>..<HASH> 100644 --- a/pattern/src/main/java/org/openbase/jul/pattern/AbstractObservable.java +++ b/pattern/src/main/java/org/openbase/jul/pattern/AbstractObservable.java @@ -165,7 +165,7 @@ public abstract class AbstractObservable<T> implements Observable<T> { synchronized (LOCK) { try { if (unchangedValueFilter && isValueAvailable() && observable.hashCode() == latestValueHash) { - LOGGER.debug("Skip notification because observable has not been changed!"); + LOGGER.debug("Skip notification because " + this + " has not been changed!"); return false; } @@ -238,4 +238,9 @@ public abstract class AbstractObservable<T> implements Observable<T> { public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } + + @Override + public String toString() { + return Observable.class.getSimpleName() + "[" + (source == this ? source.getClass().getSimpleName() : source) + "]"; + } } diff --git a/pattern/src/main/java/org/openbase/jul/pattern/ObservableImpl.java b/pattern/src/main/java/org/openbase/jul/pattern/ObservableImpl.java index <HASH>..<HASH> 100644 --- a/pattern/src/main/java/org/openbase/jul/pattern/ObservableImpl.java +++ b/pattern/src/main/java/org/openbase/jul/pattern/ObservableImpl.java @@ -21,11 +21,8 @@ package org.openbase.jul.pattern; * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ -import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.openbase.jul.exception.CouldNotPerformException; -import org.openbase.jul.exception.MultiException; -import org.openbase.jul.exception.MultiException.ExceptionStack; import org.openbase.jul.exception.NotAvailableException; import org.openbase.jul.exception.TimeoutException; import org.slf4j.Logger; @@ -140,5 +137,4 @@ public class ObservableImpl<T> extends AbstractObservable<T> { protected void applyValueUpdate(final T value) { this.value = value; } - }
Cleanup and AbstractObservable toString implemented.
openbase_jul
train
ab133caa8c37efd2fa92a0b43c433a4725213f65
diff --git a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php +++ b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php @@ -80,7 +80,9 @@ class FrameworkBundle extends Bundle $container->addCompilerPass(new TemplatingPass()); $container->addCompilerPass(new AddConstraintValidatorsPass(), PassConfig::TYPE_BEFORE_REMOVING); $container->addCompilerPass(new AddValidatorInitializersPass()); - $container->addCompilerPass(new AddConsoleCommandPass()); + if (class_exists(AddConsoleCommandPass::class)) { + $container->addCompilerPass(new AddConsoleCommandPass()); + } $container->addCompilerPass(new FormPass()); $container->addCompilerPass(new TranslatorPass()); $container->addCompilerPass(new LoggingTranslatorPass());
[FrameworkBundle] Prevent an error when the console component isn't installed
symfony_symfony
train
c11116822afcdaab05ccd9f76549e9089bb44f47
diff --git a/examples/doh.js b/examples/doh.js index <HASH>..<HASH> 100644 --- a/examples/doh.js +++ b/examples/doh.js @@ -26,12 +26,12 @@ const buf = dnsPacket.encode({ }) const options = { - hostname: 'dns.google.com', + hostname: 'dns.google', port: 443, - path: '/experimental', + path: '/dns-query', method: 'POST', headers: { - 'Content-Type': 'application/dns-udpwireformat', + 'Content-Type': 'application/dns-message', 'Content-Length': Buffer.byteLength(buf) } }
Update DoH example from internet-draft to RFC <I>. (#<I>)
mafintosh_dns-packet
train
5c802f728a777ae60dd29f3dc42fe4d7a27ff946
diff --git a/src/Opulence/Applications/Application.php b/src/Opulence/Applications/Application.php index <HASH>..<HASH> 100644 --- a/src/Opulence/Applications/Application.php +++ b/src/Opulence/Applications/Application.php @@ -18,7 +18,7 @@ use Opulence\Applications\Tasks\TaskTypes; class Application { /** @var string The current Opulence version */ - private static $opulenceVersion = "1.0.0-beta4"; + private static $opulenceVersion = "1.0.0-beta5"; /** @var ITaskDispatcher The task dispatcher */ private $taskDispatcher = null; /** @var string The version of the application */
Incremented app version, fixed #<I> (previously accidentally said <I>)
opulencephp_Opulence
train
32f18f0017f0f43f3457fdd0d59632d09d24ad6b
diff --git a/src/worker.py b/src/worker.py index <HASH>..<HASH> 100644 --- a/src/worker.py +++ b/src/worker.py @@ -132,14 +132,21 @@ class Worker(Thread): def read_headers(self, sock_file): headers = dict() l = sock_file.readline() + lname = None + lval = None while l != b('\r\n'): try: - # HTTP header values are latin-1 encoded - l = l.split(b(':'), 1) - # HTTP header names are us-ascii encoded - lname = u(l[0].strip(), 'us-ascii').replace(u('-'), u('_')) - lval = u(l[-1].strip(), 'latin-1') - headers.update({u('HTTP_')+lname.upper(): lval}) + if l[0] in b(' \t') and lname: + # Some headers take more than one line + lval += u(', ') + u(l, 'latin-1').strip() + else: + # HTTP header values are latin-1 encoded + l = l.split(b(':'), 1) + # HTTP header names are us-ascii encoded + lname = u(l[0].strip(), 'us-ascii').replace(u('-'), u('_')) + lname = u('HTTP_')+lname.upper() + lval = u(l[-1].strip(), 'latin-1') + headers.update({lname: lval}) except UnicodeDecodeError: self.log.warning('Client sent invalid header: ' + l.__repr__())
Added multi-line http header handling
explorigin_Rocket
train
a804f9ad414a4b1c0c451c4d0ba751fd2396fd52
diff --git a/spec/runner.rb b/spec/runner.rb index <HASH>..<HASH> 100755 --- a/spec/runner.rb +++ b/spec/runner.rb @@ -29,10 +29,10 @@ cap['browserstack.tunnelIdentifier'] = ENV['TRAVIS_JOB_ID'] cap['browserstack.tunnel'] = 'true' cap['browserstack.debug'] = 'false' -cap['databaseEnabled'] = true -cap['browserConnectionEnabled'] = true -cap['locationContextEnabled'] = true -cap['webStorageEnabled'] = true +cap['databaseEnabled'] = 'true' +cap['browserConnectionEnabled'] = 'true' +cap['locationContextEnabled'] = 'true' +cap['webStorageEnabled'] = 'true' print 'Loading...'
spec/runner: use strings for capabilities
opal_opal-browser
train
8e067b0b44b83c92e2417fb7256192be73e5a933
diff --git a/actionpack/lib/action_controller/mime_responds.rb b/actionpack/lib/action_controller/mime_responds.rb index <HASH>..<HASH> 100644 --- a/actionpack/lib/action_controller/mime_responds.rb +++ b/actionpack/lib/action_controller/mime_responds.rb @@ -161,7 +161,7 @@ module ActionController #:nodoc: @responses[@order.first].call return else - if priority === @order + if @responses[priority] @responses[priority].call return # mime type match found, be happy and return end
Fixed that a response has to be available for that exact mime type for it to be called (otherwise <I> should occur) git-svn-id: <URL>
rails_rails
train
9d723652b6d91c5be23c75fa72e446668d6f76d6
diff --git a/integration/windows/Vagrantfile b/integration/windows/Vagrantfile index <HASH>..<HASH> 100644 --- a/integration/windows/Vagrantfile +++ b/integration/windows/Vagrantfile @@ -153,7 +153,8 @@ enable_ssh = <<-SHELL $OpenSSHZipPath = "C:\\bosh\\OpenSSH-Win64.zip" Push-Location $env:PROGRAMFILES -Expand-Archive -Path $OpenSSHZipPath -DestinationPath .\\ +Add-Type -AssemblyName System.IO.Compression.FileSystem +[System.IO.Compression.ZipFile]::ExtractToDirectory($OpenSSHZipPath, $env:PROGRAMFILES) Rename-Item .\\OpenSSH-Win64 OpenSSH Push-Location OpenSSH diff --git a/integration/windows/environment_test.go b/integration/windows/environment_test.go index <HASH>..<HASH> 100644 --- a/integration/windows/environment_test.go +++ b/integration/windows/environment_test.go @@ -195,6 +195,10 @@ func (e *WindowsEnvironment) RunPowershellCommandWithOffsetAndResponses( return outString, errString, exitCode, err } +func (e *WindowsEnvironment) RunPowershellCommandWithResponses(cmd string, cmdFmtArgs ...interface{}) (string, string, int, error) { + return e.RunPowershellCommandWithOffsetAndResponses(1, cmd, cmdFmtArgs...) +} + func (e *WindowsEnvironment) RunPowershellCommand(cmd string, cmdFmtArgs ...interface{}) string { return e.RunPowershellCommandWithOffset(1, cmd, cmdFmtArgs...) } diff --git a/integration/windows/windows_test.go b/integration/windows/windows_test.go index <HASH>..<HASH> 100644 --- a/integration/windows/windows_test.go +++ b/integration/windows/windows_test.go @@ -137,7 +137,7 @@ var _ = Describe("An Agent running on Windows", func() { Expect(setupResult.Status).To(Equal("success")) - output := agent.RunPowershellCommand(fmt.Sprintf(`get-wmiobject -class win32_userprofile | Where { $_.LocalPath -eq 'C:\Users\%s'}`, sshTestUser)) + output := agent.RunPowershellCommand(`get-wmiobject -class win32_userprofile | Where { $_.LocalPath -eq 'C:\Users\%s'}`, sshTestUser) Expect(output).To(MatchRegexp(sshTestUser)) client, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", AgentPublicIP), sshClientConfig) @@ -154,10 +154,10 @@ var _ = Describe("An Agent running on Windows", func() { Expect(cleanupResult.Status).To(Equal("success")) - sshUsers := agent.RunPowershellCommand(fmt.Sprintf(`Get-LocalUser | Where { $_.Name -like "%s" }`, sshTestUser)) - Expect(sshUsers).To(BeEmpty()) + _, _, exitCode, _ := agent.RunPowershellCommandWithResponses(`NET.exe USER %s`, sshTestUser) + Expect(exitCode).To(Equal(1)) - deletableUserProfileContent := agent.RunPowershellCommand(fmt.Sprintf(`Get-ChildItem -force -recurse -attributes !Directory -Exclude 'ntuser.dat*' , 'usrclass.dat*' /users/%s`, sshTestUser)) + deletableUserProfileContent := agent.RunPowershellCommand(`Get-ChildItem -force -recurse -attributes !Directory -Exclude 'ntuser.dat*' , 'usrclass.dat*' /users/%s`, sshTestUser) Expect(deletableUserProfileContent).To(BeEmpty()) })
<I>R2 doesn't have get-localuser or expand-archive [#<I>]
cloudfoundry_bosh-agent
train
4e8eccfd235df82242894907233a0d89e8200905
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -488,5 +488,13 @@ class ApplicationController < ActionController::Base } end end + + # Parse the input provided and return the value of displayMessage. If displayMessage is not available, return "". + # (Note: this can be used to pull the displayMessage from a Candlepin exception.) + # This assumes that the input follows a syntax similar to: + # "{\"displayMessage\":\"Import is older than existing data\"}" + def parse_display_message input + display_message = input.include?("displayMessage") ? input.split(":\"").last.split("\"").first : "" + end end diff --git a/app/controllers/providers_controller.rb b/app/controllers/providers_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/providers_controller.rb +++ b/app/controllers/providers_controller.rb @@ -68,10 +68,13 @@ class ProvidersController < ApplicationController temp_file.write params[:provider][:contents].read temp_file.close @provider.import_manifest File.expand_path(temp_file.path) - notice _("Subscription uploaded successfully"), {:synchronous_request => false} + notice _("Subscription manifest uploaded successfully for provider '%{name}'." % {:name => @provider.name}), {:synchronous_request => false} rescue Exception => error - errors _("There was a format error with your Subscription Manifest"), {:synchronous_request => false} + display_message = parse_display_message(error.response) + error_text = _("Subscription manifest upload for provider '%{name}' failed." % {:name => @provider.name}) + error_text += _("%{newline}Reason: %{reason}" % {:reason => display_message, :newline => "<br />"}) unless display_message.blank? + errors error_text Rails.logger.error "error uploading subscriptions." Rails.logger.error error Rails.logger.error error.backtrace.join("\n") @@ -81,7 +84,7 @@ class ProvidersController < ApplicationController redhat_provider else # user didn't provide a manifest to upload - errors _("Subscription Manifest must be specified on upload.") + errors _("Subscription manifest must be specified on upload.") render :nothing => true end end @@ -93,7 +96,10 @@ class ProvidersController < ApplicationController begin setup_subs rescue Exception => error - errors _("Unable to retrieve your Subscription Manifest"), {:synchronous_request => false} + display_message = parse_display_message(error.response) + error_text = _("Unable to retrieve subscription manifest for provider '%{name}." % {:name => @provider.name}) + error_text += _("%{newline}Reason: %{reason}" % {:reason => display_message, :newline => "<br />"}) unless display_message.blank? + errors error_text, {:synchronous_request => false} Rails.logger.error "Error fetching subscriptions from Candlepin" Rails.logger.error error Rails.logger.error error.backtrace.join("\n")
<I> - include candlepin error text in error notice on manifest upload error With this commit, if the user attempts to upload a manifest and it generates an error from candlepin, the error text (displayMessage) from candelpin will be included in the notice generated to the user. E.g. Subscription manifest upload for provider 'Red Hat' failed. Reason: Import is older than existing data
Katello_katello
train
e078b17eb0fcd6b64f452a4f712f327dace7fb09
diff --git a/lib/bitescript/asm.rb b/lib/bitescript/asm.rb index <HASH>..<HASH> 100644 --- a/lib/bitescript/asm.rb +++ b/lib/bitescript/asm.rb @@ -4,6 +4,9 @@ module BiteScript module ASM begin # try mangled names for the version included with JRuby + java.lang.Class.for_name 'jruby.objectweb.asm.Opcodes' + + # no error, proceed with mangled name asm_package = Java::jruby.objectweb.asm java_import asm_package.Opcodes rescue Exception diff --git a/lib/bitescript/builder.rb b/lib/bitescript/builder.rb index <HASH>..<HASH> 100644 --- a/lib/bitescript/builder.rb +++ b/lib/bitescript/builder.rb @@ -197,14 +197,7 @@ module BiteScript include Util include QuickTypes include Annotatable - - begin - java_import "jruby.objectweb.asm.Opcodes" - java_import "jruby.objectweb.asm.ClassWriter" - rescue - java_import "org.objectweb.asm.Opcodes" - java_import "org.objectweb.asm.ClassWriter" - end + include ASM java_import java.lang.Object java_import java.lang.Void @@ -416,15 +409,10 @@ module BiteScript end class MethodBuilder - begin - java_import "jruby.objectweb.asm.Opcodes" - rescue - java_import "org.objectweb.asm.Opcodes" - end - include QuickTypes include Annotatable include BiteScript::Bytecode + include ASM attr_reader :method_visitor attr_reader :static
Clean up verbose warnings when attempting to load the mangled ASM packages.
headius_bitescript
train
1caaf334f374bc5bd290fbbf70309da2a8c31395
diff --git a/src/renderWindow.js b/src/renderWindow.js index <HASH>..<HASH> 100644 --- a/src/renderWindow.js +++ b/src/renderWindow.js @@ -285,22 +285,14 @@ vglModule.renderWindow = function(canvas) { } }; - //////////////////////////////////////////////////////////////////////////// /** - * Get the focusDisplayPoint based on activeRenderer and its camera + * Get the focusDisplayPoint from the activeRenderer * @returns {vec4} */ - //////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////// this.focusDisplayPoint = function() { - var camera = m_activeRender.camera(), - focalPoint = camera.focalPoint(), - focusWorldPt = vec4.fromValues( - focalPoint[0], focalPoint[1], focalPoint[2], 1); - - return m_activeRender.worldToDisplay( - focusWorldPt, camera.viewMatrix(), - camera.projectionMatrix(), m_width, m_height); + return m_activeRender.focusDisplayPoint(); }; //////////////////////////////////////////////////////////////////////////// @@ -315,7 +307,7 @@ vglModule.renderWindow = function(canvas) { this.displayToWorld = function(x, y, focusDisplayPoint) { var camera = m_activeRender.camera(); if(!focusDisplayPoint) { - focusDisplayPoint = this.focusDisplayPoint(); + focusDisplayPoint = m_activeRender.focusDisplayPoint(); } return m_activeRender.displayToWorld( diff --git a/src/renderer.js b/src/renderer.js index <HASH>..<HASH> 100644 --- a/src/renderer.js +++ b/src/renderer.js @@ -496,6 +496,22 @@ vglModule.renderer = function() { return worldPt; }; + //////////////////////////////////////////////////////////////////////////// + /** + * Get the focusDisplayPoint + * @returns {vec4} + */ + //////////////////////////////////////////////////////////////////////////// + this.focusDisplayPoint = function() { + var focalPoint = m_camera.focalPoint(), + focusWorldPt = vec4.fromValues( + focalPoint[0], focalPoint[1], focalPoint[2], 1); + + return this.worldToDisplay( + focusWorldPt, m_camera.viewMatrix(), + m_camera.projectionMatrix(), m_width, m_height); + }; + return this; };
Move focus point computation to the renderer
OpenGeoscience_vgl
train
90710b0d50ba748137bac5029a4be0a6d98d8951
diff --git a/ocrd/logging.py b/ocrd/logging.py index <HASH>..<HASH> 100644 --- a/ocrd/logging.py +++ b/ocrd/logging.py @@ -71,26 +71,32 @@ def getLogger(*args, **kwargs): # Default logging config -logging.basicConfig(level=logging.INFO) -logging.getLogger('').setLevel(logging.INFO) -# logging.getLogger('ocrd.resolver').setLevel(logging.INFO) -# logging.getLogger('ocrd.resolver.download_to_directory').setLevel(logging.INFO) -# logging.getLogger('ocrd.resolver.add_files_to_mets').setLevel(logging.INFO) -logging.getLogger('PIL').setLevel(logging.INFO) - -# Allow overriding - -CONFIG_PATHS = [ - os.path.curdir, - os.path.join(os.path.expanduser('~')), - '/etc', -] - - -for p in CONFIG_PATHS: - config_file = os.path.join(p, 'ocrd_logging.py') - if os.path.exists(config_file): - logging.info("Loading logging configuration from '%s'", config_file) - with open(config_file) as f: - code = compile(f.read(), config_file, 'exec') - exec(code, globals(), locals()) # pylint: disable=exec-used +def initLogging(): + """ + Sets logging defaults + """ + logging.basicConfig(level=logging.INFO) + logging.getLogger('').setLevel(logging.INFO) + # logging.getLogger('ocrd.resolver').setLevel(logging.INFO) + # logging.getLogger('ocrd.resolver.download_to_directory').setLevel(logging.INFO) + # logging.getLogger('ocrd.resolver.add_files_to_mets').setLevel(logging.INFO) + logging.getLogger('PIL').setLevel(logging.INFO) + + # Allow overriding + + CONFIG_PATHS = [ + os.path.curdir, + os.path.join(os.path.expanduser('~')), + '/etc', + ] + + + for p in CONFIG_PATHS: + config_file = os.path.join(p, 'ocrd_logging.py') + if os.path.exists(config_file): + logging.info("Loading logging configuration from '%s'", config_file) + with open(config_file) as f: + code = compile(f.read(), config_file, 'exec') + exec(code, globals(), locals()) # pylint: disable=exec-used + +initLogging() diff --git a/test/test_cli.py b/test/test_cli.py index <HASH>..<HASH> 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -2,7 +2,7 @@ from test.base import TestCase, main import click from click.testing import CliRunner from ocrd.decorators import ocrd_cli_options -from ocrd.logging import setOverrideLogLevel +from ocrd.logging import setOverrideLogLevel, initLogging @click.command() @ocrd_cli_options @@ -12,6 +12,7 @@ def cli(*args, **kwargs): # pylint: disable=unused-argument class TestCli(TestCase): def setUp(self): + initLogging() self.runner = CliRunner() def test_minimal(self): diff --git a/test/test_logging.py b/test/test_logging.py index <HASH>..<HASH> 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -4,11 +4,13 @@ from test.base import TestCase, main from ocrd.logging import ( getLevelName, setOverrideLogLevel, + initLogging ) class TestLogging(TestCase): - # def runTest(self): + def setUp(self): + initLogging() def test_getLevelName(self): self.assertEqual(getLevelName('ERROR'), logging.ERROR)
loggin: initLogging to explicitly (re-)initialize logging
OCR-D_core
train
7f33c7f007ddde1f8455d815dc902942524bb235
diff --git a/src/org/openscience/cdk/io/MDLWriter.java b/src/org/openscience/cdk/io/MDLWriter.java index <HASH>..<HASH> 100644 --- a/src/org/openscience/cdk/io/MDLWriter.java +++ b/src/org/openscience/cdk/io/MDLWriter.java @@ -126,7 +126,11 @@ public class MDLWriter extends DefaultChemObjectWriter { else if (object instanceof Molecule) { try{ - writeMolecule((Molecule)object); + boolean[] isVisible=new boolean[((Molecule)object).getAtomCount()]; + for(int i=0;i<isVisible.length;i++){ + isVisible[i]=true; + } + writeMolecule((Molecule)object,isVisible); } catch(Exception ex){ logger.error(ex.getMessage()); @@ -153,7 +157,11 @@ public class MDLWriter extends DefaultChemObjectWriter { Molecule[] molecules = som.getMolecules(); try { - writeMolecule(molecules[0]); + boolean[] isVisible=new boolean[molecules[0].getAtomCount()]; + for(int i=0;i<isVisible.length;i++){ + isVisible[i]=true; + } + writeMolecule(molecules[0], isVisible); } catch (Exception exc) { @@ -164,7 +172,11 @@ public class MDLWriter extends DefaultChemObjectWriter { { writer.write("$$$$"); writer.newLine(); - writeMolecule(molecules[i]); + boolean[] isVisible=new boolean[molecules[i].getAtomCount()]; + for(int k=0;k<isVisible.length;k++){ + isVisible[k]=true; + } + writeMolecule(molecules[i], isVisible); } catch (Exception exc) { @@ -182,27 +194,61 @@ public class MDLWriter extends DefaultChemObjectWriter { * @param molecule Molecule that is written to an OutputStream */ public void writeMolecule(Molecule molecule) throws Exception { + boolean[] isVisible=new boolean[molecule.getAtomCount()]; + for(int i=0;i<isVisible.length;i++){ + isVisible[i]=true; + } + writeMolecule(molecule, isVisible); + } + + /** + * Writes a Molecule to an OutputStream in MDL sdf format. + * + * @param molecule Molecule that is written to an OutputStream + * @param isVisible Should a certain atom be written to mdl? + */ + public void writeMolecule(Molecule molecule, boolean[] isVisible) throws Exception { int Bonorder, stereo; String line = ""; // write header block + // lines get shortened to 80 chars, that's in the spec String title = (String)molecule.getProperty(CDKConstants.TITLE); if (title == null) title = ""; + if(title.length()>80) + title=title.substring(0,80); writer.write(title + "\n"); writer.write(" CDK\n"); String comment = (String)molecule.getProperty(CDKConstants.REMARK); if (comment == null) comment = ""; + if(comment.length()>80) + comment=comment.substring(0,80); writer.write(comment + "\n"); // write Counts line - line += formatMDLInt(molecule.getAtomCount(), 3); - line += formatMDLInt(molecule.getBondCount(), 3); + int upToWhichAtom=0; + for(int i=0;i<isVisible.length;i++){ + if(isVisible[i]) + upToWhichAtom++; + } + line += formatMDLInt(upToWhichAtom, 3); + int numberOfBonds=0; + if(upToWhichAtom<molecule.getAtomCount()){ + for(int i=0;i<molecule.getBondCount();i++){ + if(isVisible[molecule.getAtomNumber(molecule.getBondAt(i).getAtoms()[0])] && isVisible[molecule.getAtomNumber(molecule.getBondAt(i).getAtoms()[1])]) + numberOfBonds++; + } + }else{ + numberOfBonds=molecule.getBondCount(); + } + line += formatMDLInt(numberOfBonds, 3); line += " 0 0 0 0 0 0 0 0999 V2000\n"; writer.write(line); // write Atom block Atom[] atoms = molecule.getAtoms(); for (int f = 0; f < atoms.length; f++) { + if(isVisible[f]){ Atom atom = atoms[f]; line = ""; if (atom.getPoint3D() != null) { @@ -224,11 +270,13 @@ public class MDLWriter extends DefaultChemObjectWriter { line += " 0 0 0 0 0 0 0 0 0 0 0 0"; writer.write(line); writer.newLine(); + } } // write Bond block Bond[] bonds = molecule.getBonds(); for (int g = 0; g < bonds.length; g++) { + if(upToWhichAtom==molecule.getAtomCount() || (isVisible[molecule.getAtomNumber(molecule.getBondAt(g).getAtoms()[0])] && isVisible[molecule.getAtomNumber(molecule.getBondAt(g).getAtoms()[1])])){ Bond bond = bonds[g]; if (bond.getAtoms().length != 2) { logger.warn("Skipping bond with more/less than two atoms: " + bond); @@ -262,13 +310,14 @@ public class MDLWriter extends DefaultChemObjectWriter { case CDKConstants.STEREO_BOND_DOWN_INV: line += "6"; break; - default: + default: line += "0"; } line += " 0 0 0 "; writer.write(line); writer.newLine(); } + } } // write formal atomic charges
Now cuts comments since the spec restricts length of comments to <I> chars git-svn-id: <URL>
cdk_cdk
train
64800aacf8b6ddc129e4f2259de6d56bb6d47173
diff --git a/runipy/notebook_runner.py b/runipy/notebook_runner.py index <HASH>..<HASH> 100644 --- a/runipy/notebook_runner.py +++ b/runipy/notebook_runner.py @@ -225,7 +225,5 @@ class NotebookRunner(object): progress_callback(i) def count_code_cells(self): - """ - Return the number of code cells in the notebook - """ + """Return the number of code cells in the notebook.""" return sum(1 for _ in self.iter_code_cells())
runipy/notebook_runner.py: Put short docstring on one line and add a period at the end.
paulgb_runipy
train
61ef343d9069cc256f82b1fa460ca9b19aadd86a
diff --git a/src/main/java/biweekly/util/Period.java b/src/main/java/biweekly/util/Period.java index <HASH>..<HASH> 100644 --- a/src/main/java/biweekly/util/Period.java +++ b/src/main/java/biweekly/util/Period.java @@ -42,8 +42,8 @@ public final class Period { * @param endDate the end date */ public Period(Date startDate, Date endDate) { - this.startDate = startDate; - this.endDate = endDate; + this.startDate = copy(startDate); + this.endDate = copy(endDate); duration = null; } @@ -53,7 +53,7 @@ public final class Period { * @param duration the length of time after the start date */ public Period(Date startDate, Duration duration) { - this.startDate = startDate; + this.startDate = copy(startDate); this.duration = duration; endDate = null; } @@ -73,7 +73,7 @@ public final class Period { * @return the start date */ public Date getStartDate() { - return startDate; + return copy(startDate); } /** @@ -81,7 +81,7 @@ public final class Period { * @return the end date or null if not set */ public Date getEndDate() { - return endDate; + return copy(endDate); } /** @@ -129,4 +129,8 @@ public final class Period { return false; return true; } + + private Date copy(Date date) { + return (date == null) ? null : new Date(date.getTime()); + } }
Date objects need to be copied in order to make the class immutable.
mangstadt_biweekly
train
befe64cb7e38d1682923c681df6bb466db3a1dde
diff --git a/example.js b/example.js index <HASH>..<HASH> 100644 --- a/example.js +++ b/example.js @@ -1,7 +1,7 @@ // // Require our fs lib, not the original. // -var fs = require('./lib/fs.js'); +var fs = require('./lib/fs'); // // Example with non-recursion. @@ -24,4 +24,8 @@ fs.mkdir('example_dir/first/second/third/fourth/fifth', 0777, true, function (er } else { console.log('Directory created'); } -}); \ No newline at end of file +}); + +// +// Synchronous example with recursion. +fs.mkdirSync('example_sync/first/second/third/fourth/fifth', 0777, true); \ No newline at end of file
Added recursive mkdirSync() example.
bpedro_node-fs
train
a1ae250c979e25974652314f1a79b66147d5731c
diff --git a/source/sortable-item-handle.js b/source/sortable-item-handle.js index <HASH>..<HASH> 100644 --- a/source/sortable-item-handle.js +++ b/source/sortable-item-handle.js @@ -25,7 +25,7 @@ mainModule.directive('sortableItemHandle', ['sortableConfig', '$helper', '$window', '$document', function (sortableConfig, $helper, $window, $document) { return { - require: '^sortableItem', + require: ['^sortableItem', '^sortable'], scope: true, restrict: 'A', controller: 'ui.sortable.sortableItemHandleController', @@ -45,17 +45,33 @@ isDragBefore,//is element moved up direction. isPlaceHolderPresent,//is placeholder present. bindDrag,//bind drag events. + unbindDrag,//unbind drag events. bindEvents,//bind the drag events. unBindEvents,//unbind the drag events. hasTouch,// has touch support. - dragHandled; //drag handled. + dragHandled, //drag handled. + isEnabled = true; //sortable is enabled hasTouch = $window.hasOwnProperty('ontouchstart'); if (sortableConfig.handleClass) { element.addClass(sortableConfig.handleClass); } - scope.itemScope = itemController.scope; + + scope.itemScope = controllers[0].scope; + scope.sortableScope = controllers[1].scope; + + scope.$watch('sortableScope.isEnabled', function(newVal){ + if (isEnabled !== newVal) { + isEnabled = newVal; + + if (isEnabled) { + bindDrag(); + } else { + unbindDrag(); + } + } + }); /** * Triggered when drag event starts. @@ -396,4 +412,4 @@ } }; }]); -}()); \ No newline at end of file +}()); diff --git a/source/sortable.js b/source/sortable.js index <HASH>..<HASH> 100644 --- a/source/sortable.js +++ b/source/sortable.js @@ -184,8 +184,13 @@ }); scope.callbacks = callbacks; }, true); + + // Set isEnabled if attr is set, if undefined isEnabled = true + scope.$watch(attrs.isEnabled, function (newVal, oldVal) { + scope.isEnabled = newVal !== undefined ? newVal : true; + }, true); } }; }); -}()); \ No newline at end of file +}());
New Feature: isEnabled attribute on sortable
a5hik_ng-sortable
train
5668a594658d094c564f31f408ffdc020fcede59
diff --git a/PHPCompatibility/Sniffs/FunctionUse/NewFunctionsSniff.php b/PHPCompatibility/Sniffs/FunctionUse/NewFunctionsSniff.php index <HASH>..<HASH> 100644 --- a/PHPCompatibility/Sniffs/FunctionUse/NewFunctionsSniff.php +++ b/PHPCompatibility/Sniffs/FunctionUse/NewFunctionsSniff.php @@ -4472,6 +4472,10 @@ class NewFunctionsSniff extends AbstractNewFeatureSniff '7.4' => false, '8.0' => true, ), + 'str_contains' => array( + '7.4' => false, + '8.0' => true, + ), 'openssl_cms_encrypt' => array( '7.4' => false, '8.0' => true, diff --git a/PHPCompatibility/Tests/FunctionUse/NewFunctionsUnitTest.inc b/PHPCompatibility/Tests/FunctionUse/NewFunctionsUnitTest.inc index <HASH>..<HASH> 100644 --- a/PHPCompatibility/Tests/FunctionUse/NewFunctionsUnitTest.inc +++ b/PHPCompatibility/Tests/FunctionUse/NewFunctionsUnitTest.inc @@ -990,3 +990,4 @@ fdiv(); get_debug_type(); get_resource_id(); preg_last_error_msg(); +str_contains(); diff --git a/PHPCompatibility/Tests/FunctionUse/NewFunctionsUnitTest.php b/PHPCompatibility/Tests/FunctionUse/NewFunctionsUnitTest.php index <HASH>..<HASH> 100644 --- a/PHPCompatibility/Tests/FunctionUse/NewFunctionsUnitTest.php +++ b/PHPCompatibility/Tests/FunctionUse/NewFunctionsUnitTest.php @@ -1050,6 +1050,7 @@ class NewFunctionsUnitTest extends BaseSniffTest array('get_debug_type', '7.4', array(990), '8.0'), array('get_resource_id', '7.4', array(991), '8.0'), array('preg_last_error_msg', '7.4', array(992), '8.0'), + array('str_contains', '7.4', array(993), '8.0'), array('openssl_cms_encrypt', '7.4', array(984), '8.0'), array('openssl_cms_decrypt', '7.4', array(985), '8.0'), array('openssl_cms_read', '7.4', array(986), '8.0'),
PHP <I>: NewFunctions: account for new str_contains() function > Added str_contains($haystack, $needle) function, which checks whether > $haystack contains $needle as a sub-string. It is equivalent to writing > strpos($haystack, $needle) !== false. Refs: * <URL>
PHPCompatibility_PHPCompatibility
train
5c77d24d9e1092b13a4ca03c6d0c6b66b77f5fe0
diff --git a/Media/DisplayMedia/Strategies/ImageStrategy.php b/Media/DisplayMedia/Strategies/ImageStrategy.php index <HASH>..<HASH> 100644 --- a/Media/DisplayMedia/Strategies/ImageStrategy.php +++ b/Media/DisplayMedia/Strategies/ImageStrategy.php @@ -60,5 +60,4 @@ class ImageStrategy extends AbstractStrategy { return "image"; } - } diff --git a/Media/DisplayMedia/Strategies/PdfStrategy.php b/Media/DisplayMedia/Strategies/PdfStrategy.php index <HASH>..<HASH> 100644 --- a/Media/DisplayMedia/Strategies/PdfStrategy.php +++ b/Media/DisplayMedia/Strategies/PdfStrategy.php @@ -10,6 +10,8 @@ use Symfony\Component\HttpFoundation\RequestStack; */ class PdfStrategy extends AbstractStrategy { + const MIME_TYPE_PDF = 'application/pdf'; + protected $request; /** @@ -27,7 +29,7 @@ class PdfStrategy extends AbstractStrategy */ public function support(MediaInterface $media) { - return 'application/pdf' == $media->getMimeType(); + return self::MIME_TYPE_PDF == $media->getMimeType(); } /** diff --git a/Media/DisplayMedia/Strategies/VideoStrategy.php b/Media/DisplayMedia/Strategies/VideoStrategy.php index <HASH>..<HASH> 100644 --- a/Media/DisplayMedia/Strategies/VideoStrategy.php +++ b/Media/DisplayMedia/Strategies/VideoStrategy.php @@ -10,6 +10,8 @@ use Symfony\Component\HttpFoundation\RequestStack; */ class VideoStrategy extends AbstractStrategy { + const MIME_TYPE_FRAGMENT_VIDEO = 'video'; + protected $request; /** @@ -27,7 +29,7 @@ class VideoStrategy extends AbstractStrategy */ public function support(MediaInterface $media) { - return strpos($media->getMimeType(), 'video') === 0; + return strpos($media->getMimeType(), self::MIME_TYPE_FRAGMENT_VIDEO) === 0; } /**
Use constants in ThumbnailStrategy
open-orchestra_open-orchestra-media-bundle
train
746f096989b33d4bec724e337c701e16e406828e
diff --git a/lib/fields/datetime.js b/lib/fields/datetime.js index <HASH>..<HASH> 100644 --- a/lib/fields/datetime.js +++ b/lib/fields/datetime.js @@ -33,7 +33,7 @@ var util = require( 'util' ) DateTimeField = new Class({ inherits:ApiField ,options:{ - format:'%Y-%m-%dT%M:%H:%S.%LZ' + format:'%Y-%m-%dT%H:%M:%S.%LZ' } ,convert: function convert( value ){
fixing the date format in datetime field. hour and minute were flipped
node-tastypie_tastypie
train
6abeb3ec2647e177e863e8f00babdd65acbdd276
diff --git a/lepton3.go b/lepton3.go index <HASH>..<HASH> 100644 --- a/lepton3.go +++ b/lepton3.go @@ -59,9 +59,9 @@ const ( // New returns a new Lepton3 instance. func New(spiSpeed int64) *Lepton3 { // The ring buffer is used to avoid memory allocations for SPI - // transfers. It needs to be big enough to handle all the SPI - // transfers for at least a single frame. - ringChunks := int(math.Ceil(float64(maxPacketsPerFrame) / float64(packetsPerRead))) + // transfers. We aim to have it big enough to handle all the SPI + // transfers for at least a 3 frames. + ringChunks := 3 * int(math.Ceil(float64(maxPacketsPerFrame)/float64(packetsPerRead))) return &Lepton3{ spiSpeed: spiSpeed, ring: newRing(ringChunks, transferSize),
Make SPI ring buffer bigger Avoid any possibility of a collision.
TheCacophonyProject_lepton3
train
a57fe5ca52d4e02936c76892138e516889573cf6
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -74,21 +74,13 @@ if 'setuptools.extension' in sys.modules: sys.modules['distutils.extension'].Extension = _Extension sys.modules['distutils.command.build_ext'].Extension = _Extension -with_pyrex = None -if sys.version_info[0] < 3: - try: - from Cython.Distutils.extension import Extension as _Extension - from Cython.Distutils import build_ext as _build_ext - with_pyrex = 'cython' - except ImportError: - try: - # Pyrex cannot build _yaml.c at the moment, - # but it may get fixed eventually. - from Pyrex.Distutils import Extension as _Extension - from Pyrex.Distutils import build_ext as _build_ext - with_pyrex = 'pyrex' - except ImportError: - pass +with_cython = False +try: + from Cython.Distutils.extension import Extension as _Extension + from Cython.Distutils import build_ext as _build_ext + with_cython = True +except ImportError: + pass class Distribution(_Distribution): @@ -135,7 +127,7 @@ class Extension(_Extension): def __init__(self, name, sources, feature_name, feature_description, feature_check, **kwds): - if not with_pyrex: + if not with_cython: for filename in sources[:]: base, ext = os.path.splitext(filename) if ext == '.pyx': @@ -179,9 +171,7 @@ class build_ext(_build_ext): self.check_extensions_list(self.extensions) filenames = [] for ext in self.extensions: - if with_pyrex == 'pyrex': - self.pyrex_sources(ext.sources, ext) - elif with_pyrex == 'cython': + if with_cython: self.cython_sources(ext.sources, ext) for filename in ext.sources: filenames.append(filename) @@ -211,9 +201,7 @@ class build_ext(_build_ext): with_ext = self.check_extension_availability(ext) if not with_ext: continue - if with_pyrex == 'pyrex': - ext.sources = self.pyrex_sources(ext.sources, ext) - elif with_pyrex == 'cython': + if with_cython: ext.sources = self.cython_sources(ext.sources, ext) self.build_extension(ext)
Dropped pyrex build support; Cython now supports Python 3.
yaml_pyyaml
train
9a41e01d97dfc75588ce06a1036d091828d5306c
diff --git a/phoebe/backend/fitting.py b/phoebe/backend/fitting.py index <HASH>..<HASH> 100644 --- a/phoebe/backend/fitting.py +++ b/phoebe/backend/fitting.py @@ -226,7 +226,7 @@ def run(system,params=None,fitparams=None,mpi=None,accept=False): reinitialize_from_priors(system, fitparams) monte_carlo(system, fitparams) - system.compute() + #system.compute() # Then solve the current system feedback = solver(system, params=params, mpi=mpi, fitparams=fitparams) diff --git a/phoebe/backend/universe.py b/phoebe/backend/universe.py index <HASH>..<HASH> 100644 --- a/phoebe/backend/universe.py +++ b/phoebe/backend/universe.py @@ -2148,8 +2148,8 @@ class Body(object): """ Return the coordinates of the star in a convenient coordinate system. - Phi is longitude - theta is colatitude + Phi is longitude (between -PI and +PI) + theta is colatitude (between 0 and +PI) Can be useful for surface maps or so. @@ -5404,6 +5404,11 @@ class BinaryRocheStar(PhysicalBody): self.params['orbit'].add_constraint(constraint) init_mesh(self) + + # Check for leftover kwargs and report to the user + if kwargs: + logger.warning("Unused keyword arguments {} upon initialization of BinaryRocheStar".format(kwargs.keys())) + def set_label(self,label): self.params['component']['label'] = label @@ -5934,6 +5939,10 @@ class PulsatingBinaryRocheStar(BinaryRocheStar): else: rotperiod = np.inf + loc, velo, euler = keplerorbit.get_binary_orbit(time, + self.params['orbit'], + ('primary' if component==0 else 'secondary')) + # The mesh of a PulsatingBinaryRocheStar rotates along the orbit, and # it is independent of the rotation of the star. Thus, we need to # specifically specify in which phase the mesh is. It has an "orbital" @@ -5941,9 +5950,10 @@ class PulsatingBinaryRocheStar(BinaryRocheStar): # same orientation as a single star at phase 0. # to match coordinate system of Star: - mesh_phase = np.pi / 2.0 + mesh_phase = 0 # to correct for orbital phase: - mesh_phase+= (time % orbperiod)/orbperiod * 2*np.pi + mesh_phase += euler[0] + #mesh_phase+= (time % orbperiod)/orbperiod * 2*np.pi # to correct for rotational phase: mesh_phase-= (time % rotperiod)/rotperiod * 2*np.pi
fix in pulsational mesh-orientation-correction for eccentric rotating PulsatingBinaryRocheStars
phoebe-project_phoebe2
train
9fc08c449bbe92d261fcf71599fc1e6ffe51826b
diff --git a/lib/plugins/aws/package/compile/events/apiGateway/lib/method/index.js b/lib/plugins/aws/package/compile/events/apiGateway/lib/method/index.js index <HASH>..<HASH> 100644 --- a/lib/plugins/aws/package/compile/events/apiGateway/lib/method/index.js +++ b/lib/plugins/aws/package/compile/events/apiGateway/lib/method/index.js @@ -85,7 +85,8 @@ module.exports = { ); template.Properties.RequestValidatorId = { Ref: validatorLogicalId }; - template.Properties.RequestModels = { [contentType]: { Ref: modelLogicalId } }; + template.Properties.RequestModels = template.Properties.RequestModels || {}; + template.Properties.RequestModels[contentType] = { Ref: modelLogicalId }; _.merge(this.serverless.service.provider.compiledCloudFormationTemplate.Resources, { [modelLogicalId]: {
#<I>: Support multiple schemas, don't overwrite RequestModels for each
serverless_serverless
train
1718c183b3fd7203a054b4ce397db541c8f6a5ca
diff --git a/src/Charcoal/Admin/Ui/CollectionContainerTrait.php b/src/Charcoal/Admin/Ui/CollectionContainerTrait.php index <HASH>..<HASH> 100644 --- a/src/Charcoal/Admin/Ui/CollectionContainerTrait.php +++ b/src/Charcoal/Admin/Ui/CollectionContainerTrait.php @@ -62,6 +62,8 @@ trait CollectionContainerTrait private $propertyDisplayFactory; + protected $currentObjId; + private $proto; /** @@ -372,6 +374,7 @@ trait CollectionContainerTrait 'objectProperties' => $objectProperties ]; + $this->currentObjId = $object->id(); yield $row; } } diff --git a/src/Charcoal/Admin/Widget/TableWidget.php b/src/Charcoal/Admin/Widget/TableWidget.php index <HASH>..<HASH> 100644 --- a/src/Charcoal/Admin/Widget/TableWidget.php +++ b/src/Charcoal/Admin/Widget/TableWidget.php @@ -236,23 +236,44 @@ class TableWidget extends AdminWidget implements CollectionContainerInterface */ public function objectActions() { - return [/* - [ - 'label' => 'Quick Edit', - 'ident' => 'quick-edit', - 'is_button' => true - ], - [ - 'label' => 'Inline Edit', - 'ident' => 'inline-edit', - 'is_button' => true - ], - [ - 'label' => 'Delete', - 'ident' => 'delete', - 'is_button' => true - ] - */]; + $obj = $this->proto(); + $props = $obj->metadata()->properties(); + $collectionIdent = $this->collectionIdent(); + + if(!$collectionIdent) { + return []; + } + + $metadata = $obj->metadata(); + $adminMetadata = isset($metadata['admin']) ? $metadata['admin'] : null; + $listOptions = $adminMetadata['lists'][$collectionIdent]; + + $objectActions = isset($listOptions['object_actions']) ? $listOptions['object_actions'] : []; + foreach($objectActions as &$action) { + if(isset($action['url'])) { + if ($obj->view() !== null) { + $action['url'] = $obj->render($action['url']); + } + else { + $action['url'] = str_replace('{{id}}', $this->currentObjId, $action['url']); + } + $action['url'] = $this->adminUrl().$action['url']; + } else { + $action['url'] = '#'; + } + + } + return $objectActions; + + } + + public function defaultObjectActions() + { + return [ + 'label' => new TranslationString('Modifier'), + 'url' => $this->objectEditUrl().'&amp;obj_id={{id}}', + 'ident' => 'edit' + ]; } /** diff --git a/templates/charcoal/admin/widget/table.mustache b/templates/charcoal/admin/widget/table.mustache index <HASH>..<HASH> 100644 --- a/templates/charcoal/admin/widget/table.mustache +++ b/templates/charcoal/admin/widget/table.mustache @@ -65,12 +65,12 @@ This widget expects to be in a context (model) of type `Charcoal\Admin\Widget\Ta {{#showTableHeader}} <thead> <tr> - <th class="table_checkbox"> + <!--<th class="table_checkbox"> <div class="checkbox -nolabel"> <input type="checkbox" class="select-all" id="checkboxall"> <label for="checkboxall"></label> </div> - </th> + </th>--> {{#collectionProperties}} <th>{{label}}</td> {{/collectionProperties}} @@ -85,27 +85,27 @@ This widget expects to be in a context (model) of type `Charcoal\Admin\Widget\Ta {{!-- Loop the list objects (from CollectionContainerTrait) --}} {{#objectRows}} <tr class="js-table-row" data-id="{{objectId}}"> - <td class="table_checkbox"> + <!--<td class="table_checkbox"> <div class="checkbox -nolabel"> <input type="checkbox" class="select-row" id="checkbox{{objectId}}"> <label for="checkbox{{objectId}}"></label> </div> - </td> + </td>--> {{#objectProperties}} <td class="property-{{ident}}">{{&val}}</td> {{/objectProperties}} {{#showObjectActions}} <td> <div class="btn-group"> - <a href="{{adminUrl}}{{objectEditUrl}}&amp;obj_id={{objectId}}" class="btn btn-primary">Modifier</a> + <a href="{{adminUrl}}{{objectEditUrl}}&amp;obj_id={{objectId}}" class="btn btn-primary">{{#_t}}Modifier{{/_t}}</a> {{#hasObjectActions}} <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> - <span class="sr-only">Toggle Dropdown</span> + <span class="sr-only">{{#_t}}Toggle Dropdown{{/_t}}</span> </button> <ul class="dropdown-menu"> {{#objectActions}} - <li><a class="js-obj-{{ident}}" href="#">{{label}}</a></li> + <li><a class="js-obj-{{ident}}" href="{{url}}">{{label}}</a></li> {{/objectActions}} </ul> {{/hasObjectActions}}
Hack: custom object actions for table / list.
locomotivemtl_charcoal-admin
train
cd1344a4a5b7e8fe2fe1cf13f3e7e80c4575eabd
diff --git a/lib/service/state.go b/lib/service/state.go index <HASH>..<HASH> 100644 --- a/lib/service/state.go +++ b/lib/service/state.go @@ -20,7 +20,9 @@ import ( "sync/atomic" "time" + "github.com/gravitational/teleport" "github.com/gravitational/teleport/lib/defaults" + "github.com/prometheus/client_golang/prometheus" ) const ( @@ -35,6 +37,15 @@ const ( stateDegraded = 2 ) +var stateGauge = prometheus.NewGauge(prometheus.GaugeOpts{ + Name: teleport.MetricState, + Help: "State of the teleport process: 0 - ok, 1 - recovering, 2 - degraded", +}) + +func init() { + prometheus.MustRegister(stateGauge) +} + // processState tracks the state of the Teleport process. type processState struct { process *TeleportProcess @@ -57,10 +68,12 @@ func (f *processState) Process(event Event) { // Ready event means Teleport has started successfully. case TeleportReadyEvent: atomic.StoreInt64(&f.currentState, stateOK) + stateGauge.Set(stateOK) f.process.Infof("Detected that service started and joined the cluster successfully.") // If a degraded event was received, always change the state to degraded. case TeleportDegradedEvent: atomic.StoreInt64(&f.currentState, stateDegraded) + stateGauge.Set(stateDegraded) f.process.Infof("Detected Teleport is running in a degraded state.") // If the current state is degraded, and a OK event has been // received, change the state to recovering. If the current state is @@ -71,11 +84,13 @@ func (f *processState) Process(event Event) { switch atomic.LoadInt64(&f.currentState) { case stateDegraded: atomic.StoreInt64(&f.currentState, stateRecovering) + stateGauge.Set(stateRecovering) f.recoveryTime = f.process.Clock.Now() f.process.Infof("Teleport is recovering from a degraded state.") case stateRecovering: if f.process.Clock.Now().Sub(f.recoveryTime) > defaults.ServerKeepAliveTTL*2 { atomic.StoreInt64(&f.currentState, stateOK) + stateGauge.Set(stateOK) f.process.Infof("Teleport has recovered from a degraded state.") } } diff --git a/metrics.go b/metrics.go index <HASH>..<HASH> 100644 --- a/metrics.go +++ b/metrics.go @@ -129,6 +129,9 @@ const ( // MetricLostNetworkEvents measures the number of network events that were lost. MetricLostNetworkEvents = "bpf_lost_network_events" + // MetricState tracks the state of the teleport process. + MetricState = "process_state" + // TagRange is a tag specifying backend requests TagRange = "range"
Add prometheus metric mirroring /readyz state This allows users to get the health of their nodes from prometheus metrics pipeline instead of polling readyz separately. Updates #<I>
gravitational_teleport
train
c0de24fbca76f70a8629dcdae1fca38d4b60bac0
diff --git a/lib/model/generic_folder.rb b/lib/model/generic_folder.rb index <HASH>..<HASH> 100644 --- a/lib/model/generic_folder.rb +++ b/lib/model/generic_folder.rb @@ -196,7 +196,7 @@ module Viewpoint resp.items.each do |i| key = i.keys.first items[key] = [] unless items[key].is_a?(Array) - if(key == :delete) + if(key == :delete || key == :read_flag_change) items[key] << i[key][:item_id] else i_type = i[key].keys.first @@ -211,7 +211,7 @@ module Viewpoint # Return the appropriate id based on whether it is a DistinguishedFolderId or # simply just a FolderId def self.normalize_id(folder_id) - tfolder_id = folder_id.downcase + tfolder_id = folder_id.to_s.downcase # If the folder_id is a DistinguishedFolderId change it to a symbol so our SOAP # method does the right thing. @@distinguished_folder_ids.find_index(tfolder_id) ? tfolder_id.to_sym : folder_id
Minor bug fix for sync and a Ruby <I> fix.
WinRb_Viewpoint
train
6ad992f7bb7743578ab0a56b8d858c291d07f4e1
diff --git a/system/Test/Fabricator.php b/system/Test/Fabricator.php index <HASH>..<HASH> 100644 --- a/system/Test/Fabricator.php +++ b/system/Test/Fabricator.php @@ -90,7 +90,7 @@ class Fabricator * * @var array|null */ - protected $tmpOverrides; + protected $tempOverrides; /** * Default formatter to use when nothing is detected @@ -145,7 +145,7 @@ class Fabricator { $this->setFormatters(); - $this->overrides = $this->tmpOverrides = []; + $this->overrides = $this->tempOverrides = []; $this->locale = config('App')->defaultLocale; $this->faker = Factory::create($this->locale); @@ -187,15 +187,15 @@ class Fabricator //-------------------------------------------------------------------- /** - * Return and reset tmpOverrides + * Return and reset tempOverrides * * @return array */ public function getOverrides(): array { - $overrides = $this->tmpOverrides ?? $this->overrides; + $overrides = $this->tempOverrides ?? $this->overrides; - $this->tmpOverrides = $this->overrides; + $this->tempOverrides = $this->overrides; return $overrides; } @@ -215,7 +215,7 @@ class Fabricator $this->overrides = $overrides; } - $this->tmpOverrides = $overrides; + $this->tempOverrides = $overrides; return $this; }
Succumb to Lonnie's attentiveness
codeigniter4_CodeIgniter4
train
3214e107552b0264f76878d2d6dec636a873838c
diff --git a/conf.py b/conf.py index <HASH>..<HASH> 100644 --- a/conf.py +++ b/conf.py @@ -60,7 +60,7 @@ author = 'Martin Majlis' # The short X.Y version. version = "0.4" # The full version, including alpha/beta/rc tags. -release = "0.4.4" +release = "0.4.5" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ tests_require = [] setup( name='Wikipedia-API', - version="0.4.4", + version="0.4.5", description='Python Wrapper for Wikipedia', long_description=README + '\n\n' + CHANGES, classifiers=[ diff --git a/wikipediaapi/__init__.py b/wikipediaapi/__init__.py index <HASH>..<HASH> 100644 --- a/wikipediaapi/__init__.py +++ b/wikipediaapi/__init__.py @@ -6,7 +6,7 @@ from Wikipedia. Documentation provides code snippets for the most common use cases. """ -__version__ = (0, 4, 4) +__version__ = (0, 4, 5) import logging import re from enum import IntEnum
Update version to <I> for new release.
martin-majlis_Wikipedia-API
train
e573f355f8ae5812d874cf6bc14e72bb25a9bede
diff --git a/spec/html_grid_spec.rb b/spec/html_grid_spec.rb index <HASH>..<HASH> 100644 --- a/spec/html_grid_spec.rb +++ b/spec/html_grid_spec.rb @@ -114,4 +114,31 @@ describe MagicGrid::HtmlGrid do subject.order_class(2).should == 'sort-none' end end + + describe "#magic_pager" do + let(:definition) { MagicGrid::Definition.new(column_list) } + let(:collection) { definition.magic_collection } + it "should use will_paginate if available" do + view = double.tap { |v| + v.should_receive(:will_paginate). + with(collection.collection, {}). + and_return("WillPaginate was used!") + } + grid = MagicGrid::HtmlGrid.new(definition, view) + grid.magic_pager(collection).should == "WillPaginate was used!" + end + it "should use paginate if available and will_paginate is not" do + view = double.tap { |v| + v.should_receive(:paginate). + with(collection.collection, {}). + and_return("#paginate was used!") + } + grid = MagicGrid::HtmlGrid.new(definition, view) + grid.magic_pager(collection).should == "#paginate was used!" + end + it "should leave a comment for the dev if paginate and will_paginate are both missing" do + grid = MagicGrid::HtmlGrid.new(definition, double) + grid.magic_pager(collection).should =~ /INSTALL WillPaginate or Kaminari/ + end + end end
Add specs for HtmlGrid#magic_pager Yay for <I>% code coverage using only RSpec
rmg_magic_grid
train
42ff0b2c5da2d1ae7fbf42f16114c93cafb171ca
diff --git a/tests/test_proxy_functional.py b/tests/test_proxy_functional.py index <HASH>..<HASH> 100644 --- a/tests/test_proxy_functional.py +++ b/tests/test_proxy_functional.py @@ -643,7 +643,7 @@ async def test_proxy_auth() -> None: async with aiohttp.ClientSession() as session: with pytest.raises( ValueError, - message="proxy_auth must be None or BasicAuth() tuple"): + match=r"proxy_auth must be None or BasicAuth\(\) tuple"): await session.get('http://python.org', proxy='http://proxy.example.com', proxy_auth=('user', 'pass'))
[<I>] Fix pytest <I> compatibility (#<I>) (#<I>) (cherry picked from commit <I>bc3c2b)
aio-libs_aiohttp
train
b9fe04ae9cc5f9683a26b332cb9ec8302986861a
diff --git a/system/CodeIgniter.php b/system/CodeIgniter.php index <HASH>..<HASH> 100644 --- a/system/CodeIgniter.php +++ b/system/CodeIgniter.php @@ -93,7 +93,7 @@ class CodeIgniter protected $router; /** - * @var string + * @var string|\Closure */ protected $controller; @@ -158,6 +158,19 @@ class CodeIgniter $this->startController(); + // Closure controller has run in startController(). + if ( ! is_callable($this->controller)) + { + $controller = $this->createController(); + + //-------------------------------------------------------------------- + // Is there a "post_controller_constructor" hook? + //-------------------------------------------------------------------- + Hooks::trigger('post_controller_constructor'); + + $this->runController($controller); + } + //-------------------------------------------------------------------- // Is there a "post_controller" hook? //-------------------------------------------------------------------- @@ -334,7 +347,8 @@ class CodeIgniter // Is it routed to a Closure? if (is_callable($this->controller)) { - echo $this->controller(...$this->router->params()); + $controller = $this->controller; + echo $controller(...$this->router->params()); } else { @@ -357,21 +371,19 @@ class CodeIgniter } } } - - $this->createControllerAndRun(); } - protected function createControllerAndRun() + protected function createController() { $class = new $this->controller($this->request, $this->response); $this->benchmark->stop('controller_constructor'); - //-------------------------------------------------------------------- - // Is there a "post_controller_constructor" hook? - //-------------------------------------------------------------------- - Hooks::trigger('post_controller_constructor'); + return $class; + } + protected function runController($class) + { if (method_exists($class, '_remap')) { $class->_remap($this->method, ...$this->router->params()); @@ -396,12 +408,13 @@ class CodeIgniter else if (is_array($override)) { $this->controller = $override[0]; - $this->method = $override[1]; + $this->method = $override[1]; unset($override); } - $this->createControllerAndRun(); + $controller = $this->createController(); + $this->runController($controller); $this->gatherOutput(); $this->sendResponse(); return; diff --git a/tests/system/CodeIgniterTest.php b/tests/system/CodeIgniterTest.php index <HASH>..<HASH> 100644 --- a/tests/system/CodeIgniterTest.php +++ b/tests/system/CodeIgniterTest.php @@ -3,7 +3,7 @@ use Config\App; use Config\Services; -class CodeIgniterTest extends \PHPUnit_Framework_TestCase +class CodeIgniterTest extends \CIUnitTestCase { /** * @var \CodeIgniter\CodeIgniter @@ -30,11 +30,6 @@ class CodeIgniterTest extends \PHPUnit_Framework_TestCase ]; $_SERVER['argc'] = 2; - // Inject mock router. - $routes = Services::routes(); - $router = Services::router($routes); - Services::injectMock('router', $router); - ob_start(); $this->codeigniter->run(); $output = ob_get_clean(); @@ -51,11 +46,6 @@ class CodeIgniterTest extends \PHPUnit_Framework_TestCase ]; $_SERVER['argc'] = 1; - // Inject mock router. - $routes = Services::routes(); - $router = Services::router($routes); - Services::injectMock('router', $router); - ob_start(); $this->codeigniter->run(); $output = ob_get_clean(); @@ -88,4 +78,30 @@ class CodeIgniterTest extends \PHPUnit_Framework_TestCase //-------------------------------------------------------------------- + public function testRunClosureRoute() + { + $_SERVER['argv'] = [ + 'index.php', + 'pages/about', + ]; + $_SERVER['argc'] = 2; + + // Inject mock router. + $routes = Services::routes(); + $routes->add('pages/(:segment)', function($segment) + { + echo 'You want to see "'.esc($segment).'" page.'; + }); + $router = Services::router($routes); + Services::injectMock('router', $router); + + ob_start(); + $this->codeigniter->run(); + $output = ob_get_clean(); + + $this->assertContains('You want to see "about" page.', $output); + } + + //-------------------------------------------------------------------- + }
Fix bug that closure route does not work And refactor CodeIgniter::run(). Now all Hooks::trigger() are in the run() method.
codeigniter4_CodeIgniter4
train
9e1b01c83df7e1aff048b1a341bbba2642bd5ae7
diff --git a/alot/db/utils.py b/alot/db/utils.py index <HASH>..<HASH> 100644 --- a/alot/db/utils.py +++ b/alot/db/utils.py @@ -352,7 +352,8 @@ def extract_body(mail, types=None, field_key='copiousoutput'): continue enc = part.get_content_charset() or 'ascii' - raw_payload = part.get_payload() + raw_payload = part.get_payload(decode=True).decode(enc) + if ctype == 'text/plain': body_parts.append(string_sanitize(raw_payload)) else: @@ -437,7 +438,7 @@ def decode_header(header, normalize=False): for v, enc in valuelist: v = string_decode(v, enc) decoded_list.append(string_sanitize(v)) - value = u' '.join(decoded_list) + value = ''.join(decoded_list) if normalize: value = re.sub(r'\n\s+', r' ', value) return value
fix messages with content transfer encoding in py3k the change to raw payload makes sense to me, we need to tell it to decode using the content-transfer-encoding, and then transform tat back into a str. the need to join with '' instead of ' ' doesn't.
pazz_alot
train
435643d220a36483a63ebad7e64b9bc57eb6537b
diff --git a/pyof/foundation/constants.py b/pyof/foundation/constants.py index <HASH>..<HASH> 100644 --- a/pyof/foundation/constants.py +++ b/pyof/foundation/constants.py @@ -11,5 +11,3 @@ OFP_MAX_PORT_NAME_LEN = 16 OFP_MAX_TABLE_NAME_LEN = 32 SERIAL_NUM_LEN = 32 DESC_STR_LEN = 256 - -VLAN_TPID = 33024 diff --git a/pyof/foundation/network_types.py b/pyof/foundation/network_types.py index <HASH>..<HASH> 100644 --- a/pyof/foundation/network_types.py +++ b/pyof/foundation/network_types.py @@ -10,7 +10,6 @@ from enum import IntEnum from pyof.foundation.base import GenericStruct from pyof.foundation.basic_types import ( BinaryData, HWAddress, IPAddress, UBInt8, UBInt16) -from pyof.foundation.constants import VLAN_TPID from pyof.foundation.exceptions import PackException, UnpackException __all__ = ('ARP', 'Ethernet', 'EtherType', 'GenericTLV', 'IPv4', 'VLAN', @@ -75,7 +74,7 @@ class ARP(GenericStruct): tha = HWAddress() tpa = IPAddress() - def __init__(self, htype=1, ptype=0x800, hlen=6, plen=4, oper=1, + def __init__(self, htype=1, ptype=EtherType.IPV4, hlen=6, plen=4, oper=1, sha='00:00:00:00:00:00', spa='0.0.0.0', tha="00:00:00:00:00:00", tpa='0.0.0.0'): """Create an ARP with the parameters below. @@ -109,7 +108,7 @@ class ARP(GenericStruct): def is_valid(self): """Assure the ARP contains Ethernet and IPv4 information.""" - return self.htype == 1 and self.ptype == 0x800 + return self.htype == 1 and self.ptype == EtherType.IPV4 def unpack(self, buff, offset=0): """Unpack a binary struct into this object's attributes. @@ -135,7 +134,7 @@ class VLAN(GenericStruct): """802.1q VLAN header.""" #: tpid (:class:`UBInt16`): Tag Protocol Identifier - tpid = UBInt16(VLAN_TPID) + tpid = UBInt16(EtherType.VLAN) #: _tci (:class:`UBInt16`): Tag Control Information - has the #: Priority Code Point, DEI/CFI bit and the VLAN ID _tci = UBInt16() @@ -155,7 +154,7 @@ class VLAN(GenericStruct): vid (int): VLAN ID. If no VLAN is specified, value is 0. """ super().__init__() - self.tpid = VLAN_TPID + self.tpid = EtherType.VLAN self.pcp = pcp self.cfi = cfi self.vid = vid @@ -186,7 +185,7 @@ class VLAN(GenericStruct): def _validate(self): """Assure this is a 802.1q VLAN header instance.""" - if self.tpid.value != VLAN_TPID: + if self.tpid.value != EtherType.VLAN: raise UnpackException return @@ -215,7 +214,7 @@ class VLAN(GenericStruct): self.cfi = (self._tci.value >> 12) & 1 self.vid = self._tci.value & 4095 else: - self.tpid = VLAN_TPID + self.tpid = EtherType.VLAN self.pcp = None self.cfi = None self.vid = None @@ -291,11 +290,11 @@ class Ethernet(GenericStruct): UnpackException: If there is a struct unpacking error. """ - # Checking if the EtherType bytes are actually equal to VLAN_TPID - + # Check if the EtherType bytes are actually equal to EtherType.VLAN, # indicating that the packet is tagged. If it is not, we insert the # equivalent to 'NULL VLAN data' (\x00\x00\x00\x00) to enable the # correct unpacking process. - if buff[12:14] != VLAN_TPID.to_bytes(2, 'big'): + if buff[12:14] != EtherType.VLAN.to_bytes(2, 'big'): buff = buff[0:12] + b'\x00\x00\x00\x00' + buff[12:] super().unpack(buff, offset)
Replace constants and values with EtherType items
kytos_python-openflow
train
f738a810c8e29311268416deb548dc47427d899d
diff --git a/lib/ssh.js b/lib/ssh.js index <HASH>..<HASH> 100644 --- a/lib/ssh.js +++ b/lib/ssh.js @@ -4788,6 +4788,29 @@ function KEXDH_REPLY(self, e) { // server signer.update(outstate.exchangeHash, 'binary'); signature = signer.sign(privateKey, 'binary'); + if (hostkeyAlgo === 'ssh-dss') { + // strip ASN.1 notation to bare r and s values only (minus leading zeros), + // 40 bytes total + var asn1Reader = new Ber.Reader(new Buffer(signature, 'binary')), + zeros, + r, + s; + asn1Reader.readSequence(); + r = asn1Reader.readString(Ber.Integer, true); + s = asn1Reader.readString(Ber.Integer, true); + zeros = 0; + while ((r.length - zeros) > 20 && r[zeros] === 0x00) + ++zeros; + if (zeros > 0) + r = r.slice(zeros); + zeros = 0; + while ((s.length - zeros) > 20 && s[zeros] === 0x00) + ++zeros; + if (zeros > 0) + s = s.slice(zeros); + signature = r.toString('binary') + s.toString('binary'); + } + /* byte SSH_MSG_KEXDH_REPLY string server public host key and certificates (K_S)
SSH2Stream: fix DSA signature sent by server
mscdex_ssh2-streams
train
dae6f6250ce9ad731791089c63624e28702ac930
diff --git a/lib/utils.js b/lib/utils.js index <HASH>..<HASH> 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -45,6 +45,7 @@ exports.parseBuffer = (buffer, start) => { let bulkStartIndex = result[1] let bulkLen = parseInt(result[0], 10) let bulkEndIndex = bulkStartIndex + bulkLen + result[1] = result[1] + bulkLen + 2 if (bulkLen === -1) { // Null result[0] = null
fix the index of decoded bulk string
DavidCai1993_resper
train
e3df4f863e53387eb76815f3ae7f6c67f25db7cb
diff --git a/lib/nakal/dsl.rb b/lib/nakal/dsl.rb index <HASH>..<HASH> 100644 --- a/lib/nakal/dsl.rb +++ b/lib/nakal/dsl.rb @@ -10,7 +10,7 @@ module Nakal diff_screen, diff_metric = orignal_screen.compare(current_screen) Timeout::timeout(Nakal.timeout) { - until diff_metric < 0.05 do + until diff_metric == 0.00 do sleep 1 current_screen = Nakal.current_platform::Screen.new("#{image_file_name}_current", :capture) diff_screen, diff_metric = orignal_screen.compare(current_screen) diff --git a/lib/nakal/version.rb b/lib/nakal/version.rb index <HASH>..<HASH> 100644 --- a/lib/nakal/version.rb +++ b/lib/nakal/version.rb @@ -1,3 +1,3 @@ module Nakal - VERSION = "0.0.6" + VERSION = "0.0.7" end
Changing the comparison diff to exact match
rajdeepv_nakal
train
f68df00bcff7e991279f8c30ce2fbe679e5e74c6
diff --git a/lib/compiler/generators/core/function.js b/lib/compiler/generators/core/function.js index <HASH>..<HASH> 100644 --- a/lib/compiler/generators/core/function.js +++ b/lib/compiler/generators/core/function.js @@ -110,6 +110,10 @@ Func.prototype.appendEnd = function(opt_token) { }; Func.prototype.appendBaseCall = function(opt_ctx, opt_args) { + if (this.sequence != null) { + this.sequence.close(opt_ctx); + } + this.template.appendBaseCall(opt_ctx, this.nameToUse, opt_args, this.buffer); if (this.options.appendLineNumbersFor.baseCall)
added missed sequence close before base block call
dimsmol_ojster
train
4b4f15cc58f480c87fea9d77c47e4c8af609c6c1
diff --git a/timeside/plugins/analyzer/externals/yaafe.py b/timeside/plugins/analyzer/externals/yaafe.py index <HASH>..<HASH> 100644 --- a/timeside/plugins/analyzer/externals/yaafe.py +++ b/timeside/plugins/analyzer/externals/yaafe.py @@ -62,11 +62,11 @@ class Yaafe(Analyzer): ... input_samplerate=16000) >>> pipe = (decoder | yaafe) >>> pipe.run() - >>> print yaafe.results.keys() + >>> print(yaafe.results.keys()) ['yaafe.mfccd1', 'yaafe.mfcc', 'yaafe.mfccd2', 'yaafe.zcr'] >>> # Access to one of the result: >>> res_mfcc = yaafe.results['yaafe.mfcc'] - >>> print type(res_mfcc.data_object) + >>> print(type(res_mfcc.data_object)) <class 'timeside.core.analyzer.FrameValueObject'> >>> res_mfcc.data # doctest: +ELLIPSIS array([[...]])
[plugins] use print() in analyzer/externals/yaafe.py
Parisson_TimeSide
train
8f0e2b2315357cc381ba0b336b27c023c91533bb
diff --git a/blueocean-rest/src/main/java/io/jenkins/blueocean/rest/ApiHead.java b/blueocean-rest/src/main/java/io/jenkins/blueocean/rest/ApiHead.java index <HASH>..<HASH> 100644 --- a/blueocean-rest/src/main/java/io/jenkins/blueocean/rest/ApiHead.java +++ b/blueocean-rest/src/main/java/io/jenkins/blueocean/rest/ApiHead.java @@ -1,6 +1,5 @@ package io.jenkins.blueocean.rest; -import com.google.inject.Inject; import hudson.Extension; import hudson.ExtensionList; import io.jenkins.blueocean.BlueOceanUI; @@ -10,6 +9,7 @@ import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.pageable.Pageable; import io.jenkins.blueocean.rest.pageable.Pageables; import io.jenkins.blueocean.rest.pageable.PagedResponse; +import jenkins.model.Jenkins; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; @@ -27,8 +27,7 @@ import java.util.Map; @Extension public final class ApiHead implements RootRoutable, Reachable { - @Inject - private BlueOceanUI blueOceanUI; + private volatile BlueOceanUI blueOceanUI; private final Map<String,ApiRoutable> apis = new HashMap<>(); @@ -85,6 +84,7 @@ public final class ApiHead implements RootRoutable, Reachable { @Override public Link getLink() { + setBlueOceanUI(); //lazily initialize BlueOceanUI return new Link("/"+blueOceanUI.getUrlBase()).rel(getUrlName()); } @@ -100,4 +100,18 @@ public final class ApiHead implements RootRoutable, Reachable { return null; } + + // Lazy initialize BlueOcean UI via injection + // Fix for: https://issues.jenkins-ci.org/browse/JENKINS-37429 + private void setBlueOceanUI(){ + BlueOceanUI boui = blueOceanUI; + if(boui == null){ + synchronized (this){ + boui = blueOceanUI; + if(boui == null){ + blueOceanUI = boui = Jenkins.getInstance().getInjector().getInstance(BlueOceanUI.class); + } + } + } + } }
JENKINS-<I># Fix circular dependency that cause errors during plugin installation (#<I>)
jenkinsci_blueocean-plugin
train
75b846c70e555c8edc32d7f928c502e849023c21
diff --git a/pyocd/coresight/ap.py b/pyocd/coresight/ap.py index <HASH>..<HASH> 100644 --- a/pyocd/coresight/ap.py +++ b/pyocd/coresight/ap.py @@ -326,7 +326,7 @@ class MEM_AP(AccessPort, memory_interface.MemoryInterface): self.write_reg(MEM_AP_CSW, CSW_VALUE | CSW_SIZE32) self.write_reg(MEM_AP_TAR, addr) try: - self.link.write_ap_multiple(MEM_AP_DRW, data) + self.link.write_ap_multiple((self.ap_num << APSEL_SHIFT) | MEM_AP_DRW, data) except exceptions.TransferFaultError as error: # Annotate error with target address. self._handle_error(error, num) @@ -351,7 +351,7 @@ class MEM_AP(AccessPort, memory_interface.MemoryInterface): self.write_reg(MEM_AP_CSW, CSW_VALUE | CSW_SIZE32) self.write_reg(MEM_AP_TAR, addr) try: - resp = self.link.read_ap_multiple(MEM_AP_DRW, size) + resp = self.link.read_ap_multiple((self.ap_num << APSEL_SHIFT) | MEM_AP_DRW, size) except exceptions.TransferFaultError as error: # Annotate error with target address. self._handle_error(error, num)
Fixed MEM_AP memory transfers for non-zero APSEL.
mbedmicro_pyOCD
train
775f432037f0f36461e5999652a468f6b3707065
diff --git a/src/debuggability.js b/src/debuggability.js index <HASH>..<HASH> 100644 --- a/src/debuggability.js +++ b/src/debuggability.js @@ -150,6 +150,17 @@ Promise.config = function(opts) { } }; +function checkForgottenReturns(returnValue, promisesCreated, name, promise) { + if (returnValue === undefined && + promisesCreated > 0 && + config.longStackTraces && + config.warnings) { + var msg = "a promise was created in a " + name + + " handler but was not returned from it"; + promise._warn(msg); + } +} + function deprecated(name, replacement) { var message = name + " is deprecated and will be removed in a future version."; @@ -679,6 +690,7 @@ return { warnings: function() { return config.warnings; }, + checkForgottenReturns: checkForgottenReturns, setBounds: setBounds, warn: warn, deprecated: deprecated, diff --git a/src/join.js b/src/join.js index <HASH>..<HASH> 100644 --- a/src/join.js +++ b/src/join.js @@ -1,6 +1,6 @@ "use strict"; module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug) { var util = require("./util.js"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; @@ -49,7 +49,9 @@ if (canEvaluate) { var handler = this.callers[total]; promise._pushContext(); var ret = tryCatch(handler)(this); - promise._popContext(); + var promisesCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, promisesCreated, "Promise.join", promise); if (ret === errorObj) { promise._rejectCallback(ret.e, false); } else { diff --git a/src/map.js b/src/map.js index <HASH>..<HASH> 100644 --- a/src/map.js +++ b/src/map.js @@ -3,7 +3,8 @@ module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, - INTERNAL) { + INTERNAL, + debug) { var ASSERT = require("./assert.js"); var util = require("./util.js"); var tryCatch = util.tryCatch; @@ -57,11 +58,18 @@ MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { } if (preservedValues !== null) preservedValues[index] = value; + var promise = this._promise; var callback = this._callback; - var receiver = this._promise._boundTo; - this._promise._pushContext(); + var receiver = promise._boundTo; + promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); - this._promise._popContext(); + var promisesCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promisesCreated, + preservedValues !== null ? "Promise.filter" : "Promise.map", + promise + ); if (ret === errorObj) return this._reject(ret.e); // If the mapper function returned a promise we simply reuse diff --git a/src/promise.js b/src/promise.js index <HASH>..<HASH> 100644 --- a/src/promise.js +++ b/src/promise.js @@ -721,6 +721,7 @@ require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); require("./finally.js")(Promise, tryConvertToPromise); require("./direct_resolve.js")(Promise); require("./synchronous_inspection.js")(Promise); -require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +require("./join.js")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug); Promise.Promise = Promise; }; diff --git a/src/reduce.js b/src/reduce.js index <HASH>..<HASH> 100644 --- a/src/reduce.js +++ b/src/reduce.js @@ -3,7 +3,8 @@ module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, - INTERNAL) { + INTERNAL, + debug) { var util = require("./util.js"); var tryCatch = util.tryCatch; @@ -119,7 +120,13 @@ function gotValue(value) { ret = fn.call(promise._boundTo, this.accum, value, this.index, this.length); } - promise._popContext(); + var promisesCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promisesCreated, + array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", + promise + ); return ret; } }; diff --git a/src/using.js b/src/using.js index <HASH>..<HASH> 100644 --- a/src/using.js +++ b/src/using.js @@ -1,6 +1,6 @@ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL) { + createContext, INTERNAL, debug) { var util = require("./util.js"); var TypeError = require("./errors.js").TypeError; var inherits = require("./util.js").inherits; @@ -151,7 +151,9 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, } promise._pushContext(); var ret = tryCatch(fn).apply(undefined, inspections); - promise._popContext(); + var promisesCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, promisesCreated, "Promise.using", promise); return ret; });
Add forgotten return warnings to map, each, filter, reduce, using and join
petkaantonov_bluebird
train
c3de35b5a93f5209982da302928e62b001671649
diff --git a/src/__tests__/starWarsData.js b/src/__tests__/starWarsData.js index <HASH>..<HASH> 100644 --- a/src/__tests__/starWarsData.js +++ b/src/__tests__/starWarsData.js @@ -13,7 +13,11 @@ * JSON objects in a more complex demo. */ -var luke = { +/** + * We export luke directly because the schema returns him + * from a root field, and hence needs to reference him. + */ +export var luke = { id: '1000', name: 'Luke Skywalker', friends: ['1002', '1003', '2000', '2001'], diff --git a/src/__tests__/starWarsIntrospectionTests.js b/src/__tests__/starWarsIntrospectionTests.js index <HASH>..<HASH> 100644 --- a/src/__tests__/starWarsIntrospectionTests.js +++ b/src/__tests__/starWarsIntrospectionTests.js @@ -34,6 +34,9 @@ describe('Star Wars Introspection Tests', () => { name: 'Query' }, { + name: 'Episode' + }, + { name: 'Character' }, { @@ -43,9 +46,6 @@ describe('Star Wars Introspection Tests', () => { name: 'String' }, { - name: 'Episode' - }, - { name: 'Droid' }, { @@ -327,7 +327,20 @@ describe('Star Wars Introspection Tests', () => { fields: [ { name: 'hero', - args: [] + args: [ + { + defaultValue: null, + description: 'If omitted, returns the hero of the whole ' + + 'saga. If provided, returns the hero of ' + + 'that particular episode.', + name: 'episode', + type: { + kind: 'ENUM', + name: 'Episode', + ofType: null + } + } + ] }, { name: 'human', diff --git a/src/__tests__/starWarsQueryTests.js b/src/__tests__/starWarsQueryTests.js index <HASH>..<HASH> 100644 --- a/src/__tests__/starWarsQueryTests.js +++ b/src/__tests__/starWarsQueryTests.js @@ -344,5 +344,24 @@ describe('Star Wars Query Tests', () => { var result = await graphql(StarWarsSchema, query); expect(result).to.deep.equal({ data: expected }); }); + + it('Allows us to verify that Luke is a human', async () => { + var query = ` + query CheckTypeOfLuke { + hero(episode: EMPIRE) { + __typename + name + } + } + `; + var expected = { + hero: { + __typename: 'Human', + name: 'Luke Skywalker' + }, + }; + var result = await graphql(StarWarsSchema, query); + expect(result).to.deep.equal({ data: expected }); + }); }); }); diff --git a/src/__tests__/starWarsSchema.js b/src/__tests__/starWarsSchema.js index <HASH>..<HASH> 100644 --- a/src/__tests__/starWarsSchema.js +++ b/src/__tests__/starWarsSchema.js @@ -17,7 +17,7 @@ import { GraphQLString, } from '../type'; -import { starWarsData, getFriends, artoo } from './starWarsData.js'; +import { starWarsData, getFriends, artoo, luke } from './starWarsData.js'; /** * This is designed to be an end-to-end test, demonstrating @@ -60,7 +60,7 @@ import { starWarsData, getFriends, artoo } from './starWarsData.js'; * } * * type Query { - * hero: Character + * hero(episode: Episode): Character * human(id: String!): Human * droid(id: String!): Droid * } @@ -222,7 +222,7 @@ var droidType = new GraphQLObjectType({ * * This implements the following type system shorthand: * type Query { - * hero: Character + * hero(episode: Episode): Character * human(id: String!): Human * droid(id: String!): Droid * } @@ -233,7 +233,21 @@ var queryType = new GraphQLObjectType({ fields: () => ({ hero: { type: characterInterface, - resolve: () => artoo, + args: { + episode: { + description: 'If omitted, returns the hero of the whole saga. If ' + + 'provided, returns the hero of that particular episode.', + type: episodeEnum + } + }, + resolve: (root, {episode}) => { + if (episode === 5) { + // Luke is the hero of Episode V. + return luke; + } + // Artoo is the hero otherwise. + return artoo; + } }, human: { type: humanType,
Allow an episode to be passed to hero
graphql_graphql-js
train
d195b4fe81c50c4f6fa3a39c221897a46c961151
diff --git a/safe/impact_function/impact_function.py b/safe/impact_function/impact_function.py index <HASH>..<HASH> 100644 --- a/safe/impact_function/impact_function.py +++ b/safe/impact_function/impact_function.py @@ -52,6 +52,7 @@ from safe.gisv4.raster.clip_bounding_box import clip_by_extent from safe.gisv4.raster.reclassify import reclassify as reclassify_raster from safe.gisv4.raster.polygonize import polygonize from safe.gisv4.raster.zonal_statistics import zonal_stats +from safe.gisv4.raster.align import align_rasters from safe.definitions.post_processors import post_processors from safe.definitions.analysis_steps import analysis_steps from safe.definitions.utilities import definition @@ -83,6 +84,7 @@ from safe.common.exceptions import ( NoFeaturesInExtentError, ProcessingInstallationError, ) +from safe.impact_function.earthquake import itb_fatality_rates from safe.impact_function.postprocessors import ( run_single_post_processor, enough_input) from safe.impact_function.create_extra_layers import ( @@ -1029,38 +1031,22 @@ class ImpactFunction(object): if self.aggregation: self.datastore.add_layer(self.aggregation, 'aggregation') + self._performance_log = profiling_log() + self.callback(2, step_count, analysis_steps['aggregation_preparation']) + self.aggregation_preparation() + # Special case for Raster Earthquake hazard on Raster population. + damage_curve = False if self.hazard.type() == QgsMapLayer.RasterLayer: if self.hazard.keywords.get('hazard') == 'earthquake': if self.exposure.type() == QgsMapLayer.RasterLayer: if self.exposure.keywords.get('exposure') == 'population': - # return self.state() - - # These layers are not generated. - self._exposure_impacted = None - self._aggregate_hazard_impacted = None - return - - self._performance_log = profiling_log() - self.callback(2, step_count, analysis_steps['aggregation_preparation']) - self.aggregation_preparation() - - self._performance_log = profiling_log() - self.callback(3, step_count, analysis_steps['hazard_preparation']) - self.hazard_preparation() + damage_curve = True - self._performance_log = profiling_log() - self.callback( - 4, step_count, analysis_steps['aggregate_hazard_preparation']) - self.aggregate_hazard_preparation() - - self._performance_log = profiling_log() - self.callback(5, step_count, analysis_steps['exposure_preparation']) - self.exposure_preparation() - - self._performance_log = profiling_log() - self.callback(6, step_count, analysis_steps['combine_hazard_exposure']) - self.intersect_exposure_and_aggregate_hazard() + if damage_curve: + self.damage_curve_analysis() + else: + self.gis_overlay_analysis() self._performance_log = profiling_log() self.callback(7, step_count, analysis_steps['post_processing']) @@ -1123,6 +1109,40 @@ class ImpactFunction(object): check_inasafe_fields(self._analysis_impacted) @profile + def gis_overlay_analysis(self): + """Perform an overlay analysis between the exposure and the hazard.""" + step_count = len(analysis_steps) + + self._performance_log = profiling_log() + self.callback(3, step_count, analysis_steps['hazard_preparation']) + self.hazard_preparation() + + self._performance_log = profiling_log() + self.callback( + 4, step_count, analysis_steps['aggregate_hazard_preparation']) + self.aggregate_hazard_preparation() + + self._performance_log = profiling_log() + self.callback(5, step_count, analysis_steps['exposure_preparation']) + self.exposure_preparation() + + self._performance_log = profiling_log() + self.callback(6, step_count, analysis_steps['combine_hazard_exposure']) + self.intersect_exposure_and_aggregate_hazard() + + @profile + def damage_curve_analysis(self): + """Perform a damage curve analysis.""" + # For now we support only the earthquake raster on population raster. + self.earthquake_raster_population_raster() + + @profile + def earthquake_raster_population_raster(self): + """Perform a damage curve analysis with EQ raster on population raster. + """ + pass + + @profile def aggregation_preparation(self): """This function is doing the aggregation preparation.""" if not self.aggregation:
add damage curve analysis in the impact function
inasafe_inasafe
train
6eb2ea36498b4daf95dd32334417b4c5a440612a
diff --git a/src/GeoIPServiceProvider.php b/src/GeoIPServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/GeoIPServiceProvider.php +++ b/src/GeoIPServiceProvider.php @@ -23,9 +23,11 @@ class GeoIPServiceProvider extends ServiceProvider return $app['geoip']; }; - $this->publishes([ - __DIR__.'/config/config.php' => config_path('geoip.php'), - ], 'config'); + if (function_exists('config_path')) { + $this->publishes([ + __DIR__.'/config/config.php' => config_path('geoip.php'), + ], 'config'); + } } /**
Improved compatibility with lumen #<I>
pulkitjalan_geoip
train
cb7bf01c9864a2bf542a5b5f0b793c8781b081ec
diff --git a/paxtools-core/src/main/java/org/biopax/paxtools/impl/level3/BioSourceImpl.java b/paxtools-core/src/main/java/org/biopax/paxtools/impl/level3/BioSourceImpl.java index <HASH>..<HASH> 100644 --- a/paxtools-core/src/main/java/org/biopax/paxtools/impl/level3/BioSourceImpl.java +++ b/paxtools-core/src/main/java/org/biopax/paxtools/impl/level3/BioSourceImpl.java @@ -1,11 +1,16 @@ package org.biopax.paxtools.impl.level3; +import static org.biopax.paxtools.util.SetEquivalenceChecker.hasEquivalentIntersection; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.biopax.paxtools.model.BioPAXElement; import org.biopax.paxtools.model.level3.BioSource; import org.biopax.paxtools.model.level3.CellVocabulary; import org.biopax.paxtools.model.level3.TissueVocabulary; +import org.biopax.paxtools.model.level3.UnificationXref; +import org.biopax.paxtools.model.level3.Xref; +import org.biopax.paxtools.util.ClassFilterSet; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.DynamicInsert; @@ -44,7 +49,6 @@ public class BioSourceImpl extends NamedImpl implements BioSource return BioSource.class; } - //TODO right now, it's always FALSE due to changes in the superclass protected boolean semanticallyEquivalent(BioPAXElement element) { if(!(element instanceof BioSource)) @@ -60,10 +64,9 @@ public class BioSourceImpl extends NamedImpl implements BioSource (tissue != null ? tissue.isEquivalent(bioSource.getTissue()) : bioSource.getTissue() == null) - && - // Named, XReferrable equivalence test - super.semanticallyEquivalent(bioSource); - //TODO nonsense call (always false, after the method disappeared from XReferrableImpl) + && hasEquivalentIntersection( + new ClassFilterSet<Xref, UnificationXref>(getXref(), UnificationXref.class), + new ClassFilterSet<Xref, UnificationXref>(bioSource.getXref(), UnificationXref.class)); } public int equivalenceCode() diff --git a/paxtools-core/src/main/java/org/biopax/paxtools/impl/level3/XReferrableImpl.java b/paxtools-core/src/main/java/org/biopax/paxtools/impl/level3/XReferrableImpl.java index <HASH>..<HASH> 100644 --- a/paxtools-core/src/main/java/org/biopax/paxtools/impl/level3/XReferrableImpl.java +++ b/paxtools-core/src/main/java/org/biopax/paxtools/impl/level3/XReferrableImpl.java @@ -1,10 +1,8 @@ package org.biopax.paxtools.impl.level3; -import org.biopax.paxtools.model.level3.UnificationXref; import org.biopax.paxtools.model.level3.XReferrable; import org.biopax.paxtools.model.level3.Xref; import org.biopax.paxtools.util.BPCollections; -import org.biopax.paxtools.util.ClassFilterSet; import org.biopax.paxtools.util.XrefFieldBridge; import org.hibernate.annotations.*; import org.hibernate.search.annotations.Analyze; @@ -17,8 +15,6 @@ import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import java.util.Set; -import static org.biopax.paxtools.util.SetEquivalenceChecker.hasEquivalentIntersection; - /** * This class helps with managing the bidirectional xref links. * @@ -92,17 +88,4 @@ public abstract class XReferrableImpl extends L3ElementImpl implements XReferrab return 1; } - /** - * This method returns true if two {@link XReferrable} objects have at least one UnificationXref in common - * or neither have any. - * - * @param xReferrable - * @return true if this and that either share - or neither have a UnificationXref! - */ - protected boolean hasCommonUnificationXref(XReferrable xReferrable) - { - return hasEquivalentIntersection(new ClassFilterSet<Xref, UnificationXref>(xref, UnificationXref.class), - new ClassFilterSet<Xref, UnificationXref>(xReferrable.getXref(), - UnificationXref.class)); - } } diff --git a/psimi-converter/src/main/java/org/biopax/paxtools/converter/psi/EntryMapper.java b/psimi-converter/src/main/java/org/biopax/paxtools/converter/psi/EntryMapper.java index <HASH>..<HASH> 100644 --- a/psimi-converter/src/main/java/org/biopax/paxtools/converter/psi/EntryMapper.java +++ b/psimi-converter/src/main/java/org/biopax/paxtools/converter/psi/EntryMapper.java @@ -561,7 +561,7 @@ class EntryMapper { ((Gene)entity).setOrganism(getBioSource(interactor)); } - //try to avoid duplicate entities + //try to avoid duplicate physical entities or genes boolean hasEquivalentEntity = false; for(BioPAXElement ety : bpModel.getObjects(entity.getModelInterface())) { if(ety.isEquivalent(entity)) {
Fixed bug #<I> (at least for BioSourceImpl).
BioPAX_Paxtools
train
487dbbf2782a920de321915c43a4e261ddf2e7f9
diff --git a/client/actions/show-heartbeat/index.js b/client/actions/show-heartbeat/index.js index <HASH>..<HASH> 100644 --- a/client/actions/show-heartbeat/index.js +++ b/client/actions/show-heartbeat/index.js @@ -20,7 +20,7 @@ export class HeartbeatFlow { } this.data = { - // Required fields + // Required fields response_version: 2, experiment_version: '-', person_id: 'NA', @@ -31,7 +31,7 @@ export class HeartbeatFlow { question_text: survey.message, variation_id: recipe.revision_id.toString(), - // Optional fields + // Optional fields score: null, max_score: 5, flow_began_ts: Date.now(), @@ -59,7 +59,6 @@ export class HeartbeatFlow { defaultBrowser: client.isDefaultBrowser, plugins, flashVersion: flashPlugin ? flashPlugin.version : undefined, - doNotTrack: navigator.doNotTrack === '1', }, is_test: normandy.testing, }; @@ -104,10 +103,10 @@ export default class ShowHeartbeatAction extends Action { const lastShown = await this.getLastShownDate(); const shouldShowSurvey = ( - this.normandy.testing - || lastShown === null - || Date.now() - lastShown > LAST_SHOWN_DELAY - ); + this.normandy.testing + || lastShown === null + || Date.now() - lastShown > LAST_SHOWN_DELAY + ); if (!shouldShowSurvey) { return; } @@ -119,9 +118,8 @@ export default class ShowHeartbeatAction extends Action { const flow = new HeartbeatFlow(this); flow.save(); - // A bit redundant but the action argument names shouldn't necessarily rely - // on the argument names showHeartbeat takes. - + // A bit redundant but the action argument names shouldn't necessarily rely + // on the argument names showHeartbeat takes. const heartbeatData = { message: this.survey.message, engagementButtonLabel: this.survey.engagementButtonLabel, @@ -160,7 +158,7 @@ export default class ShowHeartbeatAction extends Action { } setLastShownDate() { - // Returns a promise, but there's nothing to do if it fails. + // Returns a promise, but there's nothing to do if it fails. this.storage.setItem('lastShown', Date.now()); } @@ -170,7 +168,7 @@ export default class ShowHeartbeatAction extends Action { } annotatePostAnswerUrl(url) { - // Don't bother with empty URLs. + // Don't bother with empty URLs. if (!url) { return url; } @@ -185,7 +183,7 @@ export default class ShowHeartbeatAction extends Action { syncSetup: this.client.syncSetup ? 1 : 0, }; - // Append testing parameter if in testing mode. + // Append testing parameter if in testing mode. if (this.normandy.testing) { args.testing = 1; } @@ -201,16 +199,16 @@ export default class ShowHeartbeatAction extends Action { return annotatedUrl.href; } - /** - * From the given list of surveys, choose one based on their relative - * weights and return it. - * - * @param {array} surveys Array of weighted surveys from the arguments - * object. - * @param {object} defaults Default values for survey attributes if they aren't - * specified. - * @return {object} The chosen survey, with the defaults applied. - */ + /** + * From the given list of surveys, choose one based on their relative + * weights and return it. + * + * @param {array} surveys Array of weighted surveys from the arguments + * object. + * @param {object} defaults Default values for survey attributes if they aren't + * specified. + * @return {object} The chosen survey, with the defaults applied. + */ chooseSurvey(surveys, defaults) { const finalSurvey = Object.assign({}, weightedChoose(surveys)); for (const prop in defaults) {
Remove navigator field from heartbeat action
mozilla_normandy
train
774bbb174b03cd8ba8da56341c477cd459b53e4b
diff --git a/django_afip/models.py b/django_afip/models.py index <HASH>..<HASH> 100644 --- a/django_afip/models.py +++ b/django_afip/models.py @@ -536,7 +536,9 @@ class Receipt(models.Model): verbose_name=_('receipt batch'), help_text=_( 'Receipts are validated in batches, so it must be assigned one ' - 'before validation is possible.'), + 'before validation is possible.' + ), + on_delete=models.PROTECT, ) concept = models.ForeignKey( ConceptType,
Disallow deleting batches with receipts
WhyNotHugo_django-afip
train
afc699494b5f7a7eba22d623128325adb5263502
diff --git a/docs/index.js b/docs/index.js index <HASH>..<HASH> 100644 --- a/docs/index.js +++ b/docs/index.js @@ -15,7 +15,7 @@ clickExpanderEls.forEach(function(el, i) { el.addEventListener('collapsed', function(e) { console.log(e); }); - expanderWidgets.push(new Expander(el)); + expanderWidgets.push(new Expander(el, { click: true })); }); focusExpanderEls.forEach(function(el, i) { diff --git a/docs/static/bundle.js b/docs/static/bundle.js index <HASH>..<HASH> 100644 --- a/docs/static/bundle.js +++ b/docs/static/bundle.js @@ -763,7 +763,7 @@ var focusables = require('/makeup-focusables$0.0.1/index'/*'makeup-focusables'*/ var defaultOptions = { autoCollapse: true, - click: true, + click: false, contentSelector: '.expander__content', focus: false, focusManagement: null, @@ -818,10 +818,6 @@ module.exports = function () { this._leaveListener = this.collapse.bind(this); if (this.expandeeEl) { - // const newExpandee = new Expandee(this.expandeeEl, this.options); - - // this.expandee = newExpandee; - // the expander controls the expandee this.hostEl.setAttribute('aria-controls', this.expandeeEl.id); this.hostEl.setAttribute('aria-expanded', 'false'); @@ -829,8 +825,6 @@ module.exports = function () { this.click = this.options.click; this.focus = this.options.focus; this.hover = this.options.hover; - - this.expandeeEl.classList.add('expandee--js'); } } @@ -938,7 +932,7 @@ clickExpanderEls.forEach(function(el, i) { el.addEventListener('collapsed', function(e) { console.log(e); }); - expanderWidgets.push(new Expander(el)); + expanderWidgets.push(new Expander(el, { click: true })); }); focusExpanderEls.forEach(function(el, i) { diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -12,7 +12,7 @@ var focusables = require('makeup-focusables'); var defaultOptions = { autoCollapse: true, - click: true, + click: false, contentSelector: '.expander__content', focus: false, focusManagement: null, @@ -67,10 +67,6 @@ module.exports = function () { this._leaveListener = this.collapse.bind(this); if (this.expandeeEl) { - // const newExpandee = new Expandee(this.expandeeEl, this.options); - - // this.expandee = newExpandee; - // the expander controls the expandee this.hostEl.setAttribute('aria-controls', this.expandeeEl.id); this.hostEl.setAttribute('aria-expanded', 'false'); @@ -78,8 +74,6 @@ module.exports = function () { this.click = this.options.click; this.focus = this.options.focus; this.hover = this.options.hover; - - this.expandeeEl.classList.add('expandee--js'); } } diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -6,7 +6,7 @@ const focusables = require('makeup-focusables'); const defaultOptions = { autoCollapse: true, - click: true, + click: false, contentSelector: '.expander__content', focus: false, focusManagement: null, @@ -59,10 +59,6 @@ module.exports = class { this._leaveListener = this.collapse.bind(this); if (this.expandeeEl) { - // const newExpandee = new Expandee(this.expandeeEl, this.options); - - // this.expandee = newExpandee; - // the expander controls the expandee this.hostEl.setAttribute('aria-controls', this.expandeeEl.id); this.hostEl.setAttribute('aria-expanded', 'false'); @@ -70,8 +66,6 @@ module.exports = class { this.click = this.options.click; this.focus = this.options.focus; this.hover = this.options.hover; - - this.expandeeEl.classList.add('expandee--js'); } } diff --git a/test/static/bundle-module.js b/test/static/bundle-module.js index <HASH>..<HASH> 100644 --- a/test/static/bundle-module.js +++ b/test/static/bundle-module.js @@ -169,7 +169,7 @@ var focusables = require('/makeup-focusables$0.0.1/index'/*'makeup-focusables'*/ var defaultOptions = { autoCollapse: true, - click: true, + click: false, contentSelector: '.expander__content', focus: false, focusManagement: null, @@ -224,10 +224,6 @@ module.exports = function () { this._leaveListener = this.collapse.bind(this); if (this.expandeeEl) { - // const newExpandee = new Expandee(this.expandeeEl, this.options); - - // this.expandee = newExpandee; - // the expander controls the expandee this.hostEl.setAttribute('aria-controls', this.expandeeEl.id); this.hostEl.setAttribute('aria-expanded', 'false'); @@ -235,8 +231,6 @@ module.exports = function () { this.click = this.options.click; this.focus = this.options.focus; this.hover = this.options.hover; - - this.expandeeEl.classList.add('expandee--js'); } }
Changed click to false by default Reason: cater for controls such as combobox that would manually call the expand/collapse/toggle methods.
makeup-js_makeup-expander
train
9a16ebfe8e92b87844efea1d5067079f98237cc6
diff --git a/lib/braid/config.rb b/lib/braid/config.rb index <HASH>..<HASH> 100644 --- a/lib/braid/config.rb +++ b/lib/braid/config.rb @@ -34,7 +34,7 @@ module Braid def get(path) @db.transaction(true) do - if attributes = @db[path] + if attributes = @db[path.to_s.sub(/\/$/, '')] Mirror.new(path, attributes) end end
Remove trailing slash when getting mirrors
cristibalan_braid
train
8f84d1764c3d1403e08aad1dcd5779368cf41c94
diff --git a/src/Pdo/Oci8.php b/src/Pdo/Oci8.php index <HASH>..<HASH> 100644 --- a/src/Pdo/Oci8.php +++ b/src/Pdo/Oci8.php @@ -467,7 +467,7 @@ class Oci8 extends PDO { $sessionMode = array_key_exists('session_mode', $options) ? $options['session_mode'] : null; - if (array_key_exists(PDO::ATTR_PERSISTENT, $options)) { + if (array_key_exists(PDO::ATTR_PERSISTENT, $options) && $options[PDO::ATTR_PERSISTENT]) { $this->dbh = @oci_pconnect($username, $password, $dsn, $charset, $sessionMode); } else { $this->dbh = @oci_connect($username, $password, $dsn, $charset, $sessionMode);
Fix PDO::ATTR_PERSISTENT when is set to false When PDO::ATTR_PERSISTENT is configured in the database.php file, the connections are always persistent, because the key exists in the config file (even if is setted false), ignoring DB_PERSISTENT variable in .env.
yajra_pdo-via-oci8
train
d69e3dffcf283eaa85ac90c539680b846bb0403a
diff --git a/src/ContaoCommunityAlliance/DcGeneral/Clipboard/AbstractItem.php b/src/ContaoCommunityAlliance/DcGeneral/Clipboard/AbstractItem.php index <HASH>..<HASH> 100644 --- a/src/ContaoCommunityAlliance/DcGeneral/Clipboard/AbstractItem.php +++ b/src/ContaoCommunityAlliance/DcGeneral/Clipboard/AbstractItem.php @@ -111,38 +111,41 @@ abstract class AbstractItem implements ItemInterface * {@inheritdoc} * * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) */ public function equals(ItemInterface $item) { - // It is exactly the same item + // It is exactly the same item. if ($this === $item) { return true; } - return !( - // The actions are not equal - $this->getAction() !== $item->getAction() - // One have a parent ID, the other not - || $this->getParentId() && !$item->getParentId() - || !$this->getParentId() && $item->getParentId() - // The parent IDs are not equal - || ( - $this->getParentId() - && !$this->getParentId()->equals($item->getParentId()) - ) - - // One have a model ID, the other not - || $this->getModelId() && !$item->getModelId() - || !$this->getModelId() && $item->getModelId() - - // Both has no model id. - || ( - !($this->getModelId() || $item->getModelId()) - && ($this->getDataProviderName() !== $item->getDataProviderName()) - ) - - // The model IDs are not equal - || !$this->getModelId()->equals($item->getModelId()) - ); + // The actions are not equal. + if ($this->getAction() !== $item->getAction()) { + return false; + } + + // One has a parent ID, the other not. + if (($this->getParentId() && !$item->getParentId()) || (!$this->getParentId() && $item->getParentId())) { + return false; + } + + // The parent IDs are not equal. + if ($this->getParentId() && !$this->getParentId()->equals($item->getParentId())) { + return false; + } + + // One has a model ID, the other not. + if (($this->getModelId() && !$item->getModelId()) || (!$this->getModelId() && $item->getModelId())) { + return false; + } + + // Both have no model id and the data provider is different. + if (!($this->getModelId() || $item->getModelId())) { + return ($this->getDataProviderName() === $item->getDataProviderName()); + } + + // The model IDs are not equal + return $this->getModelId()->equals($item->getModelId()); } }
Rewrite AbstractItem::equals() to not bail when neither have model id but same parent.
contao-community-alliance_dc-general
train
ea554ae696704660487e7cfaf5f132f1ba99b59f
diff --git a/classes/phing/types/Path.php b/classes/phing/types/Path.php index <HASH>..<HASH> 100644 --- a/classes/phing/types/Path.php +++ b/classes/phing/types/Path.php @@ -310,21 +310,19 @@ class Path extends DataType { } $tok = new PathTokenizer($source); - $element = ""; - while ($tok->hasMoreTokens()) { + while ($tok->hasMoreTokens()) { $pathElement = $tok->nextToken(); try { - $element .= self::resolveFile($project, $pathElement); + $element = self::resolveFile($project, $pathElement); + for ($i = 0, $_i=strlen($element); $i < $_i; $i++) { + self::translateFileSep($element, $i); + } + $result[] = $element; } catch (BuildException $e) { - $this->project->log("Dropping path element " . $pathElement - . " as it is not valid relative to the project", + $this->project->log("Dropping path element " . $pathElement + . " as it is not valid relative to the project", Project::MSG_VERBOSE); } - - for ($i = 0, $_i=strlen($element); $i < $_i; $i++) { - self::translateFileSep($element, $i); - } - $result[] = $element; } return $result;
#<I> - fix path duplicates (patch by Benjamin Stover)
phingofficial_phing
train
0ffa573f340b69b9298f6539e6ab4324b413fe51
diff --git a/sam/sam-common/src/main/java/org/talend/esb/sam/common/service/MonitoringService.java b/sam/sam-common/src/main/java/org/talend/esb/sam/common/service/MonitoringService.java index <HASH>..<HASH> 100644 --- a/sam/sam-common/src/main/java/org/talend/esb/sam/common/service/MonitoringService.java +++ b/sam/sam-common/src/main/java/org/talend/esb/sam/common/service/MonitoringService.java @@ -21,15 +21,12 @@ package org.talend.esb.sam.common.service; import java.util.List; -import javax.jws.WebService; - import org.talend.esb.sam.common.event.Event; /** * Public interface for the business logic of MonitoringService. */ -@WebService public interface MonitoringService { /**
TESB-<I> Unrequited WebService annotation is removed
Talend_tesb-rt-se
train
0b6d79ba4bc6cf4408c89f132db87807bb568c41
diff --git a/src/react-super-select.js b/src/react-super-select.js index <HASH>..<HASH> 100644 --- a/src/react-super-select.js +++ b/src/react-super-select.js @@ -49,9 +49,11 @@ var ReactSuperSelect = React.createClass({ return { isOpen: false, focusedId: undefined, + labelKey: this.props.optionLabelKey || 'name', lastOptionId: (data.length > 0) ? data.length - 1 : undefined, searchString: undefined, - value: [] + value: [], + valueKey: this.props.optionValueKey || 'id' }; }, @@ -144,10 +146,10 @@ var ReactSuperSelect = React.createClass({ }, _findArrayOfOptionDataObjectsByValue: function(value) { - var valueKey = this.props.optionValueKey || 'id'; - value = _.isArray(value) ? _.pluck(value, valueKey) : [value]; + var self = this, + valuesArray = _.isArray(value) ? _.pluck(value, this.state.valueKey) : [value]; return _.reject(this.props.dataSource, function(item) { - return !_.contains(value, item[valueKey]); + return !_.contains(valuesArray, item[self.state.valueKey]); }); }, @@ -232,8 +234,7 @@ var ReactSuperSelect = React.createClass({ // render custom template if provided with a rendering function return self.props.customOptionTemplateFunction(value); } else { - var labelKey = self.props.optionLabelKey || 'name'; - return value[labelKey]; + return value[self.state.labelKey]; } }); return markup; @@ -275,10 +276,8 @@ var ReactSuperSelect = React.createClass({ }, _getTagMarkup: function(value) { - var labelKey = this.props.optionLabelKey || 'name', - label = value[labelKey], - valueKey = this.props.optionValueKey || 'id', - displayValue = value[valueKey], + var label = value[this.state.labelKey], + displayValue = value[this.state.valueKey], tagKey = 'tag_' + displayValue, buttonName = "RemoveTag_" + displayValue; @@ -349,12 +348,11 @@ var ReactSuperSelect = React.createClass({ }, _mapDataToCustomTemplateMarkup: function() { - var valueKey = this.props.optionValueKey || 'id', - data = this._getDataSource(), + var data = this._getDataSource(), self = this; return _.map(data, function(dataOption, index) { - var itemKey = "drop_li_" + dataOption[valueKey], + var itemKey = "drop_li_" + dataOption[self.state.valueKey], indexRef = 'option_' + index, customOptionMarkup = self.props.customOptionTemplateFunction(dataOption), classes = classNames('r-ss-dropdown-option', { @@ -362,27 +360,25 @@ var ReactSuperSelect = React.createClass({ }); return ( - <li ref={indexRef} tabIndex="0" className={classes} key={itemKey} data-option-value={dataOption[valueKey]} onClick={self._selectItemOnOptionClick.bind(null, dataOption[valueKey])} role="menuitem"> + <li ref={indexRef} tabIndex="0" className={classes} key={itemKey} data-option-value={dataOption[self.state.valueKey]} onClick={self._selectItemOnOptionClick.bind(null, dataOption[self.state.valueKey])} role="menuitem"> {customOptionMarkup} </li>); }); }, _mapDataToDefaultTemplateMarkup: function() { - var labelKey = this.props.optionLabelKey || 'name', - valueKey = this.props.optionValueKey || 'id', - data = this._getDataSource(), + var data = this._getDataSource(), self = this; return _.map(data, function(dataOption, index) { - var itemKey = "drop_li_" + dataOption[valueKey], + var itemKey = "drop_li_" + dataOption[self.state.valueKey], indexRef = 'option_' + index, classes = classNames('r-ss-dropdown-option', { 'selected': self._isCurrentlySelected(dataOption) }); return ( - <li ref={indexRef} tabIndex="0" className={classes} key={itemKey} data-option-value={dataOption[valueKey]} onClick={self._selectItemOnOptionClick.bind(null, dataOption[valueKey])} role="menuitem"> - {dataOption[labelKey]} + <li ref={indexRef} tabIndex="0" className={classes} key={itemKey} data-option-value={dataOption[self.state.valueKey]} onClick={self._selectItemOnOptionClick.bind(null, dataOption[self.state.valueKey])} role="menuitem"> + {dataOption[self.state.labelKey]} </li>); }); }, @@ -467,10 +463,10 @@ var ReactSuperSelect = React.createClass({ _removeTag: function(value, event) { event.preventDefault(); event.stopPropagation(); - var valueKey = this.props.optionValueKey || 'id'; + var self = this; this.setState({ value: _.reject(this.state.value, function(tag) { - return tag[valueKey] === value[valueKey]; + return tag[self.state.valueKey] === value[self.state.valueKey]; }) }); }, @@ -478,7 +474,7 @@ var ReactSuperSelect = React.createClass({ _selectItemByValues: function(value, isAdditionalOption) { var objectValues = this._findArrayOfOptionDataObjectsByValue(value); - if (isAdditionalOption && this.state.value) { + if (this.props.tags || (isAdditionalOption && this.state.value)) { objectValues = this.state.value.concat(objectValues); }
move labelKey and valueKey to state to make things more DRY make tags avoid meta or ctrl-key click for seleting multiple
alsoscotland_react-super-select
train
181fc18804c3164e0c92a3ad9d7c96baf5e289ba
diff --git a/src/kefir.atom.js b/src/kefir.atom.js index <HASH>..<HASH> 100644 --- a/src/kefir.atom.js +++ b/src/kefir.atom.js @@ -51,11 +51,10 @@ export class AbstractMutable extends Kefir.Property { // -export class LensedAtom extends AbstractMutable { - constructor(source, lens) { +export class MutableWithSource extends AbstractMutable { + constructor(source) { super() this._source = source - this._lens = lens this._$handleValue = null } get() { @@ -65,12 +64,6 @@ export class LensedAtom extends AbstractMutable { else return this._getFromSource() } - modify(fn) { - this._source.modify(L.modify(this._lens, fn)) - } - _getFromSource() { - return L.get(this._lens, this._source.get()) - } _handleValue() { this._maybeEmitValue(this._getFromSource()) } @@ -88,6 +81,21 @@ export class LensedAtom extends AbstractMutable { // +export class LensedAtom extends MutableWithSource { + constructor(source, lens) { + super(source) + this._lens = lens + } + modify(fn) { + this._source.modify(L.modify(this._lens, fn)) + } + _getFromSource() { + return L.get(this._lens, this._source.get()) + } +} + +// + export class Atom extends AbstractMutable { constructor(value) { super()
Refactor to `LensedAtom :> MutableWithSource :> AbstractMutable` The new `MutableWithSource` abstract class can be used to introduce new subclasses of `AbstractMutable` with properties as sources.
calmm-js_kefir.atom
train
e24d937bcbc698208979b04f718858f1f04a8b5c
diff --git a/lib/melodiest/command.rb b/lib/melodiest/command.rb index <HASH>..<HASH> 100644 --- a/lib/melodiest/command.rb +++ b/lib/melodiest/command.rb @@ -37,7 +37,7 @@ module Melodiest end def self.run(app_name, target_dir) - generator = Melodiest::Generator.new app_name + generator = Melodiest::Generator.new app_name, target_dir generator.generate_gemfile generator.generate_bundle_config diff --git a/lib/melodiest/generator.rb b/lib/melodiest/generator.rb index <HASH>..<HASH> 100644 --- a/lib/melodiest/generator.rb +++ b/lib/melodiest/generator.rb @@ -9,7 +9,7 @@ module Melodiest def initialize(app_name, destination=nil) @app_name = app_name @app_class_name = app_name.split("_").map{|s| s.capitalize }.join("") - destination ||= @app_name + destination = destination ? "#{destination}/#{@app_name}" : @app_name unless File.directory?(destination) FileUtils.mkdir_p(destination) diff --git a/spec/melodiest/command_spec.rb b/spec/melodiest/command_spec.rb index <HASH>..<HASH> 100644 --- a/spec/melodiest/command_spec.rb +++ b/spec/melodiest/command_spec.rb @@ -25,9 +25,10 @@ describe Melodiest::Command do end it "has --directory option as target directory" do - app = Melodiest::Command.parse %w(-n my_app --dir /tmp/melodiest) + app = Melodiest::Command.parse %w(-n my_app --dir /tmp) - expect(app).to include "my_app is successfully generated in /tmp/melodiest" + expect(app).to include "my_app is successfully generated in /tmp" + expect(Dir.exists?("/tmp/my_app")).to be_truthy end context "when has no --name option and only --dir option" do diff --git a/spec/melodiest/generator_spec.rb b/spec/melodiest/generator_spec.rb index <HASH>..<HASH> 100644 --- a/spec/melodiest/generator_spec.rb +++ b/spec/melodiest/generator_spec.rb @@ -21,11 +21,11 @@ describe Melodiest::Generator do end it "sets new destination path even if it's not exist yet" do - expect(generator.destination).to eq dest + expect("/tmp/melodiest/my_app").to eq "#{dest}/#{app}" end describe "#generate_gemfile" do - let(:gemfile) { "#{dest}/Gemfile" } + let(:gemfile) { "#{dest}/#{app}/Gemfile" } it "should generate Gemfile with correct content" do generator.generate_gemfile @@ -38,7 +38,7 @@ describe Melodiest::Generator do end describe "#generate_bundle_config" do - let(:bundle_config) { "#{dest}/config.ru" } + let(:bundle_config) { "#{dest}/#{app}/config.ru" } it "should generate config.ru with correct content" do generator.generate_bundle_config @@ -54,9 +54,11 @@ describe Melodiest::Generator do end describe "#generate_app" do + let(:target_dir) { "#{dest}/#{app}" } + it "generates <app_name>.rb" do generator.generate_app - app_file = "#{dest}/{my_app}.rb" + app_file = "#{target_dir}/my_app.rb" file_content = File.read(app_file) expected_file_content = @@ -75,11 +77,11 @@ DOC expect(File.exists?(app_file)).to be_truthy expect(file_content).to eq expected_file_content - expect(Dir.exists?("#{dest}/db/migrations")).to be_truthy - expect(Dir.exists?("#{dest}/app")).to be_truthy - expect(Dir.exists?("#{dest}/app/routes")).to be_truthy - expect(Dir.exists?("#{dest}/app/models")).to be_truthy - expect(Dir.exists?("#{dest}/app/views")).to be_truthy + expect(Dir.exists?("#{target_dir}/db/migrations")).to be_truthy + expect(Dir.exists?("#{target_dir}/app")).to be_truthy + expect(Dir.exists?("#{target_dir}/app/routes")).to be_truthy + expect(Dir.exists?("#{target_dir}/app/models")).to be_truthy + expect(Dir.exists?("#{target_dir}/app/views")).to be_truthy end end
fix generated app does not create under target directory
kuntoaji_sinator
train
971679a64c87048ccec7cfdd0de33e0a1ff43000
diff --git a/scripts/roles.json b/scripts/roles.json index <HASH>..<HASH> 100644 --- a/scripts/roles.json +++ b/scripts/roles.json @@ -3130,11 +3130,11 @@ "aria-keyshortcuts", "aria-label", "aria-labelledby", - "aria-level", "aria-live", "aria-owns", "aria-relevant", - "aria-roledescription" + "aria-roledescription", + ["aria-level", "2"] ], "relatedConcepts": [ { @@ -3176,9 +3176,7 @@ ], "requiredContextRole": [], "requiredOwnedElements": [], - "requiredProps": [ - ["aria-level", 2] - ], + "requiredProps": [["aria-level", "2"]], "superClass": ["sectionhead"] }, "img": { @@ -5860,7 +5858,7 @@ "relatedConcepts": [], "requiredContextRole": ["group", "tree"], "requiredOwnedElements": [], - "requiredProps": [], + "requiredProps": ["aria-selected"], "superClass": ["listitem", "option"] }, "widget": { diff --git a/src/etc/roles/literal/headingRole.js b/src/etc/roles/literal/headingRole.js index <HASH>..<HASH> 100644 --- a/src/etc/roles/literal/headingRole.js +++ b/src/etc/roles/literal/headingRole.js @@ -12,7 +12,7 @@ const headingRole: ARIARoleDefinition = { ], prohibitedProps: [], props: { - 'aria-level': null, + 'aria-level': '2', }, relatedConcepts: [ { @@ -56,7 +56,7 @@ const headingRole: ARIARoleDefinition = { requiredContextRole: [], requiredOwnedElements: [], requiredProps: { - 'aria-level': 2, + 'aria-level': '2', }, superClass: [ [ diff --git a/src/etc/roles/literal/treeitemRole.js b/src/etc/roles/literal/treeitemRole.js index <HASH>..<HASH> 100644 --- a/src/etc/roles/literal/treeitemRole.js +++ b/src/etc/roles/literal/treeitemRole.js @@ -25,7 +25,9 @@ const treeitemRole: ARIARoleDefinition = { 'tree', ], requiredOwnedElements: [], - requiredProps: {}, + requiredProps: { + 'aria-selected': null, + }, superClass: [ [ 'roletype',
fix: Normalize required props (#<I>)
A11yance_aria-query
train
36f39fd569306b2d0abbdc7d416988099b5e1532
diff --git a/modules/wycs/src/wycs/transforms/VerificationCheck.java b/modules/wycs/src/wycs/transforms/VerificationCheck.java index <HASH>..<HASH> 100644 --- a/modules/wycs/src/wycs/transforms/VerificationCheck.java +++ b/modules/wycs/src/wycs/transforms/VerificationCheck.java @@ -137,6 +137,7 @@ public class VerificationCheck implements Transform<WycsFile> { Code.Op.NOT, stmt.condition); Code nnf = NormalForms.negationNormalForm(neg); Code pnf = NormalForms.prefixNormalForm(nnf); + int assertion = translate(pnf,automaton,new HashMap<String,Integer>()); //int assertion = translate(stmt.condition,automaton,new HashMap<String,Integer>());
Thinking, pondering, thinking some more.
Whiley_WhileyCompiler
train
04f9edf993fe3dd16fb6b0d6d1c35d90308ddf8a
diff --git a/txaws/service.py b/txaws/service.py index <HASH>..<HASH> 100644 --- a/txaws/service.py +++ b/txaws/service.py @@ -51,14 +51,14 @@ class AWSServiceEndpoint(object): uri = "%s:%s" % (uri, self.port) return uri + self.path -# XXX needs tests! + class AWSServiceRegion(object): """ This object represents a collection of client factories that use the same credentials. With Amazon, this collection is associated with a region (e.g., US or EU). """ - def __init__(self, creds=None, location=REGION_US): + def __init__(self, creds=None, region=REGION_US): self.creds = creds self._clients = {} if region == REGION_US: diff --git a/txaws/tests/test_service.py b/txaws/tests/test_service.py index <HASH>..<HASH> 100644 --- a/txaws/tests/test_service.py +++ b/txaws/tests/test_service.py @@ -4,7 +4,8 @@ import os from txaws.credentials import AWSCredentials -from txaws.service import AWSServiceEndpoint, AWSServiceRegion +from txaws.ec2.client import EC2Client +from txaws.service import AWSServiceEndpoint, AWSServiceRegion, EC2_ENDPOINT_US from txaws.tests import TXAWSTestCase class AWSServiceEndpointTestCase(TXAWSTestCase): @@ -54,3 +55,49 @@ class AWSServiceEndpointTestCase(TXAWSTestCase): self.assertEquals( self.endpoint.get_uri(), "http://my.service/newpath") + + +class AWSServiceRegionTestCase(TXAWSTestCase): + + def setUp(self): + self.creds = AWSCredentials("foo", "bar") + self.region = AWSServiceRegion(creds=self.creds) + + def test_simple_creation(self): + self.assertEquals(self.creds, self.region.creds) + self.assertEquals(self.region._clients, {}) + self.assertEquals(self.region.ec2_endpoint.get_uri(), EC2_ENDPOINT_US) + + def test_get_client_with_empty_cache(self): + key = str(EC2Client) + str(self.creds) + str(self.region.ec2_endpoint) + original_client = self.region._clients.get(key) + new_client = self.region.get_client( + EC2Client, self.creds, self.region.ec2_endpoint) + self.assertEquals(original_client, None) + self.assertNotEquals(original_client, new_client) + self.assertTrue(isinstance(new_client, EC2Client)) + + def test_get_client_from_cache(self): + client1 = self.region.get_client( + EC2Client, self.creds, self.region.ec2_endpoint) + client2 = self.region.get_client( + EC2Client, self.creds, self.region.ec2_endpoint) + self.assertTrue(isinstance(client1, EC2Client)) + self.assertTrue(isinstance(client2, EC2Client)) + self.assertEquals(client2, client2) + + def test_get_ec2_client_from_cache(self): + client1 = self.region.get_ec2_client(self.creds) + client2 = self.region.get_ec2_client(self.creds) + self.assertTrue(isinstance(client1, EC2Client)) + self.assertTrue(isinstance(client2, EC2Client)) + self.assertEquals(client2, client2) + + def test_get_s3_client(self): + self.assertRaises(NotImplementedError, self.region.get_s3_client) + + def test_get_simpledb_client(self): + self.assertRaises(NotImplementedError, self.region.get_simpledb_client) + + def test_get_sqs_client(self): + self.assertRaises(NotImplementedError, self.region.get_sqs_client)
Added missing tests for the AWS service region object.
twisted_txaws
train
367609ff3f33c3fb7319128725b4cc3c54ddf107
diff --git a/ga4gh/frontend.py b/ga4gh/frontend.py index <HASH>..<HASH> 100644 --- a/ga4gh/frontend.py +++ b/ga4gh/frontend.py @@ -257,21 +257,6 @@ def indexRedirect(version): return index() [email protected]('/<version>/references/<id>', methods=['GET']) -def getReference(version, id): - raise exceptions.PathNotFoundException() - - [email protected]('/<version>/references/<id>/bases', methods=['GET']) -def getReferenceBases(version, id): - raise exceptions.PathNotFoundException() - - [email protected]('/<version>/referencesets/<id>', methods=['GET']) -def getReferenceSet(version, id): - raise exceptions.PathNotFoundException() - - @app.route('/<version>/callsets/search', methods=['POST']) def searchCallSets(version): return handleFlaskPostRequest( @@ -296,11 +281,6 @@ def searchReferenceSets(version): version, flask.request, app.backend.searchReferenceSets) [email protected]('/<version>/references/search', methods=['POST']) -def searchReferences(version): - raise exceptions.PathNotFoundException() - - @app.route('/<version>/variantsets/search', methods=['POST', 'OPTIONS']) def searchVariantSets(version): return handleFlaskPostRequest(
Take out unused paths Issue #<I>
ga4gh_ga4gh-server
train
8dbfed664dc642e4227e2e30c5a011e280efd1fe
diff --git a/salt/states/mount.py b/salt/states/mount.py index <HASH>..<HASH> 100644 --- a/salt/states/mount.py +++ b/salt/states/mount.py @@ -173,6 +173,7 @@ def mounted(name, 'defaults', 'delay_connect', 'intr', + 'loop', 'nointr', 'nobootwait', 'nofail',
Don't remount loop back filesystems upon every state run
saltstack_salt
train
4b3f70644c64fa5aefbf6335f16a8ec929d313e0
diff --git a/source/Application/views/admin/de/lang.php b/source/Application/views/admin/de/lang.php index <HASH>..<HASH> 100644 --- a/source/Application/views/admin/de/lang.php +++ b/source/Application/views/admin/de/lang.php @@ -142,6 +142,7 @@ $aLang = array( 'GENERAL_ARTICLE_OXREMINDAMOUNT' => 'Zuwenig Lagerbestand Mindestmenge', 'GENERAL_ARTICLE_OXAMITEMID' => 'oxamitemid', 'GENERAL_ARTICLE_OXAMTASKID' => 'oxamtaskid', + 'GENERAL_ARTICLE_OXVARMAXPRICE' => 'Höchster Variantenpreis', 'GENERAL_ARTICLE_OXVENDORID' => 'Lieferant ID', 'GENERAL_ARTICLE_OXMANUFACTURERID' => 'Hersteller ID', 'GENERAL_ARTICLE_OXVARCOUNT' => 'Varianten Anzahl',
GENERAL_ARTICLE_OXVARMAXPRICE was missing. added translation for 'GENERAL_ARTICLE_OXVARMAXPRICE'
OXID-eSales_oxideshop_ce
train
39f448e656cbc4fcc9291b0a5a6e152baf105eac
diff --git a/SwatDB/SwatDBDataObject.php b/SwatDB/SwatDBDataObject.php index <HASH>..<HASH> 100644 --- a/SwatDB/SwatDBDataObject.php +++ b/SwatDB/SwatDBDataObject.php @@ -1371,14 +1371,14 @@ class SwatDBDataObject extends SwatObject } foreach ($this->getSerializablePrivateProperties() as $property) { - $data[$property] = &$this->$property; + $data[$property] = $this->$property; } $reflector = new ReflectionObject($this); foreach ($reflector->getProperties() as $property) { if ($property->isPublic() && !$property->isStatic()) { $name = $property->getName(); - $data[$name] = &$this->$name; + $data[$name] = $this->$name; } } diff --git a/SwatDB/SwatDBRecordsetWrapper.php b/SwatDB/SwatDBRecordsetWrapper.php index <HASH>..<HASH> 100644 --- a/SwatDB/SwatDBRecordsetWrapper.php +++ b/SwatDB/SwatDBRecordsetWrapper.php @@ -646,8 +646,9 @@ abstract class SwatDBRecordsetWrapper extends SwatObject 'options', ); - foreach ($private_properties as $property) - $data[$property] = &$this->$property; + foreach ($private_properties as $property) { + $data[$property] = $this->$property; + } return serialize($data); } @@ -659,8 +660,9 @@ abstract class SwatDBRecordsetWrapper extends SwatObject { $data = unserialize($data); - foreach ($data as $property => $value) + foreach ($data as $property => $value) { $this->$property = $value; + } } // }}}
Don't assign by reference when building serialized array representations of objects. Assigning by reference causes session corruption on newer versions of PHP. Copy-on-write semantics of arrays means this code will not use more memory or be slower than the code that assigned by reference.
silverorange_swat
train
d82a7107fbe42b99ee6832383f0694c298535fdd
diff --git a/src/Neutrino/Providers/View.php b/src/Neutrino/Providers/View.php index <HASH>..<HASH> 100644 --- a/src/Neutrino/Providers/View.php +++ b/src/Neutrino/Providers/View.php @@ -58,8 +58,6 @@ class View extends Injectable implements Providable [ 'compiledPath' => $config->compiled_path, 'compiledSeparator' => '_', - ], - [ 'compileAlways' => APP_ENV === Env::DEVELOPMENT, ], isset($config->options) ? (array)$config->options : []
feat(Provider\View): View engine options configurable & always compile when env is development
phalcon-nucleon_framework
train
b28c464df5b26e05894b712ac996347f6e339350
diff --git a/src/View/View.php b/src/View/View.php index <HASH>..<HASH> 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -55,6 +55,7 @@ use RuntimeException; * @property \Cake\View\Helper\SessionHelper $Session * @property \Cake\View\Helper\TextHelper $Text * @property \Cake\View\Helper\TimeHelper $Time + * @property \Cake\View\Helper\UrlHelper $Url * @property \Cake\View\ViewBlock $Blocks */ class View implements EventDispatcherInterface
Adding UrlHelper as @property comment
cakephp_cakephp
train
9658efd3310f84af4df3cc202fbb54ccd392d279
diff --git a/app/sweepers/monologue/posts_sweeper.rb b/app/sweepers/monologue/posts_sweeper.rb index <HASH>..<HASH> 100644 --- a/app/sweepers/monologue/posts_sweeper.rb +++ b/app/sweepers/monologue/posts_sweeper.rb @@ -5,8 +5,9 @@ class Monologue::PostsSweeper < ActionController::Caching::Sweeper def sweep(post) root_path = Monologue::Engine.routes.url_helpers.root_path if root_path.nil? # TODO: why do I have to do this to make tests pass? There must be something much more clean to make tests pass page_cache_directory = Rails.public_path if page_cache_directory.nil? # TODO: we should not need this either... - unless post.just_the_revision_one_before.nil? - current_post_path = "#{page_cache_directory}#{post.just_the_revision_one_before.url}.html" + if post.posts_revisions.count > 0 + current_post_path = "#{page_cache_directory}#{post.just_the_revision_one_before.url}.html" unless post.just_the_revision_one_before.nil? + current_post_path = "#{page_cache_directory}#{post.posts_revisions.last.url}.html" if post.posts_revisions.count == 1 File.delete current_post_path if File.exists? current_post_path end diff --git a/spec/requests/cache_spec.rb b/spec/requests/cache_spec.rb index <HASH>..<HASH> 100644 --- a/spec/requests/cache_spec.rb +++ b/spec/requests/cache_spec.rb @@ -2,22 +2,11 @@ require 'spec_helper' describe "cache" do before(:each) do - user = Factory(:user) - posts = 0 - published_at = DateTime.now - 30.days - 25.times do - revisions = 0 - posts+=1 - @post = Factory(:post) - 3.times do - revisions += 1 - published_at = published_at + 1.day - @post.posts_revisions.build(Factory.attributes_for(:posts_revision, user_id: user.id, url: "/monologue/post/#{posts}" , title: "post #{posts} | revision #{revisions}", published_at: published_at )) - end - @post.save - end - - ActionController::Base.perform_caching = true + @post_1 = Factory(:posts_revision).post + @post_2 = Factory(:posts_revision).post + @post_3 = Factory(:posts_revision).post + 25.times { |i| Factory(:posts_revision, title: "post #{i}", url: "/monologue/post/#{i}") } + ActionController::Base.perform_caching = true # TODO: make that work. This does not seem to work flawlessly, so it's set in dummy's config/environments/test.rb too... clear_cache end @@ -42,7 +31,7 @@ describe "cache" do describe "sweeper" do before(:each) do - @test_paths = ["/monologue", "/monologue/post/2", "/monologue/post/3"] + @test_paths = ["/monologue", @post_1.latest_revision.url, @post_2.latest_revision.url, @post_3.latest_revision.url] @test_paths.each do |path| assert_create_cache(path) end @@ -52,22 +41,22 @@ describe "cache" do it "should clear cache on create" do post = Factory(:post) cache_sweeped?(["/monologue"]).should be_true - cache_sweeped?(["/monologue/post/2", "/monologue/post/3"]).should be_false + cache_sweeped?([@post_2.latest_revision.url, @post_3.latest_revision.url]).should be_false cache_sweeped?([feed_path], "rss").should be_true - end + end it "should clear cache on update" do - @post.save! - cache_sweeped?([@post.latest_revision.url]).should be_true + @post_1.save! + cache_sweeped?([@post_1.latest_revision.url]).should be_true cache_sweeped?(["/monologue/"]).should be_true - cache_sweeped?(["/monologue/post/2", "/monologue/post/3"]).should be_false + cache_sweeped?([@post_2.latest_revision.url, @post_3.latest_revision.url]).should be_false cache_sweeped?([feed_path], "rss").should be_true end it "should clear cache on destroy" do - @post.destroy + @post_1.destroy cache_sweeped?(["/monologue/"]).should be_true - cache_sweeped?(["/monologue/post/2", "/monologue/post/3"]).should be_false + cache_sweeped?([@post_2.latest_revision.url, @post_3.latest_revision.url]).should be_false cache_sweeped?([feed_path], "rss").should be_true end end
fixed sweeper and refactored the tests fixin #<I> and #<I>
jipiboily_monologue
train