hash
stringlengths
40
40
diff
stringlengths
131
26.7k
message
stringlengths
7
694
project
stringlengths
5
67
split
stringclasses
1 value
diff_languages
stringlengths
2
24
e745c18c685506b7efcf9256aa12131bc78cc248
diff --git a/slackminion/bot.py b/slackminion/bot.py index <HASH>..<HASH> 100644 --- a/slackminion/bot.py +++ b/slackminion/bot.py @@ -77,6 +77,9 @@ class Bot(object): if output: self.send_message(msg.channel.channelid, output) sleep(0.1) + except KeyboardInterrupt: + # On ctrl-c, just exit + pass except: self.log.exception('Unhandled exception') diff --git a/slackminion/dispatcher.py b/slackminion/dispatcher.py index <HASH>..<HASH> 100644 --- a/slackminion/dispatcher.py +++ b/slackminion/dispatcher.py @@ -52,6 +52,7 @@ class MessageDispatcher(object): def push(self, message): args = self._parse_message(message) cmd = args[0] + self.log.info("Received from %s: execute %s, args %s", message.user.username, cmd, args[1:]) self.log.debug("Received command %s with args %s", cmd, args[1:]) if cmd[0] == '!': cmd = cmd[1:]
Exit on ctrl-c
arcticfoxnv_slackminion
train
py,py
cc1e779926bab49e920e086889e965e33a3b106d
diff --git a/lib/player.js b/lib/player.js index <HASH>..<HASH> 100644 --- a/lib/player.js +++ b/lib/player.js @@ -43,8 +43,8 @@ var REPLAYGAIN_PREAMP = 0.75; var REPLAYGAIN_DEFAULT = 0.25; Player.REPEAT_OFF = 0; -Player.REPEAT_ALL = 1; -Player.REPEAT_ONE = 2; +Player.REPEAT_ONE = 1; +Player.REPEAT_ALL = 2; Player.trackWithoutIndex = trackWithoutIndex; diff --git a/src/client/app.js b/src/client/app.js index <HASH>..<HASH> 100644 --- a/src/client/app.js +++ b/src/client/app.js @@ -362,7 +362,7 @@ var LoadStatus = { NoServer: 'Server is down.', GoodToGo: '[good to go]' }; -var repeatModeNames = ["Off", "All", "One"]; +var repeatModeNames = ["Off", "One", "All"]; var load_status = LoadStatus.Init; var settings_ui = { auth: {
repeat goes off, 1, all instead of off, all, 1
andrewrk_groovebasin
train
js,js
0702b88e71372db2c8fae7dd7a7a9b4c64f9cff6
diff --git a/app/models/unidom/common/concerns/sha2_digester.rb b/app/models/unidom/common/concerns/sha2_digester.rb index <HASH>..<HASH> 100644 --- a/app/models/unidom/common/concerns/sha2_digester.rb +++ b/app/models/unidom/common/concerns/sha2_digester.rb @@ -7,6 +7,16 @@ module Unidom::Common::Concerns::Sha2Digester included do |includer| + ## + # 对明文 message 进行 SHA-2 摘要, pepper 是用于增加混乱的内容。如: + # class SomeModel + # include Unidom::Common::Concerns::Sha2Digester + # def some_method(param_1) + # digest param_1 + # # 或者 + # digest param_1, pepper: 'my_pepper' + # end + # end def digest(message, pepper: nil) self.class.digest message, pepper: pepper end
1, Improve the SHA-2 Digester for the document.
topbitdu_unidom-common
train
rb
9138a0fa888d65bb247cb1b2b3396f15111fea1f
diff --git a/client/components/steps/steps-container-stack.js b/client/components/steps/steps-container-stack.js index <HASH>..<HASH> 100644 --- a/client/components/steps/steps-container-stack.js +++ b/client/components/steps/steps-container-stack.js @@ -19,18 +19,14 @@ class StepsContainerStack extends Component { // If it pass, jump to the next step. // If not, define it as current. // + let step = this.state.step validations && validations.length && validations.map((validate, index) => { - console.log('validate', validate()) - const { step } = this.state const position = index + 1 - const isCurrent = step === position const isLast = validations.length === position - - if (isCurrent && !isLast && validate()) { - this.setState({ ...this.state, step: position + 1 }) - } + if (isCurrent && !isLast && validate()) step++ }) + this.setState({ ...this.state, step }) } componentWillReceiveProps (nextProps) {
Fix the StepsContainerStack component steps state refresh
nossas_bonde-client
train
js
cc97b4f43d460b8c9819cb4ed40630f304b1187b
diff --git a/dbpool/src/main/java/com/proofpoint/dbpool/H2EmbeddedDataSource.java b/dbpool/src/main/java/com/proofpoint/dbpool/H2EmbeddedDataSource.java index <HASH>..<HASH> 100644 --- a/dbpool/src/main/java/com/proofpoint/dbpool/H2EmbeddedDataSource.java +++ b/dbpool/src/main/java/com/proofpoint/dbpool/H2EmbeddedDataSource.java @@ -31,6 +31,7 @@ public class H2EmbeddedDataSource extends ManagedDataSource try { setConfig(connection, "CACHE_SIZE", config.getCacheSize()); setConfig(connection, "COMPRESS_LOB", config.getCompressLob()); + setConfig(connection, "DB_CLOSE_DELAY ", "-1"); Reader fileReader; String fileName = config.getInitScript();
Do not close db when all connections are closed
airlift_airlift
train
java
cbd4d3e5d306a5ffe4ba48318305602ab9ff9d77
diff --git a/dateparser/conf.py b/dateparser/conf.py index <HASH>..<HASH> 100644 --- a/dateparser/conf.py +++ b/dateparser/conf.py @@ -56,14 +56,17 @@ settings = Settings() def apply_settings(f): @wraps(f) def wrapper(*args, **kwargs): - if 'settings' in kwargs: - if isinstance(kwargs['settings'], dict): - kwargs['settings'] = settings.replace(**kwargs['settings']) - elif isinstance(kwargs['settings'], Settings): - kwargs['settings'] = kwargs['settings'] - else: - raise TypeError("settings can only be either dict or instance of Settings class") - else: + kwargs['settings'] = kwargs.get('settings', settings) + + if kwargs['settings'] is None: kwargs['settings'] = settings + + if isinstance(kwargs['settings'], dict): + kwargs['settings'] = settings.replace(**kwargs['settings']) + + if not isinstance(kwargs['settings'], Settings): + raise TypeError( + "settings can only be either dict or instance of Settings class") + return f(*args, **kwargs) return wrapper
Re-wrote conditions for apply_settings
scrapinghub_dateparser
train
py
8c9a308c9afb9de13a7374cb9a64332e87f5cc66
diff --git a/requesting.go b/requesting.go index <HASH>..<HASH> 100644 --- a/requesting.go +++ b/requesting.go @@ -231,7 +231,14 @@ func (p *Peer) applyRequestState(next desiredRequestState) bool { continue } existing := t.requestingPeer(req) - if existing != nil && existing != p && existing.uncancelledRequests() > current.Requests.GetCardinality() { + if existing != nil && existing != p { + // Don't steal from the poor. + diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1) + // Steal a request that leaves us with one more request than the existing peer + // connection if the stealer more recently received a chunk. + if diff > 1 || (diff == 1 && p.lastUsefulChunkReceived.Before(existing.lastUsefulChunkReceived)) { + continue + } t.cancelRequest(req) } more = p.mustRequest(req)
Only steal an odd request if the stealer more recently received a chunk This helps break the stealing cycle during endgame, and lets us trickle the request to the peer conn with the best record. It might not be sufficient but works nice in testing so far.
anacrolix_torrent
train
go
4f7fc5330dd12d3c0544b34d0964cbe5c88c4cce
diff --git a/lib/asyncflow.js b/lib/asyncflow.js index <HASH>..<HASH> 100644 --- a/lib/asyncflow.js +++ b/lib/asyncflow.js @@ -220,6 +220,7 @@ asyncflow.wrapped = { }; asyncflow.extension = { wrap: function() { return asyncflow.wrap(this) }, + cwrap: function() { return asyncflow.cwrap(this) }, collection: function(method) { return function() { var args = Array.prototype.slice.call(arguments);
Add cwrap to extension facilities.
sethyuan_asyncflow
train
js
ee5b766d5b59b1a6da765114444a733690b2ed75
diff --git a/tests/main.py b/tests/main.py index <HASH>..<HASH> 100644 --- a/tests/main.py +++ b/tests/main.py @@ -47,3 +47,6 @@ Available tasks: """.lstrip() ) + + def exposes_hosts_flag_in_help(self): + expect("--help", "-H STRING, --hosts=STRING", test=assert_contains)
Failing test re: extended core arg for host stuff
fabric_fabric
train
py
d50f4e163fcb62527b1dcbb167dc7c2ac6bcac10
diff --git a/tillthen.js b/tillthen.js index <HASH>..<HASH> 100644 --- a/tillthen.js +++ b/tillthen.js @@ -215,7 +215,9 @@ // Fulfil the promise state = "fulfilled"; - for (var i = 0, l = fulfillQueue.length; i < l; ++i) { fulfillQueue[i](value); } + _.evaluateOnNextTurn(function (fq) { + for (var i = 0, l = fq.length; i < l; ++i) { fq[i](value); } + }, fulfillQueue); fulfillQueue = []; result = value; @@ -232,7 +234,9 @@ // Reject the promise state = "rejected"; - for (var i = 0, l = rejectQueue.length; i < l; ++i) { rejectQueue[i](reason); } + _.evaluateOnNextTurn(function (rq) { + for (var i = 0, l = rq.length; i < l; ++i) { rq[i](reason); } + }, rejectQueue); rejectQueue = []; result = reason;
Evaluate reject/fullfil queues on next turn
biril_tillthen
train
js
23ac061d83d4d5235a68953c0b3f7b11c9e10982
diff --git a/packager.js b/packager.js index <HASH>..<HASH> 100644 --- a/packager.js +++ b/packager.js @@ -66,6 +66,9 @@ if (options.projectRoots) { if (__dirname.match(/node_modules\/react-native\/packager$/)) { // packager is running from node_modules of another project options.projectRoots = [path.resolve(__dirname, '../../..')]; + } else if (__dirname.match(/Pods\/React\/packager$/)) { + // packager is running from node_modules of another project + options.projectRoots = [path.resolve(__dirname, '../../..')]; } else { options.projectRoots = [path.resolve(__dirname, '..')]; } @@ -88,6 +91,8 @@ if (options.assetRoots) { } else { if (__dirname.match(/node_modules\/react-native\/packager$/)) { options.assetRoots = [path.resolve(__dirname, '../../..')]; + } else if (__dirname.match(/Pods\/React\/packager$/)) { + options.assetRoots = [path.resolve(__dirname, '../../..')]; } else { options.assetRoots = [path.resolve(__dirname, '..')]; }
Added support for React installed in the application via Cocoapods Summary: Similarly to npm-installed react, this change makes changes to the packager so that it understands that it's been installed via Cocoapods and determines the project and asset roots properly (from the main application directory). Closes <URL>
facebook_metro
train
js
ddc43d80176153c40081a744476e3d1b9b404dda
diff --git a/client/my-sites/hosting/data-loss-warning/index.js b/client/my-sites/hosting/data-loss-warning/index.js index <HASH>..<HASH> 100644 --- a/client/my-sites/hosting/data-loss-warning/index.js +++ b/client/my-sites/hosting/data-loss-warning/index.js @@ -28,7 +28,7 @@ const DataLossWarning = ( { avatars, translate } ) => { </strong> &nbsp; { translate( - 'If you need help or have any questions our Happiness Engineers are here when you need them!' + 'If you need help or have any questions, our Happiness Engineers are here when you need them!' ) } </p> <div className="data-loss-warning__contact">
Hosting: Correct grammar in warning. (#<I>)
Automattic_wp-calypso
train
js
60f37109c8f9b67deec55f180cda71336ca925d1
diff --git a/solidity/test/LiquidityPoolV2Converter.js b/solidity/test/LiquidityPoolV2Converter.js index <HASH>..<HASH> 100644 --- a/solidity/test/LiquidityPoolV2Converter.js +++ b/solidity/test/LiquidityPoolV2Converter.js @@ -1945,7 +1945,7 @@ contract('LiquidityPoolV2Converter', accounts => { let referenceRate = normalizedRate; let lastConversionRate = normalizedRate; - for (let i = 1; i < 40; ++i) { + for (let i = 1; i < 10; ++i) { const totalTimeElapsed = timeElapsed.add(new BN(i)); await converter.setReferenceRateUpdateTime(now.sub(totalTimeElapsed));
reduced specific test # of iterations
bancorprotocol_contracts
train
js
ffda6372aa9b355f3df84bb220872725b3931c13
diff --git a/src/Instant.php b/src/Instant.php index <HASH>..<HASH> 100644 --- a/src/Instant.php +++ b/src/Instant.php @@ -276,6 +276,18 @@ class Instant extends ReadableInstant } /** + * Returns a ZonedDateTime formed from this instant and the specified time-zone. + * + * @param TimeZone $timeZone + * + * @return ZonedDateTime + */ + public function atTimeZone(TimeZone $timeZone) + { + return ZonedDateTime::ofInstant($this, $timeZone); + } + + /** * @return string */ public function __toString()
Added Instant::atTimeZone() as an alternative to ZonedDateTime::ofInstant()
brick_date-time
train
php
7b2ac450d223f209a19d53dc34fe43b6cfb00534
diff --git a/Resources/public/fluidvids/fluidvids.js b/Resources/public/fluidvids/fluidvids.js index <HASH>..<HASH> 100644 --- a/Resources/public/fluidvids/fluidvids.js +++ b/Resources/public/fluidvids/fluidvids.js @@ -25,7 +25,7 @@ /* * RegExp, extend this if you need more players */ - players = /www.youtube.com|player.vimeo.com/; + players = /www.youtube.com|player.vimeo.com|slideshare.net/; /* * If the RegExp pattern exists within the current iframe
Added slideshare to fluidvids.js
claroline_FrontEndBundle
train
js
41614156a345e0de3066fcd9ee2971c055983cea
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -34,6 +34,7 @@ class Trench { let ended = false; req.end = function() { + ended = true; reqEnd.apply(req, arguments); };
set ended to true when res.end() is called
montyanderson_trench
train
js
ca569f4655e15106c8b5d9b5b7624bf9e4bcd2fa
diff --git a/src/Auth0/Login/LoginServiceProvider.php b/src/Auth0/Login/LoginServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/Auth0/Login/LoginServiceProvider.php +++ b/src/Auth0/Login/LoginServiceProvider.php @@ -2,10 +2,11 @@ use Illuminate\Support\ServiceProvider; use Auth0\SDK\API\ApiClient; +use Auth0\SDK\API\InformationHeaders; class LoginServiceProvider extends ServiceProvider { - const SDK_VERSION = "2.1.1"; + const SDK_VERSION = "2.1.2"; /** * Indicates if loading of the provider is deferred. @@ -37,8 +38,18 @@ class LoginServiceProvider extends ServiceProvider { ]); $laravel = app(); - ApiClient::addHeaderInfoMeta('Laravel:'.$laravel::VERSION); - ApiClient::addHeaderInfoMeta('SDK:'.self::SDK_VERSION); + + $oldInfoHeaders = ApiClient::getInfoHeadersData(); + + if ($oldInfoHeaders) { + $infoHeaders = InformationHeaders::Extend($oldInfoHeaders); + + $infoHeaders->setEnvironment('Laravel', $laravel::VERSION); + $infoHeaders->setPackage('laravel-auth0', self::SDK_VERSION); + + ApiClient::setInfoHeadersData($infoHeaders); + } + } /**
Added override of info headers
auth0_laravel-auth0
train
php
c23541325b291a8c20523dc608c617121bad6397
diff --git a/src/controllers/AbstractController.php b/src/controllers/AbstractController.php index <HASH>..<HASH> 100644 --- a/src/controllers/AbstractController.php +++ b/src/controllers/AbstractController.php @@ -37,9 +37,9 @@ abstract class AbstractController extends \hidev\base\Controller return array_merge(parent::options($actionId), array_keys(Helper::getPublicVars(get_called_class()))); } - public function perform() + public function perform($action = 'make') { - return $this->runActions(['before', 'make', 'after']); + return $this->runActions(['before', $action, 'after']); } public function actionBefore() diff --git a/src/controllers/CommonController.php b/src/controllers/CommonController.php index <HASH>..<HASH> 100644 --- a/src/controllers/CommonController.php +++ b/src/controllers/CommonController.php @@ -18,9 +18,14 @@ use Yii; */ class CommonController extends AbstractController { + public $performName; + public $performPath; + public function actionPerform($name = null, $path = null) { + $this->performName = $name; + $this->performPath = $path; Yii::trace("Started: '$this->id'"); - return $this->perform(['before', 'make', 'after']); + return $this->perform(); } }
improved AbstractController::perform()
hiqdev_hidev
train
php,php
4d94dfc9622b1f44a263ea403fb08f35ec97f4eb
diff --git a/inc/utility/namespace.php b/inc/utility/namespace.php index <HASH>..<HASH> 100644 --- a/inc/utility/namespace.php +++ b/inc/utility/namespace.php @@ -1279,7 +1279,7 @@ function rmrdir( $dirname, $only_empty = false ) { /** - * Comma separated, Oxford comma (or semicolon if comma is part of any array element), localized and between the last two items + * Comma separated, Oxford semicolon localized and between the last two items * * @since 5.0.0 * @@ -1303,7 +1303,7 @@ function oxford_comma( array $vars ) { } /** - * Explode an oxford comma (or semicolon if comma and semicolon are present in the string) seperated list of items + * Explode an oxford semicolon seperated list of items * * @param $string *
Fix oxford comma methods utility docs
pressbooks_pressbooks
train
php
1676f01c904c5c0a90722760c006147095a6b0ee
diff --git a/packages/ember-runtime/lib/mixins/action_handler.js b/packages/ember-runtime/lib/mixins/action_handler.js index <HASH>..<HASH> 100644 --- a/packages/ember-runtime/lib/mixins/action_handler.js +++ b/packages/ember-runtime/lib/mixins/action_handler.js @@ -242,7 +242,7 @@ Ember.ActionHandler = Ember.Mixin.create({ var hashName; if (!props._actions) { - Ember.assert(this + " 'actions' should not be a function", typeof(props.actions) !== 'function'); + Ember.assert("'actions' should not be a function", typeof(props.actions) !== 'function'); if (typeOf(props.actions) === 'object') { hashName = 'actions';
Don't call toString at extend time Doing so will memoize the function so that any Ember.View subclass will return the same value for toString.
emberjs_ember.js
train
js
f8071f5ae74e86af66b6103da37af9fe61ab6182
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ import setuptools setuptools.setup( name="nbserverproxy", - version='0.2.0', + version='0.3.0', url="https://github.com/jupyterhub/nbserverproxy", author="Ryan Lovett", author_email="[email protected]",
Update version to <I>.
jupyterhub_jupyter-server-proxy
train
py
fb72bc8058a7d6d16c1757877742693da981b688
diff --git a/spec/dummy/config/boot.rb b/spec/dummy/config/boot.rb index <HASH>..<HASH> 100644 --- a/spec/dummy/config/boot.rb +++ b/spec/dummy/config/boot.rb @@ -2,4 +2,3 @@ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) -$LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
Removes manipulation from dummy app's boot script
csm123_starburst
train
rb
d32bc2e4f18ce94823b8b9b4cc4297b9ac4072e4
diff --git a/packages/build-tools/utils/bolt-versions.js b/packages/build-tools/utils/bolt-versions.js index <HASH>..<HASH> 100644 --- a/packages/build-tools/utils/bolt-versions.js +++ b/packages/build-tools/utils/bolt-versions.js @@ -30,9 +30,26 @@ async function writeVersionDataToJson(versionData) { } async function gatherBoltVersions() { + const config = await getConfig(); + const versionSpinner = ora( chalk.blue('Gathering data on the latest Bolt Design System releases...'), ).start(); + + // Skip over checking for Bolt releases when not in prod mode to speed up the initial build + if (!config.prod) { + versionSpinner.succeed( + chalk.green('Skipped gathering data on every Bolt release -- dev build!'), + ); + return [ + { + label: 'Local Dev', + type: 'option', + value: `http://localhost:${config.port}/${config.startPath}`, + }, + ]; + } + const tags = await gitSemverTags(); const tagUrls = [];
feat: update build process to automatically skip over the check for all available Bolt versions — speeds up initial boot up process when doing local dev work
bolt-design-system_bolt
train
js
f855636f8a0f43609f483d26e668824bc1d92407
diff --git a/feather/application.py b/feather/application.py index <HASH>..<HASH> 100644 --- a/feather/application.py +++ b/feather/application.py @@ -9,7 +9,7 @@ class Application(object): plugins. Applications expect, at the least, a Plugin that listens for 'APP_START', - and one that generates 'APP_END' + and one that generates 'APP_STOP' """ def __init__(self, messages): @@ -22,7 +22,7 @@ class Application(object): self.needed_listeners.add('APP_START') self.needed_messengers = set(messages) - self.needed_messengers.add('APP_END') + self.needed_messengers.add('APP_STOP') self.valid = False
change 'APP_END' to 'APP_STOP'
jdodds_feather
train
py
3bb149941f206153003726f1c18264dc62197f51
diff --git a/lib/ember-cli/app.rb b/lib/ember-cli/app.rb index <HASH>..<HASH> 100644 --- a/lib/ember-cli/app.rb +++ b/lib/ember-cli/app.rb @@ -15,7 +15,9 @@ module EmberCLI def compile prepare silence_stream STDOUT do - system(env_hash, command, chdir: app_path, err: :out) + Dir.chdir app_path do + system(env_hash, command, err: :out) + end end end
fix chdir support for jruby
thoughtbot_ember-cli-rails
train
rb
e372dcaea2f4232649b7d286a44426c8ac7a5525
diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -23,6 +23,12 @@ module Test::Integration URL = "http://localhost:9200" def setup + begin + ::RestClient.get URL + rescue Errno::ECONNREFUSED + abort "\n\n#{'-'*87}\n[ABORTED] You have to run ElasticSearch on #{URL} for integration tests\n#{'-'*87}\n\n" + end + ::RestClient.delete "#{URL}/articles-test" rescue nil ::RestClient.post "#{URL}/articles-test", '' fixtures_path.join('articles').entries.each do |f|
Aborting integration tests when ElasticSearch is not running
karmi_retire
train
rb
ad912a737a51070cc621715458740578d466c5b7
diff --git a/peewee_migrate/router.py b/peewee_migrate/router.py index <HASH>..<HASH> 100644 --- a/peewee_migrate/router.py +++ b/peewee_migrate/router.py @@ -112,7 +112,8 @@ class BaseRouter(object): if fake: with mock.patch('peewee.Model.select'): with mock.patch('peewee.InsertQuery.execute'): - migrate(migrator, self.database) + with mock.patch('peewee.UpdateQuery.execute'): + migrate(migrator, self.database) if force: self.model.create(name=name)
Update router.py Allow updates in migrations
klen_peewee_migrate
train
py
fac5beda463a64a02df907ade1c579e163bec881
diff --git a/tx.go b/tx.go index <HASH>..<HASH> 100644 --- a/tx.go +++ b/tx.go @@ -111,6 +111,12 @@ func (t *tx) EndSegment() error { return nil } +// ReportError reports an error that occured during the transaction. +func (t *tx) ReportError(exceptionType, errorMessage, stackTrace, stackFrameDelim string) error { + _, err := t.Tracer.ReportError(t.id, exceptionType, errorMessage, stackTrace, stackFrameDelim) + return err +} + // WithTx inserts a newrelic.Tx into the provided context. func WithTx(ctx context.Context, t Tx) context.Context { return context.WithValue(ctx, txKey, t)
Add ReportError to Tx
remind101_newrelic
train
go
c4ce04fed604b51090593482620182906edfb6f7
diff --git a/src/Sql.php b/src/Sql.php index <HASH>..<HASH> 100644 --- a/src/Sql.php +++ b/src/Sql.php @@ -815,6 +815,9 @@ class Sql foreach ($params as $val) { $pos = strpos($tmpQuery, "?"); + if ($pos === false) { + continue; + } $newQuery .= substr($tmpQuery, 0, $pos); $tmpQuery = substr($tmpQuery, $pos + 1);
Prevent an error when parameters are passed but aren't used
duncan3dc_sql-class
train
php
a56b2c2e003f63266578b04778194948d9b9f896
diff --git a/Stagehand/TestRunner/PHPUnit2TestRunner.php b/Stagehand/TestRunner/PHPUnit2TestRunner.php index <HASH>..<HASH> 100644 --- a/Stagehand/TestRunner/PHPUnit2TestRunner.php +++ b/Stagehand/TestRunner/PHPUnit2TestRunner.php @@ -135,7 +135,7 @@ class Stagehand_TestRunner_PHPUnit2TestRunner public static function getDirectories($directory) { $directory = realpath($directory); - self::$_directories[] = $directory; + array_push(self::$_directories, $directory); $files = scandir($directory); for ($i = 0; $i < count($files); ++$i) {
- Changed a code to the previous code.
piece_stagehand-testrunner
train
php
43d9af175b3e82afd480515cc0f638a041fabdba
diff --git a/publishes/config.php b/publishes/config.php index <HASH>..<HASH> 100755 --- a/publishes/config.php +++ b/publishes/config.php @@ -74,4 +74,9 @@ return [ */ 'segment' => 2, ], + + 'export' => [ + 'default' => ['xml', 'csv', 'json'], + // 'users' => ['csv', 'pdf'], + ], ]; diff --git a/src/Traits/Module/AllowFormats.php b/src/Traits/Module/AllowFormats.php index <HASH>..<HASH> 100755 --- a/src/Traits/Module/AllowFormats.php +++ b/src/Traits/Module/AllowFormats.php @@ -20,7 +20,7 @@ trait AllowFormats { return property_exists($this, 'exportableTo') ? $this->exportableTo - : ['xml', 'csv', 'json']; + : config('administrator.export.' . $this->url(), config('administrator.export.default')); } /**
Make exportable formats configuable
adminarchitect_core
train
php,php
081b074c106e54abb3bc971afb0e170a094732ec
diff --git a/app.js b/app.js index <HASH>..<HASH> 100755 --- a/app.js +++ b/app.js @@ -46,7 +46,8 @@ else if (opts.directory && opts.outdir) { } files.forEach(function(fpath) { // snip the absolute part to get the directory structure for outdir - var relativeDir = fpath.replace(absDirectory, ""); + // Also make sure we're speaking the same slashes + var relativeDir = fpath.replace(absDirectory.replace(/\\/g, "/"), ""); var outFilePath = path.join(absOutDirectory, relativeDir); // make directories after stripping filename mkdirp.sync(path.dirname(outFilePath)); @@ -66,6 +67,7 @@ else if (opts.directory && opts.outdir) { rs.pipe(ws); return; } + console.log(fpath); var output = jsdocFlow(fs.readFileSync(fpath, "utf8")); fs.writeFileSync(outFilePath, output); }); diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -250,7 +250,7 @@ function getCommentedClassNode(node) { } } - if (!constructNode) { + if (!constructNode || !constructNode.leadingComments) { return null; }
Fix slashes with -d on Windows. Log each file path when using -d for debugging invalid ES6 line numbers
Kegsay_flow-jsdoc
train
js,js
a52c4bce6689b5b5255fbd1ea905cd525169e3c0
diff --git a/builtin/providers/azure/resource_azure_sql_database_server_firewall_rule.go b/builtin/providers/azure/resource_azure_sql_database_server_firewall_rule.go index <HASH>..<HASH> 100644 --- a/builtin/providers/azure/resource_azure_sql_database_server_firewall_rule.go +++ b/builtin/providers/azure/resource_azure_sql_database_server_firewall_rule.go @@ -209,6 +209,9 @@ func resourceAzureSqlDatabaseServerFirewallRuleDelete(d *schema.ResourceData, me // go ahead and delete the rule: log.Printf("[INFO] Issuing deletion of Azure Database Server Firewall Rule %q in Server %q.", name, serverName) if err := sqlClient.DeleteFirewallRule(serverName, name); err != nil { + if strings.Contains(err.Error(), "Cannot open server") { + break + } return fmt.Errorf("Error deleting Azure Database Server Firewall Rule %q for Server %q: %s", name, serverName, err) }
provider/azure: Don't delete firewall rules on non-existent servers
hashicorp_terraform
train
go
025dd072c6bcb6aa3b81cb3c8c130b84c3d1919c
diff --git a/framework/db/ActiveQuery.php b/framework/db/ActiveQuery.php index <HASH>..<HASH> 100644 --- a/framework/db/ActiveQuery.php +++ b/framework/db/ActiveQuery.php @@ -772,11 +772,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface */ public function viaTable($tableName, $link, callable $callable = null) { - if ($this->primaryModel === null) { - throw new InvalidConfigException('The "primaryModel" property is not set. The query must be a relation to use junction tables. You probably need to call hasOne() or hasMany() method first.'); - } - - $modelClass = get_class($this->primaryModel); + $modelClass = $this->primaryModel ? get_class($this->primaryModel) : $this->modelClass; $relation = new self($modelClass, [ 'from' => [$tableName], 'link' => $link,
Replaces commit dfcf<I>c7. The prvious idea was wrong and broke some tests
yiisoft_yii2
train
php
2da7cb6b9ce1748a0522252d7268873591fbc453
diff --git a/src/Wrapper.php b/src/Wrapper.php index <HASH>..<HASH> 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -108,6 +108,13 @@ class Wrapper } } + // Workaround for shared boards + foreach ($this->cache['boards'] as $item) { + if ($name == $item['name']) { + return $item['id']; + } + } + break; case 'list': if (!isset($options['organization'])) {
Add workaround to search shared boards when getting a board id
gregoriohc_laravel-trello
train
php
7aae8c9489f5b7d4308c63799ed3e9caca6f920f
diff --git a/spec/support/rails_template_with_data.rb b/spec/support/rails_template_with_data.rb index <HASH>..<HASH> 100644 --- a/spec/support/rails_template_with_data.rb +++ b/spec/support/rails_template_with_data.rb @@ -189,6 +189,15 @@ inject_into_file 'app/admin/post.rb', <<-RUBY, after: "ActiveAdmin.register Post end end + member_action :toggle_starred, method: :put do + resource.update(starred: !resource.starred) + redirect_to resource_path, notice: "Post updated." + end + + action_item :toggle_starred, only: :show do + link_to 'Toggle Starred', toggle_starred_admin_post_path(post), method: :put + end + show do |post| attributes_table do row :id
Add custom action item and member action Simple action here to toggle the starred attribute on post.
activeadmin_activeadmin
train
rb
54548645fb51ff9b1695eedc46d515f6f9e43997
diff --git a/common/src/main/java/tachyon/HeartbeatThread.java b/common/src/main/java/tachyon/HeartbeatThread.java index <HASH>..<HASH> 100644 --- a/common/src/main/java/tachyon/HeartbeatThread.java +++ b/common/src/main/java/tachyon/HeartbeatThread.java @@ -30,8 +30,10 @@ public final class HeartbeatThread implements Runnable { private final long mFixedExecutionIntervalMs; /** - * @param threadName - * @param hbExecutor + * @param threadName Identifies the heartbeat thread name. + * @param hbExecutor Identifies the heartbeat thread executor; an + * instance of a class that implements the HeartbeatExecutor + * interface. * @param fixedExecutionIntervalMs Sleep time between different heartbeat. */ public HeartbeatThread(String threadName, HeartbeatExecutor hbExecutor,
Describing the constructors for the HeartbeatThread class.
Alluxio_alluxio
train
java
76991704beea3cf995541c42a19eed2a30bd853b
diff --git a/shared/idmapset_test_linux.go b/shared/idmapset_test_linux.go index <HASH>..<HASH> 100644 --- a/shared/idmapset_test_linux.go +++ b/shared/idmapset_test_linux.go @@ -81,3 +81,12 @@ func TestIdmapSetAddSafe_upper(t *testing.T) { return } } + +func TestIdmapSetIntersects(t *testing.T) { + orig := IdmapSet{Idmap: []IdmapEntry{IdmapEntry{Isuid: true, Hostid: 165536, Nsid: 0, Maprange: 65536}}} + + if orig.Intersects(IdmapEntry{Isuid: true, Hostid: 231072, Nsid: 0, Maprange: 65536}) { + t.Error("ranges don't intersect") + return + } +}
add a test for IdmapSet Intersection
lxc_lxd
train
go
44c6e0ff454b9c39851019cfe1ccdd4dfe72bde7
diff --git a/openxc/src/com/openxc/messages/NamedVehicleMessage.java b/openxc/src/com/openxc/messages/NamedVehicleMessage.java index <HASH>..<HASH> 100644 --- a/openxc/src/com/openxc/messages/NamedVehicleMessage.java +++ b/openxc/src/com/openxc/messages/NamedVehicleMessage.java @@ -35,6 +35,13 @@ public class NamedVehicleMessage extends KeyedMessage { } @Override + public int compareTo(VehicleMessage other) { + NamedVehicleMessage otherMessage = (NamedVehicleMessage) other; + int nameComp = getName().compareTo(otherMessage.getName()); + return nameComp == 0 ? super.compareTo(other) : nameComp; + } + + @Override public boolean equals(Object obj) { if(!super.equals(obj) || getClass() != obj.getClass()) { return false;
Add comparator for Named messages, but sort isn't working in dashboard.
openxc_openxc-android
train
java
d2560c503439234fc135841d5522f4b9d48a80d9
diff --git a/src/main/java/uk/co/real_logic/agrona/collections/Int2IntHashMap.java b/src/main/java/uk/co/real_logic/agrona/collections/Int2IntHashMap.java index <HASH>..<HASH> 100644 --- a/src/main/java/uk/co/real_logic/agrona/collections/Int2IntHashMap.java +++ b/src/main/java/uk/co/real_logic/agrona/collections/Int2IntHashMap.java @@ -384,8 +384,12 @@ public class Int2IntHashMap implements Map<Integer, Integer> { int min = size == 0 ? missingValue : Integer.MAX_VALUE; - for (final int value : values) + final int[] entries = this.entries; + @DoNotSub final int length = entries.length; + + for (@DoNotSub int i = 1; i < length; i += 2) { + final int value = entries[i]; if (value != missingValue) { min = Math.min(min, value); @@ -404,8 +408,12 @@ public class Int2IntHashMap implements Map<Integer, Integer> { int max = size == 0 ? missingValue : Integer.MIN_VALUE; - for (final int value : values) + final int[] entries = this.entries; + @DoNotSub final int length = entries.length; + + for (@DoNotSub int i = 1; i < length; i += 2) { + final int value = entries[i]; if (value != missingValue) { max = Math.max(max, value);
[Java]: Faster iteration for max and min functions on map.
real-logic_agrona
train
java
cbe2ea7b232fd9e9fbf19a71b0d795115142f004
diff --git a/example.php b/example.php index <HASH>..<HASH> 100644 --- a/example.php +++ b/example.php @@ -211,10 +211,7 @@ if (!isset($_GET['oauth_verifier'])) { // Step 1: Get a Request Token // // Get a temporary request token to facilitate the user authorization - // in step 2. We make a request to the OAuthGetRequestToken endpoint, - // submitting the scope of the access we need (in this case, all the - // user's calendars) and also tell Google where to go once the token - // authorization on their side is finished. + // in step 2. We make a request to the RequestToken endpoint // $result = $oauthObject->sign(array( 'path' => $xro_settings['site'].$xro_consumer_options['request_token_path'],
edited comments talked about google calendars, not relevant to this example
XeroAPI_XeroOAuth-PHP
train
php
b04f8ea7abc477f3f9862538fb81d5183dfa9389
diff --git a/lib/pansophy/tasks.rb b/lib/pansophy/tasks.rb index <HASH>..<HASH> 100644 --- a/lib/pansophy/tasks.rb +++ b/lib/pansophy/tasks.rb @@ -4,6 +4,6 @@ namespace :config do require 'pansophy/config_synchronizer' require 'dotenv' Dotenv.load - Pansophy::ConfigSynchronizer.new.pull + Pansophy::ConfigSynchronizer.new.merge end end
Fixes broken method call in task
sealink_pansophy
train
rb
e934c3e2a27024514b6d5f97b5c45c5edc652fe9
diff --git a/cmd/xl-v1.go b/cmd/xl-v1.go index <HASH>..<HASH> 100644 --- a/cmd/xl-v1.go +++ b/cmd/xl-v1.go @@ -227,8 +227,10 @@ func (xl xlObjects) CrawlAndGetDataUsage(ctx context.Context, endCh <-chan struc } wg.Wait() - var dataUsageInfo DataUsageInfo - for i := 0; i < len(dataUsageResults); i++ { + var dataUsageInfo = dataUsageResults[0] + // Pick the crawling result of the disk which has the most + // number of objects in it. + for i := 1; i < len(dataUsageResults); i++ { if dataUsageResults[i].ObjectsCount > dataUsageInfo.ObjectsCount { dataUsageInfo = dataUsageResults[i] }
usage: Fix buckets count calculation when no object is present (#<I>) XL crawling wrongly returns a zero buckets count when there are no objects uploaded in the server yet. The reason is data of the crawler of posix returns invalid result when all disks has zero objects. A simple fix is to always pick the crawling result of the first disk but choose over the result of the disk which has the most objects in it.
minio_minio
train
go
1d2f9f9d92dd26353bd11d4fc8f8a3c772064e53
diff --git a/src/builders/CreateTableSelectOptionBuilder.php b/src/builders/CreateTableSelectOptionBuilder.php index <HASH>..<HASH> 100644 --- a/src/builders/CreateTableSelectOptionBuilder.php +++ b/src/builders/CreateTableSelectOptionBuilder.php @@ -54,7 +54,10 @@ class CreateTableSelectOptionBuilder { return ""; } $option = $parsed['select-option']; - // TODO + + $sql = ($option['duplicates'] === false ? '' : (' ' . $option['duplicates'])); + $sql .= ($option['as'] === false ? '' : ' AS'); + return $sql; } } ?>
ADD: the builder for the select-option of the CREATE TABLE statement has been implemented. git-svn-id: <URL>
greenlion_PHP-SQL-Parser
train
php
2c19025dc51578f074b889ad4b78ac9e0625e715
diff --git a/ccmlib/node.py b/ccmlib/node.py index <HASH>..<HASH> 100644 --- a/ccmlib/node.py +++ b/ccmlib/node.py @@ -535,7 +535,10 @@ class Node(): cli = common.join_bin(cdir, 'bin', 'cqlsh') env = common.make_cassandra_env(cdir, self.get_path()) host = self.network_interfaces['thrift'][0] - port = self.network_interfaces['thrift'][1] + if self.cluster.version() >= "2.1": + port = self.network_interfaces['binary'][1] + else: + port = self.network_interfaces['thrift'][1] args = cqlsh_options + [ host, str(port) ] sys.stdout.flush() if cmds is None:
Makes cqlsh use native protocol port on <I>+
riptano_ccm
train
py
e357248edaea57586f77d92ce0bcd54c62546839
diff --git a/pykrige/lib/__init__.py b/pykrige/lib/__init__.py index <HASH>..<HASH> 100644 --- a/pykrige/lib/__init__.py +++ b/pykrige/lib/__init__.py @@ -1,3 +1 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - +__all__ = ['cok', 'lapack', 'variogram_models']
fix Cython extension importing error.
bsmurphy_PyKrige
train
py
a917fe84578b30b7e60d5aaa06456bdd2cac9adc
diff --git a/spec/unit/knife/data_bag_create_spec.rb b/spec/unit/knife/data_bag_create_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/knife/data_bag_create_spec.rb +++ b/spec/unit/knife/data_bag_create_spec.rb @@ -79,7 +79,28 @@ describe Chef::Knife::DataBagCreate do expect { knife.run }.to exit_with_code(1) end end - + + context "when part of the name is a reserved name" do + before do + exception = double("404 error", :code => "404") + %w{node role client environment}.each do |name| + allow(rest).to receive(:get) + .with("data/sudoing_#{name}_admins") + .and_raise(Net::HTTPServerException.new("404", exception)) + end + end + + it "will create a data bag containing a reserved word" do + %w{node role client environment}.each do |name| + knife.name_args = ["sudoing_#{name}_admins"] + expect(rest).to receive(:post).with("data", { "name" => knife.name_args[0] }) + expect(knife.ui).to receive(:info).with("Created data_bag[#{knife.name_args[0]}]") + + knife.run + end + end + end + context "when given one argument" do before do knife.name_args = [bag_name]
added test for data bag name containing reserved word
chef_chef
train
rb
b910b496324fc2b78af0ba816544083237653eb0
diff --git a/mir_eval/structure.py b/mir_eval/structure.py index <HASH>..<HASH> 100644 --- a/mir_eval/structure.py +++ b/mir_eval/structure.py @@ -298,10 +298,12 @@ def nce(reference_intervals, reference_labels, estimated_intervals, estimated_la - S_over Over-clustering score: ``1 - H(y_est | y_ref) / log(|y_est|)`` + If `|y_est|==1`, then `S_over` will be 0. - S_under Under-clustering score: ``1 - H(y_ref | y_est) / log(|y_ref|)`` + If `|y_ref|==1`, then `S_under` will be 0. - S_F F-measure for (S_over, S_under) @@ -339,11 +341,11 @@ def nce(reference_intervals, reference_labels, estimated_intervals, estimated_la true_given_est = p_est.dot(scipy.stats.entropy(contingency, base=2)) pred_given_ref = p_ref.dot(scipy.stats.entropy(contingency.T, base=2)) - score_under = np.nan + score_under = 0.0 if contingency.shape[0] > 1: score_under = 1. - true_given_est / np.log2(contingency.shape[0]) - score_over = np.nan + score_over = 0.0 if contingency.shape[1] > 1: score_over = 1. - pred_given_ref / np.log2(contingency.shape[1])
reverted np.nan to zero for nce metrics
craffel_mir_eval
train
py
d550dc6212f219d8eb2ac373d53a332e36866b6e
diff --git a/docs/src/Flyout.doc.js b/docs/src/Flyout.doc.js index <HASH>..<HASH> 100644 --- a/docs/src/Flyout.doc.js +++ b/docs/src/Flyout.doc.js @@ -111,7 +111,7 @@ function FlyoutExample() { size="md" > <Box padding={3} display="flex" alignItems="center" direction="column" column={12}> - <Text align="center" weight="bold"> + <Text align="center"> Need help with something? Check out our Help Center. </Text> <Box paddingX={2} marginTop={3}> @@ -156,7 +156,7 @@ function FlyoutExample() { size="md" > <Box padding={3} column={12}> - <Text align="center" weight="bold"> + <Text align="center"> Flyout with a caret, not a 🥕 </Text> </Box> @@ -196,7 +196,7 @@ function ErrorFlyoutExample() { size="md" > <Box padding={3}> - <Text color="white" weight="bold"> + <Text color="white"> Oops! This item is out of stock. </Text> </Box>
Update Flyout Docs - Remove bold text (#<I>) Design realized there was a mistake in the docs with the text being bold by default in flyouts. It should be regular weight.
pinterest_gestalt
train
js
b23c9ba8413ba0368e190e46e952d9718384c7de
diff --git a/lib/slideshow/helpers/syntax/sh_helper.rb b/lib/slideshow/helpers/syntax/sh_helper.rb index <HASH>..<HASH> 100644 --- a/lib/slideshow/helpers/syntax/sh_helper.rb +++ b/lib/slideshow/helpers/syntax/sh_helper.rb @@ -8,7 +8,7 @@ module Slideshow def sh_worker( code, opts ) - lang = opts.fetch( :lang, SH_LANG ) + lang = opts.fetch( :lang, headers.get( 'code-language', SH_LANG )) line_numbers_value = opts.fetch( :line_numbers, headers.get( 'code-line-numbers', SH_LINE_NUMBERS )) line_numbers = (line_numbers_value =~ /true|yes|on/i) ? true : false
code language could also be from the headers just like code-line-numbers
slideshow-s9_slideshow
train
rb
668b9d8c170e67e8a5697ca6262e53808f4e551e
diff --git a/lib/countries/translations.rb b/lib/countries/translations.rb index <HASH>..<HASH> 100644 --- a/lib/countries/translations.rb +++ b/lib/countries/translations.rb @@ -6,7 +6,7 @@ module ISO3166 # to `pt` to prevent from showing nil values class Translations < Hash def [](locale) - super(locale) || super(locale.sub(/-.*/, '')) + super(locale) || super(locale.to_s.sub(/-.*/, '')) end end end
Fix error when getting ISO<I>::Country.translations with a symbol instead of a string when there are custom countries
hexorx_countries
train
rb
6d212fea03fe722c0faf93e7fbc1852ac4839759
diff --git a/lib/steam-api/steam/player.rb b/lib/steam-api/steam/player.rb index <HASH>..<HASH> 100644 --- a/lib/steam-api/steam/player.rb +++ b/lib/steam-api/steam/player.rb @@ -7,7 +7,7 @@ module Steam # Get Owned Games # @param [Hash] params Parameters to pass to the API # @option params [Fixnum] :steamid The 64 bit ID of the player. (Optional) - # @option params [Boolean] :include_appinfo (false) Whether or not to include additional + # @option params [Integer] :include_appinfo (0) Whether or not to include additional # details of apps - name and images. # @option params [Boolean] :include_played_free_games (false) Whether or not to list # free-to-play games in the results.
Update `:include_appinfo` param doc It doesn't take `true` or `false`, but instead `1` or `0`. (wtf?)
bhaberer_steam-api
train
rb
615f96dd27b2651e5d8280032d1ffa03e43968e5
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -249,7 +249,7 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_group_by_summed_field_having_condition_from_select - skip if current_adapter?(:PostgreSQLAdapter) + skip if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) c = Account.select("MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("min_credit_limit > 50").sum(:credit_limit) assert_nil c[1] assert_equal 60, c[2]
Oracle database also does not allow aliases in the having clause Follow up #<I>
rails_rails
train
rb
c4ceb833778669d892a1cd7121da45391f975933
diff --git a/cli/e2e.js b/cli/e2e.js index <HASH>..<HASH> 100644 --- a/cli/e2e.js +++ b/cli/e2e.js @@ -136,11 +136,13 @@ function e2e(argv) { const webpackConfig = require('../config/webpack/serve.webpack.config'); const skyPagesConfig = require('../config/sky-pages/sky-pages.config'); const config = webpackMerge( - webpackConfig.getWebpackConfig(skyPagesConfig.getSkyPagesConfig()), - { - argv: { + webpackConfig.getWebpackConfig( + { noOpen: true }, + skyPagesConfig.getSkyPagesConfig() + ), + { devServer: { colors: false }, diff --git a/test/cli-e2e.spec.js b/test/cli-e2e.spec.js index <HASH>..<HASH> 100644 --- a/test/cli-e2e.spec.js +++ b/test/cli-e2e.spec.js @@ -6,7 +6,7 @@ const mock = require('mock-require'); const logger = require('winston'); const selenium = require('selenium-standalone'); -describe('cli test', () => { +describe('cli e2e', () => { let returnSeleniumServer; let webpackDevServerCalled;
Refactored e2e code for Webpack 2 changes
blackbaud_skyux-builder
train
js,js
e23eb2004939e1b6a9afe11af7512646c5b2c1cd
diff --git a/ninio-http/src/main/java/com/davfx/ninio/http/HttpResponseReader.java b/ninio-http/src/main/java/com/davfx/ninio/http/HttpResponseReader.java index <HASH>..<HASH> 100644 --- a/ninio-http/src/main/java/com/davfx/ninio/http/HttpResponseReader.java +++ b/ninio-http/src/main/java/com/davfx/ninio/http/HttpResponseReader.java @@ -155,10 +155,14 @@ final class HttpResponseReader { break; } + keepAlive = http11; + /*%% if (http11) { keepAlive = true; // (contentLength >= 0); // Websocket ready! } + */ for (String connectionValue : headers.get(HttpHeaderKey.CONNECTION)) { + keepAlive = false; if (connectionValue.equalsIgnoreCase(HttpHeaderValue.CLOSE)) { keepAlive = false; } else if (connectionValue.equalsIgnoreCase(HttpHeaderValue.KEEP_ALIVE)) {
Better impl with keep-alive
davidfauthoux_ninio
train
java
5aa4af75c2c4c66541f1fd24ef82c5d46a79940d
diff --git a/core/src/main/java/hudson/init/InitStrategy.java b/core/src/main/java/hudson/init/InitStrategy.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/init/InitStrategy.java +++ b/core/src/main/java/hudson/init/InitStrategy.java @@ -51,10 +51,10 @@ public class InitStrategy { getBundledPluginsFromProperty(r); // similarly, we prefer *.jpi over *.hpi - listPluginFiles(pm, ".hpl", r); // linked plugin. for debugging. (for backward compatibility) listPluginFiles(pm, ".jpl", r); // linked plugin. for debugging. - listPluginFiles(pm, ".hpi", r); // plugin jar file (for backward compatibility) + listPluginFiles(pm, ".hpl", r); // linked plugin. for debugging. (for backward compatibility) listPluginFiles(pm, ".jpi", r); // plugin jar file + listPluginFiles(pm, ".hpi", r); // plugin jar file (for backward compatibility) return r; }
we want to prefer *.jpi over *.hpi, but the code was other way around
jenkinsci_jenkins
train
java
5fb3004a271076b53f3b9ec577c60e4452761518
diff --git a/salt/utils/decorators/__init__.py b/salt/utils/decorators/__init__.py index <HASH>..<HASH> 100644 --- a/salt/utils/decorators/__init__.py +++ b/salt/utils/decorators/__init__.py @@ -43,7 +43,7 @@ class Depends(object): return 'foo' ''' - log.debug( + log.trace( 'Depends decorator instantiated with dep list of {0}'.format( dependencies ) @@ -77,7 +77,7 @@ class Depends(object): for module, func, fallback_function in dependent_set: # check if you have the dependency if dependency in dir(module): - log.debug( + log.trace( 'Dependency ({0}) already loaded inside {1}, ' 'skipping'.format( dependency, @@ -85,7 +85,7 @@ class Depends(object): ) ) continue - log.debug( + log.trace( 'Unloading {0}.{1} because dependency ({2}) is not ' 'imported'.format( module, @@ -108,7 +108,7 @@ class Depends(object): del functions[mod_key] except AttributeError: # we already did??? - log.debug('{0} already removed, skipping'.format(mod_key)) + log.trace('{0} already removed, skipping'.format(mod_key)) continue
Debug log level makes the test logs unusable. These need to be at trace
saltstack_salt
train
py
544c7b6f7f9a17c4aff4b2b289e221e3ed0a1e9d
diff --git a/pybar/scans/analyze_example_conversion.py b/pybar/scans/analyze_example_conversion.py index <HASH>..<HASH> 100644 --- a/pybar/scans/analyze_example_conversion.py +++ b/pybar/scans/analyze_example_conversion.py @@ -39,6 +39,7 @@ def analyze_raw_data(input_file, output_file_hits): analyze_raw_data.use_trigger_number = False analyze_raw_data.set_stop_mode = False # special analysis if data was taken in stop mode analyze_raw_data.interpreter.use_tdc_word(False) # use the TDC word to align the events, assume that they are first words in the event + analyze_raw_data.interpreter.use_trigger_time_stamp(False) # use the trigger number as a time stamp analyze_raw_data.interpreter.set_debug_output(False) # std. setting is False analyze_raw_data.interpreter.set_info_output(False) # std. setting is False
ENH: new trigger time stamp example
SiLab-Bonn_pyBAR
train
py
7087b05a309841b237ecac211dc8f9bae2498d24
diff --git a/gorp.go b/gorp.go index <HASH>..<HASH> 100644 --- a/gorp.go +++ b/gorp.go @@ -978,7 +978,7 @@ func (m *DbMap) Select(i interface{}, query string, args ...interface{}) ([]inte } // Exec runs an arbitrary SQL statement. args represent the bind parameters. -// This is equivalent to running: Prepare(), Exec() using database/sql +// This is equivalent to running: Exec() using database/sql func (m *DbMap) Exec(query string, args ...interface{}) (sql.Result, error) { m.trace(query, args) //stmt, err := m.Db.Prepare(query) @@ -1122,12 +1122,7 @@ func (t *Transaction) Select(i interface{}, query string, args ...interface{}) ( // Exec has the same behavior as DbMap.Exec(), but runs in a transaction. func (t *Transaction) Exec(query string, args ...interface{}) (sql.Result, error) { t.dbmap.trace(query, args) - stmt, err := t.tx.Prepare(query) - if err != nil { - return nil, err - } - defer stmt.Close() - return stmt.Exec(args...) + return t.tx.Exec(query, args...) } // SelectInt is a convenience wrapper around the gorp.SelectInt function.
Don't create single-used prepared statements for Exec inside a txn
go-gorp_gorp
train
go
7b3638ea773dafe1c1eb2723d21a8a5c553bd747
diff --git a/plugin/pkg/scheduler/schedulercache/node_info.go b/plugin/pkg/scheduler/schedulercache/node_info.go index <HASH>..<HASH> 100644 --- a/plugin/pkg/scheduler/schedulercache/node_info.go +++ b/plugin/pkg/scheduler/schedulercache/node_info.go @@ -510,12 +510,11 @@ func getPodKey(pod *v1.Pod) (string, error) { // matches NodeInfo.node and the pod is not found in the pods list. Otherwise, // returns true. func (n *NodeInfo) Filter(pod *v1.Pod) bool { - pFullName := util.GetPodFullName(pod) if pod.Spec.NodeName != n.node.Name { return true } for _, p := range n.pods { - if util.GetPodFullName(p) == pFullName { + if p.Name == pod.Name && p.Namespace == pod.Namespace { return true } }
Avoid string concatenation when comparing pods. Pod comparison in (*NodeInfo).Filter was using GetPodFullName before comparing pod names. This is a concatenation of pod name and pod namespace, and it is significantly faster to compare name & namespace instead.
kubernetes_kubernetes
train
go
302b9532c7cc185df3cf14e47482e3fbb43fc2d7
diff --git a/abydos/distance/_raup_crick.py b/abydos/distance/_raup_crick.py index <HASH>..<HASH> 100644 --- a/abydos/distance/_raup_crick.py +++ b/abydos/distance/_raup_crick.py @@ -50,7 +50,6 @@ class RaupCrick(_TokenDistance): Notes ----- - Observe that Raup-Crick similarity is related to Henderson-Heron similarity in that the former is the sum of all Henderson-Heron similarities for an intersection size ranging from 0 to the true intersection size.
satisfied pydocstyle warnings
chrislit_abydos
train
py
f9055c77dbde0bff61f1a5dfdc67a1569af52161
diff --git a/ui/admin/src/main/java/org/openengsb/ui/admin/ruleEditorPanel/RuleEditorPanel.java b/ui/admin/src/main/java/org/openengsb/ui/admin/ruleEditorPanel/RuleEditorPanel.java index <HASH>..<HASH> 100644 --- a/ui/admin/src/main/java/org/openengsb/ui/admin/ruleEditorPanel/RuleEditorPanel.java +++ b/ui/admin/src/main/java/org/openengsb/ui/admin/ruleEditorPanel/RuleEditorPanel.java @@ -71,6 +71,7 @@ public class RuleEditorPanel extends Panel { add(form); feedbackPanel = new FeedbackPanel("feedback"); feedbackPanel.setOutputMarkupId(true); + error(""); add(feedbackPanel); } @@ -212,6 +213,7 @@ public class RuleEditorPanel extends Panel { try { ruleManagerProvider.getRuleManager().update(selection, text); } catch (RuleBaseException e) { + target.addComponent(feedbackPanel); error(e.getLocalizedMessage()); } }
[OPENENGSB-<I>] now there is an error message if an error occeurs while saving a rule
openengsb_openengsb
train
java
d6a6a737029b457691733dcac46b4b896cf61196
diff --git a/lib/action_kit_api/event.rb b/lib/action_kit_api/event.rb index <HASH>..<HASH> 100644 --- a/lib/action_kit_api/event.rb +++ b/lib/action_kit_api/event.rb @@ -5,7 +5,7 @@ module ActionKitApi include Searchable # Required - attr_accessor :id, :campaign, :creator, :title + attr_accessor :id, :campaign_id, :creator_id, :title # Other/Active attr_accessor :address1, :address2, :attendee_count, :city, :country, @@ -16,7 +16,7 @@ module ActionKitApi :starts_at, :state, :status, :status_summary, :venue, :zip def initialize(*args) - @required_attrs = [:campaign, :creator, :title] + @required_attrs = [:campaign_id, :creator_id, :title] @read_only_attrs = [:attendee_count] super
Switched attribute names to reflect the real ones :-/
Democracy-for-America_ActionKitApi
train
rb
daea335221739aa3a5d6ea64a29bd6be87ba948e
diff --git a/src/Ixudra/Core/Services/Factories/BaseFactory.php b/src/Ixudra/Core/Services/Factories/BaseFactory.php index <HASH>..<HASH> 100644 --- a/src/Ixudra/Core/Services/Factories/BaseFactory.php +++ b/src/Ixudra/Core/Services/Factories/BaseFactory.php @@ -11,6 +11,10 @@ abstract class BaseFactory { $results = array(); foreach( $keys as $key => $value ) { + if( array_key_exists( $prefix . $key, $input) ) { + $results[ $key ] = $input[ $prefix . $key ]; + } + $results[ $key ] = $input[ $prefix . $key ]; }
Added check to BaseFactory
ixudra_core
train
php
28654d3af1ebfcac2d29ced5f2d6f5543c282052
diff --git a/lib/iniparse/generator.rb b/lib/iniparse/generator.rb index <HASH>..<HASH> 100644 --- a/lib/iniparse/generator.rb +++ b/lib/iniparse/generator.rb @@ -71,8 +71,6 @@ module IniParse # max_trains = 500 ; More = slower # class Generator - Context = Struct.new(:context, :opts) - attr_reader :context attr_reader :document
Didn't mean for that to be left there. :)
antw_iniparse
train
rb
5f0e5bb3f08240779f7b3b20ed94b46caded745c
diff --git a/core-bundle/contao/pages/PageRegular.php b/core-bundle/contao/pages/PageRegular.php index <HASH>..<HASH> 100644 --- a/core-bundle/contao/pages/PageRegular.php +++ b/core-bundle/contao/pages/PageRegular.php @@ -274,6 +274,9 @@ class PageRegular extends \Frontend // Add the layout specific CSS if ($strFramework != '') { + // Do not apply on mobile devices + $strFramework = '@media (min-width:768px){' . $strFramework . '}'; + if ($objPage->outputFormat == 'xhtml') { $this->Template->framework .= '<style type="text/css">' . "\n";
[Core] Made the layout builder generate responsive columns
contao_contao
train
php
9c7b4541e6671b87ec1e2ff65a62fc255bf7713e
diff --git a/src/main/java/water/api/AUC.java b/src/main/java/water/api/AUC.java index <HASH>..<HASH> 100644 --- a/src/main/java/water/api/AUC.java +++ b/src/main/java/water/api/AUC.java @@ -70,7 +70,6 @@ public class AUC extends Func { */ public AUC(hex.ConfusionMatrix[] cms, float[] thresh, String[] domain) { aucdata = new AUCData().compute(cms, thresh, domain, threshold_criterion); - computeGainsLift(); } private void computeGainsLift() {
PUB-<I>: Don't compute Gains/Lift table from AUC constructor that was given the CMs.
h2oai_h2o-2
train
java
2703dd48568fde8da889d53a3121f207218842db
diff --git a/slick.grid.js b/slick.grid.js index <HASH>..<HASH> 100644 --- a/slick.grid.js +++ b/slick.grid.js @@ -65,6 +65,7 @@ * EVENTS: * onSort - * onHeaderContextMenu - + * onHeaderClick - Matt Baker: Added onHeaderClick for column headers * onClick - * onDblClick - * onContextMenu - @@ -406,6 +407,7 @@ if (!jQuery.fn.drag) { $canvas.bind("contextmenu", handleContextMenu); $canvas.bind("mouseover", handleHover); $headerScroller.bind("contextmenu", handleHeaderContextMenu); + $headerScroller.bind("click", handleHeaderClick); } function measureScrollbar() { @@ -1809,6 +1811,18 @@ if (!jQuery.fn.drag) { self.onHeaderContextMenu(e); } } + + function handleHeaderClick(e) { + + var $col = $(e.target).closest(".slick-header-column"); + if ($col.length ==0) { return; } + var column = columns[getSiblingIndex($col[0])]; + + if (self.onHeaderClick && options.editorLock.commitCurrentEdit()) { + e.preventDefault(); + self.onHeaderClick(e, column); + } + } function handleHover(e) { if (!options.enableAutoTooltips) return;
Added onHeaderClick event
coatue-oss_slickgrid2
train
js
2019661ff2b8e89fae804f8c38d16989ed513b95
diff --git a/lib/heroku/plugin.rb b/lib/heroku/plugin.rb index <HASH>..<HASH> 100644 --- a/lib/heroku/plugin.rb +++ b/lib/heroku/plugin.rb @@ -10,14 +10,14 @@ module Heroku DEPRECATED_PLUGINS = %w( heroku-cedar heroku-certs - heroku-releases - heroku-postgresql - heroku-shared-postgresql - heroku-pgdumps heroku-kill heroku-labs heroku-logging heroku-netrc + heroku-pgdumps + heroku-postgresql + heroku-releases + heroku-shared-postgresql heroku-status heroku-stop heroku-suggest
alpha sort deprecated plugins list to simplify comparison/lookup
heroku_legacy-cli
train
rb
23b667d123a8c5028075043e12c54ee14e726781
diff --git a/pydoop/mapreduce/pipes.py b/pydoop/mapreduce/pipes.py index <HASH>..<HASH> 100644 --- a/pydoop/mapreduce/pipes.py +++ b/pydoop/mapreduce/pipes.py @@ -115,7 +115,8 @@ class CombineRunner(RecordWriter): ctx = self.ctx writer = ctx.writer ctx.writer = None - for ctx._key, ctx._values in self.data.iteritems(): + for key, values in self.data.iteritems(): + ctx._key, ctx._values = key, iter(values) self.reducer.reduce(ctx) ctx.writer = writer self.data.clear() @@ -226,6 +227,7 @@ class TaskContext(MapContext, ReduceContext): def next_value(self): try: + logger.debug("%s" % self._values) self._value = self._values.next() return True except StopIteration: @@ -340,6 +342,7 @@ class StreamRunner(object): mapper = factory.create_mapper(ctx) reader = reader if reader else get_key_value_stream(self.cmd_stream) ctx.set_combiner(factory, input_split, n_reduces) + for ctx._key, ctx._value in reader: logger.debug("key: %r, value: %r " % (ctx.key, ctx.value)) if send_progress:
Fix bug in ReducerContext.next_value tha was triggered when using Combiner
crs4_pydoop
train
py
3dd1f0e336da16a6d91f67ee11c8a118f770098d
diff --git a/lib/svtplay_dl/service/viaplay.py b/lib/svtplay_dl/service/viaplay.py index <HASH>..<HASH> 100644 --- a/lib/svtplay_dl/service/viaplay.py +++ b/lib/svtplay_dl/service/viaplay.py @@ -285,7 +285,7 @@ class Viaplay(Service, OpenGraphThumbMixin): episode = None else: title = dataj["summary"].replace("{} - ".format(dataj["format_title"]), "") - if title[-1] == ".": + if title and title[-1] == ".": title = title[: len(title) - 1] # remove the last dot if dataj["type"] == "clip":
viafree: dont crash on empty episode names.
spaam_svtplay-dl
train
py
0dcd480d558b2a692160194d0045bcd3b532b9d6
diff --git a/ember-load-initializers.js b/ember-load-initializers.js index <HASH>..<HASH> 100644 --- a/ember-load-initializers.js +++ b/ember-load-initializers.js @@ -13,7 +13,14 @@ define("ember/load-initializers", }).forEach(function(moduleName) { var module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export an initializer.'); } - app.initializer(module['default']); + + var initializer = module['default']; + if (!initializer.name) { + var initializerName = moduleName.match(/[^\/]+\/?$/)[0]; + initializer.name = initializerName; + } + + app.initializer(initializer); }); } }
Auto-assign names to initializers if not already set
ember-cli_ember-load-initializers
train
js
89e08311c85beb51109e8273e54fb6cd54de5b69
diff --git a/go/vt/vtgate/executor.go b/go/vt/vtgate/executor.go index <HASH>..<HASH> 100644 --- a/go/vt/vtgate/executor.go +++ b/go/vt/vtgate/executor.go @@ -1359,7 +1359,7 @@ func (e *Executor) getPlan(vcursor *vcursorImpl, sql string, comments sqlparser. if err != nil { return nil, err } - if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(stmt) { + if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(stmt) && plan.Instructions != nil { e.plans.Set(planKey, plan) } return plan, nil @@ -1386,7 +1386,7 @@ func (e *Executor) getPlan(vcursor *vcursorImpl, sql string, comments sqlparser. if err != nil { return nil, err } - if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(rewrittenStatement) { + if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(rewrittenStatement) && plan.Instructions != nil { e.plans.Set(planKey, plan) } return plan, nil
do not cache plan with nil instructions
vitessio_vitess
train
go
dd8599309b864a92781547799e9b41d83a5104d1
diff --git a/salt/cli/daemons.py b/salt/cli/daemons.py index <HASH>..<HASH> 100644 --- a/salt/cli/daemons.py +++ b/salt/cli/daemons.py @@ -82,7 +82,7 @@ class DaemonsMixin(object): # pylint: disable=no-init :param action :return: ''' - log.info('%s the Salt %s', self.__class__.__name__, action) + log.info('%s the Salt %s', action, self.__class__.__name__) def start_log_info(self): '''
Fix arg order in log message When str.format() was removed from this log message in <I>bfbb, the order of arguments was not changed, which causes the info log to not make sense. This corrects that oversight.
saltstack_salt
train
py
773f61c3c4ee162553b2b33dd4daef9f7974861b
diff --git a/src/Extensions.php b/src/Extensions.php index <HASH>..<HASH> 100644 --- a/src/Extensions.php +++ b/src/Extensions.php @@ -130,6 +130,7 @@ class Extensions $map = require $mapfile; $loader->addClassMap($map); } + $loader->register(); } @@ -142,6 +143,7 @@ class Extensions require $file; } } catch (\Exception $e) { + $this->logInitFailure('Error importing extension class', $file, $e, Logger::ERROR); } } } @@ -175,6 +177,7 @@ class Extensions // Include the init file require_once $file->getRealpath(); } catch (\Exception $e) { + $this->logInitFailure('Error importing local extension class', $file->getBasename(), $e, Logger::ERROR); } } }
Have require failures report an error for extension loading
bolt_bolt
train
php
c98bb216413d9043cb19412872a60e0051c1bc26
diff --git a/test/integration/client/api-tests.js b/test/integration/client/api-tests.js index <HASH>..<HASH> 100644 --- a/test/integration/client/api-tests.js +++ b/test/integration/client/api-tests.js @@ -96,8 +96,8 @@ test("query errors are handled and do not bubble if callback is provded", functi client.query("SELECT OISDJF FROM LEIWLISEJLSE", assert.calls(function(err, result) { assert.ok(err); log("query error supplied error to callback") - sink.add(); - })) + sink.add(); + })) })) }) @@ -116,3 +116,16 @@ test('callback is fired once and only once', function() { }) })) }) + +test('can provide callback and config object', function() { + pg.connect(connectionString, assert.calls(function(err, client) { + assert.isNull(err); + client.query({ + name: 'boom', + text: 'select NOW()' + }, assert.calls(function(err, result) { + assert.isNull(err); + assert.equal(result.rows[0].now.getYear(), new Date().getYear()) + })) + })) +})
failing test for native query with object as first parameter and callback as second parameter
brianc_node-postgres
train
js
7e80b15bcf38de6aa899a0abce4afa0cdf13fcbd
diff --git a/src/TraceMiddleware.php b/src/TraceMiddleware.php index <HASH>..<HASH> 100644 --- a/src/TraceMiddleware.php +++ b/src/TraceMiddleware.php @@ -68,7 +68,8 @@ class TraceMiddleware ]); return $value; }, - function ($reason) use ($step, $name, $start) { + function ($reason) use ($step, $name, $start, $command) { + $this->flushHttpDebug($command); $this->stepOutput($start, [ 'step' => $step, 'name' => $name,
Ensuring that the HTTP flush occurs on error too
aws_aws-sdk-php
train
php
a80fb5d39f17e8465a9d187be35f6e49586cbfe3
diff --git a/test/runtime/chaos.go b/test/runtime/chaos.go index <HASH>..<HASH> 100644 --- a/test/runtime/chaos.go +++ b/test/runtime/chaos.go @@ -16,6 +16,7 @@ package RuntimeTest import ( "crypto/md5" + "fmt" "github.com/cilium/cilium/test/helpers" @@ -109,4 +110,13 @@ var _ = Describe("RuntimeChaos", func() { Expect(links).Should(Equal(originalLinks), "Some network interfaces were accidentally removed!") }, 300) + + It("Checking for file-descriptor leak", func() { + threshold := 5000 + fds, err := vm.Exec("sudo lsof -p `pidof cilium-node-monitor` -p `pidof cilium-agent` -p `pidof cilium-docker` 2>/dev/null | wc -l").IntOutput() + Expect(err).Should(BeNil()) + + Expect(fds).To(BeNumerically("<", threshold), + fmt.Sprintf("%d file descriptors open from Cilium processes", fds)) + }, 300) })
test/runtime: migrate <I>-fd-open.sh to Ginkgo
cilium_cilium
train
go
d61b0f922d940cd22e5f15f432224f6e7fab802c
diff --git a/hydra_base/lib/units.py b/hydra_base/lib/units.py index <HASH>..<HASH> 100644 --- a/hydra_base/lib/units.py +++ b/hydra_base/lib/units.py @@ -292,6 +292,18 @@ def get_unit_dimension(measure_or_unit_abbreviation,**kwargs): dimension = db.DBSession.query(Dimension).filter(Dimension.id==units[0].dimension_id).one() return str(dimension.name) +def get_dimension_by_unit_id(unit_id,**kwargs): + """ + Return the physical dimension a given unit id refers to. + """ + + try: + dimension = db.DBSession.query(Dimension).join(Unit).filter(Unit.id==unit_id).filter().one() + return get_dimension(dimension.id) + except NoResultFound: + # The dimension does not exist + raise ResourceNotFoundError("Unit %s not found"%(unit_id)) + def get_unit_by_abbreviation(unit_abbreviation, **kwargs): """ @@ -372,7 +384,7 @@ def delete_dimension(dimension_id,**kwargs): db.DBSession.flush() return True except NoResultFound: - raise ResourceNotFoundError("Dimension (dimension_name=%s) does not exist"%(dimension_name)) + raise ResourceNotFoundError("Dimension (dimension_id=%s) does not exist"%(dimension_id)) """
added the way to recover a dimension by the id of one of its units
hydraplatform_hydra-base
train
py
5108318ae3d80001fb05113dd4513ce4add43e51
diff --git a/lib/janky/chat_service/hubot.rb b/lib/janky/chat_service/hubot.rb index <HASH>..<HASH> 100644 --- a/lib/janky/chat_service/hubot.rb +++ b/lib/janky/chat_service/hubot.rb @@ -3,6 +3,8 @@ module Janky module ChatService class Hubot def initialize(settings) + @available_rooms = settings["JANKY_CHAT_HUBOT_ROOMS"] + url = settings["JANKY_CHAT_HUBOT_URL"] if url.nil? || url.empty? raise Error, "JANKY_CHAT_HUBOT_URL setting is required" @@ -15,8 +17,10 @@ module Janky end def rooms - ENV['JANKY_CHAT_HUBOT_ROOMS'].split(',').map do |room| - Room.new(room, room) + @available_rooms.split(',').map do |room| + id, name = room.strip.split(':') + name ||= id + Room.new(id, name) end end
add compatibility for campfire and hipchat
github_janky
train
rb
8ffa8d7e480f8ae0f1aec282feea5a20aa2df4b1
diff --git a/mdeploy.php b/mdeploy.php index <HASH>..<HASH> 100644 --- a/mdeploy.php +++ b/mdeploy.php @@ -258,6 +258,9 @@ class input_manager extends singleton_pattern { return (int)$raw; case input_manager::TYPE_PATH: + if (strpos($raw, '~') !== false) { + throw new invalid_option_exception('Using the tilde (~) character in paths is not supported'); + } $raw = str_replace('\\', '/', $raw); $raw = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $raw); $raw = preg_replace('~\.\.+~', '', $raw); diff --git a/mdeploytest.php b/mdeploytest.php index <HASH>..<HASH> 100644 --- a/mdeploytest.php +++ b/mdeploytest.php @@ -174,6 +174,15 @@ class mdeploytest extends PHPUnit_Framework_TestCase { $input->cast_value($invalid, input_manager::TYPE_MD5); // must throw exception } + /** + * @expectedException invalid_option_exception + */ + public function test_cast_tilde_in_path() { + $input = testable_input_manager::instance(); + $invalid = '~/public_html/moodle_dev'; + $input->cast_value($invalid, input_manager::TYPE_PATH); // must throw exception + } + public function test_has_option() { $provider = input_fake_provider::instance();
MDL-<I> Be more verbose if the tilde character is used in TYPE_PATH script options The tilde character is not generally supported in Moodle. Previously it was just removed silently and it was difficult to realize what was going on.
moodle_moodle
train
php,php
075a667b2d495f5eff25365bc9ede82f2efd84f2
diff --git a/library/src/main/java/ru/noties/scrollable/ScrollableLayout.java b/library/src/main/java/ru/noties/scrollable/ScrollableLayout.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/ru/noties/scrollable/ScrollableLayout.java +++ b/library/src/main/java/ru/noties/scrollable/ScrollableLayout.java @@ -445,9 +445,15 @@ public class ScrollableLayout extends FrameLayout { @Override public boolean dispatchTouchEvent(@SuppressWarnings("NullableProblems") MotionEvent event) { -// if (mSelfUpdateScroll) { -// return super.dispatchTouchEvent(event); -// } + if (mSelfUpdateScroll) { + mIsTouchOngoing = false; + mIsDraggingDraggable = false; + mIsScrolling = false; + mIsFlinging = false; + removeCallbacks(mIdleRunnable); + removeCallbacks(mScrollRunnable); + return super.dispatchTouchEvent(event); + } final int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { @@ -465,7 +471,6 @@ public class ScrollableLayout extends FrameLayout { } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL){ - mIsTouchOngoing = false; if (mCloseUpAlgorithm != null) {
Added cancelation of touch handling when `mSelfScroll` flag is true
noties_Scrollable
train
java
87900841ce89fd6d6834cd05062129905e3b58e7
diff --git a/python_modules/dagster/dagster/core/definitions/decorators.py b/python_modules/dagster/dagster/core/definitions/decorators.py index <HASH>..<HASH> 100644 --- a/python_modules/dagster/dagster/core/definitions/decorators.py +++ b/python_modules/dagster/dagster/core/definitions/decorators.py @@ -289,7 +289,7 @@ def solid( name (str): Name of solid. Must be unique within any :py:class:`PipelineDefinition` using the solid. description (str): Human-readable description of this solid. - input_defs (Optiona[List[InputDefinition]]): + input_defs (Optional[List[InputDefinition]]): List of input definitions. Inferred from typehints if not provided. output_defs (Optional[List[OutputDefinition]]): List of output definitions. Inferred from typehints if not provided.
Fixed a simple Typo in 'solid' decorator (#<I>) Fixed a Typo in solid decorator. Fixed "Optiona" to be "Optional".
dagster-io_dagster
train
py
48a0abfd8efc8224c5fb89c1cf0232758c1ddeeb
diff --git a/Eloquent/Concerns/QueriesRelationships.php b/Eloquent/Concerns/QueriesRelationships.php index <HASH>..<HASH> 100644 --- a/Eloquent/Concerns/QueriesRelationships.php +++ b/Eloquent/Concerns/QueriesRelationships.php @@ -493,12 +493,12 @@ trait QueriesRelationships $model = array_search($model, $morphMap, true); } - return $this->whereNot($relation->getMorphType(), $model, null, $boolean); + return $this->whereNot($relation->getMorphType(), '<=>', $model, $boolean); } return $this->whereNot(function ($query) use ($relation, $model) { - $query->where($relation->getMorphType(), $model->getMorphClass()) - ->where($relation->getForeignKeyName(), $model->getKey()); + $query->where($relation->getMorphType(), '<=>', $model->getMorphClass()) + ->where($relation->getForeignKeyName(), '<=>', $model->getKey()); }, null, null, $boolean); }
Allow for nullable morphs in whereNotMorphedTo (#<I>) * use the null safe operator to return null polymorphic relationships
illuminate_database
train
php
cb78f54d8a162bf555ee67ca8a8de7ceeec3c4f3
diff --git a/src/Psalm/CodeLocation.php b/src/Psalm/CodeLocation.php index <HASH>..<HASH> 100644 --- a/src/Psalm/CodeLocation.php +++ b/src/Psalm/CodeLocation.php @@ -296,7 +296,9 @@ class CodeLocation } $this->snippet = mb_strcut($file_contents, $this->preview_start, $this->preview_end - $this->preview_start); - $this->text = mb_strcut($file_contents, $this->selection_start, $this->selection_end - $this->selection_start); + // text is within snippet. It's 50% faster to cut it from the snippet than from the full text + $selection_length = $this->selection_end - $this->selection_start; + $this->text = mb_strcut($this->snippet, $this->selection_start - $this->preview_start, $selection_length); // reset preview start to beginning of line if ($file_contents !== '') {
Performance: cut the selected_text from snippet instead of from full text <I>% faster than cutting from full text, improves performance up to 3% depending on file length and number of errors in file
vimeo_psalm
train
php
f0785b1ba82a63366ca7ec6a3f4d3a25f9bbed13
diff --git a/besticon/besticon_test.go b/besticon/besticon_test.go index <HASH>..<HASH> 100644 --- a/besticon/besticon_test.go +++ b/besticon/besticon_test.go @@ -207,7 +207,7 @@ func TestImageSizeDetection(t *testing.T) { } func TestParseSizeRange(t *testing.T) { - // This single num behaviour ensures backwards compatability for + // This single num behaviour ensures backwards compatibility for // people who pant (at least) pixel perfect icons. sizeRange, err := ParseSizeRange("120") assertEquals(t, &SizeRange{120, 120, MaxIconSize}, sizeRange)
Fix typo in besticon_test.go comment
mat_besticon
train
go
4383d1e3b261a25f4609777322c35bd7c272b288
diff --git a/squad/core/comparison.py b/squad/core/comparison.py index <HASH>..<HASH> 100644 --- a/squad/core/comparison.py +++ b/squad/core/comparison.py @@ -53,12 +53,11 @@ class TestComparison(object): @classmethod def compare_projects(cls, *projects): builds = [p.builds.last() for p in projects] + builds = [b for b in builds if b] return cls.compare_builds(*builds) def __extract_results__(self): for build in self.builds: - if not build: - continue test_runs = list(build.test_runs.all()) environments = [t.environment for t in test_runs] self.environments[build] = sorted(set(environments), key=lambda e: e.id)
TestComparison: test for valid builds early on
Linaro_squad
train
py
ca67b5dcf2f1e0e346aa54c8d41be4cdf3fe6b42
diff --git a/acceptance/tests/agent/agent_disable_lockfile.rb b/acceptance/tests/agent/agent_disable_lockfile.rb index <HASH>..<HASH> 100644 --- a/acceptance/tests/agent/agent_disable_lockfile.rb +++ b/acceptance/tests/agent/agent_disable_lockfile.rb @@ -32,7 +32,7 @@ tuples = [ tuples.each do |expected_message, explicitly_specify_message| - with_puppet_running_on(master) do + with_puppet_running_on(master, {}) do step "disable the agent; specify message? '#{explicitly_specify_message}', message: '#{expected_message}'" do agents.each do |agent|
(#<I>) Provide mandatory arg for with_puppet_running_on
puppetlabs_puppet
train
rb
a20552924c185417368b1f2e248a866b967d27d7
diff --git a/lib/sprockets/base.rb b/lib/sprockets/base.rb index <HASH>..<HASH> 100644 --- a/lib/sprockets/base.rb +++ b/lib/sprockets/base.rb @@ -334,7 +334,7 @@ module Sprockets files = {} each_file do |filename| if logical_path = logical_path_for_filename(filename, filters) - yield logical_path unless files[logical_path] + yield logical_path, filename.to_s unless files[logical_path] files[logical_path] = true end end diff --git a/test/test_environment.rb b/test/test_environment.rb index <HASH>..<HASH> 100644 --- a/test/test_environment.rb +++ b/test/test_environment.rb @@ -221,8 +221,10 @@ module EnvironmentTests test "iterate over each logical path" do paths = [] - @env.each_logical_path do |logical_path| + filenames = [] + @env.each_logical_path do |logical_path, original_filename| paths << logical_path + filenames << original_filename end assert_equal FILES_IN_PATH, paths.length assert_equal paths.size, paths.uniq.size, "has duplicates" @@ -231,6 +233,8 @@ module EnvironmentTests assert paths.include?("coffee/foo.js") assert paths.include?("coffee/index.js") assert !paths.include?("coffee") + + assert filenames.any? { |p| p =~ /application.js.coffee/ } end test "each logical path enumerator" do
Pass also original filename to the block in each_logical_path This may be useful if you want to check the original extension of a given file while iterating through logical paths. Conflicts: lib/sprockets/base.rb
rails_sprockets
train
rb,rb
f07b87cf4cd1633aa0a8ab74345ac2a620a66965
diff --git a/src/php/wp-cli/commands/internals/core.php b/src/php/wp-cli/commands/internals/core.php index <HASH>..<HASH> 100644 --- a/src/php/wp-cli/commands/internals/core.php +++ b/src/php/wp-cli/commands/internals/core.php @@ -53,7 +53,10 @@ class Core_Command extends WP_CLI_Command { $_POST['prefix'] = isset( $assoc_args['dbprefix'] ) ? $assoc_args['dbprefix'] : 'wp_'; $_GET['step'] = 2; + + if ( WP_CLI_SILENT ) ob_start(); require WP_ROOT . '/wp-admin/setup-config.php'; + if ( WP_CLI_SILENT ) ob_end_clean(); } /**
make wp core config obey the silent flag. see #<I>
wp-cli_export-command
train
php
3538aa09fe8e0afebafccaf6e7fe4de0e0c061b2
diff --git a/babelapi/babel/tower.py b/babelapi/babel/tower.py index <HASH>..<HASH> 100644 --- a/babelapi/babel/tower.py +++ b/babelapi/babel/tower.py @@ -418,6 +418,12 @@ class TowerOfBabel(object): Returns: babelapi.data_type.StructField: A field of a struct. """ + if isinstance(babel_field, BabelVoidField): + raise InvalidSpec( + 'Struct field %s cannot have a Void type.' % + quote(babel_field.name), + babel_field.lineno, babel_field.path) + data_type = self._resolve_type(env, babel_field.type_ref) if isinstance(data_type, Void): raise InvalidSpec( diff --git a/test/test_babel.py b/test/test_babel.py index <HASH>..<HASH> 100644 --- a/test/test_babel.py +++ b/test/test_babel.py @@ -513,6 +513,19 @@ alias R = S(min_length=1) cm.exception.msg) def test_struct_semantics(self): + # Test field with implicit void type + text = """ +namespace test + +struct S + option_a +""" + t = TowerOfBabel([('test.babel', text)]) + with self.assertRaises(InvalidSpec) as cm: + t.parse() + self.assertEqual("Struct field 'option_a' cannot have a Void type.", + cm.exception.msg) + # Test duplicate fields text = """\ namespace test
Check error case where a struct field is declared with an implicit void type. Test Plan: Added test. Reviewed By: kannan
dropbox_stone
train
py,py
2f996e1e39ee3e7c0aed2a112f74dc8c0b677984
diff --git a/Model/ModelStateRepository.php b/Model/ModelStateRepository.php index <HASH>..<HASH> 100644 --- a/Model/ModelStateRepository.php +++ b/Model/ModelStateRepository.php @@ -19,7 +19,7 @@ class ModelStateRepository extends EntityRepository ->andWhere('ms.workflowIdentifier = :workflow_identifier') ->andWhere('ms.processName = :process') ->andWhere('ms.successful = :success') - ->orderBy('ms.createdAt', 'DESC') + ->orderBy('ms.id', 'DESC') ->setParameter('workflow_identifier', $workflowIdentifier) ->setParameter('process', $processName) ->setParameter('success', true)
fixed findLatestModelState() order by
lexik_LexikWorkflowBundle
train
php
223d9fe09f793bfd8c5feb233885e5ea8bd6c803
diff --git a/test/points.test.js b/test/points.test.js index <HASH>..<HASH> 100644 --- a/test/points.test.js +++ b/test/points.test.js @@ -34,6 +34,29 @@ module.exports = { test.equal(octant.distanceToSquared(point), box.max.distanceToSquared(point), "should calculate the squared distance"); test.done(); + }, + + "correctly computes the distance from its center to a point": function(test) { + + const octant = new lib.PointOctant(box.min, box.max); + + const point = new THREE.Vector3(1, 2, 3); + + test.equal(octant.distanceToCenterSquared(point), octant.getCenter().distanceToSquared(point), "should calculate the squared distance"); + test.done(); + + }, + + "can determine whether a point lies inside it": function(test) { + + const octant = new lib.PointOctant(box.min, box.max); + + const point = new THREE.Vector3(); + + test.equal(octant.contains(point.set(0, 0, 0), 0), true, "should determine that it contains the point"); + test.equal(octant.contains(point.set(2, 0, 0), 0), false, "should determine that the point lies outside"); + test.done(); + } },
Added more sanity tests.
vanruesc_sparse-octree
train
js
4d1fa508d02593a040a2bf8ded456b5bd54391c5
diff --git a/core/src/main/java/de/javakaffee/web/msm/JavaSerializationTranscoder.java b/core/src/main/java/de/javakaffee/web/msm/JavaSerializationTranscoder.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/de/javakaffee/web/msm/JavaSerializationTranscoder.java +++ b/core/src/main/java/de/javakaffee/web/msm/JavaSerializationTranscoder.java @@ -124,13 +124,15 @@ public class JavaSerializationTranscoder implements SessionAttributesTranscoder final List<Object> saveValues = new ArrayList<Object>(); for ( int i = 0; i < keys.length; i++ ) { final Object value = attributes.get( keys[i] ); - if ( value == null ) { + if ( value == null || session.exclude( keys[i] ) ) { continue; - } else if ( ( value instanceof Serializable ) && ( !session.exclude( keys[i] ) ) ) { + } else if ( value instanceof Serializable ) { saveNames.add( keys[i] ); saveValues.add( value ); } else { - session.removeAttributeInternal( keys[i], true ); + if ( LOG.isDebugEnabled() ) { + LOG.debug( "Ignoring attribute '" + keys[i] + "' as it does not implement Serializable" ); + } } }
Implemented #<I>: Don't remove unserializable attributes from active sessions (with default/java serialization)
magro_memcached-session-manager
train
java
b3ce95445fc4a15e3c3e998adfcc390358888159
diff --git a/emma2/util/log.py b/emma2/util/log.py index <HASH>..<HASH> 100644 --- a/emma2/util/log.py +++ b/emma2/util/log.py @@ -18,6 +18,9 @@ import emma2 as _emma2 log.error('error message') log.critical('critical message') """ +#TODO: setup file logging here, but do not define a logger object and use +# import logging; log=logging.getLogger(__name__) in each unit instead. +# this should work, because everthing is derived from root logger log = logging.getLogger('emma2') # set up logging to file - see previous section for more details
[util/log] added todo about future logging handling
markovmodel_PyEMMA
train
py
c110d18bd254a1c92cae0bf525db3163229ecaa2
diff --git a/pyathena/result_set.py b/pyathena/result_set.py index <HASH>..<HASH> 100644 --- a/pyathena/result_set.py +++ b/pyathena/result_set.py @@ -35,7 +35,7 @@ class AthenaResultSet(CursorIterator): assert self._query_execution, "Required argument `query_execution` not found." self._retry_config = retry_config - self._meta_data: Optional[Tuple[Any, Any]] = None + self._meta_data: Optional[Tuple[Any, ...]] = None self._rows: Deque[Tuple[Optional[Any]]] = collections.deque() self._next_token: Optional[str] = None @@ -285,7 +285,7 @@ class AthenaResultSet(CursorIterator): if not self._next_token and self._is_first_row_column_labels(rows) else 0 ) - meta_data = cast(Tuple[Any, Any], self._meta_data) + meta_data = cast(Tuple[Any, ...], self._meta_data) processed_rows = [ tuple( [
Fix Incompatible types in assignment (expression has type "Tuple[Any, ...]", variable has type "Optional[Tuple[Any, Any]]")
laughingman7743_PyAthena
train
py
b6b17b032582dbde6f4f9faecef3dd662726b3e2
diff --git a/lib/strategy/timer.js b/lib/strategy/timer.js index <HASH>..<HASH> 100644 --- a/lib/strategy/timer.js +++ b/lib/strategy/timer.js @@ -15,7 +15,7 @@ module.exports = class TimerStrategy extends Strategy { const { interval, cron, cronOptions, immediate } = this.schedule; assert(interval || cron || immediate, `[egg-schedule] ${this.key} schedule.interval or schedule.cron or schedule.immediate must be present`); - assert(is.function(this.handler), '[egg-schedule] ${this.key} strategy should override `handler()` method'); + assert(is.function(this.handler), `[egg-schedule] ${this.key} strategy should override \`handler()\` method`); // init cron parser if (cron) {
fix: should use template literal (#<I>)
eggjs_egg-schedule
train
js
4ab4bd631f7d8d2179f6d4dbf3d79c10d6be2eff
diff --git a/src/types/line.js b/src/types/line.js index <HASH>..<HASH> 100644 --- a/src/types/line.js +++ b/src/types/line.js @@ -107,8 +107,8 @@ module.exports = function(Chart) { var scale = chartInstance.scales[options.scaleID]; var pixel, endPixel; if (scale) { - pixel = helpers.isValid(options.value) ? scale.getPixelForValue(options.value) : NaN; - endPixel = helpers.isValid(options.endValue) ? scale.getPixelForValue(options.endValue) : pixel; + pixel = helpers.isValid(options.value) ? scale.getPixelForValue(options.value, options.value.index) : NaN; + endPixel = helpers.isValid(options.endValue) ? scale.getPixelForValue(options.endValue, options.value.index) : pixel; } if (isNaN(pixel)) {
Pass the index of value datapoint to getPixelValue (#<I>) Pass the index of value to getPixelValue
chartjs_chartjs-plugin-annotation
train
js
31fb7505edb32693dcc2462c7b93e5b5ed6a3e1c
diff --git a/pylint/checkers/refactoring.py b/pylint/checkers/refactoring.py index <HASH>..<HASH> 100644 --- a/pylint/checkers/refactoring.py +++ b/pylint/checkers/refactoring.py @@ -585,6 +585,11 @@ class RefactoringChecker(checkers.BaseTokenChecker): if not node.exc: # Ignore bare raises return True + if not utils.is_node_inside_try_except(node): + # If the raise statement is not inside a try/except statement + # then the exception is raised and cannot be caught. No need + # to infer it. + return True exc = utils.safe_infer(node.exc) if exc is None or exc is astroid.Uninferable: return False
Add of a test to avoid exception inference if this exception is not handled.
PyCQA_pylint
train
py
4a35bd9b90a5f586dd41df3833f2f3ba4a7da70f
diff --git a/lib/Sabre/VObject/Reader.php b/lib/Sabre/VObject/Reader.php index <HASH>..<HASH> 100644 --- a/lib/Sabre/VObject/Reader.php +++ b/lib/Sabre/VObject/Reader.php @@ -111,13 +111,15 @@ class Reader { } $propertyName = strtoupper($matches['name']); - $propertyValue = preg_replace_callback('#(\\\\(\\\\|N|n|;|,))#',function($matches) { + $propertyValue = Property::stripSlashes($matches['value']); + /* Maybe it's better to just remove '|;|,' from the regex below? + * $propertyValue = preg_replace_callback('#(\\\\(\\\\|N|n|;|,))#',function($matches) { if ($matches[2]==='n' || $matches[2]==='N') { return "\n"; } else { return $matches[2]; } - }, $matches['value']); + }, $matches['value']);*/ $obj = Property::create($propertyName, $propertyValue);
Don't strip slashes before comma and semi-colon to be able to unserialize compound values.
sabre-io_vobject
train
php