hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
e11acd3623e585320e72568318c189adcbc196cf
diff --git a/src/common/storage/mongo.js b/src/common/storage/mongo.js index <HASH>..<HASH> 100644 --- a/src/common/storage/mongo.js +++ b/src/common/storage/mongo.js @@ -53,7 +53,8 @@ define(["mongodb", "util/assert", "util/canon"], function (MONGODB, ASSERT, CANO if(options.user && options.pwd){ userString = options.user+":"+options.pwd+"@"; } - MONGODB.MongoClient.connect("mongodb://" + userString + options.host + ":" + options.port + "/" + options.database, { + options.uri = options.uri || "mongodb://" + userString + options.host + ":" + options.port + "/" + options.database; + MONGODB.MongoClient.connect(options.uri, { 'w': 1, 'native-parser': true, 'auto_reconnect': true,
adding uri parameter to storage so the mongoDB connection can be used in an easier form - the uri option is not cover the 'connection options' as of yet Former-commit-id: <I>f<I>a5be<I>b<I>c<I>d5c<I>c5dd<I>a<I>ea
webgme_webgme-engine
train
22d4e2234fb810b698b2d7eacd13a6d4d9133f64
diff --git a/plugins/java/java.go b/plugins/java/java.go index <HASH>..<HASH> 100644 --- a/plugins/java/java.go +++ b/plugins/java/java.go @@ -106,6 +106,10 @@ func (p *Plugin) Build(fn *function.Function, zip *archive.Archive) error { // Clean runs mvn clean. func (p *Plugin) Clean(fn *function.Function) error { + if fn.Runtime != RuntimeCanonical { + return nil + } + fn.Log.Debug("cleaning mvn tmpfiles") cmd := exec.Command("mvn", "clean") cmd.Dir = fn.Path
add runtime guard to Java Clean method
apex_apex
train
01384bfcf0cadc5fb7ccf5fa88b0099bfc4bb263
diff --git a/lib/Rx/Operator/DefaultIfEmptyOperator.php b/lib/Rx/Operator/DefaultIfEmptyOperator.php index <HASH>..<HASH> 100644 --- a/lib/Rx/Operator/DefaultIfEmptyOperator.php +++ b/lib/Rx/Operator/DefaultIfEmptyOperator.php @@ -30,24 +30,27 @@ class DefaultIfEmptyOperator implements OperatorInterface public function __invoke(ObservableInterface $observable, ObserverInterface $observer, SchedulerInterface $scheduler = null) { $disposable = new SerialDisposable(); - $disposable->setDisposable($observable->subscribe(new CallbackObserver( + $cbObserver = new CallbackObserver( function ($x) use ($observer) { $this->passThrough = true; $observer->onNext($x); - }, function ($e) use ($observer) { $observer->onError($e); }, - function () use ($observer, $disposable) { + function () use ($observer, $disposable, $scheduler) { if (!$this->passThrough) { - $disposable->setDisposable($this->observable->subscribe($observer)); + $disposable->setDisposable($this->observable->subscribe($observer, $scheduler)); return; } $observer->onCompleted(); } - ), $scheduler)); + ); + + $subscription = $observable->subscribe($cbObserver, $scheduler); + + $disposable->setDisposable($subscription); return $disposable; } diff --git a/test/Rx/Functional/Operator/DefaultIfEmptyTest.php b/test/Rx/Functional/Operator/DefaultIfEmptyTest.php index <HASH>..<HASH> 100644 --- a/test/Rx/Functional/Operator/DefaultIfEmptyTest.php +++ b/test/Rx/Functional/Operator/DefaultIfEmptyTest.php @@ -75,9 +75,13 @@ class DefaultIfEmptyTest extends FunctionalTestCase return $xs->defaultIfEmpty(new ReturnObservable(null)); }); + // Note: these tests differ from the RxJS tests that they were based on because RxJS was + // explicitly using the immediate scheduler on subscribe internally. When we pass the + // proper scheduler in, the subscription gets scheduled which requires an extra tick. + $this->assertMessages([ - onNext(420, null), - onCompleted(420) + onNext(421, null), + onCompleted(421) ], $results->getMessages()); $this->assertSubscriptions([subscribe(200, 420)], $xs->getSubscriptions()); @@ -98,9 +102,12 @@ class DefaultIfEmptyTest extends FunctionalTestCase return $xs->defaultIfEmpty(new ReturnObservable(-1)); }); + // Note: these tests differ from the RxJS tests that they were based on because RxJS was + // explicitly using the immediate scheduler on subscribe internally. When we pass the + // proper scheduler in, the subscription gets scheduled which requires an extra tick. $this->assertMessages([ - onNext(420, -1), - onCompleted(420) + onNext(421, -1), + onCompleted(421) ], $results->getMessages()); $this->assertSubscriptions([subscribe(200, 420)], $xs->getSubscriptions());
Pass scheduler through defaultIfEmpty operator
ReactiveX_RxPHP
train
a83519417d9980c225ff78e46d2caeb1274e9afc
diff --git a/src/core/unit.js b/src/core/unit.js index <HASH>..<HASH> 100644 --- a/src/core/unit.js +++ b/src/core/unit.js @@ -40,7 +40,7 @@ class Basic { setData (newer, callback = () => {}) { let { DataAdaptor } = this.constructor - newer = DataAdaptor.isInstance(newer) ? newer : DataAdaptor.fromPlainObject(newer) + newer = DataAdaptor.isData(newer) ? newer : DataAdaptor.fromPlainObject(newer) let next = DataAdaptor.merge(this.data, newer) if (typeof this.compute === 'function') { diff --git a/src/data/basic.js b/src/data/basic.js index <HASH>..<HASH> 100644 --- a/src/data/basic.js +++ b/src/data/basic.js @@ -8,8 +8,8 @@ function shouleBeOverrided (name, args, result) { } class BasicDataAdaptor { - static isInstance (data) { - shouleBeOverrided('isInstance', ['data'], 'Boolean()') + static isData (data) { + shouleBeOverrided('isData', ['data'], 'Boolean()') } static fromPlainObject (plain) { diff --git a/src/data/plain.js b/src/data/plain.js index <HASH>..<HASH> 100644 --- a/src/data/plain.js +++ b/src/data/plain.js @@ -5,7 +5,7 @@ import isPlainObject from 'is-plain-obj' import BasicDataAdaptor from './basic' class PlainDataAdaptor extends BasicDataAdaptor { - static isInstance (data) { + static isData (data) { return isPlainObject(data) } diff --git a/src/data/sigmund.js b/src/data/sigmund.js index <HASH>..<HASH> 100644 --- a/src/data/sigmund.js +++ b/src/data/sigmund.js @@ -38,7 +38,7 @@ export class SigmundData { } class SigmundDataAdaptor extends BasicDataAdaptor { - static isInstance (data) { + static isData (data) { return data instanceof SigmundData } @@ -47,7 +47,7 @@ class SigmundDataAdaptor extends BasicDataAdaptor { } static merge (original, extra) { - // let extra = original.isInstance(extra) ? extra : new SigmundData(extra) + // let extra = original.isData(extra) ? extra : new SigmundData(extra) // return new SigmundData({ ...original, ...extra }) return new SigmundData({ ...original, ...extra }) } diff --git a/src/utils/helpers.js b/src/utils/helpers.js index <HASH>..<HASH> 100644 --- a/src/utils/helpers.js +++ b/src/utils/helpers.js @@ -46,7 +46,7 @@ export function linkProperties ({ TargetClass, getSourceInstance, properties }) } export function initializeData (DataAdaptor, data, properties) { - data = DataAdaptor.isInstance(data) ? data : DataAdaptor.fromPlainObject(data) + data = DataAdaptor.isData(data) ? data : DataAdaptor.fromPlainObject(data) if (typeof properties === 'object') { let defaults = DataAdaptor.fromPlainObject( map(
refactor: rename DataAdaptor.isInstance to isData
tinajs_tina
train
909c65d9219429d873911f7f6da7243275bedbc0
diff --git a/utils/examples/example_rq.py b/utils/examples/example_rq.py index <HASH>..<HASH> 100644 --- a/utils/examples/example_rq.py +++ b/utils/examples/example_rq.py @@ -1,40 +1,50 @@ +import sys import redis from scutils.redis_queue import RedisStack, RedisQueue, RedisPriorityQueue import argparse -# change these for your Redis host -host = 'scdev' -port = 6379 -redis_conn = redis.Redis(host=host, port=port, decode_responses=True) - -parser = argparse.ArgumentParser(description='Example Redis Queues.') -group = parser.add_mutually_exclusive_group(required=True) -group.add_argument('-q', '--queue', action='store_true', help="Use a RedisQueue") -group.add_argument('-s', '--stack', action='store_true', - help="Use a RedisStack") -group.add_argument('-p', '--priority', action='store_true', - help="Use a RedisPriorityQueue") - -args = vars(parser.parse_args()) - -if args['queue']: - queue = RedisQueue(redis_conn, "my_key") -elif args['stack']: - queue = RedisStack(redis_conn, "my_key") -elif args['priority']: - queue = RedisPriorityQueue(redis_conn, "my_key") - -print("Using " + queue.__class__.__name__) - -if isinstance(queue, RedisPriorityQueue): - queue.push("item1", 50) - queue.push("item2", 100) - queue.push("item3", 20) -else: - queue.push("item1") - queue.push("item2") - queue.push("item3") - -print("Pop 1 " + queue.pop()) -print("Pop 2 " + queue.pop()) -print("Pop 3 " + queue.pop()) \ No newline at end of file + +def main(): + parser = argparse.ArgumentParser(description='Example Redis Queues.') + parser.add_argument('-r', '--redis-host', action='store', default='scdev', + help="The Redis host ip") + parser.add_argument('-rp', '--redis-port', action='store', default='6379', + help="The Redis port") + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument('-q', '--queue', action='store_true', help="Use a RedisQueue") + group.add_argument('-s', '--stack', action='store_true', + help="Use a RedisStack") + group.add_argument('-p', '--priority', action='store_true', + help="Use a RedisPriorityQueue") + + args = vars(parser.parse_args()) + + host = args['redis_host'] + port = args['redis_port'] + redis_conn = redis.Redis(host=host, port=port, decode_responses=True) + + if args['queue']: + queue = RedisQueue(redis_conn, "my_key") + elif args['stack']: + queue = RedisStack(redis_conn, "my_key") + elif args['priority']: + queue = RedisPriorityQueue(redis_conn, "my_key") + + print("Using " + queue.__class__.__name__) + + if isinstance(queue, RedisPriorityQueue): + queue.push("item1", 50) + queue.push("item2", 100) + queue.push("item3", 20) + else: + queue.push("item1") + queue.push("item2") + queue.push("item3") + + print("Pop 1 " + queue.pop()) + print("Pop 2 " + queue.pop()) + print("Pop 3 " + queue.pop()) + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file
update example_rq to make it easier to work in docker container
istresearch_scrapy-cluster
train
cffcf7e0ad0324db098c787249c87aa124042ed9
diff --git a/tests/Models/PostWithReservedSlug.php b/tests/Models/PostWithReservedSlug.php index <HASH>..<HASH> 100644 --- a/tests/Models/PostWithReservedSlug.php +++ b/tests/Models/PostWithReservedSlug.php @@ -20,7 +20,7 @@ class PostWithReservedSlug extends Post return [ 'slug' => [ 'source' => 'title', - 'reserved' => ['add'] + 'reserved' => ['add','add-1'] ] ]; }
Update PostWithReservedSlug.php
cviebrock_eloquent-sluggable
train
0293a6227e85f75a46b450bdeb540e588fe8057d
diff --git a/app/assets/javascripts/thin_man.js b/app/assets/javascripts/thin_man.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/thin_man.js +++ b/app/assets/javascripts/thin_man.js @@ -16,6 +16,11 @@ var initThinMan = function(){ this.getTrigger(); this.getTarget(); this.getErrorTarget(); + this.progress_color = jq_obj.data('progress-color'); + this.progress_target = jq_obj.data('progress_target'); + if(!this.progress_target){ + this.progress_target = this.trigger + } this.insert_method = this.getInsertMethod(); var ajax_submission = this; this.ajax_options = { @@ -98,9 +103,6 @@ var initThinMan = function(){ new thin_man.AjaxFlash('success', ajax_flash.notice,this.target); } } - if ((jqXHR.status == 200) && !(typeof step === 'undefined')) { - $(form_map[step]).ScrollTo(); - } if(this.removeOnSuccess()){ if($(this.removeOnSuccess())){ $(this.removeOnSuccess()).remove(); @@ -145,7 +147,7 @@ var initThinMan = function(){ }, ajaxBefore: function(jqXHr) { this.toggleLoading(); - this.progress_indicator = new thin_man.AjaxProgress(this.trigger); + this.progress_indicator = new thin_man.AjaxProgress(this.progress_target,this.target,this.progress_color); }, ajaxError: function(jqXHR) { if(jqXHR.status == 409){ @@ -160,10 +162,10 @@ var initThinMan = function(){ toggleLoading: function() { if(this.target){ if (this.target.find('[data-loading-visible="false"]').length > 0) { - this.target.find('[data-loading-visible="false"]').addClass('hidden'); + this.target.find('[data-loading-visible="false"]').hide(); } if (this.target.find('[data-loading-visible="true"]').length > 0) { - this.target.find('[data-loading-visible="true"]').removeClass('hidden'); + this.target.find('[data-loading-visible="true"]').show(); } } }, @@ -189,7 +191,7 @@ var initThinMan = function(){ if(this.trigger.length < 1){ this.trigger = $connector; } - this.browser_push_progress_indicator = new thin_man.AjaxProgress(this.trigger); + this.browser_push_progress_indicator = new thin_man.AjaxProgress(this.trigger,this.trigger,this.progress_color); $connector.data('browser-push-progress-indicator-object', this.browser_push_progress_indicator); } }), @@ -201,22 +203,28 @@ var initThinMan = function(){ } }), AjaxProgress: Class.extend({ - init: function(target){ - if(target.not(':visible')){ - var targetOffset = target.parent().offset(); + init: function(target,alt,progress_color){ + if(target.length == 0){ + var progress_target = alt; + } else if(typeof(alt) != 'undefined' && alt.length > 0) { + var progress_target = target; } else { - var targetOffset = target.offset(); + var progress_target = $('body'); } - if(targetOffset){ - var targetLeft = targetOffset.left; - var targetTop = targetOffset.top; - this.progress_container = $('#ajax_progress_container').clone(); - uuid = new UUID; - this.progress_container.prop('id', uuid.value); - $('body').append(this.progress_container); - this.progress_container.css({position:'absolute',left: targetLeft, top: targetTop}); - this.progress_container.show(); + if(!progress_color){ + progress_color = 'black'; } + this.progress_container = $('#ajax_progress_container').clone(); + uuid = new UUID; + this.progress_container.prop('id', uuid.value); + progress_target.append(this.progress_container); + this.progress_container.css({ + display: 'block', visibility: 'visible', position: 'absolute', top: '50%', left: '50%', + 'color': progress_color, 'z-index': 1000000, + '-ms-transform': 'translate(-50%, -50%)', /* IE 9 */ + '-webkit-transform': 'translate(-50%, -50%)', /* Safari */ + 'transform': 'translate(-50%, -50%)' + }) }, stop: function(){ if(this.progress_container){ diff --git a/lib/thin_man/version.rb b/lib/thin_man/version.rb index <HASH>..<HASH> 100644 --- a/lib/thin_man/version.rb +++ b/lib/thin_man/version.rb @@ -1,3 +1,3 @@ module ThinMan - VERSION = "0.8.2" + VERSION = "0.8.5" end
fixed bug in ajax progress indicator
edraut_thin-man
train
95e66b189c308ed5d82d8a111b35e1a877555100
diff --git a/src/ConcurrentFileWriter/BlockWriter.php b/src/ConcurrentFileWriter/BlockWriter.php index <HASH>..<HASH> 100644 --- a/src/ConcurrentFileWriter/BlockWriter.php +++ b/src/ConcurrentFileWriter/BlockWriter.php @@ -86,7 +86,7 @@ class BlockWriter /** * Checks whether the argument is a valid PHP stream resource, otherwise it would be treated * as a stream of bytes. - * + * * @param mixed $input * * @return bool @@ -121,9 +121,9 @@ class BlockWriter } /** - * Writes $content into the file. $content can be an stream of bytes or a file stream. If $limit is + * Writes $content into the file. $content can be an stream of bytes or a file stream. If $limit is * given, it will limit the amounts of bytes to copy to its value. This function returns the amount - * of bytes that were wrote. + * of bytes that were wrote. * * @param mixed $content * @param int $limit
Removing whitespace from end-lines
crodas_ConcurrentFileWriter
train
ca89f12be644ea155d5d56d020a82e26bcfd78d6
diff --git a/lib/api/api_auth.go b/lib/api/api_auth.go index <HASH>..<HASH> 100644 --- a/lib/api/api_auth.go +++ b/lib/api/api_auth.go @@ -11,6 +11,7 @@ import ( "crypto/tls" "encoding/base64" "fmt" + "net" "net/http" "strings" "time" @@ -130,10 +131,16 @@ func authStatic(username string, password string, configUser string, configPassw func authLDAP(username string, password string, cfg config.LDAPConfiguration) bool { address := cfg.Address + hostname, _, err := net.SplitHostPort(address) + if err != nil { + hostname = address + } var connection *ldap.Conn - var err error if cfg.Transport == config.LDAPTransportTLS { - connection, err = ldap.DialTLS("tcp", address, &tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify}) + connection, err = ldap.DialTLS("tcp", address, &tls.Config{ + ServerName: hostname, + InsecureSkipVerify: cfg.InsecureSkipVerify, + }) } else { connection, err = ldap.Dial("tcp", address) }
lib/api: Set ServerName on LDAPS connections (fixes #<I>) (#<I>) tls.Dial needs it for certificate verification.
syncthing_syncthing
train
9db9034bf68efb7c79ec73468488abdaf2dfa74f
diff --git a/internal/service/kendra/index.go b/internal/service/kendra/index.go index <HASH>..<HASH> 100644 --- a/internal/service/kendra/index.go +++ b/internal/service/kendra/index.go @@ -589,7 +589,7 @@ func waitIndexCreated(ctx context.Context, conn *kendra.Client, id string, timeo stateConf := &resource.StateChangeConf{ Pending: IndexStatusValues(types.IndexStatusCreating), - Target: IndexStatusValues(types.IndexStatusActive, types.IndexStatusFailed), + Target: IndexStatusValues(types.IndexStatusActive), Timeout: timeout, Refresh: statusIndex(ctx, conn, id), } @@ -597,8 +597,9 @@ func waitIndexCreated(ctx context.Context, conn *kendra.Client, id string, timeo outputRaw, err := stateConf.WaitForStateContext(ctx) if output, ok := outputRaw.(*kendra.DescribeIndexOutput); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) - + if output.Status == types.IndexStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) + } return output, err } @@ -609,7 +610,7 @@ func waitIndexUpdated(ctx context.Context, conn *kendra.Client, id string, timeo stateConf := &resource.StateChangeConf{ Pending: IndexStatusValues(types.IndexStatusUpdating), - Target: IndexStatusValues(types.IndexStatusActive, types.IndexStatusFailed), + Target: IndexStatusValues(types.IndexStatusActive), Timeout: timeout, Refresh: statusIndex(ctx, conn, id), } @@ -617,8 +618,9 @@ func waitIndexUpdated(ctx context.Context, conn *kendra.Client, id string, timeo outputRaw, err := stateConf.WaitForStateContext(ctx) if output, ok := outputRaw.(*kendra.DescribeIndexOutput); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) - + if output.Status == types.IndexStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.ErrorMessage))) + } return output, err }
refactor(kendra): wait catch fails out of target
terraform-providers_terraform-provider-aws
train
b4b3387a79859785745c58b67c9c9be8ed51a1fd
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ has not yet been thoroughly tested or vetted in a production environment.** - [`role` helper](#role-helper) - [Conflicts](#conflicts) - [Transactions](#transactions) + - [Coalesced Find Requests](#coalesced-find-requests) - [Module Namespaces](#module-namespaces) - [Code Organization](#code-organization) - [Development](#development) @@ -408,7 +409,9 @@ to JSONAPI::Serializers. You may also use the special `:exclude` option to prevent specific relationships from being included in the response. This accepts the same formats as JSONAPI::Serializers does for `:include`. If you exclude a relationship, any sub-relationships will also be excluded. The -`:sort`, `:page`, and `:filter` query parameters must be handled manually. +`:sort`, `:page`, and `:filter` query parameters must be handled manually (with +the exception of the `:id` filter, discussed under "Coalesced Find Requests" +below). All arguments to action helpers are "tainted" and should be treated as potentially dangerous: IDs, attribute hashes, and [resource identifier @@ -666,6 +669,15 @@ helpers do end ``` +### Coalesced Find Requests + +If your JSON:API client coalesces find requests, the `show` action helper will +be invoked once for each ID in the `:id` filter, and the resulting collection +will be serialized on the response. Both query parameter syntaxes for arrays +are supported: `?filter[id]=1,2` and `?filter[id][]=1&filter[id][]=2`. If any +ID is not found (i.e. `show` returns `nil`), the route will halt with HTTP +status code 404. + ### Module Namespaces Everything is dual-namespaced under both Sinatra::JSONAPI and Sinja, and Sinja diff --git a/lib/sinja.rb b/lib/sinja.rb index <HASH>..<HASH> 100644 --- a/lib/sinja.rb +++ b/lib/sinja.rb @@ -68,6 +68,14 @@ module Sinja end end + app.set :pfilters do |*pfilters| + condition do + pfilters.all? do |pfilter| + params.key?('filter') && params['filter'].key?(pfilter.to_s) + end + end + end + app.set :nullif do |nullish| condition { nullish.(data) } end diff --git a/lib/sinja/resource_routes.rb b/lib/sinja/resource_routes.rb index <HASH>..<HASH> 100644 --- a/lib/sinja/resource_routes.rb +++ b/lib/sinja/resource_routes.rb @@ -7,6 +7,21 @@ module Sinja def self.registered(app) app.def_action_helpers(ACTIONS, app) + app.get '', :pfilters=>:id, :actions=>:show do + ids = params['filter'].delete('id') + ids = ids.split(',') if ids.respond_to?(:split) + + opts = {} + resources = [*ids].tap(&:uniq!).map! do |id| + self.resource, opts = show(id) + not_found "Resource '#{id}' not found" unless resource + resource + end + + # TODO: Serialize collection with opts from last model found? + serialize_models(resources, opts) + end + app.get '', :actions=>:index do serialize_models(*index) end
Add support for coalesced find requests
mwpastore_sinja
train
9e6e72c8be0a1638acc15d7857852f1fcbe1b65f
diff --git a/livy/session.py b/livy/session.py index <HASH>..<HASH> 100644 --- a/livy/session.py +++ b/livy/session.py @@ -24,12 +24,26 @@ cat(unlist(collect(toJSON({}))), sep = '\n') """ +def serialise_dataframe_code(dataframe_name, session_kind): + try: + template = { + SessionKind.SPARK: SERIALISE_DATAFRAME_TEMPLATE_SPARK, + SessionKind.PYSPARK: SERIALISE_DATAFRAME_TEMPLATE_PYSPARK, + SessionKind.SPARKR: SERIALISE_DATAFRAME_TEMPLATE_SPARKR + }[session_kind] + except KeyError: + raise RuntimeError( + f'read not supported for sessions of kind {session_kind}' + ) + return template.format(dataframe_name) + + def run_sync(coroutine): loop = asyncio.get_event_loop() return loop.run_until_complete(asyncio.ensure_future(coroutine)) -def extract_serialised_dataframe(text): +def deserialise_dataframe(text): rows = [] for line in text.split('\n'): if line: @@ -60,7 +74,7 @@ async def wait_until_statement_finished(client, session_id, statement_id, await asyncio.sleep(interval) -class LivySession: +class BaseLivySession: def __init__(self, url, kind=SessionKind.PYSPARK, echo=True, check=True): self.client = LivyClient(url) @@ -69,6 +83,29 @@ class LivySession: self.echo = echo self.check = check + async def _close(self): + await self.client.delete_session(self.session_id) + await self.client.close() + + async def _execute(self, code): + await wait_until_session_ready(self.client, self.session_id) + LOGGER.info('Beginning code statement execution') + statement = await self.client.create_statement(self.session_id, code) + await wait_until_statement_finished( + self.client, statement.session_id, statement.statement_id + ) + statement = await self.client.get_statement( + statement.session_id, statement.statement_id + ) + LOGGER.info( + 'Completed code statement execution with status ' + f'{statement.output.status}' + ) + return statement.output + + +class LivySession(BaseLivySession): + def __enter__(self): self.start() return self @@ -81,12 +118,7 @@ class LivySession: self.session_id = session.session_id def close(self): - - async def _close(): - await self.client.delete_session(self.session_id) - await self.client.close() - - run_sync(_close()) + run_sync(self._close()) def run(self, code): output = run_sync(self._execute(code)) @@ -97,36 +129,7 @@ class LivySession: return output def read(self, dataframe_name): - - try: - template = { - SessionKind.SPARK: SERIALISE_DATAFRAME_TEMPLATE_SPARK, - SessionKind.PYSPARK: SERIALISE_DATAFRAME_TEMPLATE_PYSPARK, - SessionKind.SPARKR: SERIALISE_DATAFRAME_TEMPLATE_SPARKR - }[self.kind] - except KeyError: - raise RuntimeError( - f'read not supported for sessions of kind {self.kind}' - ) - - code = template.format(dataframe_name) + code = serialise_dataframe_code(dataframe_name, self.kind) output = run_sync(self._execute(code)) output.raise_for_status() - - return extract_serialised_dataframe(output.text) - - async def _execute(self, code): - await wait_until_session_ready(self.client, self.session_id) - LOGGER.info('Beginning code statement execution') - statement = await self.client.create_statement(self.session_id, code) - await wait_until_statement_finished( - self.client, statement.session_id, statement.statement_id - ) - statement = await self.client.get_statement( - statement.session_id, statement.statement_id - ) - LOGGER.info( - 'Completed code statement execution with status ' - f'{statement.output.status}' - ) - return statement.output + return deserialise_dataframe(output.text)
Extract core LivySession logic
acroz_pylivy
train
48115c28eb0654cbae86d633e57df21b22e0168e
diff --git a/lib/slim/engine.rb b/lib/slim/engine.rb index <HASH>..<HASH> 100644 --- a/lib/slim/engine.rb +++ b/lib/slim/engine.rb @@ -5,7 +5,7 @@ module Slim # Allow users to set default options, particularly useful in Rails' environment files. # For instance, in config/environments/development.rb you probably want: # # Indent html for pretty debugging - # Slim::Engine.options[:pretty] = true + # Slim::Engine.set_default_options :pretty => true # set_default_options :pretty => false, :attr_wrapper => '"',
Corrected the comments per the previous commit.
slim-template_slim
train
0694ac64e36a02d21b8267f3cb3739649acadafe
diff --git a/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/DriverPublication.java b/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/DriverPublication.java index <HASH>..<HASH> 100644 --- a/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/DriverPublication.java +++ b/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/DriverPublication.java @@ -113,10 +113,9 @@ public class DriverPublication termRetransmitBuffers = bufferRotator.buffers().map(this::duplicateLogBuffer).toArray(ByteBuffer[]::new); retransmitHandlers = bufferRotator.buffers().map(this::newRetransmitHandler).toArray(RetransmitHandler[]::new); - this.rightEdge = new AtomicLong(controlStrategy.initialRightEdge(initialTermId, - bufferRotator.sizeOfTermBuffer())); + rightEdge = new AtomicLong(controlStrategy.initialRightEdge(initialTermId, bufferRotator.sizeOfTermBuffer())); - this.shiftsForTermId = Long.numberOfTrailingZeros(bufferRotator.sizeOfTermBuffer()); + shiftsForTermId = Long.numberOfTrailingZeros(bufferRotator.sizeOfTermBuffer()); currentTermId = new AtomicLong(initialTermId); cleanedTermId = new AtomicLong(initialTermId + 2); @@ -130,10 +129,10 @@ public class DriverPublication { final long nextOffset = (currentTermId.get() << shiftsForTermId) + nextTermOffset; final int availableWindow = (int)(rightEdge.get() - nextOffset); - final int maxLength = Math.min(availableWindow, mtuLength); + final int scanLimit = Math.min(availableWindow, mtuLength); final LogScanner scanner = scanners[currentIndex]; - workCount += scanner.scanNext(maxLength, this::onSendFrame); + workCount += scanner.scanNext(scanLimit, this::onSendFrame); if (scanner.isComplete()) { @@ -167,8 +166,8 @@ public class DriverPublication final long receiverWindow, final InetSocketAddress address) { - final long newRightEdge = controlStrategy.onStatusMessage(termId, highestContiguousSequenceNumber, - receiverWindow, address); + final long newRightEdge = + controlStrategy.onStatusMessage(termId, highestContiguousSequenceNumber, receiverWindow, address); rightEdge.lazySet(newRightEdge); @@ -257,8 +256,10 @@ public class DriverPublication private RetransmitHandler newRetransmitHandler(final LogBuffers log) { return new RetransmitHandler(new LogReader(log.logBuffer(), log.stateBuffer()), - timerWheel, MediaConductor.RETRANS_UNICAST_DELAY_GENERATOR, - MediaConductor.RETRANS_UNICAST_LINGER_GENERATOR, this::onSendRetransmit); + timerWheel, + MediaConductor.RETRANS_UNICAST_DELAY_GENERATOR, + MediaConductor.RETRANS_UNICAST_LINGER_GENERATOR, + this::onSendRetransmit); } private int determineIndexByTermId(final long termId) diff --git a/aeron-util/src/main/java/uk/co/real_logic/aeron/util/concurrent/logbuffer/LogScanner.java b/aeron-util/src/main/java/uk/co/real_logic/aeron/util/concurrent/logbuffer/LogScanner.java index <HASH>..<HASH> 100644 --- a/aeron-util/src/main/java/uk/co/real_logic/aeron/util/concurrent/logbuffer/LogScanner.java +++ b/aeron-util/src/main/java/uk/co/real_logic/aeron/util/concurrent/logbuffer/LogScanner.java @@ -101,13 +101,13 @@ public class LogScanner } /** - * Scan forward in the buffer for available frames limited by what will fit in maxLength. + * Scan forward in the buffer for available frames limited by what will fit in limit. * - * @param maxLength in bytes to scan. + * @param limit in bytes to scan. * @param handler called back if a frame is available. * @return number of frames available */ - public int scanNext(final int maxLength, final AvailabilityHandler handler) + public int scanNext(final int limit, final AvailabilityHandler handler) { int frameCount = 0; @@ -132,7 +132,7 @@ public class LogScanner length += alignedFrameLength; - if (length > maxLength) + if (length > limit) { length -= alignedFrameLength; break;
[Java:] Rename argument in prep to be consistent with LogReader.
real-logic_aeron
train
e81ebb9abef2744c23dfc9c0f45b023165adab07
diff --git a/admin/index.php b/admin/index.php index <HASH>..<HASH> 100644 --- a/admin/index.php +++ b/admin/index.php @@ -167,12 +167,7 @@ } } - $status = false; - if (file_exists("$CFG->libdir/db/install.xml")) { - $status = $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml"); //New method - } else { - print_error('dbnotsupport', 'debug', '', $CFG->dbtype); - } + $status = $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml"); //New method // all new installs are in unicode - keep for backwards compatibility and 1.8 upgrade checks set_config('unicodedb', 1);
MDL-<I> added some overlook conversions - thanks to Eloy's script ;-)
moodle_moodle
train
b291d8c54594439f70b6c383f6ec4e753bc9274a
diff --git a/jgeXml.js b/jgeXml.js index <HASH>..<HASH> 100644 --- a/jgeXml.js +++ b/jgeXml.js @@ -180,6 +180,7 @@ function staxParse(s,callback,context) { else if (c == '/') { context.newState = sEndElement; context.keepToken = true; + context.state = sAttributeSpacer; // to stop dummy attributes being emitted to pullparser context.token = context.lastElement; } } @@ -210,13 +211,13 @@ function staxParse(s,callback,context) { context.boundary = '<'; } - if (callback) { - context.state = context.newState; - } - else { - context.position = i+1; - return context; + if (!callback) { + if (((context.state & 1) == 1) && ((context.token.trim() != '') || context.state == sValue)) { + context.position = i+1; + return context; + } } + context.state = context.newState; if (!context.keepToken) context.token = ''; } @@ -242,6 +243,7 @@ module.exports = { getStateName : function(state) { return stateName(state); }, + sInitial : sInitial, sDeclaration : sDeclaration, sElement : sElement, sAttribute : sAttribute, diff --git a/pullparser.js b/pullparser.js index <HASH>..<HASH> 100644 --- a/pullparser.js +++ b/pullparser.js @@ -14,14 +14,12 @@ var depth = 0; while (!context.state || context.state != jgeXml.sEndDocument) { context = jgeXml.parse(xml,null,context); - if (context.token != '') { - if (context.state == jgeXml.sElement) { - depth++; - } - else if (context.state == jgeXml.sEndElement) { - depth--; - } - console.log(jgeXml.getStateName(context.state)+' '+context.position+' '+depth+' '+context.token); + if (context.state == jgeXml.sElement) { + depth++; } + else if (context.state == jgeXml.sEndElement) { + depth--; + } + console.log(jgeXml.getStateName(context.state)+' '+context.position+' '+depth+' '+context.token); if (depth != 0) process.exitCode = 1; } \ No newline at end of file
Emit only exported state events to pullparsers
Mermade_jgeXml
train
646ac089dc27d913f7a4d587d5e6b242bbafdd70
diff --git a/chef/lib/chef/knife/ssh.rb b/chef/lib/chef/knife/ssh.rb index <HASH>..<HASH> 100644 --- a/chef/lib/chef/knife/ssh.rb +++ b/chef/lib/chef/knife/ssh.rb @@ -24,7 +24,7 @@ require 'chef/data_bag_item' begin gem "net-ssh", ">= 2.0.23" rescue LoadError - STDERR.puts "Please install net-ssh version 2.0.23 or higher, as lower versions cause issues." + STDERR.puts "ERROR: Please install net-ssh version 2.0.23 or higher, as lower versions cause issues." exit 1 end
improved error message yet again when net-ssh version isn't correct
chef_chef
train
41c1be6f0d854ae60e5fa3190e736871ed8b9349
diff --git a/faker.go b/faker.go index <HASH>..<HASH> 100644 --- a/faker.go +++ b/faker.go @@ -109,6 +109,9 @@ var ErrValueNotPtr = "Not a pointer value" // Error when tag not supported var ErrTagNotSupported = "Tag unsupported" +// ErrTagAlreadyExists - error when tag exists and call AddProvider +var ErrTagAlreadyExists = "Tag exists" + // Error when passed more arguments var ErrMoreArguments = "Passed more arguments than is possible : (%d)" @@ -143,6 +146,17 @@ func FakeData(a interface{}) error { return nil } +// AddProvider extend faker with tag to generate fake data with specified custom algoritm +func AddProvider(tag string, provider interface{}) error { + if _, ok := mapperTag[tag]; ok { + return errors.New(ErrTagAlreadyExists) + } + + mapperTag[tag] = provider + + return nil +} + func getValue(t reflect.Type) (reflect.Value, error) { k := t.Kind() diff --git a/faker_test.go b/faker_test.go index <HASH>..<HASH> 100644 --- a/faker_test.go +++ b/faker_test.go @@ -388,5 +388,40 @@ func TestSkipField(t *testing.T) { if a.ShouldBeSkipped != 0 { t.Error("Expected that field will be skipped") } +} + +func TestExtend(t *testing.T) { + // This test is to ensure that faker can be extended new providers + + a := struct { + ID string `faker:"test"` + }{} + + err := AddProvider("test", func() string { + return "test" + }) + + if err != nil { + t.Error("Expected Not Error, But Got: ", err) + } + + err = FakeData(&a) + if err != nil { + t.Error("Expected Not Error, But Got: ", err) + } + + if a.ID != "test" { + t.Error("ID should be equal test value") + } +} + +func TestTagAlreadyExists(t *testing.T) { + // This test is to ensure that existing tag cannot be rewritten + + err := AddProvider(Email, func() {}) + + if err == nil || err.Error() != ErrTagAlreadyExists { + t.Error("Expected ErrTagAlreadyExists Error, But Got: ", err) + } }
feat: Add extending faker by custom providers (#<I>)
bxcodec_faker
train
9c8b856356039b830326e6a784acff24cd6fad4d
diff --git a/lib/cloud_crowd/server.rb b/lib/cloud_crowd/server.rb index <HASH>..<HASH> 100644 --- a/lib/cloud_crowd/server.rb +++ b/lib/cloud_crowd/server.rb @@ -95,8 +95,11 @@ module CloudCrowd # configuration with the central server. Triggers distribution of WorkUnits. put '/node/:host' do NodeRecord.check_in(params, request) - CloudCrowd.defer { WorkUnit.distribute_to_nodes } puts "Node #{params[:host]} checked in." + CloudCrowd.defer do + sleep 15 # Give the new node awhile to start listening + WorkUnit.distribute_to_nodes + end json nil end
Don't distribute tasks immediately upon check-in Oftentimes a node isn't prepared to immediately receive a new connection once it checks in, causing a Errno::ECONNRESET exception.
documentcloud_cloud-crowd
train
42783edc237df581276233aacc4ad335dc9d2879
diff --git a/Schema/Grammars/SqlServerGrammar.php b/Schema/Grammars/SqlServerGrammar.php index <HASH>..<HASH> 100755 --- a/Schema/Grammars/SqlServerGrammar.php +++ b/Schema/Grammars/SqlServerGrammar.php @@ -64,7 +64,7 @@ class SqlServerGrammar extends Grammar */ public function compileTableExists() { - return "select * from sysobjects where type = 'U' and name = ?"; + return "select * from sys.sysobjects where id = object_id(?, 'U')"; } /** @@ -75,9 +75,7 @@ class SqlServerGrammar extends Grammar */ public function compileColumnListing($table) { - return "select col.name from sys.columns as col - join sys.objects as obj on col.object_id = obj.object_id - where obj.type = 'U' and obj.object_id = object_id('$table')"; + return "select name from sys.columns where object_id = object_id('$table', 'U')"; } /** @@ -194,7 +192,7 @@ class SqlServerGrammar extends Grammar */ public function compileDropIfExists(Blueprint $blueprint, Fluent $command) { - return sprintf('if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = %s) drop table %s', + return sprintf('if exists (select * from sys.sysobjects where id = object_id(%s, \'U\')) drop table %s', "'".str_replace("'", "''", $this->getTablePrefix().$blueprint->getTable())."'", $this->wrapTable($blueprint) );
[8.x] SqlServer Grammar: Bugfixes for hasTable and dropIfExists / support for using schema names in these functions (#<I>) * - Bugfixes for dropIfExists and hasTable when using a schema in table name in SqlServer. - Shorter version for compileColumnListing * Adjusted tests
illuminate_database
train
73e76c1fdddcb9a1d8c2eea23c577f1e7c27ad2b
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -120,7 +120,7 @@ module.exports = function(grunt) { data: ['test/data/*.json'], collections: [ { - title: 'tags', + name: 'tags', inflection: 'tag', sortorder: 'DESC' } diff --git a/lib/assemble.js b/lib/assemble.js index <HASH>..<HASH> 100644 --- a/lib/assemble.js +++ b/lib/assemble.js @@ -33,7 +33,7 @@ var Assemble = function() { this.options.collections = mergeOptionsArrays(task.target, 'collections'); // add default collections - this.options.collections = _.union(this.options.collections, ['tags', 'categories', { title: 'pages' }]); + this.options.collections = _.union(this.options.collections, ['tags', 'categories', { name: 'pages' }]); this.options.collections = utils.collection.normalize(this.options.collections); diff --git a/lib/util/collection.js b/lib/util/collection.js index <HASH>..<HASH> 100644 --- a/lib/util/collection.js +++ b/lib/util/collection.js @@ -6,13 +6,13 @@ var collection = { update: function(col, page, context) { - if(!context[col.title]) { + if(!context[col.name]) { return col; } - var singularName = col.inflection || inflection.singularize(col.title); + var singularName = col.inflection || inflection.singularize(col.name); - var pageCol = context[col.title] || []; + var pageCol = context[col.name] || []; if(toString.call(pageCol) !== '[object Array]') { pageCol = [pageCol]; } @@ -114,7 +114,7 @@ var collection = { item = rtn[item]; } else { item = { - title: item, + name: item, inflection: inflection.singularize(item), sortorder: 'ASC', sortby: '', @@ -125,16 +125,16 @@ var collection = { item.items = []; } - if(item.title === 'pages') { + if(item.name === 'pages') { item.inflection = '_page'; - item.sortby = (item.sortby || '') === '' ? 'title' : item.sortby; + item.sortby = (item.sortby || '') === '' ? 'name' : item.sortby; item.items = [{ '_page': 'all', pages: [] }]; } - rtn[item.title] = item; + rtn[item.name] = item; });
updating `title` to `name` for collections
assemble_grunt-assemble
train
38a3d5055526622b1083077a45cf18571f9c5c5c
diff --git a/custom-standards/Flyeralarm/Sniffs/Docblock/ReturnTypeSniff.php b/custom-standards/Flyeralarm/Sniffs/Docblock/ReturnTypeSniff.php index <HASH>..<HASH> 100644 --- a/custom-standards/Flyeralarm/Sniffs/Docblock/ReturnTypeSniff.php +++ b/custom-standards/Flyeralarm/Sniffs/Docblock/ReturnTypeSniff.php @@ -16,6 +16,10 @@ class ReturnTypeSniff implements Sniff 'string', 'float', 'array', + 'bool[]', + 'int[]', + 'string[]', + 'float[]', 'null' ];
Allow arrays of primitive types to be returned
flyeralarm_php-code-validator
train
54c43e62f465bd741229bb46c4c7bbdd8727f1a0
diff --git a/osfclient/api.py b/osfclient/api.py index <HASH>..<HASH> 100644 --- a/osfclient/api.py +++ b/osfclient/api.py @@ -1,3 +1,4 @@ +from .exceptions import OSFException from .models import OSFCore from .models import Project @@ -20,8 +21,15 @@ class OSF(OSFCore): def project(self, project_id): """Fetch project `project_id`.""" - url = self._build_url('nodes', project_id) - return Project(self._json(self._get(url), 200), self.session) + type_ = self.guid(project_id) + url = self._build_url(type_, project_id) + if type_ in Project._types: + return Project(self._json(self._get(url), 200), self.session) + raise OSFException('{} is unrecognized type {}. Clone supports projects and registrations'.format(project_id, type_)) + + def guid(self, guid): + """Determines JSONAPI type for provided GUID""" + return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type'] @property def username(self): diff --git a/osfclient/models/project.py b/osfclient/models/project.py index <HASH>..<HASH> 100644 --- a/osfclient/models/project.py +++ b/osfclient/models/project.py @@ -3,6 +3,11 @@ from .storage import Storage class Project(OSFCore): + _types = [ + 'nodes', + 'registrations' + ] + def _update_attributes(self, project): if not project: return diff --git a/osfclient/tests/fake_responses.py b/osfclient/tests/fake_responses.py index <HASH>..<HASH> 100644 --- a/osfclient/tests/fake_responses.py +++ b/osfclient/tests/fake_responses.py @@ -2,7 +2,7 @@ import json # Use this to initialize a `Project` instance -project_node = json.loads(""" +node_json = """ { "data": { "relationships": { @@ -186,11 +186,20 @@ project_node = json.loads(""" "qatest" ] }, - "type": "nodes", + "type": "{type}", "id": "f3szh" } } -""") +""" + +def _build_node(type_): + node = json.loads(node_json) + node['data']['type'] = type_ + return node + +project_node = _build_node('nodes') +registration_node = _build_node('registrations') +fake_node = _build_node('fakes') # Use this to fake a response when asking for a project's files/storages diff --git a/osfclient/tests/test_api.py b/osfclient/tests/test_api.py index <HASH>..<HASH> 100644 --- a/osfclient/tests/test_api.py +++ b/osfclient/tests/test_api.py @@ -1,12 +1,13 @@ -from mock import patch +from mock import call, patch import pytest from osfclient import OSF +from osfclient.exceptions import OSFException from osfclient.models import OSFSession from osfclient.models import OSFCore from osfclient.models import Project -from osfclient.tests.fake_responses import project_node +from osfclient.tests.fake_responses import project_node, registration_node, fake_node from osfclient.tests.mocks import FakeResponse @@ -30,10 +31,31 @@ def test_get_project(OSFCore_get): osf = OSF() project = osf.project('f3szh') + calls = [call('https://api.osf.io/v2//guids/f3szh/'), call('https://api.osf.io/v2//nodes/f3szh/')] + OSFCore_get.assert_has_calls(calls) + assert isinstance(project, Project) + + +@patch.object(OSFCore, '_get', return_value=FakeResponse(200, registration_node)) +def test_get_registration(OSFCore_get): + osf = OSF() + project = osf.project('f3szh') + + calls = [call('https://api.osf.io/v2//guids/f3szh/'), call('https://api.osf.io/v2//registrations/f3szh/')] + OSFCore_get.assert_has_calls(calls) + assert isinstance(project, Project) + + +@patch.object(OSFCore, '_get', return_value=FakeResponse(200, fake_node)) +def test_get_fake(OSFCore_get): + osf = OSF() + with pytest.raises(OSFException) as exc: + osf.project('f3szh') + + assert exc.value.args[0] == 'f3szh is unrecognized type fakes. Clone supports projects and registrations' OSFCore_get.assert_called_once_with( - 'https://api.osf.io/v2//nodes/f3szh/' + 'https://api.osf.io/v2//guids/f3szh/' ) - assert isinstance(project, Project) @patch.object(OSFCore, '_get', return_value=FakeResponse(404, project_node)) @@ -43,5 +65,5 @@ def test_failed_get_project(OSFCore_get): osf.project('f3szh') OSFCore_get.assert_called_once_with( - 'https://api.osf.io/v2//nodes/f3szh/' + 'https://api.osf.io/v2//guids/f3szh/' )
Add clone support for registrations Check type validity when cloning projects Add tests
osfclient_osfclient
train
b9f7df27a8b4cd4bc5b227cb59053721c5665938
diff --git a/addon-test-support/index.js b/addon-test-support/index.js index <HASH>..<HASH> 100644 --- a/addon-test-support/index.js +++ b/addon-test-support/index.js @@ -164,10 +164,10 @@ export async function getDropdownItems(cssPathOrTrigger) { let contentId = await openIfClosedAndGetContentId(trigger); // Select the option with the given selector - let options = document.querySelectorAll(`#${contentId} .ember-power-select-option`); - let obtainedOptions = []; - if (options.length > 0) { - [].slice.apply(options).map((opt) => obtainedOptions.push(opt.textContent.trim())); + let rawOptions = document.querySelectorAll(`#${contentId} .ember-power-select-option`); + let extractedOptions = []; + if (rawOptions.length > 0) { + [].slice.apply(rawOptions).map((opt) => extractedOptions.push(opt.textContent.trim())); } - return obtainedOptions; + return extractedOptions; }
pushing commit by renaming the variables for build to trigger
cibernox_ember-power-select
train
dfb87dae20268b62e658ca41db5c9eaffdd1e279
diff --git a/spec/lib/mail/mail_accounts_spec.rb b/spec/lib/mail/mail_accounts_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/mail/mail_accounts_spec.rb +++ b/spec/lib/mail/mail_accounts_spec.rb @@ -5,17 +5,15 @@ require 'spec_helper' describe '[Mail] Accounts' do let(:teamlab_module) { :mail } - describe '#create_account_by_email', :skip do + describe '#create_account_by_email' do it_behaves_like 'an api request' do - skip('Some troubles connecting mail.ru account. Just hang up') let(:command) { :create_account_by_email } let(:args) { [EMAIL, EMAIL_PASS] } end end describe '#set_default_account' do - it_behaves_like 'an api request', :skip do - skip('Some troubles connecting mail.ru account. Just hang up') + it_behaves_like 'an api request' do let(:command) { :set_default_account } let(:args) { [EMAIL, true] } end
Updated password for mail account, remove pending (#<I>)
ONLYOFFICE_onlyoffice_api_gem
train
7fe4b15fd5219d3fb4e94b962be30eed620aad1b
diff --git a/ht/air_cooler.py b/ht/air_cooler.py index <HASH>..<HASH> 100644 --- a/ht/air_cooler.py +++ b/ht/air_cooler.py @@ -17,7 +17,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.''' from __future__ import division from math import atan, sin -from ht.core import LMTD +from .core import LMTD __all__ = ['Ft_aircooler'] diff --git a/ht/insulation.py b/ht/insulation.py index <HASH>..<HASH> 100644 --- a/ht/insulation.py +++ b/ht/insulation.py @@ -16,7 +16,7 @@ You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.''' from scipy.interpolate import interp1d -from ht.conduction import R_to_k +from .conduction import R_to_k import difflib __all__ = ['nearest_material', 'k_material', 'rho_material', 'Cp_material',
Added original .gitignore back for use of others coding here
CalebBell_ht
train
8df2f9f83f8abf086b797e0039884a7a76bf84b4
diff --git a/tests/karma.conf.js b/tests/karma.conf.js index <HASH>..<HASH> 100644 --- a/tests/karma.conf.js +++ b/tests/karma.conf.js @@ -68,7 +68,7 @@ module.exports = function(config) { flags: ['--no-sandbox'] } }, - browsers: env === 'ci' ? ['Chrome_travis_ci'] : ['Chrome'], + browsers: env === 'ci' ? ['Firefox'] : ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits diff --git a/tests/unit/types.js b/tests/unit/types.js index <HASH>..<HASH> 100644 --- a/tests/unit/types.js +++ b/tests/unit/types.js @@ -170,10 +170,6 @@ describe('Core: Types', () => { it('should identify undefined', () => { expect($type(undefined)).to.equal('undefined'); }); - - it('should identify symbols', () => { - expect($type(Symbol())).to.equal('symbol'); - }); }); describe('$unserialize', () => {
Return back to Firefox for travis build
weepower_wee-core
train
4ef0172ee9aed22a161b6542b219ddf0cc72d385
diff --git a/nodeup/pkg/model/sysctls.go b/nodeup/pkg/model/sysctls.go index <HASH>..<HASH> 100644 --- a/nodeup/pkg/model/sysctls.go +++ b/nodeup/pkg/model/sysctls.go @@ -115,6 +115,11 @@ func (b *SysctlBuilder) Build(c *fi.ModelBuilderContext) error { "# e.g. uses of inotify: nginx ingress controller, kubectl logs -f", "fs.inotify.max_user_instances = 8192", "fs.inotify.max_user_watches = 524288", + + "# Additional sysctl flags that kubelet expects", + "vm.overcommit_memory = 1", + "kernel.panic = 10", + "kernel.panic_on_oops = 1", "", ) } diff --git a/pkg/model/components/kubelet.go b/pkg/model/components/kubelet.go index <HASH>..<HASH> 100644 --- a/pkg/model/components/kubelet.go +++ b/pkg/model/components/kubelet.go @@ -225,5 +225,9 @@ func (b *KubeletOptionsBuilder) BuildOptions(o interface{}) error { clusterSpec.Kubelet.CgroupDriver = "systemd" } + if b.IsKubernetesGTE("1.22") && clusterSpec.Kubelet.ProtectKernelDefaults == nil { + clusterSpec.Kubelet.ProtectKernelDefaults = fi.Bool(true) + } + return nil }
Enable protect-kernel-defaults by default and set the correct sysctls in nodeup
kubernetes_kops
train
ddc81521c6ca83ae559c3817f7c5a7e41f669fe1
diff --git a/src/main/java/org/takes/misc/VerboseList.java b/src/main/java/org/takes/misc/VerboseList.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/takes/misc/VerboseList.java +++ b/src/main/java/org/takes/misc/VerboseList.java @@ -29,6 +29,7 @@ import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.cactoos.Text; +import org.cactoos.text.UncheckedText; /** * Verbose List that wraps OutOfBoundsException with custom message. @@ -211,7 +212,9 @@ public final class VerboseList<T> implements List<T> { private IndexOutOfBoundsException wrapException( final IndexOutOfBoundsException cause) { final IndexOutOfBoundsException exc = - new IndexOutOfBoundsException(this.message); + new IndexOutOfBoundsException( + new UncheckedText(this.message).asString() + ); exc.initCause(cause); return exc; }
(#<I>) Don't call `toString` explicitly
yegor256_takes
train
fb16b143e1d7beb89fde08fb88696d850cfe38f2
diff --git a/chef/spec/unit/role_spec.rb b/chef/spec/unit/role_spec.rb index <HASH>..<HASH> 100644 --- a/chef/spec/unit/role_spec.rb +++ b/chef/spec/unit/role_spec.rb @@ -238,8 +238,34 @@ describe Chef::Role do @deserial.send(t.to_sym).should == @role.send(t.to_sym) end end - end + describe "when loading from disk" do + it "should return a Chef::Role object from JSON" do + File.should_receive(:exists?).with(File.join(Chef::Config[:role_path], 'lolcat.json')).exactly(1).times.and_return(true) + IO.should_receive(:read).with(File.join(Chef::Config[:role_path], 'lolcat.json')).and_return('{"name": "ceiling_cat", "json_class": "Chef::Role" }') + @role.should be_a_kind_of(Chef::Role) + @role.class.from_disk("lolcat") + end + + it "should return a Chef::Role object from a Ruby DSL" do + File.should_receive(:exists?).with(File.join(Chef::Config[:role_path], 'lolcat.json')).exactly(1).times.and_return(false) + File.should_receive(:exists?).with(File.join(Chef::Config[:role_path], 'lolcat.rb')).exactly(2).times.and_return(true) + File.should_receive(:readable?).with(File.join(Chef::Config[:role_path], 'lolcat.rb')).exactly(1).times.and_return(true) + ROLE_DSL=<<-EOR +name "ceiling_cat" +description "like Aliens, but furry" +EOR + IO.should_receive(:read).with(File.join(Chef::Config[:role_path], 'lolcat.rb')).and_return(ROLE_DSL) + @role.should be_a_kind_of(Chef::Role) + @role.class.from_disk("lolcat") + end + + it "should raise an exception if the file does not exist" do + File.should_receive(:exists?).with(File.join(Chef::Config[:role_path], 'lolcat.json')).exactly(1).times.and_return(false) + File.should_receive(:exists?).with(File.join(Chef::Config[:role_path], 'lolcat.rb')).exactly(1).times.and_return(false) + lambda {@role.class.from_disk("lolcat")}.should raise_error(Chef::Exceptions::RoleNotFound) + end + end end
CHEF-<I>: add tests to prove we are getting Chef::Role from disk
chef_chef
train
b6fcff769001ca93f3bcf87395493c6bf31974aa
diff --git a/internetarchive/iarequest.py b/internetarchive/iarequest.py index <HASH>..<HASH> 100644 --- a/internetarchive/iarequest.py +++ b/internetarchive/iarequest.py @@ -150,8 +150,8 @@ class S3PreparedRequest(requests.models.PreparedRequest): meta_value = json.dumps(meta_value) # Convert the metadata value into a list if it is not already # iterable. - if (isinstance(meta_value, six.string_types) or - not hasattr(meta_value, '__iter__')): + if (isinstance(meta_value, six.string_types) + or not hasattr(meta_value, '__iter__')): meta_value = [meta_value] # Convert metadata items into HTTP headers and add to # ``headers`` dict. @@ -258,10 +258,10 @@ class MetadataPreparedRequest(requests.models.PreparedRequest): # Write to many targets if (isinstance(metadata, list) - or any('/' in k for k in metadata) - or all(isinstance(k, dict) for k in metadata.values())): - + or any('/' in k for k in metadata) + or all(isinstance(k, dict) for k in metadata.values())): changes = list() + if any(not k for k in metadata): raise ValueError('Invalid metadata provided, ' 'check your input and try again') diff --git a/internetarchive/item.py b/internetarchive/item.py index <HASH>..<HASH> 100644 --- a/internetarchive/item.py +++ b/internetarchive/item.py @@ -1183,7 +1183,7 @@ class Item(BaseItem): del file_metadata['name'] f = f['name'] if ((isinstance(f, string_types) and is_dir(f)) - or (isinstance(f, tuple) and is_dir(f[-1]))): + or (isinstance(f, tuple) and is_dir(f[-1]))): if isinstance(f, tuple): remote_dir_name = f[0].strip('/') f = f[-1]
Move binary operators to the beginning of the lines. (As recommended by PEP8 and W<I> in the Flake8 documentation.)
jjjake_internetarchive
train
70448ea39789c636d61cb4d0bdff2adc440514cb
diff --git a/cmd/root.go b/cmd/root.go index <HASH>..<HASH> 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -91,7 +91,7 @@ var RootCmd = &cobra.Command{ PersistentPreRun: func(cmd *cobra.Command, args []string) { setupLoggers(logFmt) if noColor { - // TODO: figure our something else... currently, with the wrappers + // TODO: figure out something else... currently, with the wrappers // below, we're stripping any colors from the output after we've // added them. The problem is that, besides being very inefficient, // this actually also strips other special characters from the diff --git a/cmd/run.go b/cmd/run.go index <HASH>..<HASH> 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -162,7 +162,10 @@ a commandline interface for interacting with it.`, initBar = executor.GetInitProgressBar() progressBarWG := &sync.WaitGroup{} progressBarWG.Add(1) - go showProgress(ctx, progressBarWG, conf, executor) + go func() { + showProgress(ctx, conf, executor) + progressBarWG.Done() + }() // Create an engine. initBar.Modify(pb.WithConstProgress(0, "Init engine")) @@ -288,9 +291,6 @@ a commandline interface for interacting with it.`, if err != nil { panic(err) // This should never happen!! } - if err != nil { - panic(err) // This should never happen!! - } _, _ = http.Post(u, mime, bytes.NewBuffer(body)) }() } diff --git a/cmd/ui.go b/cmd/ui.go index <HASH>..<HASH> 100644 --- a/cmd/ui.go +++ b/cmd/ui.go @@ -98,8 +98,7 @@ func renderMultipleBars(isTTY, goBack bool, pbs []*pb.ProgressBar) string { //TODO: show other information here? //TODO: add a no-progress option that will disable these //TODO: don't use global variables... -func showProgress(ctx context.Context, wg *sync.WaitGroup, conf Config, executor *local.Executor) { - defer wg.Done() +func showProgress(ctx context.Context, conf Config, executor *local.Executor) { if quiet || conf.HttpDebug.Valid && conf.HttpDebug.String != "" { return } diff --git a/lib/helpers.go b/lib/helpers.go index <HASH>..<HASH> 100644 --- a/lib/helpers.go +++ b/lib/helpers.go @@ -93,7 +93,7 @@ func GetMaxPossibleVUs(steps []ExecutionStep) (result uint64) { // GetEndOffset returns the time offset of the last step of the execution plan, // and whether that step is a final one, i.e. whether the number of planned or -// unplanned is 0 +// unplanned is 0. func GetEndOffset(steps []ExecutionStep) (lastStepOffset time.Duration, isFinal bool) { if len(steps) == 0 { return 0, true @@ -142,8 +142,12 @@ func StreamExecutionSteps( } select { case <-ctx.Done(): - return // exit if context is cancelled - case ch <- step: // send the step + // exit if context is cancelled + return + case ch <- step: + // ... otherwise, just send the step - the out channel is + // unbuffered, so we don't need to worry whether the other side + // will keep reading after the context is done. } } diff --git a/lib/scheduler/base_config.go b/lib/scheduler/base_config.go index <HASH>..<HASH> 100644 --- a/lib/scheduler/base_config.go +++ b/lib/scheduler/base_config.go @@ -31,6 +31,7 @@ import ( ) var schedulerNameWhitelist = regexp.MustCompile(`^[0-9a-zA-Z_-]+$`) //nolint:gochecknoglobals +const schedulerNameErr = "the scheduler name should contain only numbers, latin letters, underscores, and dashes" // BaseConfig contains the common config fields for all schedulers type BaseConfig struct { @@ -61,9 +62,7 @@ func (bc BaseConfig) Validate() (errors []error) { errors = append(errors, fmt.Errorf("scheduler name shouldn't be empty")) } if !schedulerNameWhitelist.MatchString(bc.Name) { - errors = append(errors, fmt.Errorf( - "the scheduler name should contain only numbers, latin letters, underscores, and dashes", - )) + errors = append(errors, fmt.Errorf(schedulerNameErr)) } if bc.Exec.Valid && bc.Exec.String == "" { errors = append(errors, fmt.Errorf("exec value cannot be empty"))
Fix issues pointed out in the code review
loadimpact_k6
train
0b1ec6cc9ab8f6c7ca2f135479591901ffcf922b
diff --git a/lib/chatterbot/bot.rb b/lib/chatterbot/bot.rb index <HASH>..<HASH> 100644 --- a/lib/chatterbot/bot.rb +++ b/lib/chatterbot/bot.rb @@ -19,6 +19,8 @@ module Chatterbot def initialize super + @config = load_config + # update config when we exit at_exit do raise $! if $! diff --git a/lib/chatterbot/config.rb b/lib/chatterbot/config.rb index <HASH>..<HASH> 100644 --- a/lib/chatterbot/config.rb +++ b/lib/chatterbot/config.rb @@ -4,16 +4,18 @@ module Chatterbot # routines for storing config information for the bot module Config + attr_accessor :config + # # the entire config for the bot, loaded from YAML files and the DB if applicable def config - @_config ||= load_config + @config ||= load_config end # # has the config been loaded yet? def has_config? - ! @_config.nil? + ! @config.nil? end # @@ -142,25 +144,23 @@ module Chatterbot # # get any config from our global config files def global_config - return @_global_config unless @_global_config.nil? - - @_global_config = {} + tmp = {} global_config_files.each { |f| - @_global_config.merge!(slurp_file(f) || {}) + tmp.merge!(slurp_file(f) || {}) } - @_global_config + tmp end # # bot-specific config settings def bot_config - @_bot_config ||= (slurp_file(config_file) || { }) + slurp_file(config_file) || { } end # # config settings that came from the DB def db_config - @_db_config ||= (load_config_from_db || { }) + load_config_from_db || { } end # @@ -189,15 +189,15 @@ module Chatterbot # load in the config from the assortment of places it can be specified. def load_config # load the flat-files first - @_config = global_config.merge(bot_config) - @_config[:db_uri] ||= ENV["chatterbot_db"] unless ENV["chatterbot_db"].nil? + @config = global_config.merge(bot_config) + @config[:db_uri] ||= ENV["chatterbot_db"] unless ENV["chatterbot_db"].nil? # if we have a key to load from the DB, do that now - if @_config.has_key?(:db_uri) && @_config[:db_uri] + if @config.has_key?(:db_uri) && @config[:db_uri] tmp = db_config - @_config = @_config.merge(tmp) unless tmp.nil? + @config = @config.merge(tmp) unless tmp.nil? end - @_config + @config end # diff --git a/spec/config_spec.rb b/spec/config_spec.rb index <HASH>..<HASH> 100644 --- a/spec/config_spec.rb +++ b/spec/config_spec.rb @@ -9,12 +9,17 @@ describe "Chatterbot::Config" do describe "loading" do it "loads config when we need a variable" do @bot.should_receive(:load_config).and_return({:foo => :bar}) + @bot.config = nil + @bot.config[:foo].should == :bar end it "loads both global config and local config" do @bot.should_receive(:global_config).and_return({:foo => :bar, :a => :b}) @bot.should_receive(:bot_config).and_return({:foo => :baz, :custom => :value}) + + @bot.config = nil + @bot.config[:foo].should == :baz @bot.config[:a].should == :b @@ -23,16 +28,22 @@ describe "Chatterbot::Config" do it "returns a log dest" do @bot.should_receive(:load_config).and_return({:log_dest => :bar}) + @bot.config = nil + @bot.log_dest.should == :bar end it "checks for an auth_token" do @bot.should_receive(:load_config).and_return({:token => "123"}) + @bot.config = nil + @bot.needs_auth_token?.should == false end it "checks for an auth_token" do @bot.should_receive(:load_config).and_return({}) + @bot.config = nil + @bot.needs_auth_token?.should == true end end @@ -42,6 +53,8 @@ describe "Chatterbot::Config" do @bot.stub!(:global_config).and_return({:foo => :bar, :a => :b}) @bot.stub!(:bot_config).and_return({:foo => :bar, :custom => :value}) + @bot.config = nil + @bot.config_to_save.should == { :custom => :value } end @@ -49,6 +62,8 @@ describe "Chatterbot::Config" do @bot.stub!(:global_config).and_return({:foo => :bar, :a => :b}) @bot.stub!(:bot_config).and_return({:foo => :baz, :custom => :value}) + @bot.config = nil + @bot.config_to_save.should == { :foo => :baz, :custom => :value } end @@ -71,6 +86,7 @@ describe "Chatterbot::Config" do @bot.should_receive(:slurp_file).with("config.yml").and_return({:a => 1 }) @bot.should_receive(:slurp_file).with("config2.yml").and_return({:b => 2 }) @bot.should_receive(:slurp_file).with("config3.yml").and_return({:c => 3 }) + @bot.global_config.should == { :a => 1, :b => 2, :c => 3} end
move config loading into bot class, get rid of some lazy loading
muffinista_chatterbot
train
f80ff31412fc9fa01afd5642093f304265ff1c63
diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzerTest.java index <HASH>..<HASH> 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzerTest.java @@ -17,26 +17,24 @@ */ package org.owasp.dependencycheck.analyzer; -import org.owasp.dependencycheck.analyzer.exception.AnalysisException; - -import java.io.File; - -import org.junit.After; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; +import java.io.File; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; +import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.dependency.Confidence; import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Evidence; import org.owasp.dependencycheck.utils.Settings; -import com.sun.istack.internal.logging.Logger; - /** * Tests for the AssemblyAnalyzer. * @@ -45,7 +43,7 @@ import com.sun.istack.internal.logging.Logger; */ public class AssemblyAnalyzerTest { - private static final Logger LOGGER = Logger.getLogger(AssemblyAnalyzerTest.class); + private static final Logger LOGGER = Logger.getLogger(AssemblyAnalyzerTest.class.getName()); AssemblyAnalyzer analyzer; @@ -60,7 +58,7 @@ public class AssemblyAnalyzerTest { analyzer = new AssemblyAnalyzer(); analyzer.initialize(); } catch (Exception e) { - LOGGER.warning("Exception setting up AssemblyAnalyzer. Tests will be incomplete", e); + LOGGER.log(Level.WARNING, "Exception setting up AssemblyAnalyzer. Tests will be incomplete", e); Assume.assumeNoException("Is mono installed? TESTS WILL BE INCOMPLETE", e); } }
Fixed JULI Logging (stupid fix imports) Former-commit-id: ca5b3b5ad<I>defefccea4c<I>
jeremylong_DependencyCheck
train
ce13a7ad988af25a5535359aff36f931c3c0987e
diff --git a/hazelcast-documentation/src/Query.md b/hazelcast-documentation/src/Query.md index <HASH>..<HASH> 100644 --- a/hazelcast-documentation/src/Query.md +++ b/hazelcast-documentation/src/Query.md @@ -163,6 +163,8 @@ final IMap<Integer, Student> map = instance.getMap("students"); ... ``` +Paging Predicate is not supported in Transactional Context. + ***Note***: *Please refer to [here](http://hazelcast.org/docs/latest/javadoc/com/hazelcast/query/Predicates.html) for all predicates.* diff --git a/hazelcast/src/main/java/com/hazelcast/map/tx/TransactionalMapProxy.java b/hazelcast/src/main/java/com/hazelcast/map/tx/TransactionalMapProxy.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/map/tx/TransactionalMapProxy.java +++ b/hazelcast/src/main/java/com/hazelcast/map/tx/TransactionalMapProxy.java @@ -303,6 +303,9 @@ public class TransactionalMapProxy extends TransactionalMapProxySupport implemen if (predicate == null) { throw new NullPointerException("Predicate can not be null!"); } + if (predicate instanceof PagingPredicate) { + throw new IllegalArgumentException("Paging is not supported for Transactional queries"); + } final MapService service = getService(); final QueryResultSet queryResultSet = (QueryResultSet) queryInternal(predicate, IterationType.ENTRY, false); final Set<Object> valueSet = new HashSet<Object>(); //todo: Can't we just use the original set? diff --git a/hazelcast/src/test/java/com/hazelcast/map/MapTransactionTest.java b/hazelcast/src/test/java/com/hazelcast/map/MapTransactionTest.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/test/java/com/hazelcast/map/MapTransactionTest.java +++ b/hazelcast/src/test/java/com/hazelcast/map/MapTransactionTest.java @@ -28,6 +28,7 @@ import com.hazelcast.core.MapStoreAdapter; import com.hazelcast.core.TransactionalMap; import com.hazelcast.instance.GroupProperties; import com.hazelcast.query.EntryObject; +import com.hazelcast.query.PagingPredicate; import com.hazelcast.query.Predicate; import com.hazelcast.query.PredicateBuilder; import com.hazelcast.query.SampleObjects; @@ -728,7 +729,8 @@ public class MapTransactionTest extends HazelcastTestSupport { IMap map = inst.getMap("default"); - EntryListener<String, Integer> l = new EntryAdapter<String, Integer>() {}; + EntryListener<String, Integer> l = new EntryAdapter<String, Integer>() { + }; EntryObject e = new PredicateBuilder().getEntryObject(); Predicate<String, Integer> p = e.equal(1); @@ -808,7 +810,7 @@ public class MapTransactionTest extends HazelcastTestSupport { @Test(expected = TransactionNotActiveException.class) public void testTxnMapOuterTransaction() throws Throwable { - final HazelcastInstance h1 = createHazelcastInstance(); + final HazelcastInstance h1 = createHazelcastInstance(); final TransactionContext transactionContext = h1.newTransactionContext(); transactionContext.beginTransaction(); @@ -1070,6 +1072,29 @@ public class MapTransactionTest extends HazelcastTestSupport { } + + @Test( expected = IllegalArgumentException.class) + public void testValuesWithPagingPredicate() throws TransactionException { + final int nodeCount = 1; + final String mapName = randomMapName("testValuesWithPagingPredicate"); + final Config config = new Config(); + final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(nodeCount); + final HazelcastInstance node = factory.newHazelcastInstance(config); + final IMap map = node.getMap(mapName); + + final SampleObjects.Employee emp = new SampleObjects.Employee("name", 77, true, 10D); + map.put(1, emp); + + node.executeTransaction(options, new TransactionalTask<Boolean>() { + public Boolean execute(TransactionalTaskContext context) throws TransactionException { + final TransactionalMap<Object, Object> txMap = context.getMap(mapName); + PagingPredicate predicate = new PagingPredicate(5); + txMap.values(predicate); + return true; + } + }); + } + @Test public void testValuesWithPredicate_removingExistentEntry() throws TransactionException { final int nodeCount = 1;
remark for inability to use paging predicate in a transactional context
hazelcast_hazelcast
train
762b7b56c234bb79d347118f881e803453999515
diff --git a/code/libraries/koowa/libraries/database/row/abstract.php b/code/libraries/koowa/libraries/database/row/abstract.php index <HASH>..<HASH> 100644 --- a/code/libraries/koowa/libraries/database/row/abstract.php +++ b/code/libraries/koowa/libraries/database/row/abstract.php @@ -443,8 +443,7 @@ abstract class KDatabaseRowAbstract extends KObjectArray implements KDatabaseRow * Lazy mixing is triggered by calling KDatabaseRowsetTable::is[Behaviorable](); * * @param string $method The function name - * @param array $argument The function arguments - * @throws \BadMethodCallException If method could not be found + * @param array $arguments The function arguments * @return mixed The result of the function */ public function __call($method, $arguments) @@ -454,19 +453,13 @@ abstract class KDatabaseRowAbstract extends KObjectArray implements KDatabaseRow $parts = KStringInflector::explode($method); //Check if a behavior is mixed - if ($parts[0] == 'is' && isset($parts[1])) + if($parts[0] == 'is' && isset($parts[1])) { - if(!isset($this->_mixed_methods[$method])) - { - //Lazy mix behaviors - $behavior = strtolower($parts[1]); - - if ($this->getTable()->hasBehavior($behavior)) { - $this->mixin($this->getTable()->getBehavior($behavior)); - } else { - return false; - } + if(isset($this->_mixed_methods[$method])) { + return true; } + + return false; } }
re #<I>: Take out call to mixin behaviors in KDatabaseRowAbstract::__call
timble_kodekit
train
5bcc8f4957d8af438470ff8c224276136dac5e84
diff --git a/lib/leanback.rb b/lib/leanback.rb index <HASH>..<HASH> 100644 --- a/lib/leanback.rb +++ b/lib/leanback.rb @@ -13,7 +13,7 @@ end module Document #create a document - def self.create( doc) + def self.create_doc( doc) db_name = doc[:database] doc_id = doc[:doc_id] data = doc[:data] @@ -29,7 +29,7 @@ module Document end #edit a document - def self.edit(doc) + def self.edit_doc(doc) db_name = doc[:database] doc_id = doc[:doc_id] data = doc[:data] @@ -45,7 +45,7 @@ module Document end #update a doc - def self.update (doc) + def self.update_doc(doc) db_name = doc[:database] doc_id = doc[:doc_id] data = doc[:data] @@ -53,11 +53,11 @@ module Document options = Couchdb.view doc options = options.merge(data) doc = {:database => db_name, :doc_id => doc_id, :data => options} - edit doc + edit_doc doc end #delete document - def self.delete(doc) + def self.delete_doc(doc) db_name = doc[:database] doc_id = doc[:doc_id] doc = {:database => db_name, :doc_id => doc_id} diff --git a/test/test_leanback.rb b/test/test_leanback.rb index <HASH>..<HASH> 100644 --- a/test/test_leanback.rb +++ b/test/test_leanback.rb @@ -65,7 +65,7 @@ class TestLeanback < Test::Unit::TestCase :gender =>'male'} doc = {:database => 'contacts', :doc_id => 'john', :data => data} - Document.create doc + Document.create_doc doc doc = {:database => 'contacts', :doc_id => 'john'} hash = Couchdb.view doc @@ -149,7 +149,7 @@ class TestLeanback < Test::Unit::TestCase should "create a document and handle exception if one occurs" do data = {:firstname => 'Nancy', :lastname =>'Lee', :phone => '347-808-3734',:email =>'nancy@mail.com',:gender => 'female'} doc = {:database => 'contacts', :doc_id => 'Nancy', :data => data} - hash = Document.create doc + hash = Document.create_doc doc assert_equal 'Nancy', hash["id"] assert_equal true, hash["ok"] @@ -165,7 +165,7 @@ class TestLeanback < Test::Unit::TestCase #data = {"age" => "42", "lastname" => "arnold", "phone" => "202-456-1234", "hobbies" => "football,running, video gamess" } data = {:age => "41", :lastname => "Stevens" } doc = { :database => 'contacts', :doc_id => 'john', :data => data} - hash = Document.update doc + hash = Document.update_doc doc assert_equal 'john', hash["id"] assert_equal true, hash["ok"] @@ -174,15 +174,15 @@ class TestLeanback < Test::Unit::TestCase assert_equal 'john', hash["_id"] assert_equal '41', hash["age"] assert_equal 'Stevens', hash["lastname"] - Document.delete :database => 'contacts', :doc_id => 'john' + Document.delete_doc :database => 'contacts', :doc_id => 'john' end should "delete sample documents - ready for next test run" do - Document.delete :database => 'contacts', :doc_id => 'Nancy' - Document.delete :database => 'contacts', :doc_id => '_design/more_views' - Document.delete :database => 'contacts', :doc_id => '_design/the_view' - Document.delete :database => 'contacts', :doc_id => '_design/my_views' - Document.delete :database => 'contacts', :doc_id => '_design/email_finder' + Document.delete_doc :database => 'contacts', :doc_id => 'Nancy' + Document.delete_doc :database => 'contacts', :doc_id => '_design/more_views' + Document.delete_doc :database => 'contacts', :doc_id => '_design/the_view' + Document.delete_doc :database => 'contacts', :doc_id => '_design/my_views' + Document.delete_doc :database => 'contacts', :doc_id => '_design/email_finder' end should "edit a document - handle exceptions" do @@ -190,7 +190,7 @@ class TestLeanback < Test::Unit::TestCase #see delete without _rev above data = {:firstname => 'john', :lastname =>'smith', :email => 'john@mail.com',:gender=>'male', :_rev=>'2-e813a0e902e3ac114400ff3959a2adde'} doc = {:database => 'contacts', :doc_id => 'john', :data => data} - hash = Document.edit doc + hash = Document.edit_doc doc #puts hash.inspect rescue CouchdbException => e assert_equal "CouchDB: Error - conflict. Reason - Document update conflict.", e.to_s @@ -205,10 +205,10 @@ class TestLeanback < Test::Unit::TestCase :email =>'james@mail.com'} doc = {:database => 'contacts', :doc_id => 'Sun', :data => data} - Document.create doc + Document.create_doc doc doc = {:database => 'contacts', :doc_id => 'Sun'} - hash = Document.delete doc + hash = Document.delete_doc doc assert_equal 'Sun', hash["id"] assert_equal true, hash["ok"]
made the syntax for manipulating documents more explicit
obi-a_leanback
train
57486b672ca65d74ce820844fa8621d2819c67bf
diff --git a/org/xbill/DNS/Rcode.java b/org/xbill/DNS/Rcode.java index <HASH>..<HASH> 100644 --- a/org/xbill/DNS/Rcode.java +++ b/org/xbill/DNS/Rcode.java @@ -33,6 +33,9 @@ public static final int NXDOMAIN = 3; /** The operation requested is not implemented */ public static final int NOTIMP = 4; +/** Deprecated synonym for NOTIMP. */ +public static final int NOTIMPL = 4; + /** The operation was refused by the server */ public static final int REFUSED = 5; @@ -78,6 +81,7 @@ static { rcodes.add(SERVFAIL, "SERVFAIL"); rcodes.add(NXDOMAIN, "NXDOMAIN"); rcodes.add(NOTIMP, "NOTIMP"); + rcodes.addAlias(NOTIMP, "NOTIMPL"); rcodes.add(REFUSED, "REFUSED"); rcodes.add(YXDOMAIN, "YXDOMAIN"); rcodes.add(YXRRSET, "YXRRSET");
Make NOTIMPL a synonym for NOTIMP, for compatibility. git-svn-id: <URL>
dnsjava_dnsjava
train
976777414756bfc0e14a056cdd160e56089ed1ae
diff --git a/telethon/extensions/markdown.py b/telethon/extensions/markdown.py index <HASH>..<HASH> 100644 --- a/telethon/extensions/markdown.py +++ b/telethon/extensions/markdown.py @@ -5,7 +5,7 @@ since they seem to count as two characters and it's a bit strange. """ import re -from telethon.tl import TLObject +from ..tl import TLObject from ..tl.types import ( MessageEntityBold, MessageEntityItalic, MessageEntityCode,
Fix import in markdown parser not being relative
LonamiWebs_Telethon
train
4566b64d77d638505a0931b560606694b5e2c9f3
diff --git a/discord/activity.py b/discord/activity.py index <HASH>..<HASH> 100644 --- a/discord/activity.py +++ b/discord/activity.py @@ -130,7 +130,7 @@ class BaseActivity: .. versionadded:: 1.3 """ if self._created_at is not None: - return datetime.datetime.utcfromtimestamp(self._created_at / 1000) + return datetime.datetime.utcfromtimestamp(self._created_at / 1000).replace(tzinfo=datetime.timezone.utc) class Activity(BaseActivity): @@ -583,7 +583,7 @@ class Spotify: .. versionadded:: 1.3 """ if self._created_at is not None: - return datetime.datetime.utcfromtimestamp(self._created_at / 1000) + return datetime.datetime.utcfromtimestamp(self._created_at / 1000).replace(tzinfo=datetime.timezone.utc) @property def colour(self): @@ -686,12 +686,12 @@ class Spotify: @property def start(self): """:class:`datetime.datetime`: When the user started playing this song in UTC.""" - return datetime.datetime.utcfromtimestamp(self._timestamps['start'] / 1000) + return datetime.datetime.utcfromtimestamp(self._timestamps['start'] / 1000).replace(tzinfo=datetime.timezone.utc) @property def end(self): """:class:`datetime.datetime`: When the user will stop playing this song in UTC.""" - return datetime.datetime.utcfromtimestamp(self._timestamps['end'] / 1000) + return datetime.datetime.utcfromtimestamp(self._timestamps['end'] / 1000).replace(tzinfo=datetime.timezone.utc) @property def duration(self):
Fix Activity and Spotify datetime being timezone naive
Rapptz_discord.py
train
ff29e756465a41d32a5b27e33c06e0c22d7c39df
diff --git a/Kwc/Abstract/Image/CropImage.js b/Kwc/Abstract/Image/CropImage.js index <HASH>..<HASH> 100644 --- a/Kwc/Abstract/Image/CropImage.js +++ b/Kwc/Abstract/Image/CropImage.js @@ -14,6 +14,7 @@ Kwc.Abstract.Image.CropImage = Ext.extend(Ext.BoxComponent, { minHeight: 52,//min height of crop region _image: null, _cropRegionChosen: false, + _userSelectedCropRegion: null, _ignoreRegionChangeAction: false, _centerHandle: '<div class="handle {position}"></div>', @@ -126,13 +127,14 @@ Kwc.Abstract.Image.CropImage = Ext.extend(Ext.BoxComponent, { this._resizer.getEl().addClass('kwc-abstract-image-crop-image-resizable'); this._resizer.on("resize", function() { + var res = this._getCropData(); if (this._ignoreRegionChangeAction) { this._ignoreRegionChangeAction = false; } else { this._cropRegionChosen = true; + this._userSelectedCropRegion = res; } this._updateCropRegionImage(); - var res = this._getCropData(); this.fireEvent('cropChanged', res); }, this); @@ -150,6 +152,7 @@ Kwc.Abstract.Image.CropImage = Ext.extend(Ext.BoxComponent, { }).createDelegate(this); dragDrop.endDrag = (function (e) { this._cropRegionChosen = true; + this._userSelectedCropRegion = this._getCropData(); this._updateCropRegionImage(); this._image.getEl().setStyle({ 'background-image': 'url('+this.src+')', @@ -203,12 +206,18 @@ Kwc.Abstract.Image.CropImage = Ext.extend(Ext.BoxComponent, { if (this.outWidth != 0 && this.outHeight != 0 && this.outWidth / this.outHeight != cropData.width / cropData.heigth ) { - var width = cropData.height * this.outWidth / this.outHeight; - var height = cropData.width * this.outHeight / this.outWidth; - if (width < this.width) { - cropData.width = width; - } else if (height < this.height) { - cropData.height = height; + if (this._userSelectedCropRegion) { + // Get saved user selected crop-region as base for recalculating + // width and height are set directly because else object is referenced + cropData.height = this._userSelectedCropRegion.height; + cropData.width = this._userSelectedCropRegion.width; + var width = cropData.height * this.outWidth / this.outHeight; + var height = cropData.width * this.outHeight / this.outWidth; + if (width < this.width) { + cropData.width = width; + } else if (height < this.height) { + cropData.height = height; + } } else { cropData = this._generateDefaultCrop(preserveRatio); }
Save user selected crop region for recalculating aspect-ratio changes
koala-framework_koala-framework
train
fae5bec936320a20e6212f7c87bd7c8695097954
diff --git a/lib/DefinePlugin.js b/lib/DefinePlugin.js index <HASH>..<HASH> 100644 --- a/lib/DefinePlugin.js +++ b/lib/DefinePlugin.js @@ -67,6 +67,14 @@ class DefinePlugin { if(!isTypeof) { parser.plugin("can-rename " + key, ParserHelpers.approve); parser.plugin("evaluate Identifier " + key, (expr) => { + /** + * this is needed in case there is a recursion in the DefinePlugin + * to prevent an endless recursion + * e.g.: new DefinePlugin({ + * "a": "b", + * "b": "a" + * }); + */ if(recurse) return; recurse = true; const res = parser.evaluate(code); @@ -78,6 +86,14 @@ class DefinePlugin { } const typeofCode = isTypeof ? code : "typeof (" + code + ")"; parser.plugin("evaluate typeof " + key, (expr) => { + /** + * this is needed in case there is a recursion in the DefinePlugin + * to prevent an endless recursion + * e.g.: new DefinePlugin({ + * "typeof a": "tyepof b", + * "typeof b": "typeof a" + * }); + */ if(recurseTypeof) return; recurseTypeof = true; const res = parser.evaluate(typeofCode);
add some comments to clarify why this is important here
webpack_webpack
train
ed673b765ebf737fdd616d3f7ff6df3a106b6d9d
diff --git a/lib/cieloz/requisicao_transacao.rb b/lib/cieloz/requisicao_transacao.rb index <HASH>..<HASH> 100644 --- a/lib/cieloz/requisicao_transacao.rb +++ b/lib/cieloz/requisicao_transacao.rb @@ -255,18 +255,22 @@ class Cieloz::RequisicaoTransacao < Cieloz::Base def somente_autenticar @autorizar = SOMENTE_AUTENTICAR + self end def autorizar_somente_autenticada @autorizar = AUTORIZAR_SE_AUTENTICADA + self end def autorizar_nao_autenticada @autorizar = AUTORIZAR_NAO_AUTENTICADA + self end def autorizacao_direta @autorizar = AUTORIZACAO_DIRETA + self end def autorizacao_direta? @@ -275,14 +279,17 @@ class Cieloz::RequisicaoTransacao < Cieloz::Base def recorrente @autorizar = RECORRENTE + self end def capturar_automaticamente @capturar = "true" + self end def nao_capturar_automaticamente @capturar = "false" + self end def suporta_autorizacao_direta?
Returns self on authorization methods to make it easier to use chained method declarations
fabiolnm_cieloz
train
cf5b0f0ffe4e143b1437a0731378fc099cac4e3b
diff --git a/Rakefile.rb b/Rakefile.rb index <HASH>..<HASH> 100644 --- a/Rakefile.rb +++ b/Rakefile.rb @@ -43,4 +43,9 @@ end task :default => [:specs] +desc "install gem globally" +task :install => :gem do + sh "sudo gem install pkg/#{spec.name}-#{spec.version}.gem" +end + diff --git a/example/Rakefile.rb b/example/Rakefile.rb index <HASH>..<HASH> 100644 --- a/example/Rakefile.rb +++ b/example/Rakefile.rb @@ -85,7 +85,7 @@ Compiler = OsxCompiler.new('osx') def build_source_lib(lib) objects = lib.sources.map do |s| - Compiler.create_object_file(lib, s) + Compiler.create_object_file(lib, File.basename(s)) end Compiler.create_source_lib(lib, objects) end @@ -104,15 +104,18 @@ projects.each do |p| loadContext.module_eval(File.read(p)) c = loadContext.new raise "no 'define_project' defined in project.rb" unless c.respond_to?(:define_project) - building_block = c.define_project - building_block.base = File.dirname(p) - ALL_BUILDING_BLOCKS[building_block.name] = building_block - if (building_block.instance_of?(SourceLibrary)) then - build_source_lib(building_block) - elsif (building_block.instance_of?(Exe)) then - build_exe(building_block) - else - raise 'unknown building_block' + base_dir = File.dirname(p) + cd base_dir do + building_block = c.define_project + building_block.base = base_dir + ALL_BUILDING_BLOCKS[building_block.name] = building_block + if (building_block.instance_of?(SourceLibrary)) then + build_source_lib(building_block) + elsif (building_block.instance_of?(Exe)) then + build_exe(building_block) + else + raise 'unknown building_block' + end end end diff --git a/example/exe/project.rb b/example/exe/project.rb index <HASH>..<HASH> 100644 --- a/example/exe/project.rb +++ b/example/exe/project.rb @@ -2,5 +2,6 @@ def define_project res = Exe.new('exe') res.dependencies = ['2'] res.sources = FileList["**/*.cpp"] # ['main.cpp', 'help.cpp'] + puts res.sources return res end
allow glob patterns for file paths, install task for gem
marcmo_cxxproject
train
829bf6eadb09a7455f7182a28c5023a78e0b5ffa
diff --git a/lib/MobileCommons/MobileCommons.php b/lib/MobileCommons/MobileCommons.php index <HASH>..<HASH> 100644 --- a/lib/MobileCommons/MobileCommons.php +++ b/lib/MobileCommons/MobileCommons.php @@ -150,6 +150,30 @@ class MobileCommons } /** + * Profile Opt-In + * @see https://secure.mcommons.com/help/forms#form + * + * @param array $args + * @return string + */ + public function opt_in($args = array()) { + return $this->Request->webform('join', $args); + } + + /** + * Profile Opt-Out + * @see https://secure.mcommons.com/help/forms#optout + * + * @param array $args + * @return string + */ + public function opt_out($args = array()) { + $args['company_key'] = $this->Request->getCompanyKey(); + return $this->Request->webform('opt_out', $args); + } + + + /** * Profiles: Get * @see http://www.mobilecommons.com/mobile-commons-api/rest/#ProfileSummary * diff --git a/lib/MobileCommons/Request.php b/lib/MobileCommons/Request.php index <HASH>..<HASH> 100644 --- a/lib/MobileCommons/Request.php +++ b/lib/MobileCommons/Request.php @@ -8,18 +8,28 @@ class Request { - /** + /** * Base URL */ const API_URL = 'https://secure.mcommons.com/api/'; - /** + /** + * Webform URL for opt-in and opt-outs + */ + const WEBFORM_URL = 'https://secure.mcommons.com/profiles/'; + + /** * Authentication String */ private $_authentication_string; + /** + * Company Key + */ + private $_company_key; + - /** + /** * Constructor * * @param array $base_url @@ -28,7 +38,7 @@ class Request public function __construct($config) { - //@todo - write test + //@todo - write test if (!is_array($config)) { throw new Exception("Configuration: Missing configuration."); } @@ -45,6 +55,10 @@ class Request $this->_setAuthenticationString($config['username'], $config['password']); + if (isset($config['company_key'])) { + $this->_company_key = $config['company_key']; + } + } /** @@ -69,6 +83,16 @@ class Request return $this->_authentication_string; } + /** + * Company Key Getter + * + * @return string + */ + public function getCompanyKey() { + return $this->_company_key; + } + + /** * Make an api request * @@ -126,4 +150,29 @@ class Request return $xmlObject; } + /** + * Make a request to the Web Form API. + * + * @param string $action + * @param array $params + * @return string + */ + public function webform($action, $params) { + $url = self::WEBFORM_URL . $action; + + $header = sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthenticationString())); + $header .= "Content-type: application/x-www-form-urlencoded\r\n"; + + $opts = array( + 'http' => array( + 'method' => 'POST', + 'header' => $header, + 'content' => http_build_query($params), + ) + ); + + $context = stream_context_create($opts); + return file_get_contents($url, FALSE, $context); + } + }
Added method to subscribe/unsubscribe numbers in Mobile Commons - separate request method used because these calls use the web form API, not the normal rest API - company_key can be set and used for the opt-out
DoSomething_mobilecommons-php
train
69e315822d72d4105bc053579e35429c83259151
diff --git a/lib/csvlint/streaming_validate.rb b/lib/csvlint/streaming_validate.rb index <HASH>..<HASH> 100644 --- a/lib/csvlint/streaming_validate.rb +++ b/lib/csvlint/streaming_validate.rb @@ -95,8 +95,6 @@ module Csvlint validate_metadata(@stream) if line <= 1 && !@header_processed # this should be a one shot, inelegant way of accomplishing report_line_breaks(line) parse_contents(@stream, line) - rescue OpenURI::HTTPError, Errno::ENOENT # this rescue applies to the validate_metadata method - build_errors(:not_found) # rescue CSV::MalformedCSVError => e # build_exception_message(e, @stream) ensure
Remove commented :not_found error This is handled in `validate_url` now
theodi_csvlint.rb
train
84d8892b18899fb95e6395bfea30af1341c3d985
diff --git a/multiqc/modules/bismark/bismark.py b/multiqc/modules/bismark/bismark.py index <HASH>..<HASH> 100755 --- a/multiqc/modules/bismark/bismark.py +++ b/multiqc/modules/bismark/bismark.py @@ -178,16 +178,32 @@ class MultiqcModule(BaseMultiqcModule): headers = OrderedDict() headers['percent_cpg_meth'] = { - 'title': '% Meth', - 'description': '% Cytosines methylated in CpG context (alignment)', + 'title': '% mCpG', + 'description': '% Cytosines methylated in CpG context', 'max': 100, 'min': 0, 'scale': 'Greens', 'format': '{:.1f}%' } + headers['percent_chg_meth'] = { + 'title': '% mCHG', + 'description': '% Cytosines methylated in CHG context', + 'max': 100, + 'min': 0, + 'scale': 'Oranges', + 'format': '{:.1f}%' + } + headers['percent_chh_meth'] = { + 'title': '% mCHH', + 'description': '% Cytosines methylated in CHH context', + 'max': 100, + 'min': 0, + 'scale': 'Oranges', + 'format': '{:.1f}%' + } headers['total_c'] = { 'title': "M C's", - 'description': 'Total number of C\'s analysed, in millions (alignment)', + 'description': 'Total number of C\'s analysed, in millions', 'min': 0, 'scale': 'Purples', 'modify': lambda x: x / 1000000
Added % mCHG / mCHH to general stats table for bismark.
ewels_MultiQC
train
6881e969677e907fc3f772457e322b3efaa778fa
diff --git a/tests/test_manager.py b/tests/test_manager.py index <HASH>..<HASH> 100644 --- a/tests/test_manager.py +++ b/tests/test_manager.py @@ -333,31 +333,45 @@ class TestManager(TestCase): tty = MockTTY() with mock.patch('%s.reset' % TERMINAL) as reset: - manager = _manager.Manager(stream=tty.stdout, counter_class=MockCounter) - term = manager.term - - # process_exit is False - manager._at_exit() - self.assertFalse(reset.called) - # No output - tty.stdout.write('X\n') - self.assertEqual(tty.stdread.readline(), 'X\n') - - # process_exit is True, set_scroll False - manager.process_exit = True - manager.set_scroll = False - manager._at_exit() - self.assertFalse(reset.called) - self.assertEqual(tty.stdread.readline(), term.move(25, 0) + term.cud1) - - # process_exit is True, set_scroll True - manager.set_scroll = True - manager._at_exit() - self.assertEqual(reset.call_count, 1) - self.assertEqual(tty.stdread.readline(), term.cud1) - - tty.close() - manager._at_exit() + with mock.patch.object(tty.stdout, 'flush') as flush: + manager = _manager.Manager(stream=tty.stdout, counter_class=MockCounter) + term = manager.term + + # process_exit is False + manager._at_exit() + self.assertFalse(reset.called) + self.assertFalse(flush.called) + # No output + tty.stdout.write('X\n') + self.assertEqual(tty.stdread.readline(), 'X\n') + + # process_exit is True, set_scroll False + manager.process_exit = True + manager.set_scroll = False + manager._at_exit() + self.assertFalse(reset.called) + self.assertEqual(flush.call_count, 1) + self.assertEqual(tty.stdread.readline(), term.move(25, 0) + term.cud1) + + # process_exit is True, set_scroll True + manager.set_scroll = True + manager._at_exit() + self.assertEqual(reset.call_count, 1) + self.assertEqual(flush.call_count, 2) + self.assertEqual(tty.stdread.readline(), term.cud1) + + # Ensure companion stream gets flushed + manager.companion_stream = tty.stdout + manager._at_exit() + self.assertEqual(reset.call_count, 2) + self.assertEqual(flush.call_count, 4) + self.assertEqual(tty.stdread.readline(), term.cud1) + + term = manager.term + + # Ensure no errors if tty closes before _at_exit is called + tty.close() + manager._at_exit() def test_stop(self):
Add tests for at_exit flush
Rockhopper-Technologies_enlighten
train
e1d972629b56f364d72447351725f2ea27825f89
diff --git a/lib/kappa/connection.rb b/lib/kappa/connection.rb index <HASH>..<HASH> 100644 --- a/lib/kappa/connection.rb +++ b/lib/kappa/connection.rb @@ -23,10 +23,6 @@ module Kappa def get(path, query = nil) request_url = @base_url + path - # Handle non-JSON response - # Handle invalid JSON - # Handle non-200 codes - headers = { 'Client-ID' => @client_id, }.merge(custom_headers) @@ -35,6 +31,10 @@ module Kappa self.class.get(request_url, :headers => headers, :query => query) end + # TODO: Handle non-JSON response + # TODO: Handle invalid JSON + # TODO: Handle non-200 codes + json = response.body return JSON.parse(json) end diff --git a/lib/kappa/version.rb b/lib/kappa/version.rb index <HASH>..<HASH> 100644 --- a/lib/kappa/version.rb +++ b/lib/kappa/version.rb @@ -1 +1 @@ -$version = '0.1.4.pre' +$version = '0.1.5.pre'
Bumping version, adding TODOs.
schmich_kappa
train
839e0f1e16f1c8b3a55dbfa5061cb4d9833db710
diff --git a/lib/waterline/methods/replace-collection.js b/lib/waterline/methods/replace-collection.js index <HASH>..<HASH> 100644 --- a/lib/waterline/methods/replace-collection.js +++ b/lib/waterline/methods/replace-collection.js @@ -463,11 +463,16 @@ module.exports = function replaceCollection(/* targetRecordIds?, collectionAttrN // Now we'll build and potentially execute an update query that will null out // the foreign key on associated child records. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // FUTURE: Two things: - // (A) avoid this first "null-out" query unless there are zero associated ids - // (B) and even in that case, if this attribute is a REQUIRED singular association, - // and we're not in a state where we can just skip it, then use a better error - // message. + // FUTURE: Three things: + // (A) avoid this first "null-out" query altogether if there are zero matches + // (B) exclude any `associatedIds` from this first "null-out" query (using `nin`) + // (C) if there are >=1 matches and the foreign key attribute is a REQUIRED + // singular association, then use a better error message that explains + // what's wrong (i.e. it should suggest that you probably need to destroy + // orphaned child records before attempting to null out replace their containing + // collection. For example, if you have a car with four tires, and you set out + // to replace the four old tires with only three new ones, then you'll need to + // destroy the spare tire before attempting to call `Car.replaceCollection()`) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - var nullOutCriteria = {
Fix typo in null out query caveat, and add more details
balderdashy_waterline
train
1e8d4eb412c89960010917a263cd73fc8eb6231d
diff --git a/PPI/ServiceManager/Factory/ConfigFactory.php b/PPI/ServiceManager/Factory/ConfigFactory.php index <HASH>..<HASH> 100644 --- a/PPI/ServiceManager/Factory/ConfigFactory.php +++ b/PPI/ServiceManager/Factory/ConfigFactory.php @@ -9,7 +9,6 @@ namespace PPI\ServiceManager\Factory; -use PPI\ServiceManager\ParameterBag; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\Stdlib\ArrayUtils; @@ -46,15 +45,12 @@ class ConfigFactory implements FactoryInterface $serviceLocator->get('ApplicationConfig') ); - $appParameters = $serviceLocator->get('ApplicationParameters'); + $parametersBag = $serviceLocator->get('ApplicationParameters'); $config['parameters'] = isset($config['parameters']) ? - ArrayUtils::merge($appParameters, $config['parameters']) : - $config['parameters'] = $appParameters; + ArrayUtils::merge($parametersBag->all(), $config['parameters']) : + $config['parameters'] = $parametersBag->all(); - $parameterBag = new ParameterBag($config['parameters']); - $parameterBag->resolve(); - - return $parameterBag->resolveArray($config); + return $parametersBag->resolveArray($config); } } diff --git a/PPI/ServiceManager/ServiceManagerBuilder.php b/PPI/ServiceManager/ServiceManagerBuilder.php index <HASH>..<HASH> 100644 --- a/PPI/ServiceManager/ServiceManagerBuilder.php +++ b/PPI/ServiceManager/ServiceManagerBuilder.php @@ -9,6 +9,8 @@ namespace PPI\ServiceManager; +use PPI\ServiceManager\ParameterBag; + /** * ServiceManager builder. * @@ -41,8 +43,10 @@ class ServiceManagerBuilder extends ServiceManager $this->config['framework'] = array(); } - $this->setService('ApplicationConfig', $this->config); - $this->setService('ApplicationParameters', $parameters); + $parametersBag = new ParameterBag($parameters); + $parametersBag->resolve(); + $this->setService('ApplicationParameters', $parametersBag); + $this->setService('ApplicationConfig', $parametersBag->resolveArray($this->config)); foreach(array( new Config\MonologConfig(),
Move the parameters resolver back to ServiceManagerBuilder so cache paths are available before the "Config" service initialization
ppi_framework
train
02245502debda81d8b7fcef9a393b56796bd22c8
diff --git a/python/phonenumbers/shortnumberinfo.py b/python/phonenumbers/shortnumberinfo.py index <HASH>..<HASH> 100644 --- a/python/phonenumbers/shortnumberinfo.py +++ b/python/phonenumbers/shortnumberinfo.py @@ -190,7 +190,7 @@ def expected_cost_for_region(short_numobj, region_dialing_from): # The possible lengths are not present for a particular sub-type if they match the general # description; for this reason, we check the possible lengths against the general description # first to allow an early exit if possible. - if not(len(short_number) in metadata.general_desc.possible_length): + if not (len(short_number) in metadata.general_desc.possible_length): return ShortNumberCost.UNKNOWN_COST # The cost categories are tested in order of decreasing expense, since if
Fix new lint from pycodestyle <I>
daviddrysdale_python-phonenumbers
train
3676616ec14304856a978e7429752880db16d18f
diff --git a/java-lwjgl/src/playn/java/GLFWInput.java b/java-lwjgl/src/playn/java/GLFWInput.java index <HASH>..<HASH> 100644 --- a/java-lwjgl/src/playn/java/GLFWInput.java +++ b/java-lwjgl/src/playn/java/GLFWInput.java @@ -118,8 +118,7 @@ public class GLFWInput extends JavaInput { "Use the java-swt backend if you need native dialogs."; @Override public RFuture<String> getText(TextType textType, String label, String initVal) { - if (plat.needsHeadless()) return RFuture.failure( - new UnsupportedOperationException(NO_UI_ERROR)); + if (plat.needsHeadless()) throw new UnsupportedOperationException(NO_UI_ERROR); Object result = JOptionPane.showInputDialog( null, label, "", JOptionPane.QUESTION_MESSAGE, null, null, initVal); @@ -128,8 +127,7 @@ public class GLFWInput extends JavaInput { @Override public RFuture<Boolean> sysDialog(String title, String text, String ok, String cancel) { - if (plat.needsHeadless()) return RFuture.failure( - new UnsupportedOperationException(NO_UI_ERROR)); + if (plat.needsHeadless()) throw new UnsupportedOperationException(NO_UI_ERROR); int optType = JOptionPane.OK_CANCEL_OPTION; int msgType = cancel == null ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.QUESTION_MESSAGE;
Just throw those errors directly. Putting them in the future is asking for them to be ignored and cause confusion.
playn_playn
train
a29e08c22e6d063a15a27ba5ca6adee043dad364
diff --git a/admin/dashboard/app/pages/page-controller.js b/admin/dashboard/app/pages/page-controller.js index <HASH>..<HASH> 100644 --- a/admin/dashboard/app/pages/page-controller.js +++ b/admin/dashboard/app/pages/page-controller.js @@ -122,6 +122,9 @@ adminApp.controller("PageController", if(page.parent && page.parent._id) { page.parent = page.parent._id; } + if(page.redirect && page.redirect._id) { + page.redirect = page.redirect._id; + } page.regions = page.regions.filter(function(region) { return typeof region === 'object'; }).map(function(region) { diff --git a/admin/dashboard/app/pages/site-map.html b/admin/dashboard/app/pages/site-map.html index <HASH>..<HASH> 100644 --- a/admin/dashboard/app/pages/site-map.html +++ b/admin/dashboard/app/pages/site-map.html @@ -7,8 +7,12 @@ <span class="glyphicon glyphicon-plus"></span> </button> - <a href="#/pages/{{page._id}}" ng-if="!page.redirect">{{page.name}}<span ng-show="page.draft"><b>*</b></span></a> - <a href="#/pages/{{page.redirect._id}}" ng-if="page.redirect">Redirect to {{page.redirect.name}}</a> + <a href="#/pages/{{page._id}}" ng-if="!page.redirect" title="{{page.name}}"> + <span ng-show="page.draft"><b>*</b></span>{{page.name}} + </a> + <a href="#/pages/{{page._id}}" ng-if="page.redirect" title="{{page.name}} &gt; {{page.redirect.name}}"> + {{page.name}} &gt; {{page.redirect.name}} + </a> </div> <ul ng-if="page.children.length"> diff --git a/admin/dashboard/app/pages/sitemap-controller.js b/admin/dashboard/app/pages/sitemap-controller.js index <HASH>..<HASH> 100644 --- a/admin/dashboard/app/pages/sitemap-controller.js +++ b/admin/dashboard/app/pages/sitemap-controller.js @@ -23,6 +23,12 @@ adminApp.controller("SitemapController", function($scope, $rootScope, $location, var pageMap = {}; allPages = allPages.filter(function(page) { return page.status < 400; + }).sort(function(a, b) { + if (a.order < b.order) + return -1; + if (a.order > b.order) + return 1; + return 0; }); allPages.forEach(function(page) { pageMap[page._id] = page; @@ -35,12 +41,6 @@ adminApp.controller("SitemapController", function($scope, $rootScope, $location, currentPage.children = allPages.filter(function(childCandidate) { var candidateParentId = childCandidate.parent ? childCandidate.parent._id : null; return currentPage._id === candidateParentId; - }).sort(function(a, b) { - if (a.order < b.order) - return -1; - if (a.order > b.order) - return 1; - return 0; }); if(currentPage.children.length > 0) { populateChildren(currentPage.children);
Improving redirect ui and fixing ordering
pagespace_pagespace
train
1920ed1a0421636f9d19bb5bbde710c4cc3ea5d9
diff --git a/lib/ui/src/modules/ui/configs/handle_routing.js b/lib/ui/src/modules/ui/configs/handle_routing.js index <HASH>..<HASH> 100755 --- a/lib/ui/src/modules/ui/configs/handle_routing.js +++ b/lib/ui/src/modules/ui/configs/handle_routing.js @@ -40,7 +40,7 @@ export function getUrlState(data) { }; } -export function changeUrl(clientStore) { +export function changeUrl(clientStore, usePush) { // Do not change the URL if we are inside a popState event. if (config.insidePopState) return; @@ -48,7 +48,7 @@ export function changeUrl(clientStore) { if (!data.selectedKind) return; const state = getUrlState(data); - window.history.pushState(state, '', state.url); + window.history[usePush ? 'pushState' : 'replaceState'](state, '', state.url); } export function updateStore(queryParams, actions) { @@ -92,8 +92,22 @@ export default function({ clientStore }, actions) { // handle initial URL handleInitialUrl(actions, window.location); + const data = clientStore.getAll(); + let prevKind = data.selectedKind; + let prevStory = data.selectedStory; + // subscribe to clientStore and change the URL - clientStore.subscribe(() => changeUrl(clientStore)); + clientStore.subscribe(() => { + const { selectedKind, selectedStory } = clientStore.getAll(); + // use pushState only when a new story is selected + const usePush = + prevKind != null && + prevStory != null && + (selectedKind !== prevKind || selectedStory !== prevStory); + changeUrl(clientStore, usePush); + prevKind = selectedKind; + prevStory = selectedStory; + }); changeUrl(clientStore); // handle back button diff --git a/lib/ui/src/modules/ui/configs/handle_routing.test.js b/lib/ui/src/modules/ui/configs/handle_routing.test.js index <HASH>..<HASH> 100755 --- a/lib/ui/src/modules/ui/configs/handle_routing.test.js +++ b/lib/ui/src/modules/ui/configs/handle_routing.test.js @@ -10,7 +10,7 @@ describe('manager.ui.config.handle_routing', () => { config.insidePopState = false; }); - test('should put the correct URL and state to pushState', done => { + test('should put the correct URL and state to replaceState', done => { const state = { selectedKind: 'kk', selectedStory: 'ss', @@ -31,7 +31,7 @@ describe('manager.ui.config.handle_routing', () => { const url = '?customText=test&selectedKind=kk&selectedStory=ss&full=0&down=1&left=1&panelRight=1&downPanel=pp'; - const pushState = { + const replaceState = { url, selectedKind: 'kk', selectedStory: 'ss', @@ -42,16 +42,16 @@ describe('manager.ui.config.handle_routing', () => { downPanel: 'pp', customText: 'test', }; - const originalPushState = window.history.pushState; - window.history.pushState = (s, t, u) => { - expect(s).toEqual(pushState); - expect(u).toBe(pushState.url); + const originalReplaceState = window.history.replaceState; + window.history.replaceState = (s, t, u) => { + expect(s).toEqual(replaceState); + expect(u).toBe(replaceState.url); done(); }; changeUrl(clientStore); - window.history.pushState = originalPushState; + window.history.replaceState = originalReplaceState; }); });
Use replaceState instead of pushState when the story stays the same
storybooks_storybook
train
ec3de539c6e486c96dab1b54c418d5692c69f098
diff --git a/webapps/ui/admin/client/scripts/camunda-admin-ui.js b/webapps/ui/admin/client/scripts/camunda-admin-ui.js index <HASH>..<HASH> 100644 --- a/webapps/ui/admin/client/scripts/camunda-admin-ui.js +++ b/webapps/ui/admin/client/scripts/camunda-admin-ui.js @@ -100,12 +100,6 @@ var pagesModule = require('./pages/main'), $(document).ready(function () { angular.bootstrap(document, [ appNgModule.name ]); - var html = document.getElementsByTagName('html')[0]; - - html.setAttribute('ng-app', appNgModule.name); - if (html.dataset) { - html.dataset.ngApp = appNgModule.name; - } if (top !== window) { window.parent.postMessage({ type: 'loadamd' }, '*'); diff --git a/webapps/ui/cockpit/client/scripts/camunda-cockpit-ui.js b/webapps/ui/cockpit/client/scripts/camunda-cockpit-ui.js index <HASH>..<HASH> 100644 --- a/webapps/ui/cockpit/client/scripts/camunda-cockpit-ui.js +++ b/webapps/ui/cockpit/client/scripts/camunda-cockpit-ui.js @@ -90,12 +90,6 @@ var angular = require('angular'); }]); angular.bootstrap(document, [ appNgModule.name ]); - var html = document.getElementsByTagName('html')[0]; - - html.setAttribute('ng-app', appNgModule.name); - if (html.dataset) { - html.dataset.ngApp = appNgModule.name; - } if (top !== window) { window.parent.postMessage({ type: 'loadamd' }, '*');
refactor(app-bootstraping): remove html ng-app attribute
camunda_camunda-bpm-platform
train
0cb7c5e4a62eacfee2e2ce4b0e17fa4d7e1a1320
diff --git a/superset/migrations/versions/21e88bc06c02_annotation_migration.py b/superset/migrations/versions/21e88bc06c02_annotation_migration.py index <HASH>..<HASH> 100644 --- a/superset/migrations/versions/21e88bc06c02_annotation_migration.py +++ b/superset/migrations/versions/21e88bc06c02_annotation_migration.py @@ -37,18 +37,19 @@ def upgrade(): Slice.viz_type.like('line'), Slice.viz_type.like('bar'))): params = json.loads(slc.params) layers = params.get('annotation_layers', []) - new_layers = [] - if len(layers) and isinstance(layers[0], int): + if layers: + new_layers = [] for layer in layers: - new_layers.append( - { - 'annotationType': 'INTERVAL', - 'style': 'solid', - 'name': 'Layer {}'.format(layer), - 'show': True, - 'overrides': {'since': None, 'until': None}, - 'value': 1, 'width': 1, 'sourceType': 'NATIVE', - }) + new_layers.append({ + 'annotationType': 'INTERVAL', + 'style': 'solid', + 'name': 'Layer {}'.format(layer), + 'show': True, + 'overrides': {'since': None, 'until': None}, + 'value': layer, + 'width': 1, + 'sourceType': 'NATIVE', + }) params['annotation_layers'] = new_layers slc.params = json.dumps(params) session.merge(slc) @@ -57,4 +58,16 @@ def upgrade(): def downgrade(): - pass + bind = op.get_bind() + session = db.Session(bind=bind) + + for slc in session.query(Slice).filter(or_( + Slice.viz_type.like('line'), Slice.viz_type.like('bar'))): + params = json.loads(slc.params) + layers = params.get('annotation_layers', []) + if layers: + params['annotation_layers'] = [layer['value'] for layer in layers] + slc.params = json.dumps(params) + session.merge(slc) + session.commit() + session.close()
[annotations] Fixing migration for annotation layers (#<I>)
apache_incubator-superset
train
f8db672e99f903c4d93f0de3e32903b29cfec37d
diff --git a/test/test_uri.py b/test/test_uri.py index <HASH>..<HASH> 100644 --- a/test/test_uri.py +++ b/test/test_uri.py @@ -4,7 +4,7 @@ from __future__ import unicode_literals import pytest -from uri.compat import SENTINEL, Path +from uri.compat import SENTINEL, Path, str from uri.uri import URI URI_COMPONENTS = [ @@ -267,6 +267,18 @@ class TestURIBasics(object): def test_group_assignment(self, empty): with pytest.raises(TypeError): empty.authority = "bobdole.com" + + def test_protocol_assignment(self, empty): + assert empty.scheme == 'http' + + empty.scheme = b'ftp' + assert empty.scheme == 'ftp' + + def test_empty_protocol_assignment(self, empty): + assert empty.scheme == 'http' + + empty.scheme = None + assert str(empty) == "example.com/over/there" class TestURIDictlike(object):
Added tests for scheme reassignment and clearing.
marrow_uri
train
ea9b12fdd049d8072eec08927aacbd01a9adc2b5
diff --git a/code/dataobjects/WorkflowInstance.php b/code/dataobjects/WorkflowInstance.php index <HASH>..<HASH> 100755 --- a/code/dataobjects/WorkflowInstance.php +++ b/code/dataobjects/WorkflowInstance.php @@ -230,6 +230,24 @@ class WorkflowInstance extends DataObject { $this->execute(); } + /** + * Returns a set of all Members that are assigned to this instance, either directly or via a group. + * + * @todo This could be made more efficient. + * @return DataObjectSet + */ + public function getAssignedMembers() { + $members = $this->Users(); + $groups = $this->Groups(); + + foreach($groups as $group) { + $members->merge($group->Members()); + } + + $members->removeDuplicates(); + return $members; + } + public function canView($member=null) { return $this->userHasAccess($member); }
ENHANCEMENT: Added WorkflowInstance->getAssignedMembers() to return all members assigned to a workflow.
symbiote_silverstripe-advancedworkflow
train
35d1d7c91f742a9dd6547d9cadc0236196c4b69d
diff --git a/betfair/models.py b/betfair/models.py index <HASH>..<HASH> 100644 --- a/betfair/models.py +++ b/betfair/models.py @@ -172,7 +172,7 @@ class MarketBook(BetfairModel): class RunnerProfitAndLoss(BetfairModel): - selection_id = Field(DataType(float)) + selection_id = Field(DataType(int)) if_win = Field(DataType(float)) if_lose = Field(DataType(float))
Change RunnerProfitAndLoss.selection_id type to int Previously RunnerProfitAndLoss.selection_id was declared to be a float, however the API documentation says that it is a long: <URL> will return a long if the number is big enough to require it).
jmcarp_betfair.py
train
8408ffb25c9104093097a6e401f51eaff5555fd7
diff --git a/spec/helpers.rb b/spec/helpers.rb index <HASH>..<HASH> 100644 --- a/spec/helpers.rb +++ b/spec/helpers.rb @@ -1,10 +1,23 @@ require 'uri' module Helpers + + # @param [Hash] opts A hash of methods, passed directly to the double + # definition. Use this to stub other required methods. + # + # @return double for Net::HTTPResponse def res_double(opts={}) - double('Net::HTTPResponse', {to_hash: {}, body: 'response body'}.merge(opts)) + instance_double('Net::HTTPResponse', {to_hash: {}, body: 'response body'}.merge(opts)) end + # Given a Net::HTTPResponse or double and a Request or double, create a + # RestClient::Response object. + # + # @param net_http_res_double an rspec double for Net::HTTPResponse + # @param request A RestClient::Request or rspec double + # + # @return [RestClient::Response] + # def response_from_res_double(net_http_res_double, request=nil, duration: 1) request ||= request_double() start_time = Time.now - duration @@ -17,6 +30,7 @@ module Helpers response end + # Redirect stderr to a string for the duration of the passed block. def fake_stderr original_stderr = $stderr $stderr = StringIO.new @@ -26,9 +40,11 @@ module Helpers $stderr = original_stderr end + # Create a double for RestClient::Request def request_double(url: 'http://example.com', method: 'get') - double('request', url: url, uri: URI.parse(url), method: method, - user: nil, password: nil, cookie_jar: HTTP::CookieJar.new, - redirection_history: nil, args: {url: url, method: method}) + instance_double('RestClient::Request', + url: url, uri: URI.parse(url), method: method, user: nil, password: nil, + cookie_jar: HTTP::CookieJar.new, redirection_history: nil, + args: {url: url, method: method}) end end diff --git a/spec/unit/abstract_response_spec.rb b/spec/unit/abstract_response_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/abstract_response_spec.rb +++ b/spec/unit/abstract_response_spec.rb @@ -2,21 +2,21 @@ require_relative '_lib' describe RestClient::AbstractResponse, :include_helpers do + # Sample class implementing AbstractResponse used for testing. class MyAbstractResponse include RestClient::AbstractResponse attr_accessor :size - def initialize net_http_res, request - @net_http_res = net_http_res - @request = request + def initialize(net_http_res, request) + response_set_vars(net_http_res, request, Time.now - 1) end end before do - @net_http_res = double('net http response') + @net_http_res = res_double() @request = request_double(url: 'http://example.com', method: 'get') @response = MyAbstractResponse.new(@net_http_res, @request) end @@ -92,8 +92,8 @@ describe RestClient::AbstractResponse, :include_helpers do it 'handles cookies when URI scheme is implicit' do net_http_res = double('net http response') expect(net_http_res).to receive(:to_hash).and_return('set-cookie' => ['session_id=1; path=/']) - request = double(url: 'example.com', uri: URI.parse('http://example.com'), - method: 'get', cookie_jar: HTTP::CookieJar.new) + request = double('request', url: 'example.com', uri: URI.parse('http://example.com'), + method: 'get', cookie_jar: HTTP::CookieJar.new, redirection_history: nil) response = MyAbstractResponse.new(net_http_res, request) expect(response.cookie_jar).to be_a HTTP::CookieJar @@ -135,7 +135,7 @@ describe RestClient::AbstractResponse, :include_helpers do end it "should gracefully handle 302 redirect with no location header" do - @net_http_res = res_double(code: 302, location: nil) + @net_http_res = res_double(code: 302) @request = request_double() @response = MyAbstractResponse.new(@net_http_res, @request) expect(@response).to receive(:check_max_redirects).and_return('fake-check')
Helpers: switch to verifying instance_double.
rest-client_rest-client
train
e5e448c864391df161341d0a4cc2c49e493e3081
diff --git a/app/controllers/notee/application_controller.rb b/app/controllers/notee/application_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/notee/application_controller.rb +++ b/app/controllers/notee/application_controller.rb @@ -3,14 +3,19 @@ module Notee before_action :restrict_access_json def restrict_access_json - raise unless confirm_exist_token - raise unless confirm_expired_token + redirect_to new_token_path && return unless confirm_expired_token + redirect_to new_token_path && return unless confirm_exist_token end private def confirm_exist_token - Token.exists?(access_token: session[:access_token]) + if Token.exists?(access_token: session[:access_token]) + return true + else + session.delete(:access_token) + return false + end end def confirm_expired_token
fixed method {add to redirect function in restrict_access_json}
maru-u_notee
train
76971686c875e5f570a3852973bb928db58c8a86
diff --git a/src/styled/utilities/tests/transition.test.js b/src/styled/utilities/tests/transition.test.js index <HASH>..<HASH> 100644 --- a/src/styled/utilities/tests/transition.test.js +++ b/src/styled/utilities/tests/transition.test.js @@ -7,27 +7,27 @@ describe('bootstrap transition mixins', () => { const css = getTransitionUtilities(enableTransitions, 'all .2s ease-in-out', 'height .35s ease'); expect(css).not.toContain('undefined'); expect(css).not.toContain('null'); - expect(fromJS({ css }).hashCode()).toEqual(-1062749687); + expect(fromJS({ css }).hashCode()).toEqual(6006592); }); it('getTransitionUtils should have parameters', () => { const css = getTransitionUtilities(); expect(css).not.toContain('undefined'); expect(css).not.toContain('null'); - expect(fromJS({ css }).hashCode()).toEqual(11101159); + expect(fromJS({ css }).hashCode()).toEqual(419397045); }); it('fade should return a css with defaultProps', () => { const css = fade(); - expect(fromJS({ css }).hashCode()).toEqual(747721370); + expect(fromJS({ css }).hashCode()).toEqual(-297507179); }); it('fade should return a css with transition', () => { const enableTransitions = true; const css = fade(enableTransitions, 'opacity .15s linear'); - expect(fromJS({ css }).hashCode()).toEqual(747721370); + expect(fromJS({ css }).hashCode()).toEqual(-297507179); }); it('fade should return a css without transition', () => { const enableTransitions = false; const css = fade(enableTransitions, 'opacity .15s linear'); - expect(fromJS({ css }).hashCode()).toEqual(432666126); + expect(fromJS({ css }).hashCode()).toEqual(-1046095170); }); it('collapse should return a css with defaultProps', () => { const css = collapse(); diff --git a/src/styled/utilities/transition.js b/src/styled/utilities/transition.js index <HASH>..<HASH> 100644 --- a/src/styled/utilities/transition.js +++ b/src/styled/utilities/transition.js @@ -15,7 +15,8 @@ export function getTransitionUtilities( export function fade(enableTransitions = defaultProps['$enable-transitions'], transitionFade = defaultProps['$transition-fade']) { return ` - &.fade { + .fade, + &.fade { opacity: 0; ${transition(enableTransitions, transitionFade)}
extended .fade class to component adn child component so that it may be applied in alls ituations (alert or modal for example)
bootstrap-styled_bootstrap-styled
train
10c7c344f8a98bd4376469ec7597b0fcf9a5263f
diff --git a/src/Model/Tables/MelisCmsSiteHomeTable.php b/src/Model/Tables/MelisCmsSiteHomeTable.php index <HASH>..<HASH> 100644 --- a/src/Model/Tables/MelisCmsSiteHomeTable.php +++ b/src/Model/Tables/MelisCmsSiteHomeTable.php @@ -36,6 +36,19 @@ class MelisCmsSiteHomeTable extends MelisGenericTable return $data; } + public function getHomePageBySiteId($siteId) + { + $select = $this->tableGateway->getSql()->select(); + + if (!empty($siteId) && !is_null($siteId)) { + $select->where->equalTo("melis_cms_site_home.shome_site_id", $siteId); + } + + $data = $this->tableGateway->selectWith($select); + + return $data; + } + public function deleteHomePageId($id, $siteId, $langId, $pageId) { $delete = $this->tableGateway->getSql()->delete(null);
get home page id by site id
melisplatform_melis-engine
train
c195cab964e4d773ed654ea6cb1e3764338672af
diff --git a/src/frontend/org/voltdb/dbmonitor/js/voltdb.render.js b/src/frontend/org/voltdb/dbmonitor/js/voltdb.render.js index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/dbmonitor/js/voltdb.render.js +++ b/src/frontend/org/voltdb/dbmonitor/js/voltdb.render.js @@ -94,7 +94,7 @@ function alertNodeClicked(obj) { '<!-- POPUP Login -->' + '<div id="loginBoxDialogue" style="overflow: hidden" >' + '<div class="overlay-title">Login</div>' + - '<div id="UnableToLoginMsg" style="padding: 5px 0 0 20px; color: #ff0000; display: none;">Unable to connect!! Please try to login using another username/password.</div>' + + '<div id="UnableToLoginMsg" style="padding: 5px 0 0 20px; color: #ff0000; display: none;">Unable to connect. Please try to login using another username/password.</div>' + '<div class="clear"></div>' + '<div class="overlay-content" style="height:215px; min-width: 441px; padding: 0" >' + '<div id="loginBox">' + @@ -354,7 +354,7 @@ function alertNodeClicked(obj) { this.GetClusterHealth = function (callback) { if (systemOverview == null || systemOverview == undefined) { - alert("Error: Unable to extract cluster health information!!"); + alert("Error: Unable to extract cluster health information."); return; }
Removed the exclamation marks from all the error messages.
VoltDB_voltdb
train
5b22affa4c0528fcf065d50454c0002d3ce9a70e
diff --git a/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/ranking/SingleBenchmarkRankingComparator.java b/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/ranking/SingleBenchmarkRankingComparator.java index <HASH>..<HASH> 100644 --- a/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/ranking/SingleBenchmarkRankingComparator.java +++ b/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/ranking/SingleBenchmarkRankingComparator.java @@ -29,10 +29,11 @@ public class SingleBenchmarkRankingComparator implements Comparator<SingleBenchm @Override public int compare(SingleBenchmarkResult a, SingleBenchmarkResult b) { - return new CompareToBuilder() - .append(b.hasAnyFailure(), a.hasAnyFailure()) // Reverse, less is better (redundant: failed benchmarks don't get ranked at all) - .append(a.getAverageScore(), b.getAverageScore(), resilientScoreComparator) - .toComparison(); + return Comparator + // Reverse, less is better (redundant: failed benchmarks don't get ranked at all) + .comparing(SingleBenchmarkResult::hasAnyFailure, Comparator.reverseOrder()) + .thenComparing(SingleBenchmarkResult::getAverageScore, resilientScoreComparator) + .compare(a, b); } }
PLANNER-<I> Replace CompareToBuilder with Comparator.comparing(...)
kiegroup_optaplanner
train
14cc7990b2f7df78d90f29096f1006a1def94c60
diff --git a/juicer/admin/JuicerAdmin.py b/juicer/admin/JuicerAdmin.py index <HASH>..<HASH> 100644 --- a/juicer/admin/JuicerAdmin.py +++ b/juicer/admin/JuicerAdmin.py @@ -257,7 +257,7 @@ class JuicerAdmin(object): juicer.utils.Log.log_info("Login: %s" % user['login']) juicer.utils.Log.log_info("Name: %s" % user['name']) - juicer.utils.Log.log_info("Roles: %s" % user['roles']) + juicer.utils.Log.log_info("Roles: %s" % ', '.join(user['roles'])) if count < len(envs): # just want a new line
un-uglify roles in show-user for #<I>
juicer_juicer
train
47846685af896dfd361faddfa1aa75546c904cac
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ requirements = ( setup( name='combine', - version='0.0.17', + version='0.0.18.dev0', description='A helpful, simple static site generator.', long_description=long_description, long_description_content_type='text/markdown',
Back to development: <I>
dropseed_combine
train
9df8a85aa7a9c09f9a80acd8a13459fbb9f5c999
diff --git a/packages/core-js/modules/es.object.get-own-property-names.js b/packages/core-js/modules/es.object.get-own-property-names.js index <HASH>..<HASH> 100644 --- a/packages/core-js/modules/es.object.get-own-property-names.js +++ b/packages/core-js/modules/es.object.get-own-property-names.js @@ -1,5 +1,5 @@ var nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names-external').f; -var FAILS_ON_PRIMITIVES = require('../internals/fails')(function () { Object.getOwnPropertyNames(1); }); +var FAILS_ON_PRIMITIVES = require('../internals/fails')(function () { return !Object.getOwnPropertyNames(1); }); // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
Adds workaround for rollup treeshaking issue rollup treeshaking is removing the Object.getOwnPropertyNames FAILS_ON_PRIMITIVES feature test. This is related to these rollup issue <URL>
zloirock_core-js
train
180fad313a1a45078b015f39e70defb551d2e1e9
diff --git a/prestans/testsuite/test_types.py b/prestans/testsuite/test_types.py index <HASH>..<HASH> 100644 --- a/prestans/testsuite/test_types.py +++ b/prestans/testsuite/test_types.py @@ -220,6 +220,8 @@ class FloatTypeUnitTest(unittest.TestCase): self.assertRaises(prestans.exception.InvalidChoiceError, self.choices.validate, 0.0) self.assertRaises(prestans.exception.InvalidChoiceError, self.choices.validate, 2.0) self.assertRaises(prestans.exception.InvalidChoiceError, self.choices.validate, 4.0) + self.assertEqual(self.choices.validate(1.0), 1.0) + self.assertEqual(self.choices.validate(3.0), 3.0) def tearDown(self): pass
more choices unit test for float #<I>
anomaly_prestans
train
f47c05384edfa83c679558b11cdc8190fc3a7d8a
diff --git a/src/Brainwave/Support/Collection.php b/src/Brainwave/Support/Collection.php index <HASH>..<HASH> 100644 --- a/src/Brainwave/Support/Collection.php +++ b/src/Brainwave/Support/Collection.php @@ -104,12 +104,15 @@ class Collection implements /** * Get the max value of a given key. * - * @param string $key + * @param string|null $key + * * @return mixed */ - public function max($key) + public function max($key = null) { return $this->reduce(function ($result, $item) use ($key) { + $value = Arr::dataGet($item, $key); + return is_null($result) || $item->{$key} > $result ? $item->{$key} : $result; }); } @@ -117,13 +120,16 @@ class Collection implements /** * Get the min value of a given key. * - * @param string $key + * @param string|null $key + * * @return mixed */ - public function min($key) + public function min($key = null) { return $this->reduce(function ($result, $item) use ($key) { - return is_null($result) || $item->{$key} < $result ? $item->{$key} : $result; + $value = Arr::dataGet($item, $key); + + return is_null($result) || $value < $result ? $value : $result; }); } diff --git a/src/Brainwave/Support/Tests/CollectionTest.php b/src/Brainwave/Support/Tests/CollectionTest.php index <HASH>..<HASH> 100644 --- a/src/Brainwave/Support/Tests/CollectionTest.php +++ b/src/Brainwave/Support/Tests/CollectionTest.php @@ -370,6 +370,36 @@ class SupportCollectionTest extends \PHPUnit_Framework_TestCase $this->assertEquals(['foo', 'bar'], $data->pluck('email')->all()); } + public function testGettingMaxItemsFromCollection() + { + $c = new Collection([(object) ['foo' => 10], (object) ['foo' => 20]]); + $this->assertEquals(20, $c->max('foo')); + + $c = new Collection([['foo' => 10], ['foo' => 20]]); + $this->assertEquals(20, $c->max('foo')); + + $c = new Collection([1, 2, 3, 4, 5]); + $this->assertEquals(5, $c->max()); + + $c = new Collection(); + $this->assertNull($c->max()); + } + + public function testGettingMinItemsFromCollection() + { + $c = new Collection([(object) ['foo' => 10], (object) ['foo' => 20]]); + $this->assertEquals(10, $c->min('foo')); + + $c = new Collection([['foo' => 10], ['foo' => 20]]); + $this->assertEquals(10, $c->min('foo')); + + $c = new Collection([1, 2, 3, 4, 5]); + $this->assertEquals(1, $c->min()); + + $c = new Collection(); + $this->assertNull($c->min()); + } + public function testImplode() { $data = new Collection([['name' => 'narrowspark', 'email' => 'foo'], ['name' => 'sparkel', 'email' => 'bar']]);
added test for min and max, small changes on func
narrowspark_framework
train
128f3405e251c354fe5696cb7e4bf0da9e829b4e
diff --git a/tests/test_bags.py b/tests/test_bags.py index <HASH>..<HASH> 100644 --- a/tests/test_bags.py +++ b/tests/test_bags.py @@ -89,15 +89,28 @@ def test_contains(): assert 'a' not in _basebag('missing letter') -def test_compare_sets(): - """Test comparisons to Sets.""" - assert _basebag() == set() - assert _basebag('a') == set('a') - assert not _basebag('ab') == set('a') - assert not _basebag('a') == set('ab') - assert not _basebag('aa') == set('a') - assert not _basebag('aa') == set('ab') - assert not _basebag('ac') == set('ab') +@pytest.mark.parametrize("bag_data, set_data", [ + ('', ''), + ('a', 'a'), + ('ab', 'ab'), + ]) +def test_compare_eq_set(bag_data, set_data): + """Test comparisons to Sets that should be equal.""" + assert _basebag(bag_data) == set(set_data) + + +@pytest.mark.parametrize("bag_data, set_data", [ + ('ab', 'a'), + ('a', 'ab'), + ('aa', 'a'), + ('aa', 'ab'), + ('ac', 'ab'), + ]) +def test_compare_ne_set(bag_data, set_data): + assert not _basebag(bag_data) == set(set_data) + + +def test_compare_unorderable(): assert not _basebag('ac') <= set('ab') assert not _basebag('ac') >= set('ab')
Use pytest parameterize to split test into separate measurable tests
mlenzen_collections-extended
train
fa074a8fa7d501f4d4e3683ad560ab769302e40f
diff --git a/tests/integration/components/sl-date-time-test.js b/tests/integration/components/sl-date-time-test.js index <HASH>..<HASH> 100644 --- a/tests/integration/components/sl-date-time-test.js +++ b/tests/integration/components/sl-date-time-test.js @@ -131,9 +131,9 @@ test( 'Relative values applied correctly', function( assert ) { test( 'Date values applied correctly', function( assert ) { - const pastDate = window.moment().subtract( 3, 'months' ).toISOString(); + const pastDateISO = window.moment().subtract( 3, 'months' ).toISOString(); - this.set( 'value', pastDate ); + this.set( 'value', pastDateISO ); this.render( hbs` {{sl-date-time @@ -144,11 +144,12 @@ test( 'Date values applied correctly', function( assert ) { ` ); const pastRendered = this.$( '>:first-child' ).text().trim(); + const pastDate = window.moment().subtract( 3, 'months' ); assert.strictEqual( - /^\d{4}[-]\d{2}[-]\d{2}$/.test( pastRendered ), - true, - 'Default date string matches default ISO date pattern' + pastRendered, + pastDate.format( 'YYYY-MM-DD' ), + 'Default date string matches default date pattern' ); const datetimeAttr = this.$( '>:first-child' ).attr( 'datetime' );
changed 3 months ago relative date from code review
softlayer_sl-ember-components
train
a1de0e2e202409f737f3f8a7dcb1a4055b68d2ac
diff --git a/lib/grape/entity.rb b/lib/grape/entity.rb index <HASH>..<HASH> 100644 --- a/lib/grape/entity.rb +++ b/lib/grape/entity.rb @@ -232,7 +232,10 @@ module Grape return nil if object.nil? opts = options.merge(runtime_options || {}) exposures.inject({}) do |output, (attribute, exposure_options)| - output[key_for(attribute)] = value_for(attribute, opts) if conditions_met?(exposure_options, opts) + partial_output = value_for(attribute, opts) if conditions_met?(exposure_options, opts) + partial_output = partial_output.serializable_hash(runtime_options) if partial_output.respond_to? :serializable_hash + output[key_for(attribute)] = partial_output + output end end diff --git a/spec/grape/entity_spec.rb b/spec/grape/entity_spec.rb index <HASH>..<HASH> 100644 --- a/spec/grape/entity_spec.rb +++ b/spec/grape/entity_spec.rb @@ -257,6 +257,28 @@ describe Grape::Entity do fresh_class.expose :name expect{ fresh_class.new(nil).serializable_hash }.not_to raise_error end + + it 'should serialize embedded objects which respond to #serializable_hash' do + class EmbeddedExample + def serializable_hash(opts = {}) + {:abc => 'def'} + end + end + + class SimpleExample + def name + "abc" + end + + def embedded + EmbeddedExample.new + end + end + + fresh_class.expose :name, :embedded + presenter = fresh_class.new(SimpleExample.new) + presenter.serializable_hash.should == {:name => "abc", :embedded => {:abc => "def"}} + end end describe '#value_for' do
Grape::Entity#serializable_hash should call #serializable_hash if the data returned from #value_for responds to that method so that nested Grape::Entity presentation works correctly.
ruby-grape_grape
train
c2a4f3b39ef9e1b93fa4c4bc341265f49ccce9ef
diff --git a/src/constants.js b/src/constants.js index <HASH>..<HASH> 100644 --- a/src/constants.js +++ b/src/constants.js @@ -1,5 +1,5 @@ -const UPDATE_BLUEPRINT = '@@resmix/updateBlueprint'; -const UPDATE = '@@resmix/update'; +const UPDATE_BLUEPRINT = '@@feedbacks/updateBlueprint'; +const UPDATE = '@@feedbacks/update'; module.exports = { UPDATE, diff --git a/src/resmix.js b/src/resmix.js index <HASH>..<HASH> 100644 --- a/src/resmix.js +++ b/src/resmix.js @@ -269,7 +269,7 @@ function createEngine(blueprint, { loader } = {} ) { const blueprintResult = effectRunner.run({[EffectRunner.RECURSIVE]: blueprint}, (result) => { //if (result.path.length) - update(result.path, result.value); + update(result.path, result.value, undefined, {cause:{ type:'initialization'}}); }); // console.log("A======", result1.value); // console.log("B======", initialState);
renaming constants; cause for initialization action
hex13_feedbacks
train
84033759f079add03cecc3683833b47d944a3ffe
diff --git a/utilities/shellSettings.js b/utilities/shellSettings.js index <HASH>..<HASH> 100644 --- a/utilities/shellSettings.js +++ b/utilities/shellSettings.js @@ -1,6 +1,7 @@ module.exports = exports = { - parseOptions: function (definedOption, options, cmd, shell) { - if (definedOption.hasOwnProperty('prompt') && definedOption.multiLinePrompt) + parseOptions: function (key, definedOptions, options, cmd, shell) { + var definedOption = definedOptions[key]; + if (definedOption.hasOwnProperty('prompt') && definedOption.multiLinePrompt && !options.hasOwnProperty(key)) shell.multiLine(); } }; \ No newline at end of file
Added check to see if supplied options already has a value.
chevex-archived_shotgun-client
train
942473c1ec8dadd16c47913eb750680a0e72e8ea
diff --git a/src/Symfony/Component/Config/Builder/ConfigBuilderGenerator.php b/src/Symfony/Component/Config/Builder/ConfigBuilderGenerator.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Config/Builder/ConfigBuilderGenerator.php +++ b/src/Symfony/Component/Config/Builder/ConfigBuilderGenerator.php @@ -430,6 +430,8 @@ public function __construct(array $value = []) return; } + $class->addUse(ParamConfigurator::class); + $class->addProperty('_extraKeys'); $class->addMethod('set', '
[Config] Add missing use statement in generated config builder classes
symfony_symfony
train
3f1d56e2bad476b3ee6cdf3e0f5ef8baf9bf8506
diff --git a/src/Infrastructure/Persistence/BlogArticleMapper.php b/src/Infrastructure/Persistence/BlogArticleMapper.php index <HASH>..<HASH> 100644 --- a/src/Infrastructure/Persistence/BlogArticleMapper.php +++ b/src/Infrastructure/Persistence/BlogArticleMapper.php @@ -82,7 +82,7 @@ class BlogArticleMapper extends EntityMapper $map->embedded(BlogArticle::DATE)->using(new DateMapper('date')); - $map->embedded(BlogArticle::ARTICLE_CONTENT)->withIssetColumn('article_content')->using(new HtmlMapper('article_content')); + $map->embedded(BlogArticle::ARTICLE_CONTENT)->withIssetColumn('article_content')->using(HtmlMapper::withLongText('article_content')); $map->property(BlogArticle::ALLOW_SHARING)->to('allow_sharing')->asBool(); diff --git a/tests/Tests/Cms/BlogArticleModuleTest.php b/tests/Tests/Cms/BlogArticleModuleTest.php index <HASH>..<HASH> 100644 --- a/tests/Tests/Cms/BlogArticleModuleTest.php +++ b/tests/Tests/Cms/BlogArticleModuleTest.php @@ -212,7 +212,7 @@ class BlogArticleModuleTest extends CrudModuleTest public function testPreviewAction() { - $article = $this->getMockWithoutInvokingTheOriginalConstructor(BlogArticle::class); + $article = $this->createMock(BlogArticle::class); $article->articleContent = new Html('content'); $this->dataSource->save($article); diff --git a/tests/Tests/Helper/BlogIocContainer.php b/tests/Tests/Helper/BlogIocContainer.php index <HASH>..<HASH> 100644 --- a/tests/Tests/Helper/BlogIocContainer.php +++ b/tests/Tests/Helper/BlogIocContainer.php @@ -2,29 +2,12 @@ namespace Dms\Package\Blog\Tests\Helper; -use Dms\Core\Auth\IAuthSystem; -use Dms\Core\Cms; -use Dms\Core\CmsDefinition; -use Dms\Core\Event\IEventDispatcher; use Dms\Core\ICms; -use Dms\Core\Ioc\IIocContainer; -use Dms\Core\Persistence\Db\Connection\Dummy\DummyConnection; -use Dms\Core\Persistence\Db\Connection\IConnection; use Dms\Core\Persistence\Db\Mapping\IOrm; -use Dms\Core\Tests\Module\Mock\MockAuthSystem; -use Dms\Core\Tests\Module\Mock\MockEventDispatcher; -use Dms\Core\Util\DateTimeClock; -use Dms\Core\Util\IClock; use Dms\Library\Testing\Helper\TestIocContainer; use Dms\Package\Blog\Cms\BlogPackage; use Dms\Package\Blog\Domain\Services\Config\BlogConfiguration; use Dms\Package\Blog\Infrastructure\Persistence\BlogOrm; -use Dms\Package\Shop\Cms\ShopPackage; -use Dms\Package\Shop\Domain\Services\Config\ShopConfiguration; -use Dms\Package\Shop\Infrastructure\Persistence\ShopOrm; -use Illuminate\Container\Container; -use Interop\Container\Exception\ContainerException; -use Interop\Container\Exception\NotFoundException; /** * @author Elliot Levin <elliotlevin@hotmail.com> @@ -41,7 +24,7 @@ class BlogIocContainer extends TestIocContainer $this->bindValue(BlogConfiguration::class, TestBlogConfiguration::build()); $this->bind(self::SCOPE_SINGLETON, IOrm::class, BlogOrm::class); - $cms = $test->getMockForAbstractClass(ICms::class); + $cms = $test->getMockBuilder(ICms::class)->getMockForAbstractClass(); $cms->method('getIocContainer')->willReturn($this); BlogPackage::boot($cms); diff --git a/tests/Tests/Services/Loader/BlogArticleLoaderTest.php b/tests/Tests/Services/Loader/BlogArticleLoaderTest.php index <HASH>..<HASH> 100644 --- a/tests/Tests/Services/Loader/BlogArticleLoaderTest.php +++ b/tests/Tests/Services/Loader/BlogArticleLoaderTest.php @@ -30,13 +30,13 @@ class BlogArticleLoaderTest extends CmsTestCase { $articles = [ new BlogArticle( - $this->getMockWithoutInvokingTheOriginalConstructor(BlogAuthor::class), - $this->getMockWithoutInvokingTheOriginalConstructor(BlogCategory::class), + $this->createMock(BlogAuthor::class), + $this->createMock(BlogCategory::class), 'title-1', 'sub-title', 'extract', 'some-slug', - $this->getMockWithoutInvokingTheOriginalConstructor(Image::class), + $this->createMock(Image::class), new Date(2000, 01, 01), new Html('content'), true, @@ -45,13 +45,13 @@ class BlogArticleLoaderTest extends CmsTestCase new MockClock('2000-01-01 00:00:00') ), new BlogArticle( - $this->getMockWithoutInvokingTheOriginalConstructor(BlogAuthor::class), - $this->getMockWithoutInvokingTheOriginalConstructor(BlogCategory::class), + $this->createMock(BlogAuthor::class), + $this->createMock(BlogCategory::class), 'title-2', 'sub-title', 'extract', 'another-slug', - $this->getMockWithoutInvokingTheOriginalConstructor(Image::class), + $this->createMock(Image::class), new Date(2000, 01, 01), new Html('content'), true,
Update PHPUnit and change article content column to long text
dms-org_package.blog
train
f3955bd9f8587f3d53e75573686190a050ae378d
diff --git a/client/on-demand-entries-client.js b/client/on-demand-entries-client.js index <HASH>..<HASH> 100644 --- a/client/on-demand-entries-client.js +++ b/client/on-demand-entries-client.js @@ -14,7 +14,12 @@ export default () => { const res = await fetch(url) const payload = await res.json() if (payload.invalid) { - location.reload() + // Payload can be invalid even if the page is not exists. + // So, we need to make sure it's exists before reloading. + const pageRes = await fetch(location.href) + if (pageRes.status === 200) { + location.reload() + } } } catch (err) { console.error(`Error with on-demand-entries-ping: ${err.message}`)
Fix page auto-reload when there's a <I>/<I> page. (#<I>)
zeit_next.js
train
04fbca7ed08ed2f2653ccdf1076f676785e247da
diff --git a/salt/modules/mac_service.py b/salt/modules/mac_service.py index <HASH>..<HASH> 100644 --- a/salt/modules/mac_service.py +++ b/salt/modules/mac_service.py @@ -2,6 +2,24 @@ ''' The service module for macOS .. versionadded:: 2016.3.0 + +This module has support for services in the following locations. + +.. code-block:: bash + /System/Library/LaunchDaemons/ + /System/Library/LaunchAgents/ + /Library/LaunchDaemons/ + /Library/LaunchAgents/ + + # As of version "Fluorine" support for user-specific services were added. + /Users/foo/Library/LaunchAgents/ + +.. note:: + + As of version "Fluorine", if a service is located in a ``LaunchAgent`` path + and a ``runas`` user is NOT specified the current console user will be used + to properly interact with the service. + ''' from __future__ import absolute_import, unicode_literals, print_function @@ -128,6 +146,8 @@ def _get_domain_target(name, service_target=False): :return: Tuple of the domain/service target and the path to the service. :rtype: tuple + + .. versionadded:: Fluorine ''' # Get service information @@ -158,15 +178,17 @@ def _launch_agent(name): :param str name: Service label, file name, or full path - :return: True if a LaunchAgent, False is not. + :return: True if a LaunchAgent, False if not. :rtype: bool + + .. versionadded:: Fluorine ''' # Get the path to the service. path = _get_service(name)['file_path'] - if not 'LaunchAgents' in path: + if 'LaunchAgents' not in path: return False return True
fixing lint error and adding more documentation.
saltstack_salt
train
bb53df18aa0fd10f2e347a83acd7949a26a4dd52
diff --git a/hazelcast-jet-kafka/src/main/java/com/hazelcast/jet/kafka/KafkaSources.java b/hazelcast-jet-kafka/src/main/java/com/hazelcast/jet/kafka/KafkaSources.java index <HASH>..<HASH> 100644 --- a/hazelcast-jet-kafka/src/main/java/com/hazelcast/jet/kafka/KafkaSources.java +++ b/hazelcast-jet-kafka/src/main/java/com/hazelcast/jet/kafka/KafkaSources.java @@ -74,20 +74,30 @@ public final class KafkaSources { * If you start a new job from an exported state, you can change the source * parameters as needed:<ul> * <li>if you add a topic, it will be consumed from the default position - * <li>if you remove a topic, restored offsets will be ignored (there - * will be a warning logged) + * <li>if you remove a topic, restored offsets for that topic will be + * ignored (there will be a warning logged) * <li>if you connect to another cluster, the offsets will be used based - * on the equality of the topic name. To avoid this, give different - * {@linkplain Stage#setName name} to this source + * on the equality of the topic name. If you want to start from default + * position, give different {@linkplain Stage#setName name} to this + * source * <li>if the partition count is lower after a restart, the extra * offsets will be ignored * </ul> * <p> - * If and only if snapshotting is disabled, the source commits the offsets - * to Kafka using {@link KafkaConsumer#commitSync()}. Note however that - * offsets can be committed before or after the event is fully processed. - * You can configure {@code group.id} in this case. - * <p> + * The source can work in two modes: + * <ol> + * <li>if {@linkplain JobConfig#setProcessingGuarantee processing + * guarantee} is enabled, offsets are stored to the snapshot and after a + * restart or failure, the reading continues from the saved offset. You + * can achieve exactly-once or at-least-once behavior. + * + * <li>if processing guarantee is disabled, the source commits the + * offsets to Kafka using {@link KafkaConsumer#commitSync()}. But the + * offsets are committed before or after the event is fully processed. + * Therefore some events can be processed twice or not at all. You can + * configure {@code group.id} in this case. + * </ol> + * * If you add Kafka partitions at run-time, consumption from them will * start after a delay, based on the {@code metadata.max.age.ms} Kafka * property. Note, however, that events from them can be dropped as late if
More details about Kafka's two modes of operation (#<I>) Fixes #<I>
hazelcast_hazelcast
train
04ea63c2ceb8990a351e5a460366b17fe1c3d1ea
diff --git a/config.py b/config.py index <HASH>..<HASH> 100644 --- a/config.py +++ b/config.py @@ -142,3 +142,7 @@ PLUGIN_BLACKLIST = [ # PROXY_URL = "http://user:pass@corpproxy.example.com:3128" # or # PROXY_URL = "http://myproxy:80 + +# Google Application key for "image me" command +# GOOGLE_API_KEY = "FILL THIS IN" +# GOOGLE_CUSTOM_SEARCH_KEY = "FILL THIS IN" diff --git a/will/plugins/productivity/images.py b/will/plugins/productivity/images.py index <HASH>..<HASH> 100644 --- a/will/plugins/productivity/images.py +++ b/will/plugins/productivity/images.py @@ -1,5 +1,6 @@ import random import requests +from will import settings from will.plugin import WillPlugin from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template, require_settings @@ -9,19 +10,29 @@ class ImagesPlugin(WillPlugin): @respond_to("image me (?P<search_query>.*)$") def image_me(self, message, search_query): """image me ___ : Search google images for ___, and post a random one.""" + + if not (getattr(settings, "GOOGLE_API_KEY", False) and getattr("GOOGLE_CUSTOM_SEARCH_KEY")): + self.say("Sorry, the person who set me up did not configure the google api key.", color="red") + return + + # https://developers.google.com/custom-search/json-api/v1/reference/cse/list?hl=en data = { "q": search_query, - "v": "1.0", - "safe": "active", - "rsz": "8" + "key": settings.GOOGLE_API_KEY, + "cx": settings.GOOGLE_CUSTOM_SEARCH_KEY, + "safe": "medium", + "num": 8, + "searchType": "image", } - r = requests.get("http://ajax.googleapis.com/ajax/services/search/images", params=data) + r = requests.get("https://www.googleapis.com/customsearch/v1", params=data) + r.raise_for_status() try: - results = r.json()["responseData"]["results"] + response = r.json() + results = [result["link"] for result in response["items"] if "image" in r.json()] except TypeError: results = [] - if len(results) > 0: - url = random.choice(results)["unescapedUrl"] + if results: + url = random.choice(results) self.say("%s" % url, message=message) else: self.say("Couldn't find anything!", message=message)
Updated image search to use non deprecated api
skoczen_will
train
dc510bbead0569fe8dc8b97e880632b341940011
diff --git a/src/sap.ui.commons/src/sap/ui/commons/RadioButton.js b/src/sap.ui.commons/src/sap/ui/commons/RadioButton.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.commons/src/sap/ui/commons/RadioButton.js +++ b/src/sap.ui.commons/src/sap/ui/commons/RadioButton.js @@ -110,6 +110,16 @@ sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control'], } }}); + RadioButton.prototype.onAfterRendering = function(oEvent) { + + // prevents firing click event twice + var $input = this.$('RB'); + $input.click(function (event) { + event.preventDefault(); + return false; + }); + }; + /** * Event handler called, when the RadioButton is clicked. *
[FIX] sap.ui.commons.RadioButton: Click event is now fired only once BCP: <I> Change-Id: I<I>df<I>d4bc7ad8afb<I>ce<I>d<I>f<I>eed
SAP_openui5
train
66bada650d6482fe0ebe52ece154db7c01d3eee6
diff --git a/azmq/common.py b/azmq/common.py index <HASH>..<HASH> 100644 --- a/azmq/common.py +++ b/azmq/common.py @@ -226,7 +226,7 @@ class CompositeClosableAsyncObject(ClosableAsyncObject): :param child: The child instance. """ self._children.remove(child) - child.on_closed.connect(self.unregister_child) + child.on_closed.disconnect(self.unregister_child) class AsyncTaskObject(ClosableAsyncObject): diff --git a/azmq/transports/inproc.py b/azmq/transports/inproc.py index <HASH>..<HASH> 100644 --- a/azmq/transports/inproc.py +++ b/azmq/transports/inproc.py @@ -47,7 +47,6 @@ class InprocServer(CompositeClosableAsyncObject): super().on_open() self._handler = handler self._tasks = [] - self._channel_pairs = [] async def on_close(self, result): if self._tasks: @@ -65,7 +64,6 @@ class InprocServer(CompositeClosableAsyncObject): self.register_child(right) left.link(right) - self._channel_pairs.append((left, right)) task = asyncio.ensure_future(self._handler(right)) self._tasks.append(task)
Removed useless code in inproc transport
ereOn_azmq
train
0f62963b1f98989322ca320ec78a7c10c3605927
diff --git a/lib/sensu/server.rb b/lib/sensu/server.rb index <HASH>..<HASH> 100644 --- a/lib/sensu/server.rb +++ b/lib/sensu/server.rb @@ -524,11 +524,12 @@ module Sensu end end end - if subdue - puts "subdued: #{subdue}" - (check[:subdue][:at].nil? && type == :handler) || (check[:subdue][:at] && check[:subdue][:at].to_sym == type) + case + when subdue && !check[:subdue].has_key?(:at) && type == :handler + true + when subdue && check[:subdue].has_key?(:at) && check[:subdue][:at].to_sym == type + true else - puts "subdued: #{subdue}" false end end diff --git a/test/subdue_tests.rb b/test/subdue_tests.rb index <HASH>..<HASH> 100644 --- a/test/subdue_tests.rb +++ b/test/subdue_tests.rb @@ -81,25 +81,24 @@ class TestSensuSubdue < TestCase client = Sensu::Client.new(@options) server.setup_redis server.setup_rabbitmq - server.redis.flushall.callback do - server.setup_keepalives - server.setup_results - client.setup_rabbitmq - client.setup_keepalives - client.setup_subscriptions - client.setup_standalone(:test => true) - server.setup_publisher(:test => true) - EM::Timer.new(2) do - puts "get client events" - server.redis.hgetall('events:' + @settings[:client][:name]).callback do |events| - puts "events: #{events.inspect}" - assert(events.size > 0, 'Failed to receive events') - found = events.keys.find_all do |name| - name.start_with?('subdue') - end - assert(found.size == 0, 'Found subdued event(s): ' + found.join(', ')) - done + server.redis.flushall + server.setup_keepalives + server.setup_results + client.setup_rabbitmq + client.setup_keepalives + client.setup_subscriptions + client.setup_standalone(:test => true) + server.setup_publisher(:test => true) + EM::Timer.new(2) do + puts "get client events" + server.redis.hgetall('events:' + @settings[:client][:name]).callback do |events| + puts "events: #{events.inspect}" + assert(events.size > 0, 'Failed to receive events') + found = events.keys.find_all do |name| + name.start_with?('subdue') end + assert(found.size == 0, 'Found subdued event(s): ' + found.join(', ')) + done end end end
[subdue] use a case for subdue
sensu_sensu
train
3fca0faecdca0100ccb3ab097ca932349b72064d
diff --git a/mimesis/providers/development.py b/mimesis/providers/development.py index <HASH>..<HASH> 100644 --- a/mimesis/providers/development.py +++ b/mimesis/providers/development.py @@ -3,6 +3,7 @@ import typing as t from mimesis.data import LICENSES, OS, PROGRAMMING_LANGS, PROJECT_NAMES +from mimesis.enums import TLDType from mimesis.providers.base import BaseProvider from mimesis.providers.internet import Internet @@ -21,19 +22,40 @@ class Development(BaseProvider): name: t.Final[str] = "development" - def postgres_dsn(self) -> str: + def postgres_dsn( + self, + tld_type: t.Optional[TLDType] = None, + subdomains: t.Optional[t.List[str]] = None, + localhost: bool = False, + credentials: bool = False, + ) -> str: """Get a random PostgreSQL DSN. :Example: - postgres://user:password@host:port + postgresql://db.emma.pk:5432 :return: DSN. """ - scheme_designator = self.random.choice(["postgres://", "postgresql://"]) - hostname = self._internet.hostname() - password = self.random.randstr(length=8) - username = self.random.choice(PROJECT_NAMES) - return f"{scheme_designator}{username}:{password}@{hostname}:5432" + scheme = self.random.choice(["postgres", "postgresql"]) + hostname = self._internet.hostname( + tld_type=tld_type, + subdomains=subdomains, + ) + + if localhost: + hostname = self.random.choice( + [ + "127.0.0.1", + "localhost", + ] + ) + + user = "" + if credentials: + password = self.random.randstr(length=8) + username = self.random.choice(PROJECT_NAMES) + user = f"{username}:{password}@" + return f"{scheme}://{user}{hostname}:5432" def software_license(self) -> str: """Get a random software license. diff --git a/tests/test_providers/test_development.py b/tests/test_providers/test_development.py index <HASH>..<HASH> 100644 --- a/tests/test_providers/test_development.py +++ b/tests/test_providers/test_development.py @@ -2,6 +2,7 @@ import re import pytest from mimesis import Development, data +from mimesis.enums import TLDType from . import patterns @@ -59,8 +60,16 @@ class TestDevelopment: result = dev.boolean() assert result or (not result) - def test_postgres_dsn(self, dev): - result = dev.postgres_dsn() + @pytest.mark.parametrize( + "tld_type, subdomains, localhost, credentials", + [ + (TLDType.CCTLD, ["db"], False, True), + (TLDType.CCTLD, ["db"], True, False), + (TLDType.CCTLD, [], True, False), + ], + ) + def test_postgres_dsn(self, dev, tld_type, subdomains, localhost, credentials): + result = dev.postgres_dsn(tld_type, subdomains, localhost, credentials) assert result.startswith("postgres://") or result.startswith("postgresql://")
Add more params for postgres_dsn
lk-geimfari_mimesis
train
eed73fd8a3248b08da96c5e332ecd0e3d39654c5
diff --git a/dist/curse.js b/dist/curse.js index <HASH>..<HASH> 100644 --- a/dist/curse.js +++ b/dist/curse.js @@ -66,15 +66,25 @@ var Curse = (function () { if (anchorNode.nodeName === "#text") { start = this.lengthUpTo(anchorNode) + anchorOffset; } else { - child = anchorNode.childNodes[anchorOffset ? anchorOffset - 1 : 0]; - start = this.lengthUpTo(child) + this.nodeLength(child, false, true); + child = anchorNode.childNodes[anchorOffset - 1]; + + if (child) { + start = this.lengthUpTo(child) + this.nodeLength(child, false, true); + } else { + start = this.lengthUpTo(anchorNode); + } } if (focusNode.nodeName === "#text") { end = this.lengthUpTo(focusNode) + focusOffset; } else { - child = focusNode.childNodes[focusOffset ? focusOffset - 1 : 0]; - end = this.lengthUpTo(child) + this.nodeLength(child, false, true); + child = focusNode.childNodes[focusOffset - 1]; + + if (child) { + end = this.lengthUpTo(child) + this.nodeLength(child, false, true); + } else { + end = this.lengthUpTo(focusNode); + } } this.start = start; diff --git a/src/curse.js b/src/curse.js index <HASH>..<HASH> 100644 --- a/src/curse.js +++ b/src/curse.js @@ -47,15 +47,25 @@ export default class Curse { if (anchorNode.nodeName === '#text') { start = this.lengthUpTo(anchorNode) + anchorOffset; } else { - child = anchorNode.childNodes[anchorOffset ? anchorOffset - 1 : 0]; - start = this.lengthUpTo(child) + this.nodeLength(child, false, true); + child = anchorNode.childNodes[anchorOffset - 1]; + + if (child) { + start = this.lengthUpTo(child) + this.nodeLength(child, false, true); + } else { + start = this.lengthUpTo(anchorNode); + } } if (focusNode.nodeName === '#text') { end = this.lengthUpTo(focusNode) + focusOffset; } else { - child = focusNode.childNodes[focusOffset ? focusOffset - 1 : 0]; - end = this.lengthUpTo(child) + this.nodeLength(child, false, true); + child = focusNode.childNodes[focusOffset - 1]; + + if (child) { + end = this.lengthUpTo(child) + this.nodeLength(child, false, true); + } else { + end = this.lengthUpTo(focusNode); + } } this.start = start;
Fix synchronization with offset 0
usecanvas_curse
train
1d2a837b59edd649300f81204f2fcc80ad908917
diff --git a/Lib/glyphsLib/classes.py b/Lib/glyphsLib/classes.py index <HASH>..<HASH> 100755 --- a/Lib/glyphsLib/classes.py +++ b/Lib/glyphsLib/classes.py @@ -1307,11 +1307,11 @@ class GSNode(GSBase): smooth=False): if line is not None: m = re.match(self._rx, line).groups() - self.position = (float(m[0]), float(m[1])) + self.position = point(float(m[0]), float(m[1])) self.type = m[2].lower() self.smooth = bool(m[3]) else: - self.position = position + self.position = point(position[0], position[1]) self.type = nodetype self.smooth = smooth self._parent = None @@ -1321,7 +1321,7 @@ class GSNode(GSBase): if self.smooth: content += " smooth" return "<%s %g %g %s>" % \ - (self.__class__.__name__, self.position[0], self.position[1], + (self.__class__.__name__, self.position.x, self.position.y, content) userData = property( diff --git a/tests/classes_test.py b/tests/classes_test.py index <HASH>..<HASH> 100755 --- a/tests/classes_test.py +++ b/tests/classes_test.py @@ -1186,10 +1186,8 @@ class GSNodeFromFileTest(GSObjectsTestCase): def test_repr(self): self.assertIsNotNone(self.node.__repr__()) - # TODO point? def test_position(self): - # self.assertIsInstance(self.node.position, point) - self.assertIsInstance(self.node.position, tuple) + self.assertIsInstance(self.node.position, point) def test_type(self): self.assertTrue(self.node.type in
Implemented point class for GSNode.position
googlefonts_glyphsLib
train
b3ba1e7ea2cd63131d263fa388b422194dc3ffff
diff --git a/java/test/src/main/java/io/ray/test/CrossLanguageInvocationTest.java b/java/test/src/main/java/io/ray/test/CrossLanguageInvocationTest.java index <HASH>..<HASH> 100644 --- a/java/test/src/main/java/io/ray/test/CrossLanguageInvocationTest.java +++ b/java/test/src/main/java/io/ray/test/CrossLanguageInvocationTest.java @@ -170,7 +170,9 @@ public class CrossLanguageInvocationTest extends BaseTest { Assert.assertEquals(res.get(), "2".getBytes()); } - @Test + // TODO(WangTaoTheTonic): This hangs on Mac and can't be detected by `flakey-tests.ray.io`. + // Disable it for now and fix it later. + @Test(enabled = false) public void testCallingCppActor() { CppActorHandle actor = Ray.actor(CppActorClass.of("CreateCounter", "Counter")).remote(); ObjectRef<Integer> res = actor.task(CppActorMethod.of("Plus1", Integer.class)).remote();
[Test]Disable java call cpp actor case for now (#<I>)
ray-project_ray
train
53d6a5456669a7371ae401b7363fbb14870c813b
diff --git a/annotationengine/annotationclient.py b/annotationengine/annotationclient.py index <HASH>..<HASH> 100644 --- a/annotationengine/annotationclient.py +++ b/annotationengine/annotationclient.py @@ -10,7 +10,7 @@ from emannotationschemas import get_schema class AnnotationClient(object): - def __init__(self, endpoint=None): + def __init__(self, endpoint=None, dataset_name=None): """ :param endpoint: str or None @@ -20,8 +20,9 @@ class AnnotationClient(object): endpoint = os.environ.get('ANNOTATION_ENGINE_ENDPOINT', None) assert(endpoint is not None) + self.dataset_name = dataset_name self.endpoint = endpoint - self.session = requests.session() + self.session = requests.Session() def get_datasets(self): """ Returns existing datasets @@ -31,20 +32,76 @@ class AnnotationClient(object): url = "{}/dataset".format(self.endpoint) response = self.session.get(url) assert(response.status_code == 200) - return response + return response.json() - def get_dataset(self, dataset_name): + def get_dataset(self, dataset_name=None): """ Returns information about the dataset :return: dict """ + if dataset_name is None: + dataset_name = self.dataset_name url = "{}/dataset/{}".format(self.endpoint, dataset_name) response = self.session.get(url, verify=False) assert(response.status_code == 200) - return response + return response.json() - def bulk_import_df(self, dataset_name, annotation_type, data_df, - block_size=10000): + def get_annotation(self, annotation_type, oid, dataset_name=None): + """ + Returns information about one specific annotation + :param dataset_name: str + :param annotation_type: str + :param oid: int + :return dict + """ + if dataset_name is None: + dataset_name = self.dataset_name + url = "{}/annotation/dataset/{}/{}/{}".format(self.endpoint, + dataset_name, + annotation_type, + oid) + response = self.session.get(url, verify=False) + assert(response.status_code == 200) + return response.json() + + def post_annotation(self, annotation_type, data, dataset_name=None): + """ + Post an annotation to the annotationEngine. + :param dataset_name: str + :param annotation_type: str + :param data: dict + :return dict + """ + if dataset_name is None: + dataset_name = self.dataset_name + + url = "{}/annotation/dataset/{}/{}".format(self.endpoint, + dataset_name, + annotation_type) + response = self.session.post(url, json=data, verify=False) + assert(response.status_code == 200) + return response.json() + + def delete_annotation(self, annotation_type, oid, dataset_name=None): + """ + Delete an existing annotation + :param dataset_name: str + :param annotation_type: str + :param oid: int + :return dict + """ + if dataset_name is None: + dataset_name = self.dataset_name + url = "{}/annotation/dataset/{}/{}/{}".format(self.endpoint, + dataset_name, + annotation_type, + oid) + response = self.session.delete(url, verify=False) + assert(response.status_code == 200) + return response.json() + + def bulk_import_df(self, annotation_type, data_df, + block_size=10000, dataset_name=None): """ Imports all annotations from a single dataframe in one go :param dataset_name: str @@ -52,6 +109,8 @@ class AnnotationClient(object): :param data_df: pandas DataFrame :return: """ + if dataset_name is None: + dataset_name = self.dataset_name dataset_info = json.loads(self.get_dataset(dataset_name).content) cv = cloudvolume.CloudVolume(dataset_info["CV_SEGMENTATION_PATH"]) chunk_size = np.array(cv.info["scales"][0]["chunk_sizes"][0]) * 8
Added necessary changes to annotationclient for the annotation UI post and delete single annotations, plus dataset storing
seung-lab_AnnotationEngine
train
eb4ce499e0aad9841b760a4d12ba970f43275ff0
diff --git a/lib/gli.rb b/lib/gli.rb index <HASH>..<HASH> 100644 --- a/lib/gli.rb +++ b/lib/gli.rb @@ -159,12 +159,21 @@ module GLI case ex when BadCommandLine: -1 + when CustomExit: + ex.exit_code else -2 end end end + # Simpler means of exiting with a custom exit code. This will + # raise a CustomExit with the given message and exit code, which will ultimatley + # cause your application to exit with the given exit_code as its exit status + def exit_now!(message,exit_code) + raise CustomExit.new(message,exit_code) + end + # Possibly returns a copy of the passed-in Hash as an instance of GLI::Option. # By default, it will *not*, however by putting <tt>use_openstruct true</tt> # in your CLI definition, it will diff --git a/lib/gli/exceptions.rb b/lib/gli/exceptions.rb index <HASH>..<HASH> 100644 --- a/lib/gli/exceptions.rb +++ b/lib/gli/exceptions.rb @@ -5,4 +5,24 @@ module GLI super(message) end end + + # Raise this if you want to use an exit status that isn't the default + # provided by GLI. + # + # Example: + # + # raise CustomExit.new("Not connected to DB",-5) unless connected? + # raise CustomExit.new("Bad SQL",-6) unless valid_sql?(args[0]) + # + class CustomExit < Exception + attr_reader :exit_code + # Create a custom exit exception + # + # message - String containing error message to show the user + # exit_code - the exit code to use, overridding GLI's default + def initialize(message,exit_code) + super(message) + @exit_code = exit_code + end + end end diff --git a/test/tc_gli.rb b/test/tc_gli.rb index <HASH>..<HASH> 100644 --- a/test/tc_gli.rb +++ b/test/tc_gli.rb @@ -340,9 +340,32 @@ class TC_testGLI < Test::Unit::TestCase raise "Problem" end end - assert_equal -2,GLI.run('foo') + assert_equal -2,GLI.run(['foo']) end + def test_exits_nonzero_with_custom_exception + GLI.reset + GLI.on_error { true } + GLI.command(:foo) do |c| + c.action do |g,o,a| + raise CustomExit.new("Problem",45) + end + end + assert_equal 45,GLI.run(['foo']) + end + + def test_exits_nonzero_with_exit_method + GLI.reset + GLI.on_error { true } + GLI.command(:foo) do |c| + c.action do |g,o,a| + exit_now!("Problem",45) + end + end + assert_equal 45,GLI.run(['foo']) + end + + private def read_file_contents(filename)
Custom exit codes supported Fixes #<I> You can either raise a custom exception or use exit_now!
davetron5000_gli
train
8b995f931a48ecc590ac643482f98279ae284544
diff --git a/tests/etl/test_buildbot.py b/tests/etl/test_buildbot.py index <HASH>..<HASH> 100644 --- a/tests/etl/test_buildbot.py +++ b/tests/etl/test_buildbot.py @@ -1111,6 +1111,17 @@ buildernames = [ 'os': 'win', 'os_platform': 'windows8-32', 'vm': False}}), + ('WINNT 6.2 holly opt test mochitest-csb-1', + {'build_type': 'opt', + 'job_type': 'unittest', + 'name': {'group_name': 'Mochitest csb', + 'group_symbol': 'M-csb', + 'name': 'Mochitest csb', + 'job_symbol': '1'}, + 'platform': {'arch': 'x86', + 'os': 'win', + 'os_platform': 'windows8-32', + 'vm': False}}), ('Android 4.0 Panda cedar opt test instrumentation-background', {'build_type': 'opt', 'job_type': 'unittest', diff --git a/treeherder/etl/buildbot.py b/treeherder/etl/buildbot.py index <HASH>..<HASH> 100644 --- a/treeherder/etl/buildbot.py +++ b/treeherder/etl/buildbot.py @@ -355,6 +355,7 @@ JOB_NAME_BUILDERNAME = [ {"regex": re.compile('talos xperf$'), "desc": "Talos xperf"}, # ** Unit tests ** {"regex": re.compile('mozbase$'), "desc": "Mozbase Unit Tests"}, + {"regex": re.compile('mochitest-csb'), "desc": "Mochitest csb"}, {"regex": re.compile('mochitest-e10s-browser-chrome'), "desc": "Mochitest e10s Browser Chrome"}, {"regex": re.compile('mochitest-e10s-devtools-chrome'), "desc": "Mochitest e10s DevTools Browser Chrome"}, {"regex": re.compile('mochitest-e10s-other'), "desc": "Mochitest e10s Other"}, @@ -549,6 +550,7 @@ GROUP_NAMES = { "Mochitest e10s Browser Chrome": "Mochitest e10s", "Mochitest e10s DevTools Browser Chrome": "Mochitest e10s", "Mochitest e10s Other": "Mochitest e10s", + "Mochitest csb": "Mochitest csb", "Mochitest OOP": "Mochitest OOP", "Crashtest": "Reftest", "Crashtest IPC": "Reftest", @@ -726,6 +728,7 @@ SYMBOLS = { "Mochitest e10s Browser Chrome": "bc", "Mochitest e10s DevTools Browser Chrome": "dt", "Mochitest e10s Other": "oth", + "Mochitest csb": "M-csb", "Mochitest OOP": "M-oop", "Robocop": "rc", "Webapprt Content": "w", @@ -892,7 +895,7 @@ def get_symbol(name, bn): # For multi-part Mochitest, Mochitest-e10s, Mochitest OOP & W3C Web Platform # jobs, display only the job part number and not the letters. - if n and s in ["M", "M-e10s", "M-oop", "Gij", "Gij-oop", "W"]: + if n and s in ["M", "M-e10s", "M-csb", "M-oop", "Gij", "Gij-oop", "W"]: return n return "{0}{1}".format(s, n)
Bug <I> - Add support for Mochitest content sandbox tests
mozilla_treeherder
train
306b5f980f8055135f244062a19688b394f9d2eb
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -195,7 +195,9 @@ FCM.send = (senderId, payload) => { }; FCM.setNotificationCategories = (categories) => { - RNFIRMessaging.setNotificationCategories(categories); + if (Platform.OS === 'ios') { + RNFIRMessaging.setNotificationCategories(categories); + } } export default FCM;
Add check if it is iOS to setNotificationCategories
evollu_react-native-fcm
train
18fcc1cf175d08989b69a55225c52a592fed08b8
diff --git a/spatialist/raster.py b/spatialist/raster.py index <HASH>..<HASH> 100644 --- a/spatialist/raster.py +++ b/spatialist/raster.py @@ -1124,6 +1124,13 @@ class Raster(object): raise RuntimeError('overwriting the currently opened file is not supported.') update_existing = update and os.path.isfile(outname) dtype = Dtype(self.dtype if dtype == 'default' else dtype).gdalint + + if options is None: + options = [] + + tifftags = [x for x in options if x.startswith('TIFFTAG_')] + create_options = [x for x in options if not x.startswith('TIFFTAG_')] + if not update_existing: if os.path.isfile(outname) and not overwrite: raise RuntimeError('target file already exists') @@ -1133,27 +1140,24 @@ class Raster(object): nodata = self.nodata if nodata == 'default' else nodata - if options is None: - options = [] - if format == 'COG': - outname_cog = copy.deepcopy(outname) - outname = '/vsimem/' + os.path.basename(outname) + '.vrt' - options_cog = copy.deepcopy(options) - options = [] + outname_tmp = '/vsimem/' + os.path.basename(outname) + '.vrt' driver = gdal.GetDriverByName('GTiff') + outDataset = driver.Create(outname_tmp, self.cols, self.rows, + self.bands, dtype, options=[]) else: driver = gdal.GetDriverByName(format) + outDataset = driver.Create(outname, self.cols, self.rows, + self.bands, dtype, create_options) - outDataset = driver.Create(outname, self.cols, self.rows, self.bands, dtype, options) - driver = None outDataset.SetMetadata(self.raster.GetMetadata()) - outDataset.SetGeoTransform( - [self.geo[x] for x in ['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres']]) + gt_keys = ['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'] + outDataset.SetGeoTransform([self.geo[x] for x in gt_keys]) if self.projection is not None: outDataset.SetProjection(self.projection) else: outDataset = gdal.Open(outname, GA_Update) + for i in range(1, self.bands + 1): outband = outDataset.GetRasterBand(i) @@ -1183,7 +1187,8 @@ class Raster(object): dtype_mat = str(mat.dtype) dtype_ras = Dtype(dtype).numpystr if not np.can_cast(dtype_mat, dtype_ras): - warnings.warn("writing band {}: unsafe casting from type {} to {}".format(i, dtype_mat, dtype_ras)) + message = "writing band {}: unsafe casting from type {} to {}" + warnings.warn(message.format(i, dtype_mat, dtype_ras)) if nodata is not None: print('converting nan to nodata value {}'.format(nodata)) mat[np.isnan(mat)] = nodata @@ -1191,24 +1196,24 @@ class Raster(object): outband.WriteArray(mat, xoff, yoff) del mat outband.FlushCache() - outband = None if format in ['GTiff', 'COG']: - outDataset.SetMetadataItem('TIFFTAG_DATETIME', strftime('%Y:%m:%d %H:%M:%S', gmtime())) + for tag in tifftags: + outDataset.SetMetadataItem(*tag.split('=')) + if 'TIFFTAG_DATETIME' not in tifftags: + time = strftime('%Y:%m:%d %H:%M:%S', gmtime()) + outDataset.SetMetadataItem('TIFFTAG_DATETIME', time) if overviews: outDataset.BuildOverviews(overview_resampling, overviews) if format == 'COG': - options_meta = [] - for i, opt in enumerate(options_cog): - if opt.startswith('TIFFTAG_'): - options_meta.append(opt) - options_cog.pop(i) - for opt in options_meta: - opt_split = opt.split('=') - outDataset.SetMetadataItem(opt_split[0], opt_split[1]) - outDataset_cog = gdal.GetDriverByName('COG').CreateCopy(outname_cog, outDataset, - strict=1, options=options_cog) + driver_cog = gdal.GetDriverByName('COG') + outDataset_cog = driver_cog.CreateCopy(outname, outDataset, + strict=1, options=create_options) outDataset_cog = None + driver_cog = None + outband = None outDataset = None + driver = None + if format == 'ENVI': hdrfile = os.path.splitext(outname)[0] + '.hdr' with HDRobject(hdrfile) as hdr:
[Raster.write] restructuring and bug fixing
johntruckenbrodt_spatialist
train
b1316776d9a8f6cb8f1cdcde4b658b88077e3f1d
diff --git a/stagemonitor-web/src/main/java/org/stagemonitor/web/monitor/filter/HttpRequestMonitorFilter.java b/stagemonitor-web/src/main/java/org/stagemonitor/web/monitor/filter/HttpRequestMonitorFilter.java index <HASH>..<HASH> 100644 --- a/stagemonitor-web/src/main/java/org/stagemonitor/web/monitor/filter/HttpRequestMonitorFilter.java +++ b/stagemonitor-web/src/main/java/org/stagemonitor/web/monitor/filter/HttpRequestMonitorFilter.java @@ -218,6 +218,9 @@ public class HttpRequestMonitorFilter extends AbstractExclusionFilter implements } private void passthrough(ServletResponse originalResponse, HttpServletResponseBufferWrapper responseWrapper) throws IOException { + if (originalResponse.isCommitted()) { + return; + } if (responseWrapper.isUsingWriter()) { originalResponse.getWriter().write(responseWrapper.getWriter().getOutput().toString()); } else {
Only write to original response if it has not beed committed yet
stagemonitor_stagemonitor
train
ae9b02a643acf7bb939ac741dc535245f4c967ad
diff --git a/third_party/js/wgxpath/kindTest.js b/third_party/js/wgxpath/kindTest.js index <HASH>..<HASH> 100644 --- a/third_party/js/wgxpath/kindTest.js +++ b/third_party/js/wgxpath/kindTest.js @@ -99,6 +99,8 @@ wgxpath.KindTest.prototype.getName = function() { /** * @override + * @param {string=} opt_indent Optional indentation. + * @return {string} The string representation. */ wgxpath.KindTest.prototype.toString = function(opt_indent) { var indent = opt_indent || ''; diff --git a/third_party/js/wgxpath/nameTest.js b/third_party/js/wgxpath/nameTest.js index <HASH>..<HASH> 100644 --- a/third_party/js/wgxpath/nameTest.js +++ b/third_party/js/wgxpath/nameTest.js @@ -64,6 +64,8 @@ wgxpath.NameTest.prototype.getName = function() { /** * @override + * @param {string=} opt_indent Optional indentation. + * @return {string} The string representation. */ wgxpath.NameTest.prototype.toString = function(opt_indent) { var indent = opt_indent || '';
SimonStewart: Fix the build by adding in the missing param and return types. Quite why the js compiler is choking on this is left as an exercise to the interested reader: the @override annotation should have been enough of a hint. r<I>
SeleniumHQ_selenium
train
fb7997fd07a8aae1b71c04b907806b76f4027752
diff --git a/lib/commands/base.rb b/lib/commands/base.rb index <HASH>..<HASH> 100644 --- a/lib/commands/base.rb +++ b/lib/commands/base.rb @@ -59,12 +59,14 @@ module Commands name = get("git config --get pivotal.full-name").strip integration_branch = get("git config --get pivotal.integration-branch").strip only_mine = get("git config --get pivotal.only-mine").strip + append_name = get("git config --get pivotal.append-name").strip options[:api_token] = token unless token == "" options[:project_id] = id unless id == "" options[:full_name] = name unless name == "" options[:integration_branch] = integration_branch unless integration_branch == "" options[:only_mine] = (only_mine != "") unless name == "" + options[:append_name] = (append_name != "") end def parse_argv(*args) @@ -75,6 +77,7 @@ module Commands opts.on("-n", "--full-name=", "Pivotal Trakcer full name") { |n| options[:full_name] = n } opts.on("-b", "--integration-branch=", "The branch to merge finished stories back down onto") { |b| options[:integration_branch] = b } opts.on("-m", "--only-mine", "Only select Pivotal Tracker stories assigned to you") { |m| options[:only_mine] = m } + opts.on("-a", "--append-name", "whether to append the story id to branch name instead of prepend") { |a| options[:append_name] = a } opts.on("-D", "--defaults", "Accept default options. No-interaction mode") { |d| options[:defaults] = d } opts.on("-q", "--quiet", "Quiet, no-interaction mode") { |q| options[:quiet] = q } opts.on("-v", "--[no-]verbose", "Run verbosely") { |v| options[:verbose] = v } diff --git a/lib/commands/pick.rb b/lib/commands/pick.rb index <HASH>..<HASH> 100755 --- a/lib/commands/pick.rb +++ b/lib/commands/pick.rb @@ -36,14 +36,18 @@ module Commands put "Updating #{type} status in Pivotal Tracker..." if story.update(:owned_by => options[:full_name]) - suffix = "" + suffix_or_prefix = "" unless options[:quiet] || options[:defaults] - put "Enter branch name (will be prepended by #{story.id}) [#{branch_suffix}]: ", false - suffix = input.gets.chomp + put "Enter branch name (will be #{options[:append_name] ? 'appended' : 'prepended'} by #{story.id}) [#{suffix_or_prefix}]: ", false + suffix_or_prefix = input.gets.chomp end - suffix = branch_suffix if suffix == "" + suffix_or_prefix = branch_suffix if suffix_or_prefix == "" - branch = "#{story.id}-#{suffix}" + if options[:append_name] + branch = "#{suffix_or_prefix}-#{story.id}" + else + branch = "#{story.id}-#{suffix_or_prefix}" + end if get("git branch").match(branch).nil? put "Switched to a new branch '#{branch}'" sys "git checkout -b #{branch}" diff --git a/readme.markdown b/readme.markdown index <HASH>..<HASH> 100644 --- a/readme.markdown +++ b/readme.markdown @@ -50,6 +50,10 @@ The project id is best placed within your project's git config: git config -f .git/config pivotal.project-id 88888 +If you would rather have the story id appended to the branch name (feature-123456) instead of prepending (123456-feature), you can configue that: + + git config -f .git/config pivotal.append-name true + If you're not interested in storing these options in git, you can pass them into git pivotal as command line arguments. See the usage guides for more details. ##TODO diff --git a/spec/commands/base_spec.rb b/spec/commands/base_spec.rb index <HASH>..<HASH> 100644 --- a/spec/commands/base_spec.rb +++ b/spec/commands/base_spec.rb @@ -100,4 +100,24 @@ describe Commands::Base do @pick.run! end + it "should set the append name flag with the -a option" do + @pick = Commands::Base.new(@input, @output,"-a") + @pick.options[:append_name].should be_true + end + + it "should set the append name flag from git config" do + Commands::Base.any_instance.stubs(:get).with("git config --get pivotal.append-name").returns("true") + @pick = Commands::Base.new + @pick.options[:append_name].should be_true + end + + it "should set the append name flag with the --append-name" do + @pick = Commands::Base.new(@input, @output, "--append-name") + @pick.options[:append_name].should be_true + end + + it "should default the append name flag if none is specified" do + @pick = Commands::Base.new + @pick.options[:append_name].should be_false + end end \ No newline at end of file
add option for appending the branch name
trydionel_git-pivotal
train
1d8bdd3afc94ef9c17e0bdf2cc6cc07b4e350fc7
diff --git a/lib/pry-theme/commands.rb b/lib/pry-theme/commands.rb index <HASH>..<HASH> 100644 --- a/lib/pry-theme/commands.rb +++ b/lib/pry-theme/commands.rb @@ -128,22 +128,22 @@ module PryTheme end def test_theme - example = <<-TEST + example = <<-'TEST' # "#{ PryTheme.current_theme }" theme. class PryTheme::ThisIsAClass def this_is_a_method THIS_IS_A_CONSTANT = :this_is_a_symbol - this_is_a_local_var = "This is a string." + this_is_a_local_var = "#{this} is a string.\n" this_is_a_float = 10_000.00 this_is_an_integer = 10_000 # TRUE and FALSE are predefined constants. $this_is_a_global_variable = TRUE or FALSE - @this_is_an_instance_variable = `echo 'system call'` + @this_is_an_instance_variable = `echo '#{system} call\n'` @@this_is_a_class_variable = @$ # An error. - /[0-9]{1,3}this is a regexp\\w+/xi + /[0-9]{1,3}this #{is} a regexp\w+/xi end end TEST
Slightly amend `-t` output
kyrylo_pry-theme
train
2f32ae78325797cb9d543f6500401abf9a09e760
diff --git a/outdated/utils.py b/outdated/utils.py index <HASH>..<HASH> 100644 --- a/outdated/utils.py +++ b/outdated/utils.py @@ -2,10 +2,9 @@ import os import tempfile from contextlib import contextmanager from datetime import datetime, timedelta -from time import sleep from warnings import warn -import functools +from littleutils import retry from outdated.mywarnings import OutdatedCacheFailedWarning @@ -18,24 +17,6 @@ def cache_is_valid(cache_dt): return format_date(datetime.now() - timedelta(days=1)) < cache_dt -def retry(num_attempts=3, exception_class=Exception, sleeptime=1): - def decorator(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - for i in range(num_attempts): - try: - return func(*args, **kwargs) - except exception_class: - if i == num_attempts - 1: - raise - else: - sleep(sleeptime) - - return wrapper - - return decorator - - # noinspection PyCompatibility @retry() def get_url(url): diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -9,6 +9,7 @@ setup(name='outdated', author_email='alex.mojaki@gmail.com', license='MIT', packages=['outdated'], + install_requires=['littleutils'], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python',
Use retry from littleutils library
alexmojaki_outdated
train
74a5a3cfce01f26c58cb02a9055c37ce3187a202
diff --git a/elasticsearch-api/lib/elasticsearch/api/actions/cluster/reroute.rb b/elasticsearch-api/lib/elasticsearch/api/actions/cluster/reroute.rb index <HASH>..<HASH> 100644 --- a/elasticsearch-api/lib/elasticsearch/api/actions/cluster/reroute.rb +++ b/elasticsearch-api/lib/elasticsearch/api/actions/cluster/reroute.rb @@ -22,12 +22,15 @@ module Elasticsearch # @option arguments [Hash] :body The definition of `commands` to perform (`move`, `cancel`, `allocate`) # @option arguments [Boolean] :dry_run Simulate the operation only and return the resulting state # @option arguments [Boolean] :explain Return an explanation for why the commands can or cannot be executed - # @option arguments [Boolean] :filter_metadata Don't return cluster state metadata (default: false) + # @option arguments [Boolean] :metric Limit the information returned to the specified metrics. + # Defaults to all but metadata. (Options: _all, blocks, metadata, + # nodes, routing_table, master_node, version) + # @option arguments [Time] :master_timeout Specify timeout for connection to master # # @see http://elasticsearch.org/guide/reference/api/admin-cluster-reroute/ # def reroute(arguments={}) - valid_params = [ :dry_run, :explain, :filter_metadata ] + valid_params = [ :dry_run, :explain, :metric, :master_timeout, :timeout ] method = 'POST' path = "_cluster/reroute"
[API] Added the support for `metric` URL parameter to the "Reroute" API Related: elasticsearch/elasticsearch#<I>
elastic_elasticsearch-ruby
train