hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
6e8357f07695e0f957d72a97a8b42c467bd72255
diff --git a/lib/serve-command.js b/lib/serve-command.js index <HASH>..<HASH> 100644 --- a/lib/serve-command.js +++ b/lib/serve-command.js @@ -1,5 +1,6 @@ var path = require('path'), express = require('express'), + bodyParser = require('body-parser'), walker = require('./dir-walker'), gherkin = require('./gherkin-model'), markdown = require('./markdown-parser'), @@ -26,6 +27,9 @@ function execute(params) { port = params.port, metadata = readMetadataSync(); + app.disable('x-powered-by'); + app.use(bodyParser.text()); + // serve static files from the `public` folder app.use('/', express.static(path.join(__dirname, '..', 'public'))); @@ -63,7 +67,13 @@ function execute(params) { index: false })); - app.disable('x-powered-by'); + app.post('/api/rest/raw/:path', function (req, res) { + // TODO Implement me! Remember about security considerations (e.g. validate some token before saving the content). + console.log('feature to be updated:', req.params.path); + console.log('content:', req.body); + res.end(); + }); + app.listen(port); printServeStatus(port); diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,7 @@ }, "dependencies": { "bash-color": "0.0.3", + "body-parser": "^1.13.1", "commander": "^2.8.1", "express": "^4.12.4", "gherkin": "^2.12.2", diff --git a/public/scripts/feature-editor.controller.js b/public/scripts/feature-editor.controller.js index <HASH>..<HASH> 100644 --- a/public/scripts/feature-editor.controller.js +++ b/public/scripts/feature-editor.controller.js @@ -6,9 +6,9 @@ angular.module('scFeatureBook') .controller('FeatureEditorController', FeatureEditorController); - FeatureEditorController.$inject = ['$scope', '$route', '$location']; + FeatureEditorController.$inject = ['$scope', '$route', '$location', 'featureBookService']; - function FeatureEditorController($scope, $route, $location) { + function FeatureEditorController($scope, $route, $location, featureBookService) { $activate(); @@ -31,7 +31,7 @@ } $scope.onSave = function onSave() { - alert('Sorry, I am not implemented yet!'); + featureBookService.save($route.current.pathParams.path, $scope.content); }; $scope.onCancel = function onClick() { diff --git a/public/scripts/featurebook.service.js b/public/scripts/featurebook.service.js index <HASH>..<HASH> 100644 --- a/public/scripts/featurebook.service.js +++ b/public/scripts/featurebook.service.js @@ -14,7 +14,8 @@ summary: summary, findAll: findAll, getModelByPath: getModelByPath, - getContentByPath: getContentByPath + getContentByPath: getContentByPath, + save: save }; function metadata() { @@ -46,6 +47,17 @@ return response.data; }); } + + function save(path, content) { + return $http({ + method: 'POST', + url: '/api/rest/raw/' + encodeURIComponent(path), + data: content, + headers: { + 'Content-Type': 'text/plain' + } + }); + } } })(); \ No newline at end of file
Write/find an AngularJS directive that wraps Ace editor and fix #<I>
SOFTWARE-CLINIC_featurebook
train
04e49f2e072156dfce8dbfcc87e7f8ea21967ea9
diff --git a/css/igv.css b/css/igv.css index <HASH>..<HASH> 100644 --- a/css/igv.css +++ b/css/igv.css @@ -1,3 +1,6 @@ +.igv-dialog-label-centered { + text-align: center; +} /* prevent unwanted translucent blue overlay when user selects anywhere in ENCODE table */ div[id="igvEncodeModal"] { diff --git a/js/igv-utils.js b/js/igv-utils.js index <HASH>..<HASH> 100755 --- a/js/igv-utils.js +++ b/js/igv-utils.js @@ -69,7 +69,7 @@ var igv = (function (igv) { trackItems, menuItems = [ - igv.dialogMenuItem(popover, trackView, "Set track name", "Track Name", trackView.track.name, function () { + igv.dialogMenuItem(popover, trackView, "Set track name", function () { return "Track Name" }, trackView.track.name, function () { var alphanumeric = parseAlphanumeric($(this).val()); @@ -89,7 +89,7 @@ var igv = (function (igv) { }), - igv.dialogMenuItem(popover, trackView, "Set track height", "Track Height", trackHeight, function () { + igv.dialogMenuItem(popover, trackView, "Set track height", function () { return "Track Height" }, trackHeight, function () { var number = parseNumber($(this).val()); @@ -148,21 +148,25 @@ var igv = (function (igv) { if (trackView.track.removable !== false) { menuItems.push( - { - object: $('<div class="igv-track-menu-item igv-track-menu-border-top">Remove track</div>'), - click: function () { - popover.hide(); - trackView.browser.removeTrack(trackView.track); - } - } + igv.dialogMenuItem(popover, trackView, "Remove track", function () { + + return '<div class="igv-dialog-label-centered">' + 'Remove Label' + '</div>'; + + }, undefined, undefined, function () { + + popover.hide(); + trackView.browser.removeTrack(trackView.track); + + }) ); + } return menuItems; }; - igv.dialogMenuItem = function (popover, trackView, gearMenuLabel, dialogLabel, dialogInputValue, dialogInputChange) { + igv.dialogMenuItem = function (popover, trackView, gearMenuLabel, dialogLabelHTMLFunction, dialogInputValue, dialogInputChange, dialogClickOK) { return { object: $('<div class="igv-track-menu-item">' + gearMenuLabel + '</div>'), @@ -170,13 +174,30 @@ var igv = (function (igv) { igv.dialog.trackView = trackView; - igv.dialog.$dialogLabel.text(dialogLabel); + if (dialogLabelHTMLFunction) { - igv.dialog.$dialogInput.val(dialogInputValue); + igv.dialog.$dialogLabel.show(); - igv.dialog.$dialogInput.unbind(); - igv.dialog.$dialogInput.change(dialogInputChange); + igv.dialog.$dialogLabel.html(dialogLabelHTMLFunction()); + } else { + igv.dialog.$dialogLabel.hide(); + } + + if (dialogInputValue) { + + igv.dialog.$dialogInput.show(); + + igv.dialog.$dialogInput.val(dialogInputValue); + igv.dialog.$dialogInput.unbind(); + igv.dialog.$dialogInput.change(dialogInputChange); + } else { + igv.dialog.$dialogInput.hide(); + } + + if (dialogClickOK) { + igv.dialog.clickOK = dialogClickOK; + } igv.dialog.show(); popover.hide(); } diff --git a/js/trackCore.js b/js/trackCore.js index <HASH>..<HASH> 100644 --- a/js/trackCore.js +++ b/js/trackCore.js @@ -228,7 +228,7 @@ var igv = (function (igv) { default: } } - } + }; igv.setTrackLabel = function (track, label) { diff --git a/js/ui/dialog.js b/js/ui/dialog.js index <HASH>..<HASH> 100644 --- a/js/ui/dialog.js +++ b/js/ui/dialog.js @@ -75,7 +75,9 @@ var igv = (function (igv) { $columnFiller = $('<div class="igv-col-filler-ok-button">'); $columnFiller.text("OK"); $columnFiller.click(function() { + self.hide(); + self.clickOK(); }); $column.append( $columnFiller[ 0 ] ); //
Delete track menu item now presents ok/cancel.
igvteam_igv.js
train
27623dd089e93b49350468e75caccfa55c9ea1b9
diff --git a/nose/test_quantity.py b/nose/test_quantity.py index <HASH>..<HASH> 100644 --- a/nose/test_quantity.py +++ b/nose/test_quantity.py @@ -1401,13 +1401,15 @@ def test_plotting_inputAsQuantity(): xrange=[-4.*units.kpc,4.*units.kpc], yrange=[-6.*units.kpc,7.*units.kpc]) # Rotcurve - pot.plotRotcurve(Rrange=[1.*units.kpc,8.*units.kpc]) - plpot.plotRotcurve(Rrange=[1.*units.kpc,8.*units.kpc]) + pot.plotRotcurve(Rrange=[1.*units.kpc,8.*units.kpc],ro=10.,vo=250.) + plpot.plotRotcurve(Rrange=[1.*units.kpc,8.*units.kpc], + ro=10.*units.kpc,vo=250.*units.km/units.s) potential.plotRotcurve(pot,Rrange=[1.*units.kpc,8.*units.kpc]) potential.plotRotcurve([pot],Rrange=[1.*units.kpc,8.*units.kpc]) # Escapecurve - pot.plotEscapecurve(Rrange=[1.*units.kpc,8.*units.kpc]) - plpot.plotEscapecurve(Rrange=[1.*units.kpc,8.*units.kpc]) + pot.plotEscapecurve(Rrange=[1.*units.kpc,8.*units.kpc],ro=10.,vo=250.) + plpot.plotEscapecurve(Rrange=[1.*units.kpc,8.*units.kpc], + ro=10.*units.kpc,vo=250.*units.km/units.s) potential.plotEscapecurve(pot,Rrange=[1.*units.kpc,8.*units.kpc]) potential.plotEscapecurve([pot],Rrange=[1.*units.kpc,8.*units.kpc]) return None
Hit plotRotcurve and plotEscapecurve with physical units
jobovy_galpy
train
d124c52ff5313df19f978d4b5073cca98051f83d
diff --git a/tests/helpers/mock_helper.rb b/tests/helpers/mock_helper.rb index <HASH>..<HASH> 100644 --- a/tests/helpers/mock_helper.rb +++ b/tests/helpers/mock_helper.rb @@ -77,6 +77,7 @@ if Fog.mock? :ovirt_password => '123123', :libvirt_uri => 'qemu://libvirt/system', :rackspace_api_key => 'rackspace_api_key', + :rackspace_region => 'dfw', :rackspace_username => 'rackspace_username', :riakcs_access_key_id => 'riakcs_access_key_id', :riakcs_secret_access_key => 'riakcs_secret_access_key',
[rackspace] set default region in mock helper for tests
fog_fog
train
92cc6789727bee0781e85cab71a74a5b663326f1
diff --git a/databench/analysis.py b/databench/analysis.py index <HASH>..<HASH> 100644 --- a/databench/analysis.py +++ b/databench/analysis.py @@ -276,7 +276,7 @@ class MetaZMQ(Meta): executable, zmq_publish, - port_subscribe + port_subscribe=None, ): Meta.__init__(self, name, import_name, description, AnalysisZMQ) @@ -286,6 +286,16 @@ class MetaZMQ(Meta): self.zmq_analyses = {} self.zmq_confirmed = False + # check whether we have to determine port_subscribe ourselves first + if port_subscribe is None: + socket = zmq.Context().socket(zmq.PUB) + port_subscribe = socket.bind_to_random_port( + 'tcp://127.0.0.1', + min_port=3000, max_port=9000, + ) + socket.unbind('tcp://127.0.0.1:'+str(port_subscribe)) + logging.debug('determined: port_subscribe='+str(port_subscribe)) + # zmq subscription to listen for messages from backend logging.debug('main listening on port: '+str(port_subscribe)) self.zmq_sub = zmq.Context().socket(zmq.SUB) @@ -332,6 +342,10 @@ class MetaZMQ(Meta): time.sleep(0.1) gevent.Greenlet.spawn(sending_init) + def __del__(self): + self.kernel_process.terminate() + self.kernel_process.kill() + def instantiate_analysis_class(self): self.zmq_analysis_id += 1 i = self.analysis_class(self.name, diff --git a/databench/app.py b/databench/app.py index <HASH>..<HASH> 100644 --- a/databench/app.py +++ b/databench/app.py @@ -10,8 +10,11 @@ import argparse import zmq.green as zmq import flask_sockets +import werkzeug.serving +from gevent import pywsgi from flask.ext.markdown import Markdown from flask import Flask, render_template +from geventwebsocket.handler import WebSocketHandler from .analysis import MetaZMQ from . import __version__ as DATABENCH_VERSION @@ -78,8 +81,6 @@ class App(object): def run(self): """Entry point to run the app.""" # self.flask_app.run(host=self.host, port=self.port) - from gevent import pywsgi - from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer((self.host, self.port), self.flask_app, handler_class=WebSocketHandler) @@ -111,46 +112,48 @@ class App(object): """Add Markdown capability.""" Markdown(self.flask_app, extensions=['fenced_code']) - def register_analyses_py(self, zmq_publish, sub_port=8042): + def register_analyses_py(self, zmq_publish): analysis_folders = glob.glob('analyses/*_py') if not analysis_folders: analysis_folders = glob.glob('analyses_packaged/*_py') for analysis_folder in analysis_folders: name = analysis_folder[analysis_folder.find('/')+1:] + if name[0] in ['.', '_']: + continue logging.debug('creating MetaZMQ for '+name) MetaZMQ(name, __name__, "ZMQ Analysis py", ['python', analysis_folder+'/analysis.py'], - zmq_publish, sub_port) - sub_port += 1 + zmq_publish) - def register_analyses_pyspark(self, zmq_publish, sub_port=8142): + def register_analyses_pyspark(self, zmq_publish): analysis_folders = glob.glob('analyses/*_pyspark') if not analysis_folders: analysis_folders = glob.glob('analyses_packaged/*_pyspark') for analysis_folder in analysis_folders: name = analysis_folder[analysis_folder.find('/')+1:] + if name[0] in ['.', '_']: + continue logging.debug('creating MetaZMQ for '+name) MetaZMQ(name, __name__, "ZMQ Analysis py", ['pyspark', analysis_folder+'/analysis.py'], - zmq_publish, sub_port) - sub_port += 1 + zmq_publish) - def register_analyses_go(self, zmq_publish, sub_port=8042): + def register_analyses_go(self, zmq_publish): analysis_folders = glob.glob('analyses/*_go') if not analysis_folders: analysis_folders = glob.glob('analyses_packaged/*_go') for analysis_folder in analysis_folders: name = analysis_folder[analysis_folder.find('/')+1:] + if name[0] in ['.', '_']: + continue logging.info('installing '+name) os.system('cd '+analysis_folder+'; go install') logging.debug('creating MetaZMQ for '+name) MetaZMQ(name, __name__, "ZMQ Analysis go", - [name], - zmq_publish, sub_port) - sub_port += 1 + [name], zmq_publish) def import_analyses(self): """Add analyses from the analyses folder.""" @@ -269,10 +272,14 @@ def run(): print '--- databench v'+DATABENCH_VERSION+' ---' logging.info('host='+str(args.host)+', port='+str(args.port)) logging.info('delimiters='+str(delimiters)) - app = App(__name__, host=args.host, port=args.port, delimiters=delimiters) - app.run() - return app + @werkzeug.serving.run_with_reloader + def reloader(): + app = App(__name__, host=args.host, port=args.port, + delimiters=delimiters) + app.run() + return app + return reloader() if __name__ == '__main__':
Autodetect port for backend. Ignore analyses starting with . or _. Reloader.
svenkreiss_databench
train
1f4cba1e01cd5c5e5f0daeabfdc8573cd3e6c317
diff --git a/storerunner/mysqlrunner/mysql_runner.go b/storerunner/mysqlrunner/mysql_runner.go index <HASH>..<HASH> 100644 --- a/storerunner/mysqlrunner/mysql_runner.go +++ b/storerunner/mysqlrunner/mysql_runner.go @@ -5,7 +5,7 @@ import ( "fmt" "os" - _ "github.com/go-sql-driver/mysql" + "github.com/go-sql-driver/mysql" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) @@ -65,6 +65,14 @@ func (m *MySQLRunner) Reset() { } for _, query := range truncateTablesSQL { result, err := m.db.Exec(query) + switch err := err.(type) { + case *mysql.MySQLError: + if err.Number == 1146 { + // missing table error, it's fine because we're trying to truncate it + continue + } + } + Expect(err).NotTo(HaveOccurred()) Expect(result.RowsAffected()).To(BeEquivalentTo(0)) }
Allow missing table error on MySQL runner [#<I>]
cloudfoundry-attic_storeadapter
train
c70726c9bcceae28a360863583b9fd3f5666a5a1
diff --git a/mockupdb/__init__.py b/mockupdb/__init__.py index <HASH>..<HASH> 100755 --- a/mockupdb/__init__.py +++ b/mockupdb/__init__.py @@ -866,7 +866,7 @@ def _synchronized(meth): class _AutoResponder(object): def __init__(self, server, matcher, *args, **kwargs): self._server = server - if callable(matcher): + if inspect.isfunction(matcher) or inspect.ismethod(matcher): if args or kwargs: raise_args_err() self._matcher = Matcher() # Match anything. @@ -1097,6 +1097,13 @@ class MockupDB(object): ... [{'_id': 1}, {'_id': 2}]) >>> list(client.db.collection.find()) == [{'_id': 1}, {'_id': 2}] True + >>> responder = s.autoresponds(OpQuery, {'a': 1}, {'a': 2}) + >>> list(client.db.collection.find()) == [{'a': 1}, {'a': 2}] + True + + Remove an autoresponder like: + + >>> responder.cancel() If the request currently at the head of the queue matches, it is popped and replied to. Future matching requests skip the queue.
Fix autoresponds(OpQuery, ...) Any case where the first arg is a Request subclass.
ajdavis_mongo-mockup-db
train
7cb9ad235a40e21b7b58d810bca875e606b19917
diff --git a/packages/core/src/framebuffer/FramebufferSystem.js b/packages/core/src/framebuffer/FramebufferSystem.js index <HASH>..<HASH> 100644 --- a/packages/core/src/framebuffer/FramebufferSystem.js +++ b/packages/core/src/framebuffer/FramebufferSystem.js @@ -371,7 +371,6 @@ export default class FramebufferSystem extends System { // you can't have both, so one should take priority if enabled gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); } - // fbo.enableStencil(); } } @@ -428,6 +427,44 @@ export default class FramebufferSystem extends System } /** + * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. + * Used by MaskSystem, when its time to use stencil mask for Graphics element. + * + * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. + * + * @private + */ + forceStencil() + { + const framebuffer = this.current; + + if (!framebuffer) + { + return; + } + + const fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + + if (!fbo || fbo.stencil) + { + return; + } + framebuffer.enableStencil(); + + const w = framebuffer.width; + const h = framebuffer.height; + const gl = this.gl; + const stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); + + fbo.stencil = stencil; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); + } + + /** * resets framebuffer stored state, binds screen framebuffer * * should be called before renderTexture reset() diff --git a/packages/core/src/mask/StencilSystem.js b/packages/core/src/mask/StencilSystem.js index <HASH>..<HASH> 100644 --- a/packages/core/src/mask/StencilSystem.js +++ b/packages/core/src/mask/StencilSystem.js @@ -60,6 +60,8 @@ export default class StencilSystem extends System if (prevMaskCount === 0) { + // force use stencil texture in current framebuffer + this.renderer.framebuffer.forceStencil(); gl.enable(gl.STENCIL_TEST); } diff --git a/packages/core/src/renderTexture/BaseRenderTexture.js b/packages/core/src/renderTexture/BaseRenderTexture.js index <HASH>..<HASH> 100644 --- a/packages/core/src/renderTexture/BaseRenderTexture.js +++ b/packages/core/src/renderTexture/BaseRenderTexture.js @@ -86,8 +86,7 @@ export default class BaseRenderTexture extends BaseTexture this.clearColor = [0, 0, 0, 0]; this.framebuffer = new Framebuffer(this.width * this.resolution, this.height * this.resolution) - .addColorTexture(0, this) - .enableStencil(); + .addColorTexture(0, this); // TODO - could this be added the systems?
Don't enable depth/stencil by default (#<I>)
pixijs_pixi.js
train
ac09dc4a5cd9dc538bd24965ba222a6d9d80a89b
diff --git a/raiden/channel/netting_channel.py b/raiden/channel/netting_channel.py index <HASH>..<HASH> 100644 --- a/raiden/channel/netting_channel.py +++ b/raiden/channel/netting_channel.py @@ -285,8 +285,10 @@ class Channel(object): balance_proof = self.our_state.balance_proof transfer = balance_proof.transfer - # the channel was closed, update our half of the state - self.external_state.update_transfer(self.our_state.address, transfer) + # the channel was closed, update our half of the state if we need to + closing_address = self.external_state.netting_channel.closing_address() + if closing_address != self.our_state.address: + self.external_state.update_transfer(self.our_state.address, transfer) unlock_proofs = balance_proof.get_known_unlocks() self.external_state.withdraw(self.our_state.address, unlock_proofs) diff --git a/raiden/network/rpc/client.py b/raiden/network/rpc/client.py index <HASH>..<HASH> 100644 --- a/raiden/network/rpc/client.py +++ b/raiden/network/rpc/client.py @@ -932,6 +932,9 @@ class NettingChannel(object): def closed(self): return self.proxy.closed.call() + def closing_address(self): + return address_decoder(self.proxy.closingAddress()) + def settled(self): return self.proxy.settled.call() diff --git a/raiden/tests/utils/mock_client.py b/raiden/tests/utils/mock_client.py index <HASH>..<HASH> 100644 --- a/raiden/tests/utils/mock_client.py +++ b/raiden/tests/utils/mock_client.py @@ -409,6 +409,11 @@ class NettingChannelMock(object): def closed(self): return self.contract.closed + def closing_address(self): + closing_address = self.contract.closingAddress + assert len(closing_address) == 20, "Expected binary address" + return closing_address + def settled(self): return self.contract.settled diff --git a/raiden/tests/utils/tester_client.py b/raiden/tests/utils/tester_client.py index <HASH>..<HASH> 100644 --- a/raiden/tests/utils/tester_client.py +++ b/raiden/tests/utils/tester_client.py @@ -602,6 +602,9 @@ class NettingChannelTesterMock(object): closed = self.proxy.closed() return closed + def closing_address(self): + return address_decoder(self.proxy.closingAddress()) + def settled(self): settled = self.proxy.settled() return settled
Call updatetransfer only if we did not close
raiden-network_raiden
train
4ed785090f61556ee9cfb7b41cfc3b88a5b6be69
diff --git a/group_private.go b/group_private.go index <HASH>..<HASH> 100644 --- a/group_private.go +++ b/group_private.go @@ -2,7 +2,6 @@ package flags import ( "reflect" - "strings" "unicode/utf8" "unsafe" ) @@ -206,24 +205,9 @@ func (g *Group) scan() error { } func (g *Group) groupByName(name string) *Group { - name = strings.ToLower(name) - if len(name) == 0 { return g } - for _, subg := range g.groups { - lname := strings.ToLower(subg.ShortDescription) - prefix := lname + "." - - if strings.HasPrefix(name, prefix) { - if grp := subg.groupByName(name[len(prefix):]); grp != nil { - return grp - } - } else if name == lname { - return subg - } - } - - return nil + return g.Find(name) }
Use Group.Find to find group by name
jessevdk_go-flags
train
08ada5342352211740324cd4b3111d604f4b8231
diff --git a/.env b/.env index <HASH>..<HASH> 100644 --- a/.env +++ b/.env @@ -1,2 +1,2 @@ export DATABASE_URL='postgres://ryandotsmith:@localhost/queue_classic_test' -export QC_USE_PUB_SUB='false' +export QC_USE_PUB_SUB='true' diff --git a/lib/queue_classic.rb b/lib/queue_classic.rb index <HASH>..<HASH> 100644 --- a/lib/queue_classic.rb +++ b/lib/queue_classic.rb @@ -11,9 +11,6 @@ require 'queue_classic/queue' require 'queue_classic/job' module QC - - USE_PUB_SUB = ENV["QC_USE_PUB_SUB"] == "true" - def self.method_missing(sym, *args, &block) Queue.send(sym, *args, &block) end diff --git a/lib/queue_classic/database.rb b/lib/queue_classic/database.rb index <HASH>..<HASH> 100644 --- a/lib/queue_classic/database.rb +++ b/lib/queue_classic/database.rb @@ -58,9 +58,6 @@ module QC @db_params.user, @db_params.password ) - if USE_PUB_SUB - @@connection.exec("LISTEN queue_classic_jobs") - end @@connection.exec("SET application_name = 'queue_classic'") silence_warnings unless ENV["LOGGING_ENABLED"] end diff --git a/lib/queue_classic/durable_array.rb b/lib/queue_classic/durable_array.rb index <HASH>..<HASH> 100644 --- a/lib/queue_classic/durable_array.rb +++ b/lib/queue_classic/durable_array.rb @@ -8,9 +8,6 @@ module QC def <<(details) execute("INSERT INTO #{@table_name} (details) VALUES ('#{details.to_json}')") - if USE_PUB_SUB - execute("NOTIFY queue_classic_jobs, 'new-job'") - end end def count @@ -30,25 +27,8 @@ module QC find_many { "SELECT * FROM #{@table_name} WHERE details LIKE '%#{q}%'" } end - def lock_head - find_one { "SELECT * FROM lock_head('#{@table_name}')" } - end - def first - if USE_PUB_SUB - if job = lock_head - job - else - @database.connection.wait_for_notify(1) {|e,p,msg| job = lock_head if msg == "new-job" } - job - end - else - job = nil - until job - sleep(1) unless job = lock_head - end - job - end + find_one { "SELECT * FROM lock_head('#{@table_name}')" } end def each diff --git a/lib/queue_classic/worker.rb b/lib/queue_classic/worker.rb index <HASH>..<HASH> 100644 --- a/lib/queue_classic/worker.rb +++ b/lib/queue_classic/worker.rb @@ -30,7 +30,7 @@ module QC end def work - if job = @queue.dequeue #blocks until we have a job + if job = lock_job begin job.work rescue Object => e @@ -41,6 +41,24 @@ module QC end end + # blocks until we have a job + def lock_job + attempts = 0 + job = nil + until job + job = @queue.dequeue + if job.nil? + attempts += 1 + if tries < MAX_LOCK_ATTEMPTS + sleep(2**attempts) + next + end + else + end + end + job + end + #override this method to do whatever you want def handle_failure(job,e) puts "!"
remove all pubsub and use a exp backoff in the worker
QueueClassic_queue_classic
train
49edf3dea9b514a4fa24164476ce3548c02ff8d7
diff --git a/src/scidata/common.py b/src/scidata/common.py index <HASH>..<HASH> 100644 --- a/src/scidata/common.py +++ b/src/scidata/common.py @@ -89,14 +89,3 @@ class _DataWrapperMixin(object): name=('' if module is None else module + '.') + name, cls=cls.__name__) return func - - # we want something like this, right? - # def apply(self, func, dimension=None, axis=None, **kwargs): - # if dimension is not None and axis is not None: - # raise ValueError("cannot supply both 'axis' and 'dimension' " - # "arguments") - # if axis is None: - # axis = self.dimensions.index(dimension) - # f = self._unary_op(partial(func, axis=axis, **kwargs)) - # return f(self) - diff --git a/src/scidata/dataview.py b/src/scidata/dataview.py index <HASH>..<HASH> 100644 --- a/src/scidata/dataview.py +++ b/src/scidata/dataview.py @@ -377,6 +377,12 @@ class DataView(_DataWrapperMixin): ds[focus] = variable.Variable.from_stack(dataviews, dim_name) return cls(ds, focus) + def apply(self, func, *args, **kwargs): + """Apply `func` with *args and **kwargs to this dataview's data and + return the result as a new dataview + """ + return self.refocus(self.variable.apply(func, *args, **kwargs)) + def to_dataframe(self): """Convert this dataview into a pandas.DataFrame diff --git a/src/scidata/utils.py b/src/scidata/utils.py index <HASH>..<HASH> 100644 --- a/src/scidata/utils.py +++ b/src/scidata/utils.py @@ -61,7 +61,6 @@ def orthogonal_indexer(key, shape): key[n] = array_indexers[i] return tuple(key) - def remap_loc_indexers(indices, indexers): """Given mappings of indices and label based indexers, return equivalent location based indexers diff --git a/src/scidata/variable.py b/src/scidata/variable.py index <HASH>..<HASH> 100644 --- a/src/scidata/variable.py +++ b/src/scidata/variable.py @@ -480,6 +480,13 @@ class Variable(_DataWrapperMixin): return stacked + def apply(self, func, *args, **kwargs): + """Apply `func` with *args and **kwargs to this variable's data and + return the result as a new variable with the same dimensions + """ + data = np.asarray(func(self.data, *args, **kwargs)) + return type(self)(self.dimensions, data, self.attributes) + def __array_wrap__(self, result): return type(self)(self.dimensions, result, self.attributes) diff --git a/test/test_variable.py b/test/test_variable.py index <HASH>..<HASH> 100644 --- a/test/test_variable.py +++ b/test/test_variable.py @@ -185,6 +185,14 @@ class TestVariable(TestCase): # test ufuncs self.assertVarEqual(np.sin(v), Variable(['x'], np.sin(x))) + def test_apply(self): + x = np.arange(5) + v = Variable(['x'], x) + def numpy_only_square(x): + return np.asarray(x) ** 2 + self.assertArrayEqual(x ** 2, numpy_only_square(v)) + self.assertVarEqual(v ** 2, v.apply(numpy_only_square)) + def test_collapse(self): v = Variable(['time', 'x'], self.d) # intentionally test with an operation for which order matters
Added Variable.apply and DataView.apply
pydata_xarray
train
96264faeaccaaa5b24d5ed19fb7126ddb0e3bd60
diff --git a/owslib/util.py b/owslib/util.py index <HASH>..<HASH> 100644 --- a/owslib/util.py +++ b/owslib/util.py @@ -144,8 +144,10 @@ def testXMLValue(val, attrib=False): if val is not None: if attrib == True: return val.strip() - else: + elif val.text: return val.text.strip() + else: + return None else: return None
strip can not been called on empty element, for example '<Abstract />', we need to check first if the element has a text content
geopython_OWSLib
train
614495abc864ef0c63d01e49c9a6f9b848636a4f
diff --git a/plugin/acts_as_ferret/lib/acts_as_ferret.rb b/plugin/acts_as_ferret/lib/acts_as_ferret.rb index <HASH>..<HASH> 100644 --- a/plugin/acts_as_ferret/lib/acts_as_ferret.rb +++ b/plugin/acts_as_ferret/lib/acts_as_ferret.rb @@ -19,7 +19,9 @@ # SOFTWARE. require 'active_record' -require 'ferret' +require_gem 'ferret', '=0.3.2' +#require 'rferret' +#require 'ferret' # Yet another Ferret Mixin. # @@ -253,10 +255,11 @@ module FerretMixin # :num_docs - number of hits to retrieve def find_by_contents(q, options = {}) id_array = [] + scores_by_id = {} find_id_by_contents(q, options).each do |element| - id_array << element[:id] + id_array << id = element[:id].to_i + scores_by_id[id] = element[:score] end - logger.debug "id_array: #{id_array.inspect}" begin if self.superclass == ActiveRecord::Base result = self.find(id_array) @@ -270,7 +273,11 @@ module FerretMixin rescue logger.debug "REBUILD YOUR INDEX! One of the id's didn't have an associated record: #{id_array}" end - logger.debug "Result id_array: #{id_array.inspect}, result: #{result}" + + # sort results by score (descending) + result.sort! { |b, a| scores_by_id[a.id] <=> scores_by_id[b.id] } + + logger.debug "Query: #{q}\nResult id_array: #{id_array.inspect},\nresult: #{result},\nscores: #{scores_by_id.inspect}" return result end
#9 fixed, results are now ordered by score after retrieving them from the database git-svn-id: svn://projects.jkraemer.net/acts_as_ferret/trunk@<I> <I>d<I>-0a0e-<I>-9cad-a9b<I>e<I>dc
jkraemer_acts_as_ferret
train
950db5cce0a4a64d6fb6e0d56954afcd755f3d3f
diff --git a/dist/stackonly/tablesaw.stackonly.css b/dist/stackonly/tablesaw.stackonly.css index <HASH>..<HASH> 100644 --- a/dist/stackonly/tablesaw.stackonly.css +++ b/dist/stackonly/tablesaw.stackonly.css @@ -1,4 +1,4 @@ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ diff --git a/dist/stackonly/tablesaw.stackonly.jquery.js b/dist/stackonly/tablesaw.stackonly.jquery.js index <HASH>..<HASH> 100644 --- a/dist/stackonly/tablesaw.stackonly.jquery.js +++ b/dist/stackonly/tablesaw.stackonly.jquery.js @@ -1,4 +1,4 @@ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ (function (root, factory) { diff --git a/dist/stackonly/tablesaw.stackonly.js b/dist/stackonly/tablesaw.stackonly.js index <HASH>..<HASH> 100644 --- a/dist/stackonly/tablesaw.stackonly.js +++ b/dist/stackonly/tablesaw.stackonly.js @@ -1,4 +1,4 @@ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ /*! Shoestring - v2.0.0 - 2017-02-14 diff --git a/dist/stackonly/tablesaw.stackonly.scss b/dist/stackonly/tablesaw.stackonly.scss index <HASH>..<HASH> 100644 --- a/dist/stackonly/tablesaw.stackonly.scss +++ b/dist/stackonly/tablesaw.stackonly.scss @@ -1,7 +1,7 @@ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ diff --git a/dist/tablesaw-init.js b/dist/tablesaw-init.js index <HASH>..<HASH> 100644 --- a/dist/tablesaw-init.js +++ b/dist/tablesaw-init.js @@ -1,4 +1,4 @@ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ (function(win) { diff --git a/dist/tablesaw.css b/dist/tablesaw.css index <HASH>..<HASH> 100644 --- a/dist/tablesaw.css +++ b/dist/tablesaw.css @@ -1,4 +1,4 @@ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ diff --git a/dist/tablesaw.jquery.js b/dist/tablesaw.jquery.js index <HASH>..<HASH> 100644 --- a/dist/tablesaw.jquery.js +++ b/dist/tablesaw.jquery.js @@ -1,4 +1,4 @@ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ (function (root, factory) { diff --git a/dist/tablesaw.js b/dist/tablesaw.js index <HASH>..<HASH> 100644 --- a/dist/tablesaw.js +++ b/dist/tablesaw.js @@ -1,4 +1,4 @@ -/*! Tablesaw - v3.0.6 - 2017-11-17 +/*! Tablesaw - v3.0.6 - 2017-11-20 * https://github.com/filamentgroup/tablesaw * Copyright (c) 2017 Filament Group; Licensed MIT */ /*! Shoestring - v2.0.0 - 2017-02-14
<I> release dists
filamentgroup_tablesaw
train
fd39b21a32990aae532ea202b340d53f82660796
diff --git a/lib/haml/util.rb b/lib/haml/util.rb index <HASH>..<HASH> 100755 --- a/lib/haml/util.rb +++ b/lib/haml/util.rb @@ -1,5 +1,5 @@ begin - require 'erubis' + require 'erubis/tiny' rescue LoadError require 'erb' end @@ -240,7 +240,7 @@ MSG info = caller_info powerset(vars).each do |set| context = StaticConditionalContext.new(set).instance_eval {binding} - method_content = (defined?(Erubis::Eruby) && Erubis::Eruby || ERB).new(erb).result(context) + method_content = (defined?(Erubis::TinyEruby) && Erubis::TinyEruby || ERB).new(erb).result(context) klass.class_eval(<<METHOD, info[0], info[1]) def #{static_method_name(name, *vars.map {|v| set.include?(v)})}(#{args.join(', ')})
Use TinyRuby rather than Eruby for static method parsing.
haml_haml
train
c5c98c31a184837c7f5b1f43d8ef18a676a8bf30
diff --git a/integration-cli/docker_cli_exec_test.go b/integration-cli/docker_cli_exec_test.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_cli_exec_test.go +++ b/integration-cli/docker_cli_exec_test.go @@ -449,7 +449,7 @@ func (s *DockerSuite) TestInspectExecID(c *check.C) { if out != "[]" && out != "<no value>" { break } - if i == tries { + if i+1 == tries { c.Fatalf("ExecIDs should not be empty, got: %s", out) } time.Sleep(1 * time.Second)
Fix InspectExecID test The check for the end of the loop was off by one which is why we saw errors on the following inpsect() call instead of a timeout
containers_storage
train
e55fba87fb2188905ca7ec716f9a81d2db6bc8c5
diff --git a/src/Find.js b/src/Find.js index <HASH>..<HASH> 100644 --- a/src/Find.js +++ b/src/Find.js @@ -49,7 +49,7 @@ export default class Find extends BaseComponent { return_docs: false }, async ({ deleted, doc }) => { - const { docs } = this.state; + const docs = [...this.state.docs]; const index = docs.findIndex(({ _id }) => doc._id === _id); const found = index !== -1; // Document was deleted or it does not match the selector?
Immutable manipulation on array in find
ArnoSaine_react-pouchdb
train
b9cd69a0fa17570309d7ca75b1fefdd0c395945c
diff --git a/spec/lib/droplet_kit/resources/kubernetes_resource_spec.rb b/spec/lib/droplet_kit/resources/kubernetes_resource_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/droplet_kit/resources/kubernetes_resource_spec.rb +++ b/spec/lib/droplet_kit/resources/kubernetes_resource_spec.rb @@ -63,7 +63,14 @@ RSpec.describe DropletKit::KubernetesResource do expect(clusters).to all(be_kind_of(DropletKit::Kubernetes)) cluster = clusters.first + expect(cluster.id).to eq("cluster-1-id") + expect(cluster.name).to eq("test-cluster") + expect(cluster.region).to eq("nyc1") + expect(cluster.version).to eq("1.12.1-do.2") + expect(cluster.cluster_subnet).to eq("10.244.0.0/16") + expect(cluster.ipv4).to eq("0.0.0.0") + expect(cluster.tags).to match_array(["test-k8", "k8s", "k8s:cluster-1-id"]) end it 'returns an empty array of droplets' do
add more attrs to the cluster response
digitalocean_droplet_kit
train
7bed36db263432d58379bff7ebdd5b86b4976de5
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -3,7 +3,7 @@ var gulp = require('gulp'); var nugetpack = require('./index'); -gulp.task('package', function(callback) { +gulp.task('test', function(callback) { var pkg = require('./package.json'); nugetpack({ @@ -35,5 +35,3 @@ gulp.task('package', function(callback) { callback); }); - -gulp.task('test', ['package']) diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -4,8 +4,10 @@ var fs = require('fs'); var path = require('path'); var gulp = require('gulp'); var queue = require('queue-async'); -var gutil = require('gulp-util'); +var PluginError = require('plugin-error'); var through = require('through2'); +var log = require('fancy-log'); +var colors = require('ansi-colors'); var Package = require('grunt-nuget-pack/lib/Package'); var NUGETPACK_EXT = "nupkg"; @@ -14,7 +16,7 @@ module.exports = function(options, files, taskCallback) { var baseDir, pack; if (typeof options != "object") { - throw new gutil.PluginError({ + throw new PluginError({ plugin: 'nugetpack', message: "Required meta information not specified." }); @@ -47,7 +49,7 @@ module.exports = function(options, files, taskCallback) { if (!dest) { if (path.resolve(src) .indexOf(path.resolve(baseDir)) !== 0) { - throw new gutil.PluginError({ + throw new PluginError({ plugin: 'nugetpack', message: "Path for file: " + src + " isn't within the baseDir: " + @@ -88,9 +90,9 @@ module.exports = function(options, files, taskCallback) { try { pack.saveAs(packageFilePath, taskCallback); - gutil.log(gutil.colors.green("Created nupkg file:"), gutil.colors.white(packageFilePath)); + log(colors.green("Created nupkg file:"), colors.white(packageFilePath)); } catch (ex) { - throw new gutil.PluginError({ + throw new PluginError({ plugin: 'nugetpack', message: ex.message }); diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -22,11 +22,14 @@ "url": "https://github.com/w8r/gulp-nuget-pack/issues" }, "homepage": "https://github.com/w8r/gulp-nuget-pack#readme", - "devDependencies": {}, + "devDependencies": { + "ansi-colors": "^3.1.0", + "fancy-log": "^1.3.2" + }, "dependencies": { "grunt-nuget-pack": "0.0.6", - "gulp": "^3.8.11", - "gulp-util": "^3.0.4", + "gulp": "^4.0.0", + "plugin-error": "^1.0.1", "queue-async": "^1.0.7", "through2": "^0.6.5" }
Update gulp to remove vulnerabilities; remove deprecated gulp-util
w8r_gulp-nuget-pack
train
b6d12864141b0280f4dd4f54ffa31e7892bd90e2
diff --git a/lib/accesslib.php b/lib/accesslib.php index <HASH>..<HASH> 100644 --- a/lib/accesslib.php +++ b/lib/accesslib.php @@ -4110,8 +4110,7 @@ function sort_by_roleassignment_authority($users, context $context, $roles = arr * system is more flexible. If you really need, you can to use this * function but consider has_capability() as a possible substitute. * - * The caller function is responsible for including all the - * $sort fields in $fields param. + * All $sort fields are added into $fields if not present there yet. * * If $roleid is an array or is empty (all roles) you need to set $fields * (and $sort by extension) params according to it, as the first field @@ -4209,6 +4208,22 @@ function get_role_users($roleid, context $context, $parent = false, $fields = '' $params = array_merge($params, $sortparams); } + // Adding the fields from $sort that are not present in $fields. + $sortarray = preg_split('/,\s*/', $sort); + $fieldsarray = preg_split('/,\s*/', $fields); + $addedfields = array(); + foreach ($sortarray as $sortfield) { + if (!in_array($sortfield, $fieldsarray)) { + $fieldsarray[] = $sortfield; + $addedfields[] = $sortfield; + } + } + $fields = implode(', ', $fieldsarray); + if (!empty($addedfields)) { + $addedfields = implode(', ', $addedfields); + debugging('get_role_users() adding '.$addedfields.' to the query result because they were required by $sort but missing in $fields'); + } + if ($all === null) { // Previously null was used to indicate that parameter was not used. $all = true; diff --git a/lib/tests/accesslib_test.php b/lib/tests/accesslib_test.php index <HASH>..<HASH> 100644 --- a/lib/tests/accesslib_test.php +++ b/lib/tests/accesslib_test.php @@ -1443,6 +1443,16 @@ class core_accesslib_testcase extends advanced_testcase { $this->assertArrayHasKey($user1->id, $users); $this->assertArrayHasKey($user3->id, $users); + $users = get_role_users($teacherrole->id, $coursecontext, false, 'u.id, u.email'); + $this->assertDebuggingCalled('get_role_users() adding u.lastname, u.firstname to the query result because they were required by $sort but missing in $fields'); + $this->assertCount(2, $users); + $this->assertArrayHasKey($user1->id, $users); + $this->assertObjectHasAttribute('lastname', $users[$user1->id]); + $this->assertObjectHasAttribute('firstname', $users[$user1->id]); + $this->assertArrayHasKey($user3->id, $users); + $this->assertObjectHasAttribute('lastname', $users[$user3->id]); + $this->assertObjectHasAttribute('firstname', $users[$user3->id]); + $users = get_role_users($teacherrole->id, $coursecontext, false, 'u.id, u.email, u.idnumber', 'u.idnumber', null, $group->id); $this->assertCount(1, $users); $this->assertArrayHasKey($user3->id, $users); diff --git a/lib/upgrade.txt b/lib/upgrade.txt index <HASH>..<HASH> 100644 --- a/lib/upgrade.txt +++ b/lib/upgrade.txt @@ -3,6 +3,9 @@ information provided here is intended especially for developers. === 3.1 === +* The get_role_users() function will now add the $sort fields that are not part + of the requested fields to the query result and will throw a debugging message + with the added fields when that happens. * The core_user::fill_properties_cache() static method has been introduced to be a reference and allow standard user fields data validation. Right now only type validation is supported checking it against the parameter (PARAM_*) type of the target user field. MDL-52781 is
MDL-<I> accesslib: Prevent get_role_users() fail in certain cases The function get_role_users() requires the caller to include the $sort fields in the $fields argument. On PostgreSQL this will cause the function to fail when the default $sort fields aren't part of the requested fields. The behavior of the function is augmented to add the $sort fields to $fields if they are not already present.
moodle_moodle
train
db58468ed855e5d1c4d52e6dec179745330ab2c2
diff --git a/admin/admin.go b/admin/admin.go index <HASH>..<HASH> 100644 --- a/admin/admin.go +++ b/admin/admin.go @@ -102,7 +102,9 @@ func (admin *Admin) NewResource(value interface{}, config ...*Config) *Resource findOneHandler := res.FindOneHandler res.FindOneHandler = func(result interface{}, metaValues *resource.MetaValues, context *qor.Context) error { - context.ResourceID = res.GetPrimaryValue(context.Request) + if context.ResourceID == "" { + context.ResourceID = res.GetPrimaryValue(context.Request) + } return findOneHandler(result, metaValues, context) } diff --git a/admin/resource.go b/admin/resource.go index <HASH>..<HASH> 100644 --- a/admin/resource.go +++ b/admin/resource.go @@ -54,7 +54,10 @@ func (res Resource) GetAdmin() *Admin { // GetPrimaryValue get priamry value from request func (res Resource) GetPrimaryValue(request *http.Request) string { - return request.URL.Query().Get(res.ParamIDName()) + if request != nil { + return request.URL.Query().Get(res.ParamIDName()) + } + return "" } // ParamIDName return param name for primary key like :product_id
Fix set admin context's ResourceID
qor_qor
train
290516ce8ec6b2d1804ccf7294c72c9b72e84142
diff --git a/core/app/assets/javascripts/wymeditor/jquery.refinery.wymeditor.js b/core/app/assets/javascripts/wymeditor/jquery.refinery.wymeditor.js index <HASH>..<HASH> 100644 --- a/core/app/assets/javascripts/wymeditor/jquery.refinery.wymeditor.js +++ b/core/app/assets/javascripts/wymeditor/jquery.refinery.wymeditor.js @@ -4475,7 +4475,7 @@ WYMeditor.WymClassExplorer.prototype._exec = function(cmd,param) { WYMeditor.WymClassExplorer.prototype.selected = function() { var caretPos = this._iframe.contentWindow.document.caretPos; - if(caretPos != null && caretPos.parentElement != undefined) + if(caretPos != null && caretPos.parentElement != undefined) { return(caretPos.parentElement()); } };
fix js syntax error in jquery.refinery.wymeditor.js introduced earlier at <I>f9ee7a
refinery_refinerycms
train
a8129748088c1bf98ba2910e0d2a12c1682c11b8
diff --git a/lnwallet/script_utils.go b/lnwallet/script_utils.go index <HASH>..<HASH> 100644 --- a/lnwallet/script_utils.go +++ b/lnwallet/script_utils.go @@ -185,17 +185,17 @@ func ripemd160H(d []byte) []byte { // OP_IF // OP_CHECKSIG // OP_ELSE -// <recv key> +// <recv htlc key> // OP_SWAP OP_SIZE 32 OP_EQUAL // OP_NOTIF -// OP_DROP 2 OP_SWAP <sender key> 2 OP_CHECKMULTISIG +// OP_DROP 2 OP_SWAP <sender htlc key> 2 OP_CHECKMULTISIG // OP_ELSE // OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY // OP_CHECKSIG // OP_ENDIF // OP_ENDIF -func senderHTLCScript(senderKey, receiverKey, revocationKey *btcec.PublicKey, - paymentHash []byte) ([]byte, error) { +func senderHTLCScript(senderHtlcKey, receiverHtlcKey, + revocationKey *btcec.PublicKey, paymentHash []byte) ([]byte, error) { builder := txscript.NewScriptBuilder() @@ -222,7 +222,7 @@ func senderHTLCScript(senderKey, receiverKey, revocationKey *btcec.PublicKey, // the stack. This will be needed later if we decide that this is the // sender activating the time out clause with the HTLC timeout // transaction. - builder.AddData(receiverKey.SerializeCompressed()) + builder.AddData(receiverHtlcKey.SerializeCompressed()) // Atm, the top item of the stack is the receiverKey's so we use a swap // to expose what is either the payment pre-image or a signature. @@ -245,7 +245,7 @@ func senderHTLCScript(senderKey, receiverKey, revocationKey *btcec.PublicKey, builder.AddOp(txscript.OP_DROP) builder.AddOp(txscript.OP_2) builder.AddOp(txscript.OP_SWAP) - builder.AddData(senderKey.SerializeCompressed()) + builder.AddData(senderHtlcKey.SerializeCompressed()) builder.AddOp(txscript.OP_2) builder.AddOp(txscript.OP_CHECKMULTISIG) @@ -381,7 +381,7 @@ func senderHtlcSpendTimeout(receiverSig []byte, signer Signer, // of the HTLC has passed. // // Possible Input Scripts: -// RECVR: <0> <sender sig> <recvr sig> <preimage> +// RECVR: <0> <sender sig> <recvr sig> <preimage> (spend using HTLC success transaction) // REVOK: <sig> <key> // SENDR: <sig> 0 // @@ -390,18 +390,19 @@ func senderHtlcSpendTimeout(receiverSig []byte, signer Signer, // OP_IF // OP_CHECKSIG // OP_ELSE -// <sendr key> +// <sendr htlc key> // OP_SWAP OP_SIZE 32 OP_EQUAL // OP_IF // OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY -// 2 OP_SWAP <recvr key> 2 OP_CHECKMULTISIG +// 2 OP_SWAP <recvr htlc key> 2 OP_CHECKMULTISIG // OP_ELSE // OP_DROP <cltv expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP // OP_CHECKSIG // OP_ENDIF // OP_ENDIF -func receiverHTLCScript(cltvExipiry uint32, senderKey, - receiverKey, revocationKey *btcec.PublicKey, paymentHash []byte) ([]byte, error) { +func receiverHTLCScript(cltvExipiry uint32, senderHtlcKey, + receiverHtlcKey, revocationKey *btcec.PublicKey, + paymentHash []byte) ([]byte, error) { builder := txscript.NewScriptBuilder() @@ -429,7 +430,7 @@ func receiverHTLCScript(cltvExipiry uint32, senderKey, // the stack. This will be needed later if we decide that this is the // receiver transitioning the output to the claim state using their // second-level HTLC success transaction. - builder.AddData(senderKey.SerializeCompressed()) + builder.AddData(senderHtlcKey.SerializeCompressed()) // Atm, the top item of the stack is the sender's key so we use a swap // to expose what is either the payment pre-image or something else. @@ -460,7 +461,7 @@ func receiverHTLCScript(cltvExipiry uint32, senderKey, // this output, but only by the HTLC success transaction. builder.AddOp(txscript.OP_2) builder.AddOp(txscript.OP_SWAP) - builder.AddData(receiverKey.SerializeCompressed()) + builder.AddData(receiverHtlcKey.SerializeCompressed()) builder.AddOp(txscript.OP_2) builder.AddOp(txscript.OP_CHECKMULTISIG) @@ -475,7 +476,7 @@ func receiverHTLCScript(cltvExipiry uint32, senderKey, // With that item dropped off, we can now enforce the absolute // lock-time required to timeout the HTLC. If the time has passed, then // we'll proceed with a checksig to ensure that this is actually the - // sender of he original HLTC. + // sender of he original HTLC. builder.AddInt64(int64(cltvExipiry)) builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY) builder.AddOp(txscript.OP_DROP)
lnwallet: update sender/receiver HTLC scripts to use distinct HTLC keys In this commit, we modify the naming and comments of the routines that create the sender/receiver HTLC scripts to denote that a set of distinct keys are used. The scripts materially haven’t changed, but the set of keys expected has.
lightningnetwork_lnd
train
7bfb406e44cbd53547918842b9f03fc69209de64
diff --git a/simple_history/tests/tests/test_manager.py b/simple_history/tests/tests/test_manager.py index <HASH>..<HASH> 100644 --- a/simple_history/tests/tests/test_manager.py +++ b/simple_history/tests/tests/test_manager.py @@ -79,3 +79,9 @@ class AsOfAdditionalTestCase(TestCase): doc_change.save() docs_as_of_tmw = models.Document.history.as_of(now + timedelta(days=1)) self.assertFalse(list(docs_as_of_tmw)) + + def test_multiple(self): + document1 = models.Document.objects.create() + document2 = models.Document.objects.create() + historical = models.Document.history.as_of(datetime.now() + timedelta(days=1)) + self.assertEqual(list(historical), [document1, document2])
Test for multiple objects for class-based `as_of`
treyhunner_django-simple-history
train
d998b39bab3b241639b885752914e06fc46383f8
diff --git a/src/EseyeFetcher.php b/src/EseyeFetcher.php index <HASH>..<HASH> 100644 --- a/src/EseyeFetcher.php +++ b/src/EseyeFetcher.php @@ -28,6 +28,7 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; use Seat\Eseye\Containers\EsiAuthentication; use Seat\Eseye\Containers\EsiResponse; +use Seat\Eseye\Exceptions\InvalidAuthencationException; use Seat\Eseye\Exceptions\RequestFailedException; use stdClass; @@ -62,7 +63,7 @@ class EseyeFetcher * * @param \Seat\Eseye\Containers\EsiAuthentication $authentication */ - public function __construct(EsiAuthentication $authentication) + public function __construct(EsiAuthentication $authentication = null) { $this->authentication = $authentication; @@ -76,15 +77,22 @@ class EseyeFetcher * @param string $method * @param string $uri * @param array $body + * @param array $headers * * @return mixed|\Seat\Eseye\Containers\EsiResponse */ - public function call(string $method, string $uri, array $body): EsiResponse + public function call( + string $method, string $uri, array $body, array $headers = []): EsiResponse { - return $this->httpRequest($method, $uri, [ - 'Authorization' => 'Bearer ' . $this->getToken(), - ], $body); + // If we have authentication data, add the + // Authorization header. + if ($this->getAuthentication()) + $headers = array_merge($headers, [ + 'Authorization' => 'Bearer ' . $this->getToken(), + ]); + + return $this->httpRequest($method, $uri, $headers, $body); } /** @@ -181,9 +189,9 @@ class EseyeFetcher } /** - * @return \Seat\Eseye\Containers\EsiAuthentication + * @return \Seat\Eseye\Containers\EsiAuthentication|null */ - public function getAuthentication(): EsiAuthentication + public function getAuthentication() { return $this->authentication; @@ -195,6 +203,11 @@ class EseyeFetcher public function getAuthenticationScopes(): array { + // If we dont have any authentication data, then + // only public calls can be made. + if (is_null($this->getAuthentication())) + return ['public']; + // If there are no scopes that we know of, update them. // There will always be at least 1 as we add the internal // 'public' scope. @@ -230,10 +243,17 @@ class EseyeFetcher /** * @return string + * @throws \Seat\Eseye\Exceptions\InvalidAuthencationException */ private function getToken(): string { + // Ensure that we have authentication data before we try + // and get a token. + if (! $this->getAuthentication()) + throw new InvalidAuthencationException( + 'Trying to get a token without authentication data.'); + // Check the expiry date. $expires = carbon($this->getAuthentication()->token_expires);
Allow for public calls to be made with an `EsiAuthentication` instance
eveseat_eseye
train
7f1814c9e9a32f14d66d804ff3681d495fee5e99
diff --git a/src/adapters/criteo.js b/src/adapters/criteo.js index <HASH>..<HASH> 100644 --- a/src/adapters/criteo.js +++ b/src/adapters/criteo.js @@ -47,7 +47,9 @@ var CriteoAdapter = function CriteoAdapter() { slots.push( new Criteo.PubTag.DirectBidding.DirectBiddingSlot( bid.placementCode, - bid.params.zoneId + bid.params.zoneId, + undefined, + bid.transactionId ) );
Send transactionID to Criteo Services (#<I>)
prebid_Prebid.js
train
e62c24773e9fba7e2f974994fbcf2449305db0c6
diff --git a/lib/ronin/extensions/ip_addr.rb b/lib/ronin/extensions/ip_addr.rb index <HASH>..<HASH> 100644 --- a/lib/ronin/extensions/ip_addr.rb +++ b/lib/ronin/extensions/ip_addr.rb @@ -186,6 +186,8 @@ class IPAddr end end + alias resolv resolv_name + # # Resolves the host-names for the IP address. #
Aliased IPAddr#resolv to resolv_name.
ronin-ruby_ronin-support
train
ba7a6882c83f67d95f3a86f58e164c76c4bb368d
diff --git a/memproxy.go b/memproxy.go index <HASH>..<HASH> 100644 --- a/memproxy.go +++ b/memproxy.go @@ -6,16 +6,8 @@ package main import "bufio" -import "bytes" -import "crypto/rand" -import "encoding/binary" -import "errors" import "fmt" -import "io" -import "math" import "net" -import "strconv" -import "strings" import "./binaryprot" import "./common" @@ -50,46 +42,93 @@ func main() { } } +func abort(remote net.Conn, err error, binary bool) { + // separate fatal errors from "expected" + fmt.Println("Error while processing request. Closing connection. Error:", err.Error()) + // use proper serializer to respond here + remote.Close() +} + func handleConnection(remote net.Conn, local net.Conn) { remoteReader := bufio.NewReader(remote) remoteWriter := bufio.NewWriter(remote) localReader := bufio.NewReader(local) localWriter := bufio.NewWriter(local) - var binary bool - var request interface{} - var err error + var parser common.RequestParser + var responder common.Responder + var reqType common.RequestType + var request interface{} + + var binaryParser binaryprot.BinaryParser + var textParser textprot.TextParser + + var binaryResponder binaryprot.BinaryResponder + var textResponder textprot.TextResponder for { - if isBinaryRequest(remoteReader) { - binary = true - request = binaryprot.Parse(remoteReader) + binary, err := isBinaryRequest(remoteReader) + + if err != nil { + abort(remote, err, binary) + return + } + + if binary { + parser = binaryParser + responder = binaryResponder } else { - binary = false - request = textprot.Parse(remoteReader) + parser = textParser + responder = textResponder + } + + request, reqType, err = parser.ParseRequest(remoteReader) + + if err != nil { + abort(remote, err, binary) + return } // TODO: handle nil - switch request.(type) { - case common.SetRequest: - err = common.HandleSet(request, remoteReader, localReader, localWriter) + switch reqType { + case common.REQUEST_SET: + setRequest, _ := request.(common.SetRequest) + err = common.HandleSet(setRequest, remoteReader, localReader, localWriter) + + if err == nil { + responder.RespondSet(nil, remoteWriter) + } + + case common.REQUEST_DELETE: + deleteRequest, _ := request.(common.DeleteRequest) + err = common.HandleDelete(deleteRequest, localReader, localWriter) + + if err == nil { + responder.RespondDelete(nil, remoteWriter) + } - case common.DeleteRequest: - err = common.HandleDelete(request, localReader, localWriter) + case common.REQUEST_TOUCH: + touchRequest, _ := request.(common.TouchRequest) + err = common.HandleTouch(touchRequest, localReader, localWriter) - case common.TouchRequest: - err = common.HandleTouch(request, localReader, localWriter) + if err == nil { + responder.RespondTouch(nil, remoteWriter) + } - case common.GetRequest: - response, errChan := common.HandleSet(request, localReader, localWriter) + case common.REQUEST_GET: + getRequest, _ := request.(common.GetRequest) + response, errChan := common.HandleGet(getRequest, localReader, localWriter) for { select { case res, ok := <-response: if !ok { response = nil } - // do something to write stuff - case err, ok = <-errChan: + + responder.RespondGetChunk(res, remoteWriter) + + case getErr, ok := <-errChan: if !ok { errChan = nil } + err = getErr break } @@ -97,20 +136,20 @@ func handleConnection(remote net.Conn, local net.Conn) { break } } + + responder.RespondGetEnd(remoteReader, remoteWriter) } + // TODO: distinguish fatal errors from non-fatal if err != nil { - // separate fatal errors from "expected" - fmt.Println("Error while processing request. Closing connection. Error:") - fmt.Println(err.Error()) - // use proper serializer to respond here - remote.Close() + abort(remote, err, binary) + return } } } -func isBinaryRequest(reader *bufio.Reader) bool, err { +func isBinaryRequest(reader *bufio.Reader) (bool, error) { headerByte, err := reader.Peek(1) if err != nil { return false, err } - return headerByte == binaryprot.HeaderByte + return int(headerByte[0]) == binaryprot.MAGIC_REQUEST, nil }
memproxy overhaul. The main function now uses the polymorphic protocol types and kind of gets the full request/response down.
Netflix_rend
train
e43adbb5cb5f7a9fcffac5a7aa91dbc6886699a4
diff --git a/src/edit/methods.js b/src/edit/methods.js index <HASH>..<HASH> 100644 --- a/src/edit/methods.js +++ b/src/edit/methods.js @@ -415,7 +415,7 @@ export default function(CodeMirror) { clearCaches(this) scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop) updateGutterSpace(this.display) - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping) estimateLineHeights(this) signal(this, "refresh", this) }),
Make refresh always re-estimate line heights when wrapping is on Closes #<I>
codemirror_CodeMirror
train
dce19356511b8a90b260c067e1a31dec06745617
diff --git a/dvc/command/checkout.py b/dvc/command/checkout.py index <HASH>..<HASH> 100644 --- a/dvc/command/checkout.py +++ b/dvc/command/checkout.py @@ -1,6 +1,7 @@ import os import stat +from dvc.system import System from dvc.command.common.base import CmdBase from dvc.logger import Logger @@ -13,12 +14,16 @@ class CmdCheckout(CmdBase): def remove_untracked_hardlinks(self): untracked = self.project.scm.untracked_files() + cache = dict((System.inode(c), c) for c in self.project.cache.all()) + for file in untracked: + inode = System.inode(file) + if inode not in cache.keys(): + continue - for file, md5 in self.project.cache.find_cache(untracked).items(): Logger.info(u'Remove \'{}\''.format(file)) os.chmod(file, stat.S_IWRITE) os.remove(file) - os.chmod(self.project.cache.get(md5), stat.S_IREAD) + os.chmod(cache[inode], stat.S_IREAD) dir = os.path.dirname(file) if len(dir) != 0 and not os.listdir(dir):
checkout: optimize lost hardlink search Speeds up checkout for <I>K files from 6sec to <I>sec
iterative_dvc
train
e50c92ac63c859b58f247c76e6c009f8ea26ac7a
diff --git a/lib/Auth/Basic.php b/lib/Auth/Basic.php index <HASH>..<HASH> 100644 --- a/lib/Auth/Basic.php +++ b/lib/Auth/Basic.php @@ -359,6 +359,7 @@ class Auth_Basic extends AbstractController { $this->model->unload(); + // maybe can use $this->api->destroySession() here instead? $this->forget('info'); $this->forget('id');
Auth_Basic added just comment - maybe logout() can be changed to use api->destroySession() ? Any drawbacks?
atk4_atk4
train
97731e177477b18a0931850228ccb22e005c61d3
diff --git a/worker/agent.go b/worker/agent.go index <HASH>..<HASH> 100644 --- a/worker/agent.go +++ b/worker/agent.go @@ -66,6 +66,7 @@ func (a *agent) work() { } else if( err == io.EOF ){ a.disconnect_error(err) + break } a.worker.err(err) // If it is unexpected error and the connection wasn't
FIX: EOF disconnect error also called raw handler afterwards
mikespook_gearman-go
train
889d4894b228213dcdccc184fe4ace95414dea25
diff --git a/dipper/sources/MMRRC.py b/dipper/sources/MMRRC.py index <HASH>..<HASH> 100644 --- a/dipper/sources/MMRRC.py +++ b/dipper/sources/MMRRC.py @@ -142,7 +142,8 @@ class MMRRC(Source): mgi_gene_name, sds_url, accepted_date, mp_ids, pubmed_nums, research_areas) = row - if self.testMode and (strain_id not in self.test_ids): + if self.testMode and (strain_id not in self.test_ids) \ + or mgi_gene_name == 'withdrawn': continue # strip off stuff after the dash -
avoid processing variants for withdrawn genes
monarch-initiative_dipper
train
fa749cc28f6886f17e5ef157b4987730d2e7f1a6
diff --git a/bika/lims/browser/fields/aranalysesfield.py b/bika/lims/browser/fields/aranalysesfield.py index <HASH>..<HASH> 100644 --- a/bika/lims/browser/fields/aranalysesfield.py +++ b/bika/lims/browser/fields/aranalysesfield.py @@ -102,7 +102,13 @@ class ARAnalysesField(ObjectField): 'sample_due', 'sample_received', 'attachment_due', 'to_be_verified') - + # Modify existing AR specs with new form values for selected analyses + rr = instance.getResultsRange() + for i, spec in enumerate(specs): + for r in rr: + if spec['keyword'] == rr['keyword']: + for k,v in specs[i].items(): + rr[k] = v instance.setResultsRange(specs) new_analyses = []
ARAnalysesField: override individual specs instead of entire ResultsRange This field's setter must handle ar_add and manage_analyses, meaning that the list of specs passed in is not necessarily the entire list. The function now overrides existing AR specs, instead of setting them to the form values.
senaite_senaite.core
train
7c9a1bdf0cc219bb85bf8922857a38ee711373d9
diff --git a/fs/ftpfs.py b/fs/ftpfs.py index <HASH>..<HASH> 100644 --- a/fs/ftpfs.py +++ b/fs/ftpfs.py @@ -476,7 +476,10 @@ class FTPFS(FS): self._check() self.validatepath(path) _path = abspath(normpath(path)) - entries = self._read_dir(_path) + with self._lock: + if not self.getbasic(path).is_dir: + raise errors.DirectoryExpected(path) + entries = self._read_dir(_path) for entry in entries: raw_info = self._make_raw_info(entry) yield Info(raw_info) diff --git a/fs/info.py b/fs/info.py index <HASH>..<HASH> 100644 --- a/fs/info.py +++ b/fs/info.py @@ -36,6 +36,7 @@ class Info(object): """ self.raw = raw_info self._to_datetime = to_datetime + self.namespaces = frozenset(self.raw.keys()) def __repr__(self): if self.is_dir: @@ -70,7 +71,8 @@ class Info(object): def is_writeable(self, namespace, key): """ - Check if a given key in a namespace is writeable. + Check if a given key in a namespace is writable (with + :meth:`fs.base.FS.setinfo`). :param namespace: A namespace identifier. :type namespace: str diff --git a/tests/test_fs.py b/tests/test_fs.py index <HASH>..<HASH> 100644 --- a/tests/test_fs.py +++ b/tests/test_fs.py @@ -894,6 +894,8 @@ class FSTestCases(object): def test_scandir(self): # Check exception for scanning dir that doesn't exist + + with self.assertRaises(errors.ResourceNotFound): for info in self.fs.scandir('/foobar'): pass @@ -905,6 +907,11 @@ class FSTestCases(object): # Check scanning self.fs.create('foo') + + # Can't scandir on a file + with self.assertRaises(errors.DirectoryExpected): + list(self.fs.scandir('foo')) + self.fs.create('bar') self.fs.makedir('dir') iter_scandir = self.fs.scandir('/') diff --git a/tests/test_ftpfs.py b/tests/test_ftpfs.py index <HASH>..<HASH> 100644 --- a/tests/test_ftpfs.py +++ b/tests/test_ftpfs.py @@ -20,7 +20,7 @@ from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer - +from fs import errors from fs.ftpfs import FTPFS @@ -113,3 +113,8 @@ class TestFTPFS(FSTestCases, unittest.TestCase): os.system('kill {}'.format(server.pid)) shutil.rmtree(self._temp_dir) super(TestFTPFS, self).tearDown() + + def test_connection_error(self): + fs = FTPFS('ftp.not.a.chance') + with self.assertRaises(errors.RemoteConnectionError): + fs.listdir('/')
test for conection error and scandir on file
PyFilesystem_pyfilesystem2
train
b02daaa2b36a2a802248f3bd89363d97aeb4c9ad
diff --git a/lib/poleica/converters/libre_office.rb b/lib/poleica/converters/libre_office.rb index <HASH>..<HASH> 100644 --- a/lib/poleica/converters/libre_office.rb +++ b/lib/poleica/converters/libre_office.rb @@ -8,7 +8,7 @@ module Poleica include Poleica::Converters::Utils BIN_PATHS = { - linux: '/usr/bin/soffice', + linux: '/usr/bin/soffice.bin', osx: '/Applications/LibreOffice.app/Contents/MacOS/soffice' }
Replace soffice linux binary by soffice.bin
antoinelyset_poleica
train
fefd70cd1a036c08c506194d945121839c36b9e7
diff --git a/lib/transforms/subsetGoogleFonts.js b/lib/transforms/subsetGoogleFonts.js index <HASH>..<HASH> 100644 --- a/lib/transforms/subsetGoogleFonts.js +++ b/lib/transforms/subsetGoogleFonts.js @@ -268,6 +268,10 @@ function getSubsetsForFontUsage(assetGraph, htmlAssetTextsWithProps, formats) { htmlAssetTextsWithProps.forEach(function (item) { item.fontUsages.forEach(function (fontUsage) { + if (fontUsage.props.src.indexOf('https://fonts.gstatic.com') !== 0) { + return; + } + formats.forEach(function (format) { var mapId = getSubsetPromiseId(fontUsage, format);
Only try to subset using google fonts if the font is actually from there
assetgraph_assetgraph
train
72d0099d6f0cc56e48c9fdc139df1c14aa8389bf
diff --git a/base/test-core/src/test/java/org/openscience/cdk/atomtype/CDKAtomTypeMatcherTest.java b/base/test-core/src/test/java/org/openscience/cdk/atomtype/CDKAtomTypeMatcherTest.java index <HASH>..<HASH> 100644 --- a/base/test-core/src/test/java/org/openscience/cdk/atomtype/CDKAtomTypeMatcherTest.java +++ b/base/test-core/src/test/java/org/openscience/cdk/atomtype/CDKAtomTypeMatcherTest.java @@ -2078,6 +2078,9 @@ public class CDKAtomTypeMatcherTest extends AbstractCDKAtomTypeTest { mol.addAtom(atom2); mol.addAtom(atom3); mol.addAtom(atom4); + mol.addBond(1,0,Order.SINGLE); + mol.addBond(1,2,Order.SINGLE); + mol.addBond(1,3,Order.SINGLE); String[] expectedTypes = new String[]{"O.sp3", "Ga", "O.sp3", "O.sp3"}; assertAtomTypes(testedAtomTypes, expectedTypes, mol);
Regression - covalent input was not actually covalent.
cdk_cdk
train
9c6b31e905a3446079626a453f0fd1c7b08b86c2
diff --git a/src/DocBlox/Parser/Files.php b/src/DocBlox/Parser/Files.php index <HASH>..<HASH> 100644 --- a/src/DocBlox/Parser/Files.php +++ b/src/DocBlox/Parser/Files.php @@ -152,7 +152,7 @@ class DocBlox_Parser_Files extends DocBlox_Parser_Abstract */ public function addDirectory($path) { - $result = glob($path); + $result = substr($path, 0, 7) !== 'phar://' ? glob($path) : array($path); if ($result === false) { throw new DocBlox_Parser_Exception( '"'.$path . '" does not match an existing directory pattern' @@ -258,8 +258,7 @@ class DocBlox_Parser_Files extends DocBlox_Parser_Abstract } } else { // only process if it is a file and it matches the allowed extensions - if (is_file($path) && (empty($this->allowed_extensions) - || in_array( + if (is_file($path) && (empty($this->allowed_extensions) || in_array( strtolower(pathinfo($path, PATHINFO_EXTENSION)), $this->allowed_extensions ))
phar support was broken; fixed it
phpDocumentor_phpDocumentor2
train
9f7e0b0c3c17df8239da7b3f2b4fe29e8ec92a11
diff --git a/provider/ec2/environ.go b/provider/ec2/environ.go index <HASH>..<HASH> 100644 --- a/provider/ec2/environ.go +++ b/provider/ec2/environ.go @@ -1127,9 +1127,39 @@ func (e *environ) AllInstances() ([]instance.Instance, error) { // AllInstancesByState returns all instances in the environment // with one of the specified instance states. func (e *environ) AllInstancesByState(states ...string) ([]instance.Instance, error) { + // NOTE(axw) we use security group filtering here because instances + // start out untagged. If Juju were to abort after starting an instance, + // but before tagging it, it would be leaked. We only need to do this + // for AllInstances, as it is the result of AllInstances that is used + // in "harvesting" unknown instances by the provisioner. + // + // One possible alternative is to modify ec2.RunInstances to allow the + // caller to specify ClientToken, and then format it like + // <controller-uuid>:<model-uuid>:<machine-id> + // (with base64-encoding to keep the size under the 64-byte limit) + // + // It is possible to filter on "client-token", and specify wildcards; + // therefore we could use client-token filters everywhere in the ec2 + // provider instead of tags or security groups. The only danger is if + // we need to make non-idempotent calls to RunInstances for the machine + // ID. I don't think this is needed, but I am not confident enough to + // change this fundamental right now. + // + // An EC2 API call is required to resolve the group name to an id, as + // VPC enabled accounts do not support name based filtering. + // TODO: Detect classic accounts and just filter by name for those. + groupName := e.jujuGroupName() + group, err := e.groupByName(groupName) + if err != nil { + if ec2ErrCode(err) == "InvalidGroup.NotFound" { + // If there's no group, then there cannot be any instances. + return nil, nil + } + return nil, errors.Trace(err) + } filter := ec2.NewFilter() filter.Add("instance-state-name", states...) - e.addModelFilter(filter) + filter.Add("instance.group-id", group.Id) return e.allInstances(filter) } @@ -1151,6 +1181,9 @@ func (e *environ) ControllerInstances() ([]instance.Id, error) { // allControllerManagedInstances returns the IDs of all instances managed by // this environment's controller. +// +// Note that this requires that all instances are tagged; we cannot filter on +// security groups, as we do not know the names of the models. func (e *environ) allControllerManagedInstances() ([]instance.Id, error) { filter := ec2.NewFilter() filter.Add("instance-state-name", aliveInstanceStates...)
provider/ec2: reinstate security group filtering
juju_juju
train
6b21d926268f5a4a857f492d0abe91b731c98261
diff --git a/src/calendar-heatmap.component.js b/src/calendar-heatmap.component.js index <HASH>..<HASH> 100644 --- a/src/calendar-heatmap.component.js +++ b/src/calendar-heatmap.component.js @@ -72,7 +72,7 @@ class CalendarHeatmap extends React.Component { this.attr('width', this.settings.width) .attr('height', this.settings.height) - if ( !!this.data && !!this.data[0].summary ) { + if ( !!this.props.data && !!this.props.data[0].summary ) { this.drawChart() } }
Get data from the component props.
g1eb_reactjs-calendar-heatmap
train
5e1ce8794aac0d7b809a234ef2fe157f0010d28f
diff --git a/src/org/opencms/db/CmsDriverManager.java b/src/org/opencms/db/CmsDriverManager.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/db/CmsDriverManager.java +++ b/src/org/opencms/db/CmsDriverManager.java @@ -1,7 +1,7 @@ /* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/db/CmsDriverManager.java,v $ - * Date : $Date: 2003/07/29 10:43:47 $ - * Version: $Revision: 1.93 $ + * Date : $Date: 2003/07/29 11:28:52 $ + * Version: $Revision: 1.94 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System @@ -74,7 +74,7 @@ import source.org.apache.java.util.Configurations; * @author Alexander Kandzior (a.kandzior@alkacon.com) * @author Thomas Weckert (t.weckert@alkacon.com) * @author Carsten Weinholz (c.weinholz@alkacon.com) - * @version $Revision: 1.93 $ $Date: 2003/07/29 10:43:47 $ + * @version $Revision: 1.94 $ $Date: 2003/07/29 11:28:52 $ * @since 5.1 */ public class CmsDriverManager extends Object { @@ -1995,7 +1995,7 @@ public class CmsDriverManager extends Object { clearResourceCache(); m_accessCache.clear(); - m_lockDispatcher.removeResource(this, context, foldername, false); + m_lockDispatcher.removeResource(this, context, foldername, true); // inform about the file-system-change fileSystemChanged(true); @@ -7423,7 +7423,7 @@ public class CmsDriverManager extends Object { } resource = readFileHeader(context, resourcename); - m_lockDispatcher.removeResource(this, context, resource.getFullResourceName(), false); + m_lockDispatcher.removeResource(this, context, resource.getFullResourceName(), forceUnlock); /* String currentResourceName = null; diff --git a/src/org/opencms/lock/CmsLockDispatcher.java b/src/org/opencms/lock/CmsLockDispatcher.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/lock/CmsLockDispatcher.java +++ b/src/org/opencms/lock/CmsLockDispatcher.java @@ -1,7 +1,7 @@ /* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/lock/Attic/CmsLockDispatcher.java,v $ - * Date : $Date: 2003/07/29 11:00:17 $ - * Version: $Revision: 1.19 $ + * Date : $Date: 2003/07/29 11:28:52 $ + * Version: $Revision: 1.20 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System @@ -56,7 +56,7 @@ import java.util.Map; * are instances of CmsLock objects. * * @author Thomas Weckert (t.weckert@alkacon.com) - * @version $Revision: 1.19 $ $Date: 2003/07/29 11:00:17 $ + * @version $Revision: 1.20 $ $Date: 2003/07/29 11:28:52 $ * @since 5.1.4 * @see com.opencms.file.CmsObject#getLock(CmsResource) * @see org.opencms.lock.CmsLock @@ -102,8 +102,10 @@ public final class CmsLockDispatcher extends Object { * @return the new CmsLock object for the added resource */ public void addResource(CmsDriverManager driverManager, CmsRequestContext context, String resourcename, CmsUUID userId, int projectId) throws CmsException { - if (!getLock(driverManager, context, resourcename).isNullLock()) { - throw new CmsLockException("Resource is already locked", CmsLockException.C_RESOURCE_LOCKED); + CmsLock lock = getLock(driverManager, context, resourcename); + + if (!lock.isNullLock() && !lock.getUserId().equals(context.currentUser().getId()) && lock.getProjectId()!=context.currentProject().getId()) { + throw new CmsLockException("Resource is already locked by another user", CmsLockException.C_RESOURCE_LOCKED_BY_OTHER_USER); } CmsLock newLock = new CmsLock(resourcename, userId, projectId, CmsLock.C_TYPE_EXCLUSIVE); @@ -277,7 +279,7 @@ public final class CmsLockDispatcher extends Object { } return lock; - } else if (lock.getType() == CmsLock.C_TYPE_INHERITED || lock.getType() == CmsLock.C_TYPE_SHARED_INHERITED) { + } else if (!forceUnlock && (lock.getType() == CmsLock.C_TYPE_INHERITED || lock.getType() == CmsLock.C_TYPE_SHARED_INHERITED)) { throw new CmsLockException("Unable to unlock resource due to an inherited lock of a parent folder", CmsLockException.C_RESOURCE_LOCKED_INHERITED); }
Added a force option to unlock a resource.
alkacon_opencms-core
train
9b5801728ae51e8f90cae49fcb2fe31dadb283d5
diff --git a/externs/ie_event.js b/externs/ie_event.js index <HASH>..<HASH> 100644 --- a/externs/ie_event.js +++ b/externs/ie_event.js @@ -176,14 +176,8 @@ MSPointerEvent.MSPOINTER_TYPE_PEN; /** @type {number} */ MSPointerEvent.MSPOINTER_TYPE_TOUCH; -/** - * @return {Array.<MSPointerPoint>} - */ -MSPointerEvent.prototype.getPointerList; - /** @type {number} */ MSPointerEvent.prototype.pointerId; /** @type {number} */ MSPointerEvent.prototype.pointerType; -
Remove references to getPointerList which has been removed from the latest Windows 8 previews. R=nicksantos,rjfioravanti DELTA=<I> (0 added, <I> deleted, 7 changed) Revision created by MOE tool push_codebase. MOE_MIGRATION=<I> git-svn-id: <URL>
google_closure-compiler
train
9858ce896f684f58410a56bb561887015468c103
diff --git a/client/src/index.js b/client/src/index.js index <HASH>..<HASH> 100644 --- a/client/src/index.js +++ b/client/src/index.js @@ -161,7 +161,7 @@ class Fusion extends FusionEmitter { self.requestCounter = 0 self.socket = new FusionSocket(host, secure) self.listenerSet = ListenerSet.absorbEmitter(self.socket) - .fwd('error', self) + .on('error', (err) => self.emit('error', err, self)) .on('connected', () => self.emit('connected', self)) .on('disconnected', () => self.emit('disconnected', self)) // send handshake
Give the fusion object to the error callback
rethinkdb_horizon
train
1e9af51941824266116fd926656778451bb93f0d
diff --git a/.gitignore b/.gitignore index <HASH>..<HASH> 100644 --- a/.gitignore +++ b/.gitignore @@ -32,4 +32,3 @@ migrations/schema.sql .grifter/ cockroach-data/ vendor/ -cockroach-data/ diff --git a/fizz/translators/cockroach.go b/fizz/translators/cockroach.go index <HASH>..<HASH> 100644 --- a/fizz/translators/cockroach.go +++ b/fizz/translators/cockroach.go @@ -382,7 +382,7 @@ func (p *Cockroach) colType(c fizz.Column) string { func (p *Cockroach) buildForeignKey(t fizz.Table, fk fizz.ForeignKey, onCreate bool) string { refs := fmt.Sprintf("%s (%s)", fk.References.Table, strings.Join(fk.References.Columns, ", ")) - s := fmt.Sprintf("FOREIGN KEY (%s) REFERENCES %s", fk.Column, refs) + s := fmt.Sprintf("CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s", fk.Name, fk.Column, refs) if onUpdate, ok := fk.Options["on_update"]; ok { s += fmt.Sprintf(" ON UPDATE %s", onUpdate) @@ -393,7 +393,7 @@ func (p *Cockroach) buildForeignKey(t fizz.Table, fk fizz.ForeignKey, onCreate b } if !onCreate { - s = fmt.Sprintf("ALTER TABLE %s ADD CONSTRAINT %s %s;COMMIT TRANSACTION;BEGIN TRANSACTION;", t.Name, fk.Name, s) + s = fmt.Sprintf("ALTER TABLE %s ADD %s;COMMIT TRANSACTION;BEGIN TRANSACTION;", t.Name, s) } return s diff --git a/fizz/translators/cockroach_test.go b/fizz/translators/cockroach_test.go index <HASH>..<HASH> 100644 --- a/fizz/translators/cockroach_test.go +++ b/fizz/translators/cockroach_test.go @@ -98,7 +98,7 @@ CREATE TABLE "profiles" ( "last_name" VARCHAR (255) NOT NULL, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL, -FOREIGN KEY (user_id) REFERENCES users (id) +CONSTRAINT profiles_users_id_fk FOREIGN KEY (user_id) REFERENCES users (id) );COMMIT TRANSACTION;BEGIN TRANSACTION;` res, _ := fizz.AString(`
Adjust FK code for cockroach according to DB
gobuffalo_pop
train
4f01826a274572775ffde6d9f0c95473857048a3
diff --git a/lib/moodlelib.php b/lib/moodlelib.php index <HASH>..<HASH> 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -2791,8 +2791,6 @@ function set_login_session_preferences() { $SESSION->justloggedin = true; unset($SESSION->lang); - unset($SESSION->encoding); - $SESSION->encoding = current_charset(); // Restore the calendar filters, if saved if (intval(get_user_preferences('calendar_persistflt', 0))) { diff --git a/lib/setup.php b/lib/setup.php index <HASH>..<HASH> 100644 --- a/lib/setup.php +++ b/lib/setup.php @@ -457,7 +457,6 @@ global $HTTPSPAGEREQUIRED; if (!detect_munged_arguments($lang, 0) and (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang))) { $SESSION->lang = $lang; - $SESSION->encoding = get_string('thischarset'); } } if (empty($CFG->lang)) { diff --git a/lib/weblib.php b/lib/weblib.php index <HASH>..<HASH> 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -1920,7 +1920,6 @@ function print_header ($title='', $heading='', $navigation='', $focus='', $meta= if (!empty($CFG->courselang)) { moodle_setlocale(); } - $SESSION->encoding = $encoding; $meta = '<meta http-equiv="content-type" content="text/html; charset='. $encoding .'" />'. "\n". $meta ."\n"; if (!$usexml) { diff --git a/mod/resource/type/ims/resource.class.php b/mod/resource/type/ims/resource.class.php index <HASH>..<HASH> 100644 --- a/mod/resource/type/ims/resource.class.php +++ b/mod/resource/type/ims/resource.class.php @@ -676,24 +676,16 @@ class resource_ims extends resource_base { /// Configure links behaviour $fullurl = $CFG->wwwroot.'/mod/resource/view.php?r='.$resource->id.'&amp;frameset=ims&amp;page='; - /// Decide if we have to leave text in UTF-8, else convert to ISO-8859-1 - /// (interim solution until everything was migrated to UTF-8). Then we'll - // delete this hack. - $convert = true; - if ($SESSION->encoding == 'UTF-8') { - $convert = false; - } - /// Iterate over items to build the menu $currlevel = 0; $currorder = 0; $endlevel = 0; foreach ($items as $item) { - /// Convert text to ISO-8859-1 if specified (will remove this once utf-8 migration was complete- 1.6) - if ($convert) { - $item->title = utf8_decode($item->title); - } - + /// Convert text from UTF-8 to current charset if needed + if (empty($CFG->unicodedb)) { + $textlib = textlib_get_instance(); + $item->title = $textlib->convert($item->title, 'UTF-8', current_charset()); + } /// Skip pages until we arrive to $page if ($item->id < $page) { continue;
removed $SESSION->encoding now replaced by current_charset() and $CFG->unicodedb; 3rd party contribs must be fixed to be utf-8 and <I>dev compatible anyway; going to add a notice to wiki at <URL>
moodle_moodle
train
997fad7bf3560da4f8b7e0b93facca7349d204be
diff --git a/nsq_metrics_tank/aggmetric.go b/nsq_metrics_tank/aggmetric.go index <HASH>..<HASH> 100644 --- a/nsq_metrics_tank/aggmetric.go +++ b/nsq_metrics_tank/aggmetric.go @@ -49,7 +49,6 @@ func NewAggMetric(key string, chunkSpan, numChunks uint32, aggsetting ...aggSett m.aggregators = append(m.aggregators, NewAggregator(key, as.span, as.chunkSpan, as.numChunks)) } go m.stats() - go m.trimOldData() return &m } @@ -67,14 +66,6 @@ func (a *AggMetric) stats() { } } -func (a *AggMetric) trimOldData() { - a.Lock() - //for t := range time.Tick(time.Duration(a.chunkSpan) * time.Second) { - // Finish // it's ok to re-finish if already finished - // } - a.Unlock() -} - // this function must only be called while holding the lock func (a *AggMetric) indexFor(t0 uint32) uint32 { return ((t0 - a.firstT0) / a.chunkSpan) % a.numChunks
remove data trim routine the per-metric routines are expensive. also we don't actually need to trim data like this
grafana_metrictank
train
a1b2394bb2ef9e49417e3c20c84b0e936d372caa
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -124,7 +124,7 @@ setup( 'cython', 'mpi4py', 'nitime', - 'numpy', + 'numpy<1.16', # See https://github.com/Theano/Theano/pull/6671 'scikit-learn[alldeps]>=0.18', 'scipy!=1.0.0', # See https://github.com/scipy/scipy/pull/8082 'statsmodels',
dev: Workaround for Theano NumPy incompatibility (#<I>) Theano is not compatible with NumPy>=<I>. A fix exists, but it is not yet part of a release. See: <URL>
brainiak_brainiak
train
2d88f791a723fd5e2fb05b1c599dc4f3eec4f157
diff --git a/src/Router.php b/src/Router.php index <HASH>..<HASH> 100644 --- a/src/Router.php +++ b/src/Router.php @@ -223,11 +223,17 @@ class Router $class = $this->controllerPrefix . ucfirst($name); // If the controller class does not exist panic. - if (!class_exists($class) || !is_subclass_of($class, 'Joomla\\Controller\\ControllerInterface')) + if (!class_exists($class)) { throw new \RuntimeException(sprintf('Unable to locate controller `%s`.', $class), 404); } + // If the controller does not follows the implementation. + if (!is_subclass_of($class, 'Joomla\\Controller\\ControllerInterface')) + { + throw new \RuntimeException(sprintf('Wrong class implementation for controller `%s`.', $class), 404); + } + // Instantiate the controller. $controller = new $class($this->input);
[FIX] Provides a suitable response in case of bad implementation of class
joomla-framework_router
train
b42a2d45e736d898582f42d0cd978c390d069e37
diff --git a/lib/Cake/Network/Email/CakeEmail.php b/lib/Cake/Network/Email/CakeEmail.php index <HASH>..<HASH> 100644 --- a/lib/Cake/Network/Email/CakeEmail.php +++ b/lib/Cake/Network/Email/CakeEmail.php @@ -1386,7 +1386,7 @@ class CakeEmail { */ protected function _readFile($path) { $File = new File($path); - return $File->readBase64(); + return chunk_split(base64_encode($File->read())); } /** diff --git a/lib/Cake/Utility/File.php b/lib/Cake/Utility/File.php index <HASH>..<HASH> 100644 --- a/lib/Cake/Utility/File.php +++ b/lib/Cake/Utility/File.php @@ -181,17 +181,6 @@ class File { } /** - * Return the contents of this File as a base64 version of the file contents. - * The string is split into smaller chunks to match RFC 2045 semantics. - * - * @return string File contents in base64 encoding - * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::readBase64 - */ - public function readBase64() { - return chunk_split(base64_encode($this->read())); - } - -/** * Sets or gets the offset for the currently opened file. * * @param integer|boolean $offset The $offset in bytes to seek. If set to false then the current offset is returned.
Remove readBase<I>() from File utility, since it is not commonly used.
cakephp_cakephp
train
c5c290c5032a95798375842a16fd95b066c5bb66
diff --git a/agent/xds/clusters.go b/agent/xds/clusters.go index <HASH>..<HASH> 100644 --- a/agent/xds/clusters.go +++ b/agent/xds/clusters.go @@ -78,13 +78,21 @@ func (s *ResourceGenerator) clustersFromSnapshotConnectProxy(cfgSnap *proxycfg.C } for id, chain := range cfgSnap.ConnectProxy.DiscoveryChain { + upstreamCfg := cfgSnap.ConnectProxy.UpstreamConfig[id] + + explicit := upstreamCfg.HasLocalPortOrSocket() + if _, implicit := cfgSnap.ConnectProxy.IntentionUpstreams[id]; !implicit && !explicit { + // Discovery chain is not associated with a known explicit or implicit upstream so it is skipped. + continue + } + chainEndpoints, ok := cfgSnap.ConnectProxy.WatchedUpstreamEndpoints[id] if !ok { // this should not happen return nil, fmt.Errorf("no endpoint map for upstream %q", id) } - upstreamClusters, err := s.makeUpstreamClustersForDiscoveryChain(id, cfgSnap.ConnectProxy.UpstreamConfig[id], chain, chainEndpoints, cfgSnap) + upstreamClusters, err := s.makeUpstreamClustersForDiscoveryChain(id, upstreamCfg, chain, chainEndpoints, cfgSnap) if err != nil { return nil, err } diff --git a/agent/xds/endpoints.go b/agent/xds/endpoints.go index <HASH>..<HASH> 100644 --- a/agent/xds/endpoints.go +++ b/agent/xds/endpoints.go @@ -48,11 +48,19 @@ func (s *ResourceGenerator) endpointsFromSnapshotConnectProxy(cfgSnap *proxycfg. len(cfgSnap.ConnectProxy.PreparedQueryEndpoints)+len(cfgSnap.ConnectProxy.WatchedUpstreamEndpoints)) for id, chain := range cfgSnap.ConnectProxy.DiscoveryChain { + upstreamCfg := cfgSnap.ConnectProxy.UpstreamConfig[id] + + explicit := upstreamCfg.HasLocalPortOrSocket() + if _, implicit := cfgSnap.ConnectProxy.IntentionUpstreams[id]; !implicit && !explicit { + // Discovery chain is not associated with a known explicit or implicit upstream so it is skipped. + continue + } + es := s.endpointsFromDiscoveryChain( id, chain, cfgSnap.Locality, - cfgSnap.ConnectProxy.UpstreamConfig[id], + upstreamCfg, cfgSnap.ConnectProxy.WatchedUpstreamEndpoints[id], cfgSnap.ConnectProxy.WatchedGatewayEndpoints[id], ) diff --git a/agent/xds/listeners.go b/agent/xds/listeners.go index <HASH>..<HASH> 100644 --- a/agent/xds/listeners.go +++ b/agent/xds/listeners.go @@ -95,6 +95,13 @@ func (s *ResourceGenerator) listenersFromSnapshotConnectProxy(cfgSnap *proxycfg. for id, chain := range cfgSnap.ConnectProxy.DiscoveryChain { upstreamCfg := cfgSnap.ConnectProxy.UpstreamConfig[id] + + explicit := upstreamCfg.HasLocalPortOrSocket() + if _, implicit := cfgSnap.ConnectProxy.IntentionUpstreams[id]; !implicit && !explicit { + // Discovery chain is not associated with a known explicit or implicit upstream so it is skipped. + continue + } + cfg := s.getAndModifyUpstreamConfigForListener(id, upstreamCfg, chain) // If escape hatch is present, create a listener from it and move on to the next diff --git a/agent/xds/routes.go b/agent/xds/routes.go index <HASH>..<HASH> 100644 --- a/agent/xds/routes.go +++ b/agent/xds/routes.go @@ -28,7 +28,7 @@ func (s *ResourceGenerator) routesFromSnapshot(cfgSnap *proxycfg.ConfigSnapshot) switch cfgSnap.Kind { case structs.ServiceKindConnectProxy: - return s.routesForConnectProxy(cfgSnap.ConnectProxy.DiscoveryChain) + return s.routesForConnectProxy(cfgSnap) case structs.ServiceKindIngressGateway: return s.routesForIngressGateway( cfgSnap.IngressGateway.Listeners, @@ -46,13 +46,19 @@ func (s *ResourceGenerator) routesFromSnapshot(cfgSnap *proxycfg.ConfigSnapshot) // routesFromSnapshotConnectProxy returns the xDS API representation of the // "routes" in the snapshot. -func (s *ResourceGenerator) routesForConnectProxy(chains map[string]*structs.CompiledDiscoveryChain) ([]proto.Message, error) { +func (s *ResourceGenerator) routesForConnectProxy(cfgSnap *proxycfg.ConfigSnapshot) ([]proto.Message, error) { var resources []proto.Message - for id, chain := range chains { + for id, chain := range cfgSnap.ConnectProxy.DiscoveryChain { if chain.IsDefault() { continue } + explicit := cfgSnap.ConnectProxy.UpstreamConfig[id].HasLocalPortOrSocket() + if _, implicit := cfgSnap.ConnectProxy.IntentionUpstreams[id]; !implicit && !explicit { + // Discovery chain is not associated with a known explicit or implicit upstream so it is skipped. + continue + } + virtualHost, err := makeUpstreamRouteForDiscoveryChain(id, chain, []string{"*"}) if err != nil { return nil, err
Validate chains are associated with upstreams Previously we could get into a state where discovery chain entries were not cleaned up after the associated watch was cancelled. These changes add handling for that case where stray chain references are encountered.
hashicorp_consul
train
a616bf4082337ee73f6ed941436053eaafda9a22
diff --git a/superset/security.py b/superset/security.py index <HASH>..<HASH> 100644 --- a/superset/security.py +++ b/superset/security.py @@ -7,6 +7,7 @@ from __future__ import unicode_literals import logging from flask_appbuilder.security.sqla import models as ab_models +from sqlalchemy import or_ from superset import conf, db, sm from superset.connectors.connector_registry import ConnectorRegistry @@ -210,6 +211,23 @@ def create_missing_perms(): merge_pv('metric_access', metric.perm) +def clean_perms(): + """FAB leaves faulty permissions that need to be cleaned up""" + logging.info('Cleaning faulty perms') + sesh = sm.get_session() + pvms = ( + sesh.query(ab_models.PermissionView) + .filter(or_( + ab_models.PermissionView.permission == None, # NOQA + ab_models.PermissionView.view_menu == None, # NOQA + )) + ) + deleted_count = pvms.delete() + sesh.commit() + if deleted_count: + logging.info('Deleted {} faulty permissions'.format(deleted_count)) + + def sync_role_definitions(): """Inits the Superset application with security roles and such""" logging.info('Syncing role definition') @@ -231,3 +249,4 @@ def sync_role_definitions(): # commit role and view menu updates sm.get_session.commit() + clean_perms()
[cli] permission cleanup on 'superset init' (#<I>) * [cli] permission cleanup on 'superset init' FAB sometimes creates NULL/None permissions in the database, presumably a race condition when multiple gunicorn workers start at the same time, and those create issues raising "AttributeError: 'NoneType' object has no attribute 'name'" * Linting
apache_incubator-superset
train
0434df9f7f8d7eb289f2cae4551cae54ad1a01df
diff --git a/airtest/core/android/adb.py b/airtest/core/android/adb.py index <HASH>..<HASH> 100644 --- a/airtest/core/android/adb.py +++ b/airtest/core/android/adb.py @@ -1177,29 +1177,38 @@ class ADB(object): None if no IP address has been found, otherwise return the IP address """ - try: - res = self.shell('netcfg') - except AdbShellError: - res = '' - matcher = re.search(r'wlan0.* ((\d+\.){3}\d+)/\d+', res) - if matcher: - return matcher.group(1) - else: + + def get_ip_address_from_interface(interface): try: - res = self.shell('ifconfig') + res = self.shell('netcfg') except AdbShellError: res = '' - matcher = re.search(r'wlan0.*?inet addr:((\d+\.){3}\d+)', res, re.DOTALL) + matcher = re.search(interface + r'.* ((\d+\.){3}\d+)/\d+', res) if matcher: return matcher.group(1) else: try: - res = self.shell('getprop dhcp.wlan0.ipaddress') + res = self.shell('ifconfig') except AdbShellError: res = '' - matcher = IP_PATTERN.search(res) + matcher = re.search(interface + r'.*?inet addr:((\d+\.){3}\d+)', res, re.DOTALL) if matcher: - return matcher.group(0) + return matcher.group(1) + else: + try: + res = self.shell('getprop dhcp.{}.ipaddress'.format(interface)) + except AdbShellError: + res = '' + matcher = IP_PATTERN.search(res) + if matcher: + return matcher.group(0) + return None + + interfaces = ('eth0', 'eth1', 'wlan0') + for i in interfaces: + ip = get_ip_address_from_interface(i) + if ip and not ip.startswith('172.') and not ip.startswith('127.') and not ip.startswith('169.'): + return ip return None def get_gateway_address(self):
get ip address from given interface sequence.
AirtestProject_Airtest
train
120d17b1b2cf208804415e7fb4cc074851977eaf
diff --git a/salesforce/management/commands/inspectdb.py b/salesforce/management/commands/inspectdb.py index <HASH>..<HASH> 100644 --- a/salesforce/management/commands/inspectdb.py +++ b/salesforce/management/commands/inspectdb.py @@ -5,9 +5,70 @@ from django.core.management.commands.inspectdb import Command as InspectDBComman from django.db import connections, DEFAULT_DB_ALIAS from django.utils import six from salesforce.backend import introspection as sf_introspection +from salesforce import DJANGO_15_PLUS import django import salesforce +try: + from collections import OrderedDict +except ImportError: + # Python 2.6- + from django.utils.datastructures import SortedDict as OrderedDict + + +def fix_field_params_repr(params): + """ + Fixes repr() of "field_params" for Python 2 with future unicode_literals. + """ + class ReprUnicode(six.text_type): + def __new__(cls, text): + return unicode.__new__(cls, text) + def __repr__(self): + out = repr(unicode(self)) + return out[1:] if out.startswith("u'") or out.startswith('u"') else out + class ReprChoices(list): + def __new__(cls, choices): + return list.__new__(cls, choices) + def __repr__(self): + out = [] + for x0, x1 in self: + out.append('(%s, %s)' % ( + repr(ReprUnicode(x0) if isinstance(x0, unicode) else x0), + repr(ReprUnicode(x1) if isinstance(x1, unicode) else x1) + )) + return '[%s]' % (', '.join(out)) + if not DJANGO_15_PLUS or six.PY3: + return params + out = OrderedDict() + for k, v in params.items(): + if k == 'choices' and v: + v = ReprChoices(v) + elif isinstance(v, unicode): + v = ReprUnicode(v) + out[k] = v + return out + +def fix_international(text): + "Fix excaped international characters back to utf-8" + class SmartInternational(str): + def __new__(cls, text): + return str.__new__(cls, text) + def endswith(self, string): + return super(SmartInternational, self).endswith(str(string)) + if six.PY3: + return text + out = [] + last = 0 + for match in re.finditer(r'(?<=[^\\])(?:\\x[0-9a-f]{2}|\\u[0-9a-f]{4})', text): + start, end, group = match.start(), match.end(), match.group() + out.append(text[last:start]) + c = group.decode('unicode_escape') + out.append(c if ord(c) >160 and ord(c) != 173 else group) + last = end + out.append(text[last:]) + return SmartInternational(''.join(out).encode('utf-8')) + + class Command(InspectDBCommand): # This will export Salestorce to a valid models.py, if Django >=1.5. # It is recommended to use Django >=1.5 for inspectdb, even if the generated models.py will be used on Django <1.5 @@ -35,7 +96,7 @@ class Command(InspectDBCommand): elif django.VERSION[:2] == (1,5): # fix bug in Django 1.5 line = line.replace("''self''", "'self'") - self.stdout.write("%s\n" % line) + self.stdout.write(fix_international("%s\n" % line)) else: super(Command, self).handle_noargs(**options) @@ -48,7 +109,7 @@ class Command(InspectDBCommand): if 'ref_comment' in sf_params: field_notes.append(sf_params.pop('ref_comment')) field_params.update(sf_params) - return field_type, field_params, field_notes + return field_type, fix_field_params_repr(field_params), field_notes def normalize_col_name(self, col_name, used_column_names, is_relation): if self.connection.vendor == 'salesforce': @@ -82,7 +143,7 @@ class Command(InspectDBCommand): else: new_name, field_params, field_notes = super(Command, self ).normalize_col_name(col_name, used_column_names, is_relation) - return new_name, field_params, field_notes + return new_name, fix_field_params_repr(field_params), field_notes def get_meta(self, table_name): """
Fixed compatibility of inspectdb that generates the same models with Python 2 as Python 3 does, including international characters in choices.
django-salesforce_django-salesforce
train
a1b5e91f53b5098ab65d50d0a340caedafac1bf8
diff --git a/packages/blueprint-gatekeeper/app/models/-common-options.js b/packages/blueprint-gatekeeper/app/models/-common-options.js index <HASH>..<HASH> 100644 --- a/packages/blueprint-gatekeeper/app/models/-common-options.js +++ b/packages/blueprint-gatekeeper/app/models/-common-options.js @@ -14,10 +14,8 @@ * limitations under the License. */ -const {env} = require ('@onehilltech/blueprint'); -const { - merge -} = require ('lodash'); +const { env } = require ('@onehilltech/blueprint'); +const { merge } = require ('lodash'); module.exports = function (opts) { const stats = env !== 'test'; diff --git a/packages/blueprint-gatekeeper/app/models/access-token.js b/packages/blueprint-gatekeeper/app/models/access-token.js index <HASH>..<HASH> 100644 --- a/packages/blueprint-gatekeeper/app/models/access-token.js +++ b/packages/blueprint-gatekeeper/app/models/access-token.js @@ -22,6 +22,7 @@ const ref = mongodb.Schema.Types.ref; const Client = require ('./client'); const options = require ('./-common-options') ({discriminatorKey}); +options.softDelete = true; let schema = new Schema ({ /// Client the token was created with. diff --git a/packages/blueprint-gatekeeper/app/models/client-token.js b/packages/blueprint-gatekeeper/app/models/client-token.js index <HASH>..<HASH> 100644 --- a/packages/blueprint-gatekeeper/app/models/client-token.js +++ b/packages/blueprint-gatekeeper/app/models/client-token.js @@ -27,6 +27,7 @@ const { } = AccessToken; const options = require ('./-common-options') ({discriminatorKey}); +options.softDelete = true; // Define the schema for the client token. diff --git a/packages/blueprint-gatekeeper/app/models/client.js b/packages/blueprint-gatekeeper/app/models/client.js index <HASH>..<HASH> 100644 --- a/packages/blueprint-gatekeeper/app/models/client.js +++ b/packages/blueprint-gatekeeper/app/models/client.js @@ -24,6 +24,8 @@ const { } } = mongodb; +options.softDelete = true; + let schema = new mongodb.Schema ({ /// The type of client. type: {type: String, required: true}, diff --git a/packages/blueprint-gatekeeper/app/models/user-token.js b/packages/blueprint-gatekeeper/app/models/user-token.js index <HASH>..<HASH> 100644 --- a/packages/blueprint-gatekeeper/app/models/user-token.js +++ b/packages/blueprint-gatekeeper/app/models/user-token.js @@ -36,6 +36,7 @@ const { } = AccessToken; const options = require ('./-common-options') ({discriminatorKey}); +options.softDelete = true; // Define the schema for the user token.
Added soft delete to token and client models
onehilltech_blueprint
train
5747f5d5612ff38f535a6138300d3b5224bb1a58
diff --git a/ui/src/hosts/components/HostsTable.js b/ui/src/hosts/components/HostsTable.js index <HASH>..<HASH> 100644 --- a/ui/src/hosts/components/HostsTable.js +++ b/ui/src/hosts/components/HostsTable.js @@ -3,17 +3,27 @@ import shallowCompare from 'react-addons-shallow-compare'; import {Link} from 'react-router'; import _ from 'lodash'; +const { + arrayOf, + bool, + number, + shape, + string, +} = PropTypes + const HostsTable = React.createClass({ propTypes: { - hosts: PropTypes.arrayOf(PropTypes.shape({ - name: PropTypes.string, - cpu: PropTypes.number, - load: PropTypes.number, - apps: PropTypes.arrayOf(PropTypes.string.isRequired), + hosts: arrayOf(shape({ + name: string, + cpu: number, + load: number, + apps: arrayOf(string.isRequired), })), - source: PropTypes.shape({ - id: PropTypes.string.isRequired, - name: PropTypes.string.isRequired, + hostsLoading: bool, + hostsError: string, + source: shape({ + id: string.isRequired, + name: string.isRequired, }).isRequired, }, @@ -81,18 +91,23 @@ const HostsTable = React.createClass({ }, render() { - const {searchTerm, sortKey, sortDirection} = this.state; - const {hosts, source} = this.props; - const sortedHosts = this.sort(this.filter(hosts, searchTerm), sortKey, sortDirection); - const hostCount = sortedHosts.length; - - let hostsTitle; - if (hosts.length === 0) { - hostsTitle = `Loading Hosts...`; + const {searchTerm, sortKey, sortDirection} = this.state + const {hosts, hostsLoading, hostsError, source} = this.props + const sortedHosts = this.sort(this.filter(hosts, searchTerm), sortKey, sortDirection) + const hostCount = sortedHosts.length + + let hostsTitle + + if (hostsLoading) { + hostsTitle = `Loading Hosts...` + } else if (hostsError.length) { + hostsTitle = `There was a problem loading hosts` + } else if (hosts.length === 0) { + hostsTitle = `No hosts found` } else if (hostCount === 1) { - hostsTitle = `${hostCount} Host`; + hostsTitle = `${hostCount} Host` } else { - hostsTitle = `${hostCount} Hosts`; + hostsTitle = `${hostCount} Hosts` } return ( diff --git a/ui/src/hosts/containers/HostsPage.js b/ui/src/hosts/containers/HostsPage.js index <HASH>..<HASH> 100644 --- a/ui/src/hosts/containers/HostsPage.js +++ b/ui/src/hosts/containers/HostsPage.js @@ -22,6 +22,8 @@ export const HostsPage = React.createClass({ return { hosts: {}, up: {}, + hostsLoading: true, + hostsError: '', }; }, @@ -30,14 +32,35 @@ export const HostsPage = React.createClass({ Promise.all([ getCpuAndLoadForHosts(source.links.proxy, source.telegraf), getMappings(), + new Promise((resolve) => { + this.setState({hostsLoading: true}) + resolve() + }), ]).then(([hosts, {data: {mappings}}, up]) => { - this.setState({hosts, up}); + this.setState({ + hosts, + up, + hostsLoading: false, + }) getAppsForHosts(source.links.proxy, hosts, mappings, source.telegraf).then((newHosts) => { - this.setState({hosts: newHosts}); + this.setState({ + hosts: newHosts, + hostsError: '', + hostsLoading: false, + }) }).catch(() => { - addFlashMessage({type: 'error', text: 'Unable to get apps for hosts'}); + const reason = 'Unable to get apps for hosts' + addFlashMessage({type: 'error', text: reason}) + this.setState({ + hostsError: reason.toString(), + hostsLoading: false, + }) }); }).catch((reason) => { + this.setState({ + hostsError: reason.toString(), + hostsLoading: false, + }) // TODO: this isn't reachable at the moment, because getCpuAndLoadForHosts doesn't fail when it should. // (like with a bogus proxy link). We should provide better messaging to the user in this catch after that's fixed. console.error(reason); // eslint-disable-line no-console @@ -45,7 +68,8 @@ export const HostsPage = React.createClass({ }, render() { - const {source} = this.props; + const {source} = this.props + const {hosts, hostsLoading, hostsError, up} = this.state return ( <div className="page"> <div className="page-header"> @@ -64,7 +88,13 @@ export const HostsPage = React.createClass({ <div className="container-fluid"> <div className="row"> <div className="col-md-12"> - <HostsTable source={source} hosts={_.values(this.state.hosts)} up={this.state.up} /> + <HostsTable + source={source} + hosts={_.values(hosts)} + up={up} + hostsLoading={hostsLoading} + hostsError={hostsError} + /> </div> </div> </div>
Fix messaging for hosts page when there are no hosts. Add appropriate error messages.
influxdata_influxdb
train
cde758b067c35c300add1794290121f3e3d2cc8f
diff --git a/index.php b/index.php index <HASH>..<HASH> 100644 --- a/index.php +++ b/index.php @@ -1,11 +1,11 @@ <?php /** * Piwik - Open source web analytics - * + * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html Gpl v3 or later * @version $Id$ - * + * * @package Piwik */ diff --git a/piwik.php b/piwik.php index <HASH>..<HASH> 100644 --- a/piwik.php +++ b/piwik.php @@ -1,11 +1,11 @@ -<?php +<?php /** * Piwik - Open source web analytics - * + * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html Gpl v3 or later * @version $Id$ - * + * * @package Piwik */ $GLOBALS['PIWIK_TRACKER_DEBUG'] = false; @@ -27,7 +27,7 @@ if(!defined('PIWIK_USER_PATH')) if(!defined('PIWIK_INCLUDE_PATH')) { define('PIWIK_INCLUDE_PATH', PIWIK_DOCUMENT_ROOT); -} +} @ignore_user_abort(true);
touching a couple of files to trigger build (again) git-svn-id: <URL>
matomo-org_matomo
train
882c9529067daea4f40e9d1100a8d2610a6ba34b
diff --git a/src/Illuminate/Console/Scheduling/Event.php b/src/Illuminate/Console/Scheduling/Event.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Console/Scheduling/Event.php +++ b/src/Illuminate/Console/Scheduling/Event.php @@ -631,7 +631,7 @@ class Event { */ public function emailOutputTo($addresses) { - if (is_null($this->output)) + if (is_null($this->output) || $this->output == '/dev/null') { throw new LogicException("Must direct output to a file in order to e-mail results."); }
Checking for /dev/null output in emailOutputTo() As part of the artisan scheduler, the emailOutputTo() option only works when the sendOutputTo() option has been passed a file, and it does so by checking if the output string is null. Given the default output is actually '/dev/null' and not null, this check never fails and the exception is not thrown. This fix checks for '/dev/null' so the exception is thrown correctly.
laravel_framework
train
2ad7d6e1fafa8480aaa88151b8a85ad1efd49bb0
diff --git a/lib/reform/contract.rb b/lib/reform/contract.rb index <HASH>..<HASH> 100644 --- a/lib/reform/contract.rb +++ b/lib/reform/contract.rb @@ -10,20 +10,10 @@ module Reform extend Uber::InheritableAttr # representer_class gets inherited (cloned) to subclasses. - inheritable_attr :___representer_class - self.___representer_class = Reform::Representer.for(:form_class => self) # only happens in Contract/Form. + inheritable_attr :representer_class + self.representer_class = Reform::Representer.for(:form_class => self) # only happens in Contract/Form. # this should be the only mechanism to inherit, features should be stored in this as well. - def self.representer_class - @bla ||= begin - rep = ___representer_class - puts "merging #{features.inspect}" - - rep.form_features = features.keys # configure the representer class. - - rep - end - end # each contract keeps track of its features and passes them onto its local representer_class. # gets inherited, features get automatically included into inline representer. @@ -42,7 +32,8 @@ module Reform options[:private_name] = options.delete(:as) # at this point, :extend is a Form class. - options[:features] ||= features if block_given? + options[:features] ||= [] + options[:features] += features.keys if block_given? definition = representer_class.property(name, options, &block) setup_form_definition(definition) if block_given? or options[:form] @@ -79,7 +70,7 @@ module Reform # Make a module that contains these very accessors, then include it # so they can be overridden but still are callable with super. accessors = Module.new do - extend Forwardable # DISCUSS: do we really need Forwardable here? + extend Forwardable delegate [name, "#{name}="] => :fields end include accessors diff --git a/lib/reform/form.rb b/lib/reform/form.rb index <HASH>..<HASH> 100644 --- a/lib/reform/form.rb +++ b/lib/reform/form.rb @@ -5,7 +5,7 @@ require 'reform/composition' module Reform class Form < Contract - self.___representer_class = Reform::Representer.for(:form_class => self) + self.representer_class = Reform::Representer.for(:form_class => self) require "reform/form/virtual_attributes" diff --git a/lib/reform/representer.rb b/lib/reform/representer.rb index <HASH>..<HASH> 100644 --- a/lib/reform/representer.rb +++ b/lib/reform/representer.rb @@ -10,11 +10,6 @@ module Reform # self.options = {} - class << self - attr_accessor :form_features - end - - # Invokes #to_hash and/or #from_hash with #options. This provides a hook for other # modules to add options for the representational process. module WithOptions @@ -85,10 +80,7 @@ module Reform puts "inline for #{default_inline_class}, #{name}" - # features are set in Contract::representerclass, per representer class. how to inherit properly? - puts "Representer: my features are #{representable_attrs.options.inspect}" - features = form_features - + features = options[:features] Class.new(default_inline_class) do include *features diff --git a/test/active_record_test.rb b/test/active_record_test.rb index <HASH>..<HASH> 100644 --- a/test/active_record_test.rb +++ b/test/active_record_test.rb @@ -27,6 +27,11 @@ class ActiveRecordTest < MiniTest::Spec # create_table :songs do |table| # table.column :title, :string # table.column :artist_id, :integer + # table.column :album_id, :integer + # table.timestamps + # end + # create_table :albums do |table| + # table.column :title, :string # table.timestamps # end # end
pass features to ::build_inline via the options hash. this saves us from tons of state-keeping code.
trailblazer_reform
train
031d72291f87add318a7b45189826a761dbf4ba8
diff --git a/twine/settings.py b/twine/settings.py index <HASH>..<HASH> 100644 --- a/twine/settings.py +++ b/twine/settings.py @@ -302,7 +302,7 @@ class Settings: self.repository_config['repository'], self.username, self.password, - self.disable_progress_bar + self.disable_progress_bar, ) repo.set_certificate_authority(self.cacert) repo.set_client_certificate(self.client_cert)
Again, add trailing comma
pypa_twine
train
c174e4313d675e2e00b6f26cdf7c6a26e8da650a
diff --git a/zappa/cli.py b/zappa/cli.py index <HASH>..<HASH> 100755 --- a/zappa/cli.py +++ b/zappa/cli.py @@ -387,6 +387,10 @@ class ZappaCLI(object): '--force-color', action='store_true', help='Force coloring log tail output even if coloring support is not auto-detected. (example: piping)' ) + tail_parser.add_argument( + '--disable-keep-open', action='store_true', + help="Exit after printing the last available log, rather than keeping the log open." + ) ## # Undeploy @@ -593,6 +597,7 @@ class ZappaCLI(object): since=self.vargs['since'], filter_pattern=self.vargs['filter'], force_colorize=self.vargs['force_color'] or None, + keep_open=not self.vargs['disable_keep_open'] ) elif command == 'undeploy': # pragma: no cover self.undeploy( @@ -1103,7 +1108,7 @@ class ZappaCLI(object): gateway_id = self.zappa.undeploy_api_gateway( self.lambda_name, - domain_name=domain_name, + domain_name=domain_name, base_path=base_path )
Adding the ability to tail a log and immediately exit.
Miserlou_Zappa
train
245b15f9ebd538833edeb2321cf46cfe0f444376
diff --git a/inginious/frontend/pages/course_admin/utils.py b/inginious/frontend/pages/course_admin/utils.py index <HASH>..<HASH> 100644 --- a/inginious/frontend/pages/course_admin/utils.py +++ b/inginious/frontend/pages/course_admin/utils.py @@ -78,7 +78,9 @@ class INGIniousSubmissionAdminPage(INGIniousAdminPage): # Tweak if not using classrooms : classroom['students'] may content ungrouped users aggregations = dict([(username, aggregation if course.use_classrooms() or ( - username in aggregation['groups'][0]["students"]) else None + len(aggregation['groups']) and + username in aggregation['groups'][0]["students"] + ) else None ) for aggregation in aggregations for username in users]) else: @@ -89,7 +91,9 @@ class INGIniousSubmissionAdminPage(INGIniousAdminPage): # Tweak if not using classrooms : classroom['students'] may content ungrouped users aggregations = dict([(username, aggregation if course.use_classrooms() or ( - username in aggregation['groups'][0]["students"]) else None + len(aggregation['groups']) and + username in aggregation['groups'][0]["students"] + ) else None ) for aggregation in aggregations for username in aggregation["students"]]) if stype == "single":
Fix group check when downloading submissions Fixes #<I> Actually ensures that a teamed student belongs to an actual team
UCL-INGI_INGInious
train
2cda5b7b2799fdc393efb840b592318d59915d37
diff --git a/src/ShopifyApp/Middleware/AuthShop.php b/src/ShopifyApp/Middleware/AuthShop.php index <HASH>..<HASH> 100644 --- a/src/ShopifyApp/Middleware/AuthShop.php +++ b/src/ShopifyApp/Middleware/AuthShop.php @@ -52,11 +52,10 @@ class AuthShop $shopDomainSession = $session->getDomain(); $shopDomain = ShopifyApp::sanitizeShopDomain($shopDomainParam ?? $shopDomainSession); - // Get the shop based on domain and update the session service - $shopModel = Config::get('shopify-app.shop_model'); - $shop = $shopModel::withTrashed()->where(['shopify_domain' => $shopDomain])->first(); - + // Get the shop based on domaian + $shop = ShopifyApp::shop($shopDomain); $flowType = null; + if ($shop === null || $shop->trashed() || ($shopDomain && $shopDomain !== $shop->shopify_domain) === true diff --git a/src/ShopifyApp/Services/ShopSession.php b/src/ShopifyApp/Services/ShopSession.php index <HASH>..<HASH> 100644 --- a/src/ShopifyApp/Services/ShopSession.php +++ b/src/ShopifyApp/Services/ShopSession.php @@ -71,11 +71,12 @@ class ShopSession * * @param object|null $shop The shop. * - * @return void + * @return self */ public function setShop($shop = null) { $this->shop = $shop; + return $this; } /** @@ -111,12 +112,13 @@ class ShopSession * * @param string $shopDomain The Shopify domain. * - * @return void + * @return self */ public function setDomain(string $shopDomain) { $this->fixLifetime(); Session::put(self::DOMAIN, $shopDomain); + return $this; } /** @@ -135,7 +137,7 @@ class ShopSession * * @param stdClass $access * - * @return void + * @return self */ public function setAccess(stdClass $access) { @@ -151,12 +153,13 @@ class ShopSession Session::put(self::USER, $this->user); Session::put(self::TOKEN, $token); - return; + return $this; } // Offline $this->shop->{self::TOKEN} = $token; $this->shop->save(); + return $this; } /** @@ -206,7 +209,7 @@ class ShopSession /** * Forgets anything in session. * - * @return void + * @return self */ public function forget() { @@ -214,6 +217,8 @@ class ShopSession foreach ($keys as $key) { Session::forget($key); } + + return $this; } /**
Minor adjustments to authshop after PR
ohmybrew_laravel-shopify
train
94e516785db680b80c69a5953b585e40b7c32260
diff --git a/exceptions.go b/exceptions.go index <HASH>..<HASH> 100644 --- a/exceptions.go +++ b/exceptions.go @@ -4,7 +4,6 @@ import ( "bytes" "reflect" "runtime/debug" - "strconv" ) type ExceptionReporter interface { @@ -57,16 +56,10 @@ func errorBacktraceBytes(err error) [][]byte { return all[10 : len(all)-1] } -func ErrorId(err error) string { - id := int(reflect.ValueOf(err).Pointer()) - return strconv.Itoa(id) -} - func errorToMap(err error, data Data) { data["at"] = "exception" data["class"] = reflect.TypeOf(err).String() data["message"] = err.Error() - data["exception_id"] = ErrorId(err) } var byteLineBreak = []byte{'\n'} diff --git a/exceptions_test.go b/exceptions_test.go index <HASH>..<HASH> 100644 --- a/exceptions_test.go +++ b/exceptions_test.go @@ -14,7 +14,7 @@ func TestLogsException(t *testing.T) { err := fmt.Errorf("Test") reporter.Report(err, Data{"b": 2, "c": 3, "at": "overwrite me"}) - expected := fmt.Sprintf("a=1 b=2 c=3 at=exception class=*errors.errorString message=Test exception_id=%s", ErrorId(err)) + expected := "a=1 b=2 c=3 at=exception class=*errors.errorString message=Test" linePrefix := expected + " site=" for i, line := range strings.Split(logged(buf), "\n") {
remove ErrorId. cant get a pointer uint from a value object, only a pointer/chan/map/etc
technoweenie_grohl
train
a8ca8e5c7aaf5319f42ea84b2e699526a1b1e876
diff --git a/src/com/vmware/vim25/ws/XmlGen.java b/src/com/vmware/vim25/ws/XmlGen.java index <HASH>..<HASH> 100644 --- a/src/com/vmware/vim25/ws/XmlGen.java +++ b/src/com/vmware/vim25/ws/XmlGen.java @@ -58,6 +58,11 @@ public class XmlGen private static Namespace XSI = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); private static QName XSI_TYPE = new QName("type", XSI); private static String[] BASIC_TYPES = new String[] {"String", "int", "short", "long", "byte", "boolean", "Calendar"}; + + static + { + DatatypeConverter.setDatatypeConverter(DatatypeConverterImpl.theInstance); + } public static SoapFaultException parseSoapFault(String xmlStr) throws Exception { @@ -380,7 +385,6 @@ public class XmlGen } else if("Calendar".equals(type)) { - DatatypeConverter.setDatatypeConverter(DatatypeConverterImpl.theInstance); Calendar cal = DatatypeConverter.parseTime(values[0]); return cal; } @@ -490,7 +494,6 @@ public class XmlGen } else if("Calendar".equals(fType)) { - DatatypeConverter.setDatatypeConverter(DatatypeConverterImpl.theInstance); Calendar cal = DatatypeConverter.parseTime(values[0]); f.set(obj, cal); } @@ -531,6 +534,11 @@ public class XmlGen { //basic data type return "<" + tag +">" + obj + "</" + tag + ">"; } + else if(c.getSimpleName().equals("Calendar")) + { + String dateStr = DatatypeConverter.printTime((Calendar)obj); + return "<" + tag +">" + dateStr + "</" + tag + ">"; + } else { StringBuffer sb = new StringBuffer();
fix a bug with Calendar serialization to xml
yavijava_yavijava
train
45d8b16f08a3fdb97e6e7bd1189c33a318533e5f
diff --git a/lib/pageflow/page_type.rb b/lib/pageflow/page_type.rb index <HASH>..<HASH> 100644 --- a/lib/pageflow/page_type.rb +++ b/lib/pageflow/page_type.rb @@ -136,37 +136,5 @@ module Pageflow name end end - - # Include in your engine if it mainly defines new page types. Sets - # up load paths so you can place all files related to a page type - # in a single directory. The following structure is proposed for a - # page type engine: - # - # pageflow-rainbow/ - # page_types/ - # pageflow/ - # rainbow/ - # editor.js - # page.html.erb - # page_type.json.jbuilder - # rainbow.css.scss - # rainbow.js - # lib/ - # pageflow/ - # rainbow/ - # engine.rb - # page_type.rb - # - module Engine - extend ActiveSupport::Concern - - included do - paths["app/views"] << 'page_types' - - initializer :assets do |config| - Rails.application.config.assets.paths << root.join('page_types') - end - end - end end end
Remove unused Page Type Engine Mixing assets and view templates leads to conflicts.
codevise_pageflow
train
d3a68f99675d85c9d49588da930edbb9ae183782
diff --git a/foxpuppet/windows/browser/navbar.py b/foxpuppet/windows/browser/navbar.py index <HASH>..<HASH> 100644 --- a/foxpuppet/windows/browser/navbar.py +++ b/foxpuppet/windows/browser/navbar.py @@ -32,10 +32,9 @@ class NavBar(Region): """ with self.selenium.context(self.selenium.CONTEXT_CHROME): - if self.window.firefox_version >= 63: # Bug 1471713 + if self.window.firefox_version >= 63: # Bug 1471713, 1476218 el = self.root.find_element( *self._tracking_protection_shield_locator) - else: - el = self.root.find_element( - By.ID, 'tracking-protection-icon') + return el.get_attribute('active') is not None + el = self.root.find_element(By.ID, 'tracking-protection-icon') return bool(el.get_attribute('state'))
Fix method of checking that tracking protection shield is displayed
mozilla_FoxPuppet
train
5dbd3c2425bc271f4497101735f73ee289f96b80
diff --git a/bcrypt/__init__.py b/bcrypt/__init__.py index <HASH>..<HASH> 100644 --- a/bcrypt/__init__.py +++ b/bcrypt/__init__.py @@ -40,13 +40,13 @@ _ffi.cdef(""" _bcrypt_lib = _ffi.verify('#include "ow-crypt.h"', sources=[ - os.path.join(_bundled_dir, "crypt_blowfish.c"), - os.path.join(_bundled_dir, "crypt_gensalt.c"), - os.path.join(_bundled_dir, "wrapper.c"), + str(os.path.join(_bundled_dir, "crypt_blowfish.c")), + str(os.path.join(_bundled_dir, "crypt_gensalt.c")), + str(os.path.join(_bundled_dir, "wrapper.c")), # How can we get distutils to work with a .S file? - # os.path.join(_bundled_dir, "x86.S"), + # str(os.path.join(_bundled_dir, "x86.S")), ], - include_dirs=[_bundled_dir] + include_dirs=[str(_bundled_dir)] )
Use native strings to the CFFI verifier
pyca_bcrypt
train
717d662ed462954d656f8f880ef8344b2e1605cd
diff --git a/src/View.php b/src/View.php index <HASH>..<HASH> 100644 --- a/src/View.php +++ b/src/View.php @@ -35,6 +35,7 @@ class View extends PhalconView public function __construct($config = null) { parent::__construct($config['options']); + $this->response = static::$di->getShared('response'); $this->setViewsDir($config['path']); $this->_mainView = $config['top_level']; $this->_theme = $config['theme']; @@ -46,7 +47,7 @@ class View extends PhalconView protected function _engineRender($engines, $viewPath, $silence, $mustClean, BackendInterface $cache = null) { $silence = $silence && !$this->config['debug']; - $this->config['debug'] and $this->_options['debug_wrapper'] = $this->getDebugWrapper($viewPath); + $this->config['debug'] and $this->_options['debug_wrapper'] = ($viewPath == $this->_mainView ? false : $this->getDebugWrapper($viewPath)); $viewPath == $this->_mainView or $viewPath = trim($this->_theme . '/' . $viewPath, '/'); parent::_engineRender($engines, $viewPath, $silence, $mustClean, $cache); } @@ -232,7 +233,7 @@ class View extends PhalconView public static function make($path, $file, $params = null) { static::$instance or static::$instance = static::$di->getShared('view'); - return static::$instance->reset()->start()->render($path, $file, $params)->finish()->getContent(); + return static::$instance->reset()->render($path, $file, $params)->getContent(); } public static function register(Di $di) @@ -246,7 +247,11 @@ class View extends PhalconView public function render($controllerName, $actionName, $params = null) { try { - return parent::render($controllerName, $actionName, $params); + $this->start(); + $result = parent::render($controllerName, $actionName, $params); + $this->finish(); + $this->response->setContent($this->getContent()); + return $result; } catch (ViewException $e) { Log::exception($e); return false;
fix: call start() and finish() in view::render()
phwoolcon_phwoolcon
train
06100ef5e5a889c632bf182b3e603c0494541d17
diff --git a/collatex/src/main/java/eu/interedition/collatex2/implementation/indexing/AlignmentTableIndex.java b/collatex/src/main/java/eu/interedition/collatex2/implementation/indexing/AlignmentTableIndex.java index <HASH>..<HASH> 100644 --- a/collatex/src/main/java/eu/interedition/collatex2/implementation/indexing/AlignmentTableIndex.java +++ b/collatex/src/main/java/eu/interedition/collatex2/implementation/indexing/AlignmentTableIndex.java @@ -55,6 +55,8 @@ public class AlignmentTableIndex implements IAlignmentTableIndex, ITokenIndex { if (!cell.isEmpty()) { INormalizedToken token = cell.getToken(); tokens.add(token); + } else { + tokens.add(new NullToken(-1, row.getSigil())); } } // do unigram indexing diff --git a/collatex/src/main/java/eu/interedition/collatex2/implementation/tokenmatching/PhraseMatch.java b/collatex/src/main/java/eu/interedition/collatex2/implementation/tokenmatching/PhraseMatch.java index <HASH>..<HASH> 100644 --- a/collatex/src/main/java/eu/interedition/collatex2/implementation/tokenmatching/PhraseMatch.java +++ b/collatex/src/main/java/eu/interedition/collatex2/implementation/tokenmatching/PhraseMatch.java @@ -20,4 +20,8 @@ public class PhraseMatch { return witnessPhrase; } + @Override + public String toString() { + return basePhrase.getContent() + " -> "+witnessPhrase.getContent(); + } } diff --git a/collatex/src/main/java/eu/interedition/collatex2/implementation/tokenmatching/TokenMatch.java b/collatex/src/main/java/eu/interedition/collatex2/implementation/tokenmatching/TokenMatch.java index <HASH>..<HASH> 100644 --- a/collatex/src/main/java/eu/interedition/collatex2/implementation/tokenmatching/TokenMatch.java +++ b/collatex/src/main/java/eu/interedition/collatex2/implementation/tokenmatching/TokenMatch.java @@ -21,5 +21,10 @@ public class TokenMatch implements ITokenMatch { public INormalizedToken getWitnessToken() { return witnessToken; } + + @Override + public String toString() { + return baseToken.getContent() + " -> "+witnessToken.getContent(); + } }
[RHD] Fixed n-gram indexing of empty cells in alignment table
interedition_collatex
train
852ab5e476ac6e1b9a7eda578ffe77a358a84e09
diff --git a/src/PhpPact/Standalone/Installer/Service/InstallerPosixPreinstalled.php b/src/PhpPact/Standalone/Installer/Service/InstallerPosixPreinstalled.php index <HASH>..<HASH> 100644 --- a/src/PhpPact/Standalone/Installer/Service/InstallerPosixPreinstalled.php +++ b/src/PhpPact/Standalone/Installer/Service/InstallerPosixPreinstalled.php @@ -30,7 +30,7 @@ class InstallerPosixPreinstalled implements InstallerInterface return $scripts; } - private function getBinaryPath($binary) + private function getBinaryPath(string $binary): string { return trim(shell_exec('command -v ' . escapeshellarg($binary))); }
chore: Add typehints to private function
pact-foundation_pact-php
train
86273f94b8a23bbad84b5b45b2206f53dd1a582f
diff --git a/tests/GrabyFunctionalTest.php b/tests/GrabyFunctionalTest.php index <HASH>..<HASH> 100644 --- a/tests/GrabyFunctionalTest.php +++ b/tests/GrabyFunctionalTest.php @@ -117,7 +117,7 @@ class GrabyFunctionalTest extends \PHPUnit_Framework_TestCase public function testPdfFile() { $graby = new Graby(array('debug' => true)); - $res = $graby->fetchContent('http://www.relacweb.org/conferencia/images/documentos/Hoteles_cerca.pdf'); + $res = $graby->fetchContent('http://img3.free.fr/im_tv/telesites/documentation.pdf'); $this->assertCount(8, $res); @@ -132,10 +132,10 @@ class GrabyFunctionalTest extends \PHPUnit_Framework_TestCase $this->assertEquals(200, $res['status']); $this->assertEquals('', $res['language']); - $this->assertEquals('http://www.relacweb.org/conferencia/images/documentos/Hoteles_cerca.pdf', $res['url']); - $this->assertEquals('1725.PDF', $res['title']); - $this->assertContains('University of Liverpool', $res['html']); - $this->assertContains('University of Liverpool', $res['summary']); + $this->assertEquals('http://img3.free.fr/im_tv/telesites/documentation.pdf', $res['url']); + $this->assertEquals('PDF', $res['title']); + $this->assertContains('Free 2008', $res['html']); + $this->assertContains('Free 2008', $res['summary']); $this->assertEquals('application/pdf', $res['content_type']); $this->assertEquals(array(), $res['open_graph']); }
Update tests about PDF Previous URL doesn't work anymore
j0k3r_graby
train
f27ad636005888806e1fbe6eb2b07b7eaae4da50
diff --git a/pkg/apis/externaldns/types_test.go b/pkg/apis/externaldns/types_test.go index <HASH>..<HASH> 100644 --- a/pkg/apis/externaldns/types_test.go +++ b/pkg/apis/externaldns/types_test.go @@ -89,6 +89,32 @@ func TestParseFlags(t *testing.T) { LogFormat: "json", }, }, + { + title: "set everything", + args: [][]string{{"--in-cluster", + "--log-format", "yaml", + "--kubeconfig", "/some/path", + "--google-project", "project", + "--google-zone", "zone", + "--health-port", "1234", + "--dry-run", "true", + "--debug"}}, + expected: &Config{ + InCluster: true, + KubeConfig: "/some/path", + GoogleProject: "project", + GoogleZone: "zone", + HealthPort: "1234", + DryRun: true, + Debug: true, + LogFormat: "yaml", + }, + }, + { + title: "--help trigger error", + args: [][]string{{"--help"}}, + expectError: true, + }, } { t.Run(ti.title, func(t *testing.T) { cfg := NewConfig()
improve test cover for flag parsing
kubernetes-incubator_external-dns
train
fddb8fd52cbcb42ede38220b5ca7e4b12832e19c
diff --git a/src/Administration/Resources/app/administration/src/module/sw-order/page/sw-order-create/index.js b/src/Administration/Resources/app/administration/src/module/sw-order/page/sw-order-create/index.js index <HASH>..<HASH> 100644 --- a/src/Administration/Resources/app/administration/src/module/sw-order/page/sw-order-create/index.js +++ b/src/Administration/Resources/app/administration/src/module/sw-order/page/sw-order-create/index.js @@ -92,6 +92,11 @@ Component.register('sw-order-create', { }, onCancelOrder() { + if (this.customer === null || this.cart === null) { + this.redirectToOrderList(); + return; + } + State .dispatch('swOrder/cancelCart', { salesChannelId: this.customer.salesChannelId,
NTR - Fix cancel cart when it's empty
shopware_platform
train
ba32bfad373f66f453064e4505583a8eeba8afa6
diff --git a/lib/event_source/entity.rb b/lib/event_source/entity.rb index <HASH>..<HASH> 100644 --- a/lib/event_source/entity.rb +++ b/lib/event_source/entity.rb @@ -37,6 +37,9 @@ module EventSource @events end + def save + end + private def initialize diff --git a/lib/event_source/entity_repository.rb b/lib/event_source/entity_repository.rb index <HASH>..<HASH> 100644 --- a/lib/event_source/entity_repository.rb +++ b/lib/event_source/entity_repository.rb @@ -12,6 +12,7 @@ module EventSource def transaction @@current = self.new yield + @@current.commit @@current = nil end @@ -27,5 +28,9 @@ module EventSource def add(entity) @entities << entity end + + def commit + @entities.each {|e| e.save} + end end end diff --git a/spec/event_source/entity_repository_spec.rb b/spec/event_source/entity_repository_spec.rb index <HASH>..<HASH> 100644 --- a/spec/event_source/entity_repository_spec.rb +++ b/spec/event_source/entity_repository_spec.rb @@ -26,8 +26,27 @@ describe EventSource::EntityRepository do EventSource::EntityRepository.current.should be_nil end + + it 'should commit the repository after the transaction is successful' do + entity = double('entity') + entity.should_receive(:save) + + EventSource::EntityRepository.transaction do + EventSource::EntityRepository.current.add(entity) + end + end + end + + describe 'when committing the repository' do + it 'should save each entity in the list' do + entity = double('entity') + sut = EventSource::EntityRepository.new + sut.add(entity) + + entity.should_receive(:save) + sut.commit + end end - describe 'when committing the repository' describe 'when searching for an entity' end
save entities after a transaction completes
louissalin_event_source
train
1fd3ca2dd39fa9a90a844ca3fee6acd5044a21ef
diff --git a/spyder/widgets/switcher.py b/spyder/widgets/switcher.py index <HASH>..<HASH> 100644 --- a/spyder/widgets/switcher.py +++ b/spyder/widgets/switcher.py @@ -78,7 +78,7 @@ class KeyPressFilter(QObject): class SwitcherBaseItem(QStandardItem): """Base List Item.""" - _PADDING = 3 + _PADDING = 5 _WIDTH = 400 _HEIGHT = None _STYLES = None @@ -114,7 +114,7 @@ class SwitcherBaseItem(QStandardItem): # --- API def set_width(self, value): """Set the content width.""" - self._width = value - (self._padding * 2) + self._width = value - (self._padding * 3) self._set_rendered_text() def get_width(self): @@ -212,7 +212,7 @@ class SwitcherItem(SwitcherBaseItem): """ _FONT_SIZE = 10 - _HEIGHT = 15 + _HEIGHT = 20 _STYLE_ATTRIBUTES = ['title_color', 'description_color', 'section_color', 'shortcut_color', 'title_font_size', 'description_font_size', 'section_font_size', @@ -469,11 +469,10 @@ class Switcher(QDialog): sig_item_selected = Signal(object, TEXT_TYPES[-1], TEXT_TYPES[-1], ) sig_mode_selected = Signal(TEXT_TYPES[-1]) + _MAX_NUM_ITEMS = 15 _MIN_WIDTH = 580 _MIN_HEIGHT = 200 - _MAX_HEIGHT = 400 - - _MAX_NUM_ITEMS = 20 + _MAX_HEIGHT = 390 _ITEM_WIDTH = _MIN_WIDTH - 20 def __init__(self, parent, help_text=None, item_styles=ITEM_STYLES,
Switcher: Revert padding related changes - The previous ones were very well crafted. - This also reduces the max number of items to <I> because <I> is now too much given this revert.
spyder-ide_spyder
train
94b499413bf2090c743f337d1b471395c92d256b
diff --git a/mapchete/_processing.py b/mapchete/_processing.py index <HASH>..<HASH> 100644 --- a/mapchete/_processing.py +++ b/mapchete/_processing.py @@ -308,11 +308,15 @@ def compute( 1, ): if raise_errors: # pragma: no cover - if future.status in ["error", "cancelled"]: + if ( + hasattr(future, "status") + and future.status in ["error", "cancelled"] + ) or future.exception(timeout=FUTURE_TIMEOUT): exception = ( - future.exception(timeout=FUTURE_TIMEOUT) - if future.status == "error" - else future.result(timeout=FUTURE_TIMEOUT) + future.result(timeout=FUTURE_TIMEOUT) + if hasattr(future, "status") + and future.status == "cancelled" + else future.exception(timeout=FUTURE_TIMEOUT) ) raise MapcheteTaskFailed( f"{future.key.rstrip('_finished')} raised a {repr(exception)}"
workaround for concurrent.futures api
ungarj_mapchete
train
bc885f1d0842273bcee73fe34f79592ad68d48fb
diff --git a/cmd/syncthing/main.go b/cmd/syncthing/main.go index <HASH>..<HASH> 100644 --- a/cmd/syncthing/main.go +++ b/cmd/syncthing/main.go @@ -289,7 +289,6 @@ func main() { l.Infoln("No config file; starting with empty defaults") name, _ := os.Hostname() defaultRepo := filepath.Join(getHomeDir(), "Sync") - ensureDir(defaultRepo, 0755) cfg, err = config.Load(nil, myID) cfg.Repositories = []config.RepositoryConfiguration{
Don't attempt to create default repo before config (fixes #<I>) We'll create it anyway a little later during startup, as part of the general "check all repos for viability" step.
syncthing_syncthing
train
5662d318941f4765500e021b9364c69c9edc1b0f
diff --git a/task.go b/task.go index <HASH>..<HASH> 100644 --- a/task.go +++ b/task.go @@ -34,6 +34,7 @@ type Task struct { HealthCheckResults []*HealthCheckResult `json:"healthCheckResults"` Ports []int `json:"ports"` ServicePorts []int `json:"servicePorts"` + SlaveID string `json:"slaveId"` StagedAt string `json:"stagedAt"` StartedAt string `json:"startedAt"` Version string `json:"version"`
Add SlaveID field in Task struct Marathon has a "slaveId" field in "task" since <I>-RC1
gambol99_go-marathon
train
ac0f2f307f3c19eb638b6eb1dbc5c3677af35bbb
diff --git a/dss/blobstore/gcs.py b/dss/blobstore/gcs.py index <HASH>..<HASH> 100644 --- a/dss/blobstore/gcs.py +++ b/dss/blobstore/gcs.py @@ -1,5 +1,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals +import base64 +import binascii import datetime import typing @@ -77,6 +79,24 @@ class GCSBlobStore(BlobStore): return blob_obj.download_as_string() + def get_cloud_checksum( + self, + bucket: str, + object_name: str + ) -> str: + """ + Retrieves the cloud-provided checksum for a given object in a given bucket. + :param bucket: the bucket the object resides in. + :param object_name: the name of the object for which checksum is being retrieved. + :return: the cloud-provided checksum + """ + bucket_obj = self._ensure_bucket_loaded(bucket) + blob_obj = bucket_obj.get_blob(object_name) + if blob_obj is None: + raise BlobNotFoundError() + + return binascii.hexlify(base64.b64decode(blob_obj.crc32c)).decode("utf-8").lower() + def get_metadata( self, bucket: str, diff --git a/tests/test_gcsblobstore.py b/tests/test_gcsblobstore.py index <HASH>..<HASH> 100644 --- a/tests/test_gcsblobstore.py +++ b/tests/test_gcsblobstore.py @@ -12,7 +12,7 @@ sys.path.insert(0, pkg_root) from dss.blobstore.gcs import GCSBlobStore # noqa from tests import utils # noqa -from tests.test_blobstore import BlobStoreTests # noqa +from tests.test_blobstore import BlobNotFoundError, BlobStoreTests # noqa class TestGCSBlobStore(unittest.TestCase, BlobStoreTests): @@ -26,5 +26,20 @@ class TestGCSBlobStore(unittest.TestCase, BlobStoreTests): def tearDown(self): pass + def test_get_checksum(self): + """ + Ensure that the ``get_metadata`` methods return sane data. + """ + handle = self.handle # type: BlobStore + checksum = handle.get_cloud_checksum( + self.test_src_data_bucket, + "test_good_source_data/0") + self.assertEqual(checksum, "e16e07b9") + + with self.assertRaises(BlobNotFoundError): + handle.get_metadata( + self.test_src_data_bucket, + "test_good_source_data_DOES_NOT_EXIST") + if __name__ == '__main__': unittest.main()
GCS support for get_checksum. (#<I>)
HumanCellAtlas_cloud-blobstore
train
38ad57a2bde40d3d4896f148c481d0c40120c6d8
diff --git a/zxcvbn/__main__.py b/zxcvbn/__main__.py index <HASH>..<HASH> 100644 --- a/zxcvbn/__main__.py +++ b/zxcvbn/__main__.py @@ -1,5 +1,6 @@ import argparse import json +import select import sys import getpass @@ -25,7 +26,16 @@ class JSONEncoder(json.JSONEncoder): def cli(): args = parser.parse_args() - password = getpass.getpass() + + # check if stdin is ready for reading + rlist, _, _ = select.select([sys.stdin], [], [], 0.0) + if rlist: + password = rlist[0].read() + if password[-1] == '\n': # strip off the trailing newline + password = password[:-1] + else: + password = getpass.getpass() + res = zxcvbn(password, user_inputs=args.user_input) json.dump(res, sys.stdout, indent=2, cls=JSONEncoder) sys.stdout.write('\n')
Prefer stdin for password if it is readable (#<I>) * Prefer stdin for password if it is readable * Always strip off the trailing new line * Use read instead of readline
dwolfhub_zxcvbn-python
train
8abdce9c60c9d2ead839e0065d35128ec16a82a1
diff --git a/chatterbot/__main__.py b/chatterbot/__main__.py index <HASH>..<HASH> 100644 --- a/chatterbot/__main__.py +++ b/chatterbot/__main__.py @@ -8,6 +8,15 @@ if __name__ == '__main__': print(chatterbot.__version__) if 'list_nltk_data' in sys.argv: + import os import nltk.data - print('\n'.join(nltk.data.path)) + data_directories = [] + + # Find each data directory in the NLTK path that has content + for path in nltk.data.path: + if os.path.exists(path): + if os.listdir(path): + data_directories.append(path) + + print(os.linesep.join(data_directories))
Add commad line utility to find NLTK data
gunthercox_ChatterBot
train
fb622baa18416b93d87d4584431958f0f6c10ec4
diff --git a/lib/awspec/helper/finder/ec2.rb b/lib/awspec/helper/finder/ec2.rb index <HASH>..<HASH> 100644 --- a/lib/awspec/helper/finder/ec2.rb +++ b/lib/awspec/helper/finder/ec2.rb @@ -23,20 +23,28 @@ module Awspec::Helper }) end else - res = ec2_client.describe_instances({ - filters: [{ name: 'tag:Name', values: [id] }] - }) + begin + res = ec2_client.describe_instances({ + filters: [{ name: 'tag:Name', values: [id] }] + }) + rescue Aws::EC2::Errors::InvalidInstanceIDNotFound, Aws::EC2::Errors::InvalidInstanceIDMalformed => e + res = ec2_client.describe_instances({ + instance_ids: [id] + }) + if res.reservations.count > 1 + STDERR.puts "Warning: '#{id}' unexpectedly identified as a valid instance ID during fallback search" + end + end end - # rubocop:enable Style/GuardClause + return nil if res.reservations.count == 0 + return res.reservations.first.instances.single_resource(id) if res.reservations.count == 1 + raise Awspec::DuplicatedResourceTypeError, dup_ec2_instance(id) if res.reservations.count > 1 + raise "Unexpected condition of having reservations = #{res.reservations.count}" + end - if res.reservations.count == 0 - nil - elsif res.reservations.count == 1 - res.reservations.first.instances.single_resource(id) - elsif res.reservations.count > 1 - raise Awspec::DuplicatedResourceTypeError, "Duplicate instances matching id or tag #{id}" - end + def dup_ec2_instance(id) + "Duplicate instances matching id or tag #{id}" end def find_ec2_attribute(id, attribute)
refactor: fallback and rubocop errors
k1LoW_awspec
train
b49ea12a66e7452d1ea220e9730755153f0a9939
diff --git a/drivers/overlay/idmapped_utils.go b/drivers/overlay/idmapped_utils.go index <HASH>..<HASH> 100644 --- a/drivers/overlay/idmapped_utils.go +++ b/drivers/overlay/idmapped_utils.go @@ -21,17 +21,6 @@ type attr struct { userNs uint64 } -const ( - // _MOUNT_ATTR_IDMAP - Idmap mount to @userns_fd in struct mount_attr - _MOUNT_ATTR_IDMAP = 0x00100000 //nolint:golint - - // _OPEN_TREE_CLONE - Clone the source path mount - _OPEN_TREE_CLONE = 0x00000001 //nolint:golint - - // _MOVE_MOUNT_F_EMPTY_PATH - Move the path referenced by the fd - _MOVE_MOUNT_F_EMPTY_PATH = 0x00000004 //nolint:golint -) - // openTree is a wrapper for the open_tree syscall func openTree(path string, flags int) (fd int, err error) { var _p0 *byte @@ -61,7 +50,7 @@ func moveMount(fdTree int, target string) (err error) { return err } - flags := _MOVE_MOUNT_F_EMPTY_PATH + flags := unix.MOVE_MOUNT_F_EMPTY_PATH _, _, e1 := syscall.Syscall6(uintptr(unix.SYS_MOVE_MOUNT), uintptr(fdTree), uintptr(unsafe.Pointer(_p1)), @@ -98,14 +87,14 @@ func createIDMappedMount(source, target string, pid int) error { } var attr attr - attr.attrSet = _MOUNT_ATTR_IDMAP + attr.attrSet = unix.MOUNT_ATTR_IDMAP attr.attrClr = 0 attr.propagation = 0 attr.userNs = uint64(userNsFile.Fd()) defer userNsFile.Close() - targetDirFd, err := openTree(source, _OPEN_TREE_CLONE) + targetDirFd, err := openTree(source, unix.OPEN_TREE_CLONE) if err != nil { return err }
overlay: drop constants defined in unix pkg remove some constants that are also defined in the unix package.
containers_storage
train
231f5ec385ac139e4aae2b6d85204ec62029feeb
diff --git a/mutagen/flac.py b/mutagen/flac.py index <HASH>..<HASH> 100644 --- a/mutagen/flac.py +++ b/mutagen/flac.py @@ -391,7 +391,7 @@ class CueSheetTrack(object): Attributes: track_number (`int`): track number start_offset (`int`): track offset in samples from start of FLAC stream - isrc (`text`): ISRC code, exactly 12 characters + isrc (`mutagen.text`): ISRC code, exactly 12 characters type (`int`): 0 for audio, 1 for digital data pre_emphasis (`bool`): true if the track is recorded with pre-emphasis indexes (List[`mutagen.flac.CueSheetTrackIndex`]): @@ -437,7 +437,7 @@ class CueSheet(MetadataBlock): in the cue sheet. Attributes: - media_catalog_number (`text`): media catalog number in ASCII, + media_catalog_number (`mutagen.text`): media catalog number in ASCII, up to 128 characters lead_in_samples (`int`): number of lead-in samples compact_disc (`bool`): true if the cuesheet corresponds to a
docs: fix some sphinx reference warnings
quodlibet_mutagen
train
f0585ddb4e86c76dbe5a9926d4886c772df7d5e3
diff --git a/system/src/Grav/Common/Page/Medium.php b/system/src/Grav/Common/Page/Medium.php index <HASH>..<HASH> 100644 --- a/system/src/Grav/Common/Page/Medium.php +++ b/system/src/Grav/Common/Page/Medium.php @@ -120,16 +120,7 @@ class Medium extends Data $this->def('mime', 'application/octet-stream'); } - $debug = self::$grav['config']->get('system.images.debug'); - // try to override with page setting if possible - $page = self::$grav['page']; - if (!is_null($page)) { - if (isset($page->header()->images['debug'])) { - $debug = $page->header()->images['debug']; - } - } - - $this->set('debug', $debug); + $this->set('debug', self::$grav['config']->get('system.images.debug')); } /**
per-page debug setting not working as intended. Changing approaches...
getgrav_grav
train
72e4841523d475f24d332efb17155d136cd41187
diff --git a/lib/aria/checked.js b/lib/aria/checked.js index <HASH>..<HASH> 100644 --- a/lib/aria/checked.js +++ b/lib/aria/checked.js @@ -5,4 +5,12 @@ import { TristateAttrType } from './tristate' * radio buttons, and other widgets. * @see https://www.w3.org/TR/wai-aria-1.1/#aria-checked */ -export class Checked extends TristateAttrType {} +export class Checked extends TristateAttrType { + /** + * fixme https://github.com/w3c/aria/issues/773 + * @returns {undefined} + */ + static get defaultValue() { + return undefined + } +} diff --git a/lib/aria/pressed.js b/lib/aria/pressed.js index <HASH>..<HASH> 100644 --- a/lib/aria/pressed.js +++ b/lib/aria/pressed.js @@ -4,4 +4,12 @@ import { TristateAttrType } from './tristate' * @summary Indicates the current "pressed" state of toggle buttons. * @see https://www.w3.org/TR/wai-aria-1.1/#aria-pressed */ -export class Pressed extends TristateAttrType {} +export class Pressed extends TristateAttrType { + /** + * fixme https://github.com/w3c/aria/issues/773 + * @returns {undefined} + */ + static get defaultValue() { + return undefined + } +} diff --git a/lib/aria/tristate.js b/lib/aria/tristate.js index <HASH>..<HASH> 100644 --- a/lib/aria/tristate.js +++ b/lib/aria/tristate.js @@ -1,4 +1,4 @@ -import { BooleanAttrType } from './boolean' +import { ApplicableAttrType } from './applicable' const TOKEN_MIXED = 'mixed' @@ -7,26 +7,28 @@ const TOKEN_MIXED = 'mixed' * The default value for this value type is false unless otherwise specified. * @see https://www.w3.org/TR/wai-aria-1.1/#valuetype_tristate */ -export class TristateAttrType extends BooleanAttrType { +export class TristateAttrType extends ApplicableAttrType { /** * value = true * value = 'true' * value = '*' // non empty string * value = 1 - * value = * // non zero + * value = * // non zero number * => 'true' * * value = false * value = 'false' * value = '' - * value = null - * value = undefined * value = 0 - * => no attr + * => 'false' * * value = 'mixed' * => 'mixed' * + * value = null + * value = undefined + * => no attr + * * @param {*} value {boolean|string} */ set value(value) { @@ -49,6 +51,9 @@ export class TristateAttrType extends BooleanAttrType { * value === 'mixed' * => 'mixed' * + * no attr + * => false // fixme + * * @returns {boolean|string} */ get value() { @@ -56,4 +61,12 @@ export class TristateAttrType extends BooleanAttrType { TOKEN_MIXED : super.value } + + /** + * fixme https://github.com/w3c/aria/issues/773 + * @returns {boolean} + */ + static get defaultValue() { + return false + } }
TristateAttrType: inherit from the ApplicableAttrType, fix the default value of Checked and Pressed
aristov_ariamodule
train
dd90bcb7b926d1cd363a5068ab988a068a440390
diff --git a/lib/starting_blocks/version.rb b/lib/starting_blocks/version.rb index <HASH>..<HASH> 100644 --- a/lib/starting_blocks/version.rb +++ b/lib/starting_blocks/version.rb @@ -1,3 +1,3 @@ module StartingBlocks - VERSION = "0.5.1" + VERSION = "0.5.2" end
Bump the version for bug fixes.
darrencauthon_starting_blocks
train
11ec637ba3e115cbb928c3c3a5167fa81ab615db
diff --git a/Entity/ShopInterface.php b/Entity/ShopInterface.php index <HASH>..<HASH> 100644 --- a/Entity/ShopInterface.php +++ b/Entity/ShopInterface.php @@ -13,9 +13,9 @@ namespace WellCommerce\Bundle\AppBundle\Entity; use Doctrine\Common\Collections\Collection; -use WellCommerce\Bundle\AppBundle\Entity\BlameableInterface; +use WellCommerce\Bundle\UserBundle\Entity\BlameableInterface; use WellCommerce\Bundle\AppBundle\Entity\MailerConfiguration; -use WellCommerce\Bundle\AppBundle\Entity\TimestampableInterface; +use WellCommerce\Bundle\CoreBundle\Entity\TimestampableInterface; use WellCommerce\Bundle\ThemeBundle\Entity\ThemeAwareInterface; /**
AppBundle fixes (cherry picked from commit 2cd8a<I>e4ffa<I>ba<I>c6a8d<I>d<I>cb1a<I>df7)
WellCommerce_CouponBundle
train
6d1dc9fdb34b1c0be1db5a26375ccf3794acfdd2
diff --git a/code/libraries/koowa/mixin/commandchain.php b/code/libraries/koowa/mixin/commandchain.php index <HASH>..<HASH> 100644 --- a/code/libraries/koowa/mixin/commandchain.php +++ b/code/libraries/koowa/mixin/commandchain.php @@ -48,7 +48,7 @@ class KMixinCommandchain extends KMixinAbstract $this->_mixer->mixin(new KMixinCallback(new KConfig(array( 'mixer' => $this->_mixer, 'command_chain' => $this->_command_chain, - 'command_priority' => $config->_callback_priority + 'command_priority' => $config->callback_priority )))); } @@ -73,7 +73,7 @@ class KMixinCommandchain extends KMixinAbstract 'dispatch_events' => true, 'event_priority' => KCommand::PRIORITY_LOWEST, 'enable_callbacks' => false, - 'callback_priority' => KCommand::PRIORITY_HIGHEST, + 'callback_priority' => KCommand::PRIORITY_HIGH, )); parent::_initialize($config);
Fixed typo. Changed callback_priority to PRIORITY_HIGH instead of PRIORITY_HIEHEST
timble_kodekit
train
f1075605d4de755d33acfded8d2a46a29574e8be
diff --git a/pgmpy/readwrite/BIF.py b/pgmpy/readwrite/BIF.py index <HASH>..<HASH> 100644 --- a/pgmpy/readwrite/BIF.py +++ b/pgmpy/readwrite/BIF.py @@ -3,7 +3,7 @@ from string import Template import numpy from pyparsing import Word, alphanums, Suppress, Optional, CharsNotIn, Group, nums, ZeroOrMore, OneOrMore,\ - cppStyleComment, Literal, printables + cppStyleComment, Literal, printables from pgmpy.models import BayesianModel from pgmpy.factors import TabularCPD @@ -17,7 +17,6 @@ class BIFReader(object): """ def __init__(self, path=None, string=None): - """ Initialisation of BifReader object @@ -66,7 +65,6 @@ class BIFReader(object): self.variable_edges = self.get_edges() def get_variable_grammar(self): - """ A method that returns variable grammar """ @@ -85,7 +83,6 @@ class BIFReader(object): return name_expr, variable_state_expr, property_expr def get_probability_grammar(self): - """ A method that returns probability grammar """ @@ -116,7 +113,6 @@ class BIFReader(object): yield self.network[index.start():end] def get_network_name(self): - """ Retruns the name of the network @@ -136,7 +132,6 @@ class BIFReader(object): return network_name def get_variables(self): - """ Returns list of variables of the network @@ -155,7 +150,6 @@ class BIFReader(object): return variable_names def get_states(self): - """ Returns the states of variables present in the network @@ -178,7 +172,6 @@ class BIFReader(object): return variable_states def get_property(self): - """ Returns the property of the variable @@ -201,7 +194,6 @@ class BIFReader(object): return variable_properties def get_parents(self): - """ Returns the parents of the variables present in the network @@ -223,7 +215,6 @@ class BIFReader(object): return variable_parents def get_cpd(self): - """ Returns the CPD of the variables present in the network @@ -248,15 +239,22 @@ class BIFReader(object): name = self.probability_expr.searchString(block)[0][0] cpds = self.cpd_expr.searchString(block) arr = [float(j) for i in cpds for j in i] - arr = numpy.array(arr) - arr = arr.reshape((len(self.variable_states[name]), - arr.size//len(self.variable_states[name]))) + if 'table' in block: + arr = numpy.array(arr) + arr = arr.reshape((len(self.variable_states[name]), + arr.size // len(self.variable_states[name]))) + else: + length = len(self.variable_states[name]) + reshape_arr = [[] for i in range(length)] + for i, val in enumerate(arr): + reshape_arr[i % length].append(val) + arr = reshape_arr + arr = numpy.array(arr) variable_cpds[name] = arr return variable_cpds def get_edges(self): - """ Returns the edges of the network @@ -275,7 +273,6 @@ class BIFReader(object): return edges def get_model(self): - """ Returns the fitted bayesian model @@ -319,7 +316,6 @@ class BIFWriter(object): """ def __init__(self, model): - """ Initialise a BIFWriter Object @@ -347,7 +343,6 @@ class BIFWriter(object): self.tables = self.get_cpds() def BIF_templates(self): - """ Create template for writing in BIF format """ @@ -399,7 +394,6 @@ $properties}\n""") return network def get_variables(self): - """ Add variables to BIF @@ -419,7 +413,6 @@ $properties}\n""") return variables def get_states(self): - """ Add states to variable of BIF @@ -445,11 +438,10 @@ $properties}\n""") variable = cpd.variable variable_states[variable] = [] for state in range(cpd.get_cardinality([variable])[variable]): - variable_states[variable].append(str(variable)+'_'+str(state)) + variable_states[variable].append(str(variable) + '_' + str(state)) return variable_states def get_properties(self): - """ Add property to variables in BIF @@ -479,7 +471,6 @@ $properties}\n""") return property_tag def get_parents(self): - """ Add the parents to BIF @@ -509,7 +500,6 @@ $properties}\n""") return variable_parents def get_cpds(self): - """ Adds tables to BIF @@ -536,7 +526,6 @@ $properties}\n""") return tables def write_bif(self, filename): - """ Writes the BIF data into a file diff --git a/pgmpy/tests/test_readwrite/test_BIF.py b/pgmpy/tests/test_readwrite/test_BIF.py index <HASH>..<HASH> 100644 --- a/pgmpy/tests/test_readwrite/test_BIF.py +++ b/pgmpy/tests/test_readwrite/test_BIF.py @@ -42,7 +42,8 @@ variable "family-out" { //2 values property "position = (257, 99)" ; } probability ( "light-on" "family-out" ) { //2 variable(s) and 4 values - table 0.6 0.05 0.4 0.95 ; + (true) 0.6 0.4 ; + (false) 0.05 0.95 ; } probability ( "bowel-problem" ) { //1 variable(s) and 2 values table 0.01 0.99 ;
Fixed a bug in BIFReader class Actually there was an issue with the symantics of BIF file types, when table argument is present in cpd and when not, we have to reshape the things differently.For more reference refer to <URL>
pgmpy_pgmpy
train
2a61d6ddb216175d8f96aabc86677b04d1a9c4c8
diff --git a/src/main/java/edu/ksu/canvas/model/assignment/QuizAnswer.java b/src/main/java/edu/ksu/canvas/model/assignment/QuizAnswer.java index <HASH>..<HASH> 100644 --- a/src/main/java/edu/ksu/canvas/model/assignment/QuizAnswer.java +++ b/src/main/java/edu/ksu/canvas/model/assignment/QuizAnswer.java @@ -10,8 +10,10 @@ import java.util.List; public class QuizAnswer { private Integer id; private String text; - private Integer answerWeight; - private String answerComments; + private String html; + private Double weight; + private String comments; + private String commentsHtml; private String textAfterAnswers; private String answerMatchLeft; private String answerMatchRight; @@ -21,7 +23,7 @@ public class QuizAnswer { private Double margin; //margin of error for above private String start; //used if numerical_answer_type is "range_answer" private String end; //used if numerical_answer_type is "range_answer" - private Integer blankId; + private String blankId; public Integer getId() { @@ -40,20 +42,36 @@ public class QuizAnswer { this.text = text; } - public Integer getAnswerWeight() { - return answerWeight; + public String getHtml() { + return html; } - public void setAnswerWeight(Integer answerWeight) { - this.answerWeight = answerWeight; + public void setHtml(String html) { + this.html = html; } - public String getAnswerComments() { - return answerComments; + public Double getWeight() { + return weight; } - public void setAnswerComments(String answerComments) { - this.answerComments = answerComments; + public void setWeight(Double weight) { + this.weight = weight; + } + + public String getComments() { + return comments; + } + + public void setComments(String comments) { + this.comments = comments; + } + + public String getCommentsHtml() { + return commentsHtml; + } + + public void setCommentsHtml(String commentsHtml) { + this.commentsHtml = commentsHtml; } public String getTextAfterAnswers() { @@ -128,11 +146,11 @@ public class QuizAnswer { this.end = end; } - public Integer getBlankId() { + public String getBlankId() { return blankId; } - public void setBlankId(Integer blankId) { + public void setBlankId(String blankId) { this.blankId = blankId; } @@ -143,14 +161,14 @@ public class QuizAnswer { QuizAnswer that = (QuizAnswer) o; - if (answerComments != null ? !answerComments.equals(that.answerComments) : that.answerComments != null) + if (comments != null ? !comments.equals(that.comments) : that.comments != null) return false; if (answerMatchLeft != null ? !answerMatchLeft.equals(that.answerMatchLeft) : that.answerMatchLeft != null) return false; if (answerMatchRight != null ? !answerMatchRight.equals(that.answerMatchRight) : that.answerMatchRight != null) return false; if (text != null ? !text.equals(that.text) : that.text != null) return false; - if (answerWeight != null ? !answerWeight.equals(that.answerWeight) : that.answerWeight != null) + if (weight != null ? !weight.equals(that.weight) : that.weight != null) return false; if (blankId != null ? !blankId.equals(that.blankId) : that.blankId != null) return false; if (end != null ? !end.equals(that.end) : that.end != null) return false; @@ -172,8 +190,8 @@ public class QuizAnswer { public int hashCode() { int result = id.hashCode(); result = 31 * result + (text != null ? text.hashCode() : 0); - result = 31 * result + (answerWeight != null ? answerWeight.hashCode() : 0); - result = 31 * result + (answerComments != null ? answerComments.hashCode() : 0); + result = 31 * result + (weight != null ? weight.hashCode() : 0); + result = 31 * result + (comments != null ? comments.hashCode() : 0); result = 31 * result + (textAfterAnswers != null ? textAfterAnswers.hashCode() : 0); result = 31 * result + (answerMatchLeft != null ? answerMatchLeft.hashCode() : 0); result = 31 * result + (answerMatchRight != null ? answerMatchRight.hashCode() : 0);
Fixing some discrepancies in the QuizAnswer object Documentation doesn't match actual API. I am shocked.
kstateome_canvas-api
train
bdc418988cb11c68b6f9cc35e8baac424789b44e
diff --git a/pylightcurve/oec.py b/pylightcurve/oec.py index <HASH>..<HASH> 100755 --- a/pylightcurve/oec.py +++ b/pylightcurve/oec.py @@ -40,7 +40,10 @@ def oec_catalogue(): if update: - print 'Updating OEC...' + if not os.path.isfile(data_base_file_path): + print 'Installing OEC...' + else: + print 'Updating OEC...' try: socket.setdefaulttimeout(5) @@ -60,8 +63,13 @@ def oec_catalogue(): w.close() except IOError: - print 'Updating OEC failed.' - pass + + if not os.path.isfile(data_base_file_path): + 'Installing OEC failed.' + exit() + else: + print 'Updating OEC failed.' + pass return exodata.OECDatabase(data_base_file_path, stream=True)
Update oec.py
ucl-exoplanets_pylightcurve
train
ad80752715aaed449629369687c5fd30eb1bda76
diff --git a/mvcc/backend/backend.go b/mvcc/backend/backend.go index <HASH>..<HASH> 100644 --- a/mvcc/backend/backend.go +++ b/mvcc/backend/backend.go @@ -65,6 +65,8 @@ type Backend interface { // Since the backend can manage free space in a non-byte unit such as // number of pages, the returned value can be not exactly accurate in bytes. SizeInUse() int64 + // OpenReadTxN returns the number of currently open read transactions in the backend. + OpenReadTxN() int64 Defrag() error ForceCommit() Close() error @@ -89,6 +91,8 @@ type backend struct { sizeInUse int64 // commits counts number of commits since start commits int64 + // openReadTxN is the number of currently open read transactions in the backend + openReadTxN int64 mu sync.RWMutex db *bolt.DB @@ -198,6 +202,7 @@ func (b *backend) ConcurrentReadTx() ReadTx { defer b.readTx.RUnlock() // prevent boltdb read Tx from been rolled back until store read Tx is done. b.readTx.txWg.Add(1) + // TODO: might want to copy the read buffer lazily - create copy when A) end of a write transaction B) end of a batch interval. return &concurrentReadTx{ buf: b.readTx.buf.unsafeCopy(), tx: b.readTx.tx, @@ -513,6 +518,7 @@ func (b *backend) begin(write bool) *bolt.Tx { db := tx.DB() atomic.StoreInt64(&b.size, size) atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize))) + atomic.StoreInt64(&b.openReadTxN, int64(db.Stats().OpenTxN)) return tx } @@ -529,6 +535,10 @@ func (b *backend) unsafeBegin(write bool) *bolt.Tx { return tx } +func (b *backend) OpenReadTxN() int64 { + return atomic.LoadInt64(&b.openReadTxN) +} + // NewTmpBackend creates a backend implementation for testing. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) { dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test") diff --git a/mvcc/kvstore.go b/mvcc/kvstore.go index <HASH>..<HASH> 100644 --- a/mvcc/kvstore.go +++ b/mvcc/kvstore.go @@ -354,6 +354,9 @@ func (s *store) restore() error { reportDbTotalSizeInUseInBytesMu.Lock() reportDbTotalSizeInUseInBytes = func() float64 { return float64(b.SizeInUse()) } reportDbTotalSizeInUseInBytesMu.Unlock() + reportDbOpenReadTxNMu.Lock() + reportDbOpenReadTxN = func() float64 { return float64(b.OpenReadTxN()) } + reportDbOpenReadTxNMu.Unlock() min, max := newRevBytes(), newRevBytes() revToBytes(revision{main: 1}, min) diff --git a/mvcc/kvstore_test.go b/mvcc/kvstore_test.go index <HASH>..<HASH> 100644 --- a/mvcc/kvstore_test.go +++ b/mvcc/kvstore_test.go @@ -793,6 +793,7 @@ func (b *fakeBackend) ConcurrentReadTx() backend.ReadTx func (b *fakeBackend) Hash(ignores map[backend.IgnoreKey]struct{}) (uint32, error) { return 0, nil } func (b *fakeBackend) Size() int64 { return 0 } func (b *fakeBackend) SizeInUse() int64 { return 0 } +func (b *fakeBackend) OpenReadTxN() int64 { return 0 } func (b *fakeBackend) Snapshot() backend.Snapshot { return nil } func (b *fakeBackend) ForceCommit() {} func (b *fakeBackend) Defrag() error { return nil } diff --git a/mvcc/metrics.go b/mvcc/metrics.go index <HASH>..<HASH> 100644 --- a/mvcc/metrics.go +++ b/mvcc/metrics.go @@ -194,6 +194,23 @@ var ( reportDbTotalSizeInUseInBytesMu sync.RWMutex reportDbTotalSizeInUseInBytes = func() float64 { return 0 } + dbOpenReadTxN = prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + Namespace: "etcd", + Subsystem: "mvcc", + Name: "db_open_read_transactions", + Help: "The number of currently open read transactions", + }, + + func() float64 { + reportDbOpenReadTxNMu.RLock() + defer reportDbOpenReadTxNMu.RUnlock() + return reportDbOpenReadTxN() + }, + ) + // overridden by mvcc initialization + reportDbOpenReadTxNMu sync.RWMutex + reportDbOpenReadTxN = func() float64 { return 0 } + hashSec = prometheus.NewHistogram(prometheus.HistogramOpts{ Namespace: "etcd", Subsystem: "mvcc", @@ -237,6 +254,7 @@ func init() { prometheus.MustRegister(dbTotalSize) prometheus.MustRegister(dbTotalSizeDebugging) prometheus.MustRegister(dbTotalSizeInUse) + prometheus.MustRegister(dbOpenReadTxN) prometheus.MustRegister(hashSec) prometheus.MustRegister(hashRevSec) }
mvcc: add metrics dbOpenReadTxn Expose the number of currently open read transactions in backend to metrics endpoint.
etcd-io_etcd
train
1098a0698588b7c0d65ad5477779301fb8da3be3
diff --git a/src/engine/runtime.js b/src/engine/runtime.js index <HASH>..<HASH> 100644 --- a/src/engine/runtime.js +++ b/src/engine/runtime.js @@ -240,9 +240,8 @@ Runtime.prototype.toggleScript = function (topBlockId) { /** * Run a function `f` for all scripts in a workspace. * `f` will be called with two parameters: - * -the top block ID of each script - * -the opcode of that block, for convenience. - * -fields on that block, for convenience. + * - the top block ID of the script. + * - the target that owns the script. * @param {!Function} f Function to call for each script. * @param {Target=} opt_target Optionally, a target to restrict to. */ @@ -255,28 +254,31 @@ Runtime.prototype.allScriptsDo = function (f, opt_target) { var target = targets[t]; var scripts = target.blocks.getScripts(); for (var j = 0; j < scripts.length; j++) { - var topBlock = scripts[j]; - var topOpcode = target.blocks.getBlock(topBlock).opcode; - var topFields = target.blocks.getFields(topBlock); - f(topBlock, topOpcode, topFields); + var topBlockId = scripts[j]; + f(topBlockId, target); } } }; /** * Trigger all relevant hats. - * @param {!string} requestedHat Name of hat to trigger. + * @param {!string} requestedHatOpcode Opcode of hat to trigger. * @param {Object=} opt_matchFields Optionally, fields to match on the hat. * @param {Target=} opt_target Optionally, a target to restrict to. * @return {Array.<Thread>} List of threads started by this trigger. */ -Runtime.prototype.triggerHats = function (requestedHat, +Runtime.prototype.triggerHats = function (requestedHatOpcode, opt_matchFields, opt_target) { + if (!this._hats.hasOwnProperty(requestedHatOpcode)) { + // No known hat with this opcode. + return; + } var instance = this; var newThreads = []; - // Consider all scripts, looking for hats named `requestedHat`. - this.allScriptsDo(function(topBlockId, topOpcode, topFields) { - if (topOpcode !== requestedHat) { + // Consider all scripts, looking for hats with opcode `requestedHatOpcode`. + this.allScriptsDo(function(topBlockId, target) { + var potentialHatOpcode = target.blocks.getBlock(topBlockId).opcode; + if (potentialHatOpcode !== requestedHatOpcode) { // Not the right hat. return; } @@ -285,39 +287,38 @@ Runtime.prototype.triggerHats = function (requestedHat, // This needs to happen before the block is evaluated // (i.e., before the predicate can be run) because "broadcast and wait" // needs to have a precise collection of triggered threads. + var hatFields = target.blocks.getFields(topBlockId); if (opt_matchFields) { for (var matchField in opt_matchFields) { - if (topFields[matchField].value !== + if (hatFields[matchField].value !== opt_matchFields[matchField]) { // Field mismatch. return; } } } - if (instance._hats.hasOwnProperty(topOpcode)) { - // Look up metadata for the relevant hat. - var hatMeta = instance._hats[topOpcode]; - if (hatMeta.restartExistingThreads) { - // If `restartExistingThreads` is true, this trigger - // should stop any existing threads starting with the top block. - for (var i = 0; i < instance.threads.length; i++) { - if (instance.threads[i].topBlock === topBlockId) { - instance._removeThread(instance.threads[i]); - } + // Look up metadata for the relevant hat. + var hatMeta = instance._hats[requestedHatOpcode]; + if (hatMeta.restartExistingThreads) { + // If `restartExistingThreads` is true, this trigger + // should stop any existing threads starting with the top block. + for (var i = 0; i < instance.threads.length; i++) { + if (instance.threads[i].topBlock === topBlockId) { + instance._removeThread(instance.threads[i]); } - } else { - // If `restartExistingThreads` is false, this trigger - // should give up if any threads with the top block are running. - for (var j = 0; j < instance.threads.length; j++) { - if (instance.threads[j].topBlock === topBlockId) { - // Some thread is already running. - return; - } + } + } else { + // If `restartExistingThreads` is false, this trigger + // should give up if any threads with the top block are running. + for (var j = 0; j < instance.threads.length; j++) { + if (instance.threads[j].topBlock === topBlockId) { + // Some thread is already running. + return; } } - // Start the thread with this top block. - newThreads.push(instance._pushThread(topBlockId)); } + // Start the thread with this top block. + newThreads.push(instance._pushThread(topBlockId)); }, opt_target); return newThreads; };
Various renames for hat opcodes/top blocks, `allScriptsDo`
LLK_scratch-vm
train
01c730296ad930584990fd2c55c04bff3b0b7ea4
diff --git a/lib/consts/consts.go b/lib/consts/consts.go index <HASH>..<HASH> 100644 --- a/lib/consts/consts.go +++ b/lib/consts/consts.go @@ -51,11 +51,11 @@ func FullVersion() string { // Banner returns the ASCII-art banner with the k6 logo and stylized website URL func Banner() string { banner := strings.Join([]string{ - ` /\ |‾‾| /‾‾/ /‾/ `, - ` /\ / \ | |_/ / / / `, - ` / \/ \ | | / ‾‾\ `, - ` / \ | |‾\ \ | (_) | `, - ` / __________ \ |__| \__\ \___/ .io`, + ` /\ |‾‾| /‾‾/ /‾‾/ `, + ` /\ / \ | |/ / / / `, + ` / \/ \ | ( / ‾‾\ `, + ` / \ | |\ \ | (‾) | `, + ` / __________ \ |__| \__\ \_____/ .io`, }, "\n") return banner
Make the ASCII logo characters more proportional Credit goes to @rawtaz from #<I>
loadimpact_k6
train
92decd8724b3cd452fe0e73ee3d6df28f9d6d0f1
diff --git a/src/microcontroller/__init__.py b/src/microcontroller/__init__.py index <HASH>..<HASH> 100755 --- a/src/microcontroller/__init__.py +++ b/src/microcontroller/__init__.py @@ -31,6 +31,6 @@ elif platform == "linux": if board_id == "raspi_3" or board_id == "raspi_2": from adafruit_blinka.microcontroller.raspi_23 import * else: - raise NotImplementedError("Board not supported: ", board_id) + raise NotImplementedError("Board not supported:", board_id) else: - raise NotImplementedError("Microcontroller not supported: ", agnostic.microcontroller) + raise NotImplementedError("Platform not supported:", platform) diff --git a/src/microcontroller/pin.py b/src/microcontroller/pin.py index <HASH>..<HASH> 100755 --- a/src/microcontroller/pin.py +++ b/src/microcontroller/pin.py @@ -13,6 +13,6 @@ elif agnostic.platform == "linux": if agnostic.board_id == "raspi_3" or agnostic.board_id == "raspi_2": from adafruit_blinka.microcontroller.raspi_23.pin import * else: - raise NotImplementedError("Board not supported: ", agnostic.board) + raise NotImplementedError("Board not supported: ", agnostic.board_id) else: raise NotImplementedError("Microcontroller not supported")
Fix more agnostic uses.
adafruit_Adafruit_Blinka
train
99f22519ab4238092e57b72b610d69a6cf531d28
diff --git a/lib/fabrication/generator/base.rb b/lib/fabrication/generator/base.rb index <HASH>..<HASH> 100644 --- a/lib/fabrication/generator/base.rb +++ b/lib/fabrication/generator/base.rb @@ -23,6 +23,19 @@ class Fabrication::Generator::Base __instance end + def to_hash(attributes=[], callbacks=[]) + process_attributes(attributes) + (Fabrication::Config.active_support? ? HashWithIndifferentAccess.new : {}).tap do |hash| + __attributes.map do |name, value| + if value && value.respond_to?(:id) + hash["#{name}_id"] = value.id + else + hash[name] = value + end + end + end + end + def build_instance_with_init_callback(callback) self.__instance = __klass.new(*callback.call) __attributes.each do |k,v| diff --git a/lib/fabrication/schematic/definition.rb b/lib/fabrication/schematic/definition.rb index <HASH>..<HASH> 100644 --- a/lib/fabrication/schematic/definition.rb +++ b/lib/fabrication/schematic/definition.rb @@ -61,7 +61,7 @@ class Fabrication::Schematic::Definition def to_attributes(overrides={}, &block) merge(overrides, &block).instance_eval do - to_hash(generator.new(klass).build(attributes, callbacks)) + generator.new(klass).to_hash(attributes, callbacks) end end @@ -125,18 +125,4 @@ class Fabrication::Schematic::Definition params[:count] ||= 1 if !params[:count] && name != name.to_s Proc.new { Fabricate(params[:fabricator] || name.to_sym) } end - - def to_hash(object) - (Fabrication::Config.active_support? ? HashWithIndifferentAccess.new : {}).tap do |hash| - attributes.map do |attribute| - value = object.send(attribute.name) - if value && value.respond_to?(:id) - hash["#{attribute.name}_id"] = value.id - else - hash[attribute.name] = value - end - end - end - end - end
Build attributes hash in the base generator
paulelliott_fabrication
train
71d6ae569f483dd8b205b59f484b2c2f9d315f0f
diff --git a/src/Type/SelectType.php b/src/Type/SelectType.php index <HASH>..<HASH> 100644 --- a/src/Type/SelectType.php +++ b/src/Type/SelectType.php @@ -68,7 +68,6 @@ class SelectType extends DefaultType } } else { $field['options']['choices_flat'][$choiceId] = $choiceOrGroup; - break; } }
Don't break when flattening select field choices
andyvenus_form
train