hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
01165efcffd5eb08f03b0274fa690db7332ba313
diff --git a/lands/gui/view.py b/lands/gui/view.py index <HASH>..<HASH> 100644 --- a/lands/gui/view.py +++ b/lands/gui/view.py @@ -74,14 +74,29 @@ def draw_plates_on_screen(world, canvas): width = world.width height = world.height n_plates = world.n_plates() - print("N plates %i" % n_plates) for y in range(0, height): for x in range(0, width): h = world.plates[y][x]*(360/n_plates) s = 0.5 i = 64.0 r, g, b = hsi_to_rgb(h, s, i) - print("H % i S %i I %i" % (h, s, i)) - print("R % i G %i B %i" % (r, g, b)) col = QtGui.QColor(r, g, b) canvas.setPixel(x, y, col.rgb()) + + +def draw_plates_and_elevation_on_screen(world, canvas): + width = world.width + height = world.height + n_plates = world.n_plates() + max_el = world.max_elevation() + min_el = world.min_elevation() + delta_el = max_el - min_el + for y in range(0, height): + for x in range(0, width): + h = world.plates[y][x]*(360/n_plates) + el = world.elevation['data'][y][x] + s = 0.6 + i = 40.0 + 60.0 * ((el-min_el)/delta_el) + r, g, b = hsi_to_rgb(h, s, i) + col = QtGui.QColor(r, g, b) + canvas.setPixel(x, y, col.rgb()) \ No newline at end of file diff --git a/lands/guiqt.py b/lands/guiqt.py index <HASH>..<HASH> 100644 --- a/lands/guiqt.py +++ b/lands/guiqt.py @@ -214,6 +214,8 @@ class MapCanvas(QtGui.QImage): draw_bw_elevation_on_screen(world, self) elif view == 'plates': draw_plates_on_screen(world, self) + elif view == 'plates and elevation': + draw_plates_and_elevation_on_screen(world, self) else: raise Exception("Unknown view %s" % view) self._update() @@ -284,6 +286,7 @@ class LandsGui(QtGui.QMainWindow): plates_view = QtGui.QAction('Plates', self) plates_view.triggered.connect(self._on_plates_view) plates_bw_view = QtGui.QAction('Plates and elevation', self) + plates_bw_view.triggered.connect(self._on_plates_and_elevation_view) land_and_ocean_view = QtGui.QAction('Land and ocean', self) menubar = self.menuBar() @@ -308,6 +311,12 @@ class LandsGui(QtGui.QMainWindow): self.current_view = 'plates' self.canvas.draw_world(self.world, self.current_view) + + def _on_plates_and_elevation_view(self): + self.current_view = 'plates and elevation' + self.canvas.draw_world(self.world, self.current_view) + + def _on_generate(self): dialog = GenerateDialog(self) ok = dialog.exec_()
pyqt: plates and elevation view Former-commit-id: f<I>b<I>f<I>c4e<I>d<I>ea4a8c4
Mindwerks_worldengine
train
a33b695e98d1786595ed4fd575cb097f1f492d8c
diff --git a/lib/puppet/pops/issues.rb b/lib/puppet/pops/issues.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/pops/issues.rb +++ b/lib/puppet/pops/issues.rb @@ -491,7 +491,7 @@ module Puppet::Pops::Issues "This #{label.label(semantic)} is not productive. #{label.a_an_uc(container)} can not end with a non productive construct" end - RESERVED_WORD = hard_issue :RESERWED_WORD, :word do + RESERVED_WORD = hard_issue :RESERVED_WORD, :word do "Use of reserved word: #{word}, must be quoted if intended to be a String value" end
(maint) Fix a typo in reserved word symbol
puppetlabs_puppet
train
0072cefe81c0e39d5887943c20a1dc0f58a844b7
diff --git a/bin.js b/bin.js index <HASH>..<HASH> 100644 --- a/bin.js +++ b/bin.js @@ -18,8 +18,3 @@ var entries = cli.input if (!entries.length) throw new Error('entries are required') degree(entries, extend(cli.flags, {stream: process.stdout})) - .on('connect', function (server) { - var uri = server.uri - console.log('Server running at', uri) - open(uri) - })
Remove server log statement (handled by budo)
bendrucker_degree
train
c0c7058a4cec34165ef342b775f1e890c5b73fc3
diff --git a/broccoli/packages.js b/broccoli/packages.js index <HASH>..<HASH> 100644 --- a/broccoli/packages.js +++ b/broccoli/packages.js @@ -17,7 +17,6 @@ const { RELEASE, DEBUG, toConst } = require('./features'); const GlimmerTemplatePrecompiler = require('./glimmer-template-compiler'); const VERSION_PLACEHOLDER = /VERSION_STRING_PLACEHOLDER/g; const { stripIndent } = require('common-tags'); -const toES5 = require('./to-es5'); const debugTree = BroccoliDebug.buildDebugCallback('ember-source');
Fixup linting issues...
emberjs_ember.js
train
68808170da00145aabd196cca5b3358c20698ea0
diff --git a/lib/active_record/id_regions.rb b/lib/active_record/id_regions.rb index <HASH>..<HASH> 100644 --- a/lib/active_record/id_regions.rb +++ b/lib/active_record/id_regions.rb @@ -1,3 +1,5 @@ +require_relative './ar_virtual' + module ArRegion extend ActiveSupport::Concern
Load ar_virtual before ar_region The current half-each-way arrangement of ApplicationRecord extensions revealed this undeclared dependency. (transferred from ManageIQ/manageiq@<I>cef<I>e<I>fa<I>e6c2b<I>da<I>)
ManageIQ_activerecord-id_regions
train
753e3a716a6c12eb30f657ab7092c0e373c3b0e0
diff --git a/pyzyre/chat.py b/pyzyre/chat.py index <HASH>..<HASH> 100644 --- a/pyzyre/chat.py +++ b/pyzyre/chat.py @@ -116,7 +116,7 @@ def task(pipe, arg): n.whisper(address, m) else: msg = message.popstr().decode('utf-8') - n.shouts(group, msg.encode('utf-8')) + n.shouts(group[0], msg.encode('utf-8')) elif ss in items and items[ss] == zmq.POLLIN: e = ZyreEvent(n)
bugfix to shouts for default group
wesyoung_pyzyre
train
23300f4440ae35ba7604476496e7867f5eff9dab
diff --git a/activerecord/test/cases/relation/mutation_test.rb b/activerecord/test/cases/relation/mutation_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/relation/mutation_test.rb +++ b/activerecord/test/cases/relation/mutation_test.rb @@ -3,39 +3,6 @@ require "models/post" module ActiveRecord class RelationMutationTest < ActiveRecord::TestCase - FakeKlass = Struct.new(:table_name, :name) do - extend ActiveRecord::Delegation::DelegateCache - inherited self - - def connection - Post.connection - end - - def relation_delegate_class(klass) - self.class.relation_delegate_class(klass) - end - - def attribute_alias?(name) - false - end - - def sanitize_sql(sql) - sql - end - - def sanitize_sql_for_order(sql) - sql - end - - def arel_attribute(name, table) - table[name] - end - end - - def relation - @relation ||= Relation.new FakeKlass.new("posts"), Post.arel_table, Post.predicate_builder - end - (Relation::MULTI_VALUE_METHODS - [:references, :extending, :order, :unscope, :select]).each do |method| test "##{method}!" do assert relation.public_send("#{method}!", :foo).equal?(relation) @@ -167,5 +134,10 @@ module ActiveRecord relation.skip_query_cache! assert relation.skip_query_cache_value end + + private + def relation + @relation ||= Relation.new(FakeKlass, Post.arel_table, Post.predicate_builder) + end end end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -8,24 +8,6 @@ module ActiveRecord class RelationTest < ActiveRecord::TestCase fixtures :posts, :comments, :authors, :author_addresses, :ratings - FakeKlass = Struct.new(:table_name, :name) do - extend ActiveRecord::Delegation::DelegateCache - - inherited self - - def self.connection - Post.connection - end - - def self.table_name - "fake_table" - end - - def self.sanitize_sql_for_order(sql) - sql - end - end - def test_construction relation = Relation.new(FakeKlass, :b, nil) assert_equal FakeKlass, relation.klass @@ -90,7 +72,7 @@ module ActiveRecord end def test_table_name_delegates_to_klass - relation = Relation.new(FakeKlass.new("posts"), :b, Post.predicate_builder) + relation = Relation.new(FakeKlass, :b, Post.predicate_builder) assert_equal "posts", relation.table_name end diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -276,3 +276,35 @@ end class SubConditionalStiPost < ConditionalStiPost end + +class FakeKlass + extend ActiveRecord::Delegation::DelegateCache + + inherited self + + class << self + def connection + Post.connection + end + + def table_name + "posts" + end + + def attribute_alias?(name) + false + end + + def sanitize_sql(sql) + sql + end + + def sanitize_sql_for_order(sql) + sql + end + + def arel_attribute(name, table) + table[name] + end + end +end
Extract `FakeKlass` in `relation_test.rb` and `relation/mutation_test.rb` `FakeKlass` in `relation_test.rb` and `relation/mutation_test.rb` are almost the same.
rails_rails
train
5790dba6a303e3ea9e4f17b578be9f4927bd60a6
diff --git a/src/draw/handler/Draw.Rectangle.js b/src/draw/handler/Draw.Rectangle.js index <HASH>..<HASH> 100644 --- a/src/draw/handler/Draw.Rectangle.js +++ b/src/draw/handler/Draw.Rectangle.js @@ -13,7 +13,8 @@ L.Draw.Rectangle = L.Draw.SimpleShape.extend({ fillColor: null, //same as color by default fillOpacity: 0.2, clickable: true - } + }, + metric: true // Whether to use the metric meaurement system or imperial }, initialize: function (map, options) { @@ -37,5 +38,22 @@ L.Draw.Rectangle = L.Draw.SimpleShape.extend({ _fireCreatedEvent: function () { var rectangle = new L.Rectangle(this._shape.getBounds(), this.options.shapeOptions); L.Draw.SimpleShape.prototype._fireCreatedEvent.call(this, rectangle); + }, + + _getTooltipText: function () { + var tooltipText = L.Draw.SimpleShape.prototype._getTooltipText.call(this), + shape = this._shape, + latLngs, area, subtext; + + if (shape) { + latLngs = this._shape.getLatLngs(); + area = L.GeometryUtil.geodesicArea(latLngs); + subtext = L.GeometryUtil.readableArea(area, this.options.metric); + } + + return { + text: tooltipText.text, + subtext: subtext + }; } }); diff --git a/src/draw/handler/Draw.SimpleShape.js b/src/draw/handler/Draw.SimpleShape.js index <HASH>..<HASH> 100644 --- a/src/draw/handler/Draw.SimpleShape.js +++ b/src/draw/handler/Draw.SimpleShape.js @@ -56,6 +56,12 @@ L.Draw.SimpleShape = L.Draw.Feature.extend({ this._isDrawing = false; }, + _getTooltipText: function () { + return { + text: this._endLabelText + }; + }, + _onMouseDown: function (e) { this._isDrawing = true; this._startLatLng = e.latlng; @@ -70,7 +76,7 @@ L.Draw.SimpleShape = L.Draw.Feature.extend({ this._tooltip.updatePosition(latlng); if (this._isDrawing) { - this._tooltip.updateContent({ text: this._endLabelText }); + this._tooltip.updateContent(this._getTooltipText()); this._drawShape(latlng); } },
Add support for viewing area when drawing a rectangle. fixes #<I>
Leaflet_Leaflet.draw
train
e23b223a86cbec7372017877ce2b3b397c47c086
diff --git a/wptools/page.py b/wptools/page.py index <HASH>..<HASH> 100644 --- a/wptools/page.py +++ b/wptools/page.py @@ -123,6 +123,16 @@ class WPToolsPage(WPToolsRESTBase, self.__insert_image_info(title, _from, info) + def _extend_data(self, datapoint, new_data): + """ + assigns or extends datapoint with new data + """ + if new_data: + try: + self.data[datapoint].extend(new_data) + except KeyError: + self.data[datapoint] = new_data + def _missing_imageinfo(self): """ returns list of image filenames that are missing info @@ -290,12 +300,7 @@ class WPToolsPage(WPToolsRESTBase, if action == 'query': self.data['random'] = data['query']['random'][0]["title"] - backlinks = data['query'].get('backlinks') - if backlinks: - if 'backlinks' in self.data: - self.data['backlinks'].extend(backlinks) - else: - self.data['backlinks'] = backlinks + self._extend_data('backlinks', data['query'].get('backlinks')) self.data['redirected'] = data['query'].get('redirects') @@ -329,7 +334,7 @@ class WPToolsPage(WPToolsRESTBase, if length: self.data['length'] = length - self.data['links'] = utils.get_links(page.get('links')) + self._extend_data('links', utils.get_links(page.get('links'))) modified = page.get('touched') if modified:
Added page.extend_data for continuations #<I>
siznax_wptools
train
dafcb754f064c9ff879c9cdff83355072aa4b335
diff --git a/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/DefaultVelocityConfiguration.java b/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/DefaultVelocityConfiguration.java index <HASH>..<HASH> 100644 --- a/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/DefaultVelocityConfiguration.java +++ b/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/DefaultVelocityConfiguration.java @@ -129,6 +129,10 @@ public class DefaultVelocityConfiguration implements Initializable, VelocityConf this.defaultProperties.setProperty(RuntimeConstants.EVENTHANDLER_INCLUDE, RestrictParseLocationEventHandler.class.getName()); + // Allow to override global macros and to use properly skin macros. + this.defaultProperties.setProperty(RuntimeConstants.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, + Boolean.TRUE.toString()); + // The uberspectors enabled by default initializeDefaultUberspectors(); }
XCOMMONS-<I>: Upgrade to Velocity <I> * Fix issue with skin macros.
xwiki_xwiki-commons
train
261cbf94e8f54e1664f6a2717e44fa9189bc5dcb
diff --git a/src/org/parosproxy/paros/network/HttpRequestHeader.java b/src/org/parosproxy/paros/network/HttpRequestHeader.java index <HASH>..<HASH> 100644 --- a/src/org/parosproxy/paros/network/HttpRequestHeader.java +++ b/src/org/parosproxy/paros/network/HttpRequestHeader.java @@ -35,6 +35,7 @@ // requests returns the wrong port // ZAP: 2013/01/23 Clean up of exception handling/logging. // ZAP: 2013/03/08 Improved parse error reporting +// ZAP: 2013/04/14 Issue 596: Rename the method HttpRequestHeader.getSecure to isSecure package org.parosproxy.paros.network; @@ -254,12 +255,23 @@ public class HttpRequestHeader extends HttpHeader { * Get if this request header is under secure connection. * * @return + * @deprecated Replaced by {@link #isSecure()}. It will be removed in a future release. */ + @Deprecated public boolean getSecure() { return mIsSecure; } /** + * Tells whether the request is secure, or not. A request is considered secure if it's using the HTTPS protocol. + * + * @return {@code true} if the request is secure, {@code false} otherwise. + */ + public boolean isSecure() { + return mIsSecure; + } + + /** * Set if this request header is under secure connection. * * @param isSecure @@ -276,9 +288,9 @@ public class HttpRequestHeader extends HttpHeader { URI newUri = mUri; // check if URI consistent - if (getSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) { + if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) { newUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true); - } else if (!getSecure() && mUri.getScheme().equalsIgnoreCase(HTTPS)) { + } else if (!isSecure() && mUri.getScheme().equalsIgnoreCase(HTTPS)) { newUri = new URI(mUri.toString().replaceFirst(HTTPS, HTTP), true); } @@ -341,7 +353,7 @@ public class HttpRequestHeader extends HttpHeader { mUri = new URI(HTTP + "://" + getHeader(HOST) + mUri.toString(), true); } - if (getSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) { + if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) { mUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true); } @@ -417,19 +429,19 @@ public class HttpRequestHeader extends HttpHeader { * If the given {@code port} number is negative (usually -1 to represent * that no port number is defined), the port number set will be the default * port number for the used scheme known using the method - * {@code getSecure()}, either 80 for HTTP or 443 for HTTPS. + * {@code isSecure()}, either 80 for HTTP or 443 for HTTPS. * </p> * * @param port * the new port number * @see #mHostPort - * @see #getSecure() + * @see #isSecure() * @see URI#getPort() */ private void setHostPort(int port) { if (port > -1) { mHostPort = port; - } else if (this.getSecure()) { + } else if (this.isSecure()) { mHostPort = 443; } else { mHostPort = 80;
Issue <I> - Rename the method HttpRequestHeader.getSecure to isSecure - Added a new method HttpRequestHeader.isSecure; - Deprecated the old method (HttpRequestHeader.getSecure); - Replaced all calls to the old method with the new method.
zaproxy_zaproxy
train
64284838921d0478c714695f3b248cecbe87b76e
diff --git a/lib/lovely_rufus/hangout_wrapper.rb b/lib/lovely_rufus/hangout_wrapper.rb index <HASH>..<HASH> 100644 --- a/lib/lovely_rufus/hangout_wrapper.rb +++ b/lib/lovely_rufus/hangout_wrapper.rb @@ -19,8 +19,8 @@ module LovelyRufus class HangoutWrapper < Layer def hangout_line lines.each_cons 2 do |a, b| - return a if a[/\p{Space}/] and a.rindex(/\p{Space}/) >= b.size - return b if b[/\p{Space}/] and b.rindex(/\p{Space}/) >= a.size + return a if a[' '] and a.rindex(' ') >= b.size + return b if b[' '] and b.rindex(' ') >= a.size end end end end
HangoutWrapper: consider only plain spaces for now
chastell_lovely_rufus
train
da007a0455809737dbeca5af412386d9feb8ac4d
diff --git a/test/tests.js b/test/tests.js index <HASH>..<HASH> 100644 --- a/test/tests.js +++ b/test/tests.js @@ -40,11 +40,11 @@ const testEq = (expr, expect) => it(`${expr} => ${show(expect)}`, done => { describe("storage", () => { localStorage.clear() - testEq('{var x1 = Stored({key: "test:x", value: 10});' + - ' x1.set(101);' + - ' var x2 = Stored({key: "test:x", value: 10});' + + testEq('{var x1 = Stored({key: "test:x", value: [10]});' + + ' x1.set([101]);' + + ' var x2 = Stored({key: "test:x", value: [10]});' + ' return Kefir.combine([x1, Kefir.constant(x1 === x2), x2]);}', - [101, true, 101]) + [[101], true, [101]]) testEq('{var y = Stored({key: "test:y", value: "a", time: 10});' + ' y.set("b");' +
Stronger test (requires equals)
calmm-js_atom.storage
train
5b800e49adb724b3561478c25b5268bff8878404
diff --git a/src/frontend/org/voltdb/ExecutionSite.java b/src/frontend/org/voltdb/ExecutionSite.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/ExecutionSite.java +++ b/src/frontend/org/voltdb/ExecutionSite.java @@ -1463,6 +1463,12 @@ implements Runnable, SiteProcedureConnection, SiteSnapshotConnection return null; } + @Override + public void setLastCommittedTxn(long txnId, long spHandle) + { + + } + public SiteTracker getSiteTracker() { return m_tracker; } diff --git a/src/frontend/org/voltdb/SiteProcedureConnection.java b/src/frontend/org/voltdb/SiteProcedureConnection.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/SiteProcedureConnection.java +++ b/src/frontend/org/voltdb/SiteProcedureConnection.java @@ -105,6 +105,11 @@ public interface SiteProcedureConnection { public Map<Integer, List<VoltTable>> recursableRun(TransactionState currentTxnState); /** + * Set the last committed txnId and spHandle + */ + public void setLastCommittedTxn(long txnId, long spHandle); + + /** * IV2 commit / rollback interface to the EE */ public void truncateUndoLog(boolean rollback, long token, long txnId, long spHandle, List<UndoAction> undoActions); diff --git a/src/frontend/org/voltdb/iv2/MpRoSite.java b/src/frontend/org/voltdb/iv2/MpRoSite.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/iv2/MpRoSite.java +++ b/src/frontend/org/voltdb/iv2/MpRoSite.java @@ -354,6 +354,12 @@ public class MpRoSite implements Runnable, SiteProcedureConnection } @Override + public void setLastCommittedTxn(long txnId, long spHandle) + { + throw new RuntimeException("RO MP Site doesn't do this, shouldn't be here."); + } + + @Override public void truncateUndoLog(boolean rollback, long beginUndoToken, long txnId, long spHandle, List<UndoAction> undoActions) { diff --git a/src/frontend/org/voltdb/iv2/Site.java b/src/frontend/org/voltdb/iv2/Site.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/iv2/Site.java +++ b/src/frontend/org/voltdb/iv2/Site.java @@ -735,6 +735,18 @@ public class Site implements Runnable, SiteProcedureConnection, SiteSnapshotConn return currentTxnState.recursableRun(this); } + @Override + public void setLastCommittedTxn(long txnId, long spHandle) + { + m_lastCommittedTxnId = txnId; + if (TxnEgo.getPartitionId(m_lastCommittedSpHandle) != TxnEgo.getPartitionId(spHandle)) { + VoltDB.crashLocalVoltDB("Mismatch SpHandle partitiond id " + + TxnEgo.getPartitionId(m_lastCommittedSpHandle) + ", " + + TxnEgo.getPartitionId(spHandle), true, null); + } + m_lastCommittedSpHandle = spHandle; + } + private static void handleUndoLog(List<UndoAction> undoLog, boolean undo) { if (undoLog == null) return;
ENG-<I>: Add an site API for procedure site tasks to set the last committed txnId and spHandle.
VoltDB_voltdb
train
6dc1526ce6a0b0132b5a8cb7e023f9c4b1ce1e7e
diff --git a/lib/installer.js b/lib/installer.js index <HASH>..<HASH> 100644 --- a/lib/installer.js +++ b/lib/installer.js @@ -6,7 +6,7 @@ var request = require('request'); var path = require('path'); var crypto = require('crypto'); var async = require('async'); - +var prmpt = require('prmpt'); var config = require('./config'); /** @@ -210,7 +210,7 @@ exports.createAppConfig = function (cfg, username, password, callback) { * Prompts the user to create a Hoodie admin account */ -exports.promptAdminUser = function (callback) { +exports.prmptAdminUser = function (callback) { if (process.env.CI) { // hardcode username as admin for now var result = {}; @@ -218,7 +218,7 @@ exports.promptAdminUser = function (callback) { result.password = 'travis-ci'; return callback(null, result); } else { - prompt.get({ + prmpt.get({ properties: { password: { description: 'Please set an admin password: ', @@ -261,7 +261,7 @@ exports.createAdminUser = function (cfg, callback) { if (err) { return callback(err); } - exports.promptAdminUser(function (err, name) { + exports.prmptAdminUser(function (err, name) { if (err) { return callback(err); } @@ -274,9 +274,9 @@ exports.createAdminUser = function (cfg, callback) { * Ask the user for the CouchDB admin credentials */ -exports.promptCouchCredentials = function (callback) { +exports.prmptCouchCredentials = function (callback) { console.log('Please enter your CouchDB _admin credentials:'); - prompt.get({ + prmpt.get({ properties: { name: { description: 'Username: ', @@ -298,7 +298,7 @@ exports.promptCouchCredentials = function (callback) { }; /** - * Check that the stored couchdb credentials still work, prompt the user + * Check that the stored couchdb credentials still work, prmpt the user * to update them if not. */ @@ -314,7 +314,7 @@ exports.updateCouchCredentials = function (cfg, callback) { } // stored admin credentials out of date - exports.promptCouchCredentials(function (err, user, pass) { + exports.prmptCouchCredentials(function (err, user, pass) { if (err) { return callback(err); } @@ -333,7 +333,7 @@ exports.updateCouchCredentials = function (cfg, callback) { /** - * Creates internal admin user and prompts for Hoodie admin + * Creates internal admin user and prmpts for Hoodie admin */ exports.setupUsers = function (cfg, callback) { @@ -355,7 +355,7 @@ exports.setupUsers = function (cfg, callback) { }; /** - * Checks CouchDB for required users/dbs, prompts user for info + * Checks CouchDB for required users/dbs, prmpts user for info * where appropriate */
import `prompt` * * * This week of work on @hoodiehq is sponsored by Cargo Media. Their slogan is “Small Team, Big Impact” and they are hiring a Frontend and Backend Dev: <URL>
hoodiehq_hoodie
train
49b27956feefc12c56d9a57ba04b99b8fe1d2317
diff --git a/lib/USKeyboardLayout.js b/lib/USKeyboardLayout.js index <HASH>..<HASH> 100644 --- a/lib/USKeyboardLayout.js +++ b/lib/USKeyboardLayout.js @@ -277,5 +277,12 @@ module.exports = { '{': {'keyCode': 219, 'key': '{', 'code': 'BracketLeft'}, '|': {'keyCode': 220, 'key': '|', 'code': 'Backslash'}, '}': {'keyCode': 221, 'key': '}', 'code': 'BracketRight'}, - '"': {'keyCode': 222, 'key': '"', 'code': 'Quote'} + '"': {'keyCode': 222, 'key': '"', 'code': 'Quote'}, + 'SoftLeft': {'key': 'SoftLeft', 'code': 'SoftLeft', 'location': 4}, + 'SoftRight': {'key': 'SoftRight', 'code': 'SoftRight', 'location': 4}, + 'Camera': {'keyCode': 44, 'key': 'Camera', 'code': 'Camera', 'location': 4}, + 'Call': {'key': 'Call', 'code': 'Call', 'location': 4}, + 'EndCall': {'keyCode': 95, 'key': 'EndCall', 'code': 'EndCall', 'location': 4}, + 'VolumeDown': {'keyCode': 182, 'key': 'VolumeDown', 'code': 'VolumeDown', 'location': 4}, + 'VolumeUp': {'keyCode': 183, 'key': 'VolumeUp', 'code': 'VolumeUp', 'location': 4}, }; \ No newline at end of file
feat(keyboard): feature phone buttons (#<I>) I got a KaiOS phone with some awesome buttons on it I hadn't seen before on the web. This adds the following buttons to our default keyboard layout: `SoftLeft` `SoftRight` `Camera` `Call` `EndCall` `VolumeUp` `VolumeDown`
GoogleChrome_puppeteer
train
63c2558678dfec5d53d6b55b87b0fae66d32defa
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -1378,6 +1378,21 @@ core-js(-pure)/fn/symbol/async-iterator ```js core-js(-pure)/stage/2 ``` +* `Symbol#description` [proposal](https://tc39.github.io/proposal-Symbol-description/) - module [`esnext.symbol.description`](https://github.com/zloirock/core-js/blob/v3/packages/core-js/modules/esnext.symbol.description.js) +```js +class Symbol { + get description: string | void; +} +``` +[*CommonJS entry points:*](#commonjs) +```js +core-js/fn/symbol/description +``` +[*Examples*](https://goo.gl/MWizfc): +```js +Symbol('foo').description; // => 'foo' +Symbol().description; // => undefined +``` * `String#trimLeft`, `String#trimRight` / `String#trimStart`, `String#trimEnd` [proposal](https://github.com/tc39/ecmascript-string-left-right-trim) - modules [`esnext.string.trim-left`](https://github.com/zloirock/core-js/blob/v3/packages/core-js/modules/esnext.string.trim-right.js), [`esnext.string.trim-right`](https://github.com/zloirock/core-js/blob/v3/packages/core-js/modules/esnext.string.trim-right.js) ```js class String { @@ -1409,21 +1424,6 @@ core-js(-pure)/fn/string/virtual/trim-right ```js core-js(-pure)/stage/1 ``` -* `Symbol#description` [proposal](https://tc39.github.io/proposal-Symbol-description/) - module [`esnext.symbol.description`](https://github.com/zloirock/core-js/blob/v3/packages/core-js/modules/esnext.symbol.description.js) -```js -class Symbol { - get description: string | void; -} -``` -[*CommonJS entry points:*](#commonjs) -```js -core-js/fn/symbol/description -``` -[*Examples*](https://goo.gl/MWizfc): -```js -Symbol('foo').description; // => 'foo' -Symbol().description; // => undefined -``` * `String#replaceAll` [proposal](https://github.com/psmarshall/string-replace-all-proposal) - module [`esnext.string.replace-all`](https://github.com/zloirock/core-js/blob/v3/packages/core-js/modules/esnext.string.replace-all.js) ```js class String { diff --git a/packages/core-js/stage/1.js b/packages/core-js/stage/1.js index <HASH>..<HASH> 100644 --- a/packages/core-js/stage/1.js +++ b/packages/core-js/stage/1.js @@ -17,7 +17,6 @@ require('../modules/esnext.math.signbit'); require('../modules/esnext.promise.try'); require('../modules/esnext.string.replace-all'); require('../modules/esnext.string.match-all'); -require('../modules/esnext.symbol.description'); require('../modules/esnext.symbol.observable'); require('../modules/esnext.observable'); diff --git a/packages/core-js/stage/2.js b/packages/core-js/stage/2.js index <HASH>..<HASH> 100644 --- a/packages/core-js/stage/2.js +++ b/packages/core-js/stage/2.js @@ -1,3 +1,4 @@ +require('../modules/esnext.symbol.description'); require('../modules/esnext.string.trim-left'); require('../modules/esnext.string.trim-right');
move `Symbol#description` to stage 2
zloirock_core-js
train
0dd642c6ec32b3c7b2f1b3b5d229454184ab5ae4
diff --git a/pylint_django/augmentations/__init__.py b/pylint_django/augmentations/__init__.py index <HASH>..<HASH> 100644 --- a/pylint_django/augmentations/__init__.py +++ b/pylint_django/augmentations/__init__.py @@ -216,9 +216,12 @@ def is_model_field_display_method(node): if node.last_child(): # TODO: could validate the names of the fields on the model rather than # blindly accepting get_*_display - for cls in node.last_child().infered(): - if node_is_subclass(cls, 'django.db.models.base.Model'): - return True + try: + for cls in node.last_child().infered(): + if node_is_subclass(cls, 'django.db.models.base.Model'): + return True + except InferenceError: + return False return False diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from setuptools import find_packages import os -_version = '0.5.3' +_version = '0.5.4' _packages = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) _short_description = "pylint-django is a Pylint plugin to aid Pylint in recognising and understanding" \
pylint-django could fail if a type could not be inferred during one of the checks; instead, the exception is caught and ignored
PyCQA_pylint-django
train
1aeb4446cc0a13fb890ea55bb895b983af8b1c35
diff --git a/src/main/java/com/extjs/selenium/tree/TreePanel.java b/src/main/java/com/extjs/selenium/tree/TreePanel.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/extjs/selenium/tree/TreePanel.java +++ b/src/main/java/com/extjs/selenium/tree/TreePanel.java @@ -1,19 +1,16 @@ package com.extjs.selenium.tree; import com.extjs.selenium.ExtJsComponent; -import com.sdl.selenium.web.WebDriverConfig; +import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.interactions.Actions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TreePanel extends ExtJsComponent { - private static final Logger logger = LoggerFactory.getLogger(TreePanel.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TreePanel.class); public TreePanel() { - logger.warn("TreePanel is not implemented 100%"); + LOGGER.warn("TreePanel is not implemented 100%"); setClassName("TreePanel"); } @@ -28,15 +25,9 @@ public class TreePanel extends ExtJsComponent { } public boolean expand(String searchElement) { - String path = "//*[contains(@class,'x-tree-node-el')]//*[starts-with(text(),'" + searchElement + "')]"; - if (new WebLocator(null, path).exists()) { - logger.debug("Expanding the tree"); - WebDriver driver = WebDriverConfig.getDriver(); - Actions builder = new Actions(driver); - builder.doubleClick(driver.findElement(By.xpath(path))).build().perform(); - return true; - } - return false; + WebLocator node = new WebLocator(getParentNode()).setText(searchElement, SearchType.STARTS_WITH); + LOGGER.info("Expanding the tree"); + return node.doubleClickAt(); } public boolean select(String searchElement) { @@ -44,22 +35,22 @@ public class TreePanel extends ExtJsComponent { } public boolean select(String searchElement, Boolean startWith) { - String path = "//*[contains(@class,'x-tree-node-el')]//*" + - (startWith ? "[starts-with(text(),'" + searchElement + "')]" : "[text()='" + searchElement + "']"); - WebLocator currentElement = new WebLocator(getContainer(), path); - if (currentElement.isElementPresent()) { - logger.debug("Selecting the tree node"); - return currentElement.click(); - } - return false; + WebLocator node = new WebLocator(getParentNode()).setText(searchElement, startWith ? SearchType.STARTS_WITH : SearchType.EQUALS); + LOGGER.info("Selecting the tree node"); + return node.click(); } public String getStatus(String searchElement) { - String path = "//*[contains(@class,'x-tree-node-el')]//*[contains(text(),'" + searchElement + "')]/following::*"; + WebLocator node = new WebLocator(getParentNode()).setText(searchElement, SearchType.CONTAINS); + String path = node.getPath() + "/following::*"; WebLocator currentElement = new WebLocator(getContainer(), path); if (currentElement.isElementPresent()) { return currentElement.getText(); } return "INVALID"; } + + public WebLocator getParentNode() { + return new WebLocator(getContainer()).setClasses("x-tree-node-el"); + } }
TreePanel improve to not use xpath
sdl_Testy
train
4d66304ff1e46f119da6109c4069e1ad462e8318
diff --git a/pyxmpp2/ext/version.py b/pyxmpp2/ext/version.py index <HASH>..<HASH> 100644 --- a/pyxmpp2/ext/version.py +++ b/pyxmpp2/ext/version.py @@ -40,7 +40,7 @@ from ..etree import ElementTree from ..version import version as pyxmpp2_version # pylint: disable=E0611 from ..settings import XMPPSettings from ..iq import Iq -from ..interfaces import XMPPFeatureHandler +from ..interfaces import XMPPFeatureHandler, feature_uri from ..interfaces import iq_get_stanza_handler from ..interfaces import StanzaPayload, payload_element_name @@ -98,6 +98,7 @@ class VersionPayload(StanzaPayload): sub.text = self.os_name return element +@feature_uri("jabber:iq:version") class VersionProvider(XMPPFeatureHandler): """Provides the Software version (XEP-0092) service. diff --git a/pyxmpp2/interfaces.py b/pyxmpp2/interfaces.py index <HASH>..<HASH> 100644 --- a/pyxmpp2/interfaces.py +++ b/pyxmpp2/interfaces.py @@ -213,6 +213,17 @@ class XMPPFeatureHandler: __metaclass__ = ABCMeta stanza_processor = None +def feature_uri(uri): + """Decorating attaching a feature URI (for Service Discovery or Capability + to a XMPPFeatureHandler class.""" + def decorator(class_): + """Returns a decorated class""" + if "_pyxmpp_feature_uris" not in class_.__dict__: + class_._pyxmpp_feature_uris = set() + class_._pyxmpp_feature_uris.add(uri) + return class_ + return decorator + def _iq_handler(iq_type, payload_class, payload_key, usage_restriction): """Method decorator generator for decorating <iq type='get'/> stanza handler methods in `XMPPFeatureHandler` subclasses.
@feature_uri() decoreator added This decorator will provide feature information for Service Discovery (XEP-<I>) and entity capabilities (XEP-<I>)
Jajcus_pyxmpp2
train
8e16152a796e2af22944895d80aaaacecaf1b36b
diff --git a/src/system/modules/metamodelsattribute_translatedalias/MetaModelAttributeTranslatedAlias.php b/src/system/modules/metamodelsattribute_translatedalias/MetaModelAttributeTranslatedAlias.php index <HASH>..<HASH> 100644 --- a/src/system/modules/metamodelsattribute_translatedalias/MetaModelAttributeTranslatedAlias.php +++ b/src/system/modules/metamodelsattribute_translatedalias/MetaModelAttributeTranslatedAlias.php @@ -36,7 +36,7 @@ class MetaModelAttributeTranslatedAlias extends MetaModelAttributeTranslatedRefe public function getFieldDefinition($arrOverrides = array()) { - $arrFieldDef = parent::getFieldDefinition(); + $arrFieldDef = parent::getFieldDefinition($arrOverrides); $arrFieldDef['inputType'] = 'text';
Bugfix: getFieldDefinition now passes the overrides to the parent.
MetaModels_attribute_translatedalias
train
fe6ae2065277035ec6685a89bb807eaa377858f9
diff --git a/cpu/facts/facts.go b/cpu/facts/facts.go index <HASH>..<HASH> 100644 --- a/cpu/facts/facts.go +++ b/cpu/facts/facts.go @@ -257,7 +257,8 @@ func (prof *Profiler) Get() (facts *Facts, err error) { } continue } - if v == 'b' { // bogomips + // also check 2nd name pos for o as some output also have a bugs line. + if v == 'b' && prof.Val[1] == 'o' { // bogomips f, err := strconv.ParseFloat(string(prof.Val[nameLen:]), 32) if err != nil { return nil, &joe.ParseError{Info: string(prof.Val[:nameLen]), Err: err}
add check of 2nd char in name for bogomips as some systems also have a "bugs" line
mohae_joefriday
train
3f3ce11984404862c30eb35add1ccd8fc73a7999
diff --git a/jottabox/jottacloud.py b/jottabox/jottacloud.py index <HASH>..<HASH> 100644 --- a/jottabox/jottacloud.py +++ b/jottabox/jottacloud.py @@ -50,7 +50,7 @@ def filelist(jottapath, JFS): return set() # folder does not exist, so pretend it is an empty folder if not isinstance(jf, JFSFolder): return False - return set([f.name for f in jf.files()]) + return set([f.name for f in jf.files() if not f.is_deleted()]) # Only return files that aren't deleted def compare(localtopdir, jottamountpoint, JFS, followlinks=False): """Make a tree of local files and folders and compare it with what's currently on JottaCloud. @@ -79,7 +79,9 @@ def new(localfile, jottapath, JFS): """Upload a new file from local disk (doesn't exist on JottaCloud). Returns JottaFile object""" - return JFS.up(jottapath, localfile) + with open(localfile) as lf: + _new = JFS.up(jottapath, lf) + return _new def replace_if_changed(localfile, jottapath, JFS): @@ -91,7 +93,8 @@ def replace_if_changed(localfile, jottapath, JFS): with open(localfile) as lf: lf_hash = hashlib.md5(lf.read()).hexdigest() if jf.md5 == lf_hash: # hashes are the same - return jf # return the version from jottacloud + logging.debug("hash match (%s), file contents haven't changed", lf_hash) + return jf # return the version from jottaclouds else: return new(localfile, jottapath, JFS)
only return look at files that aren't deleted from the cloud
havardgulldahl_jottalib
train
5ae3e0e80c66e2538f622de9c0feffcff56dadaa
diff --git a/lib/vagrant/machine.rb b/lib/vagrant/machine.rb index <HASH>..<HASH> 100644 --- a/lib/vagrant/machine.rb +++ b/lib/vagrant/machine.rb @@ -109,6 +109,7 @@ module Vagrant def communicate # For now, we always return SSH. In the future, we'll abstract # this and allow plugins to define new methods of communication. + end # This sets the unique ID associated with this machine. This will diff --git a/lib/vagrant/plugin/v1/plugin.rb b/lib/vagrant/plugin/v1/plugin.rb index <HASH>..<HASH> 100644 --- a/lib/vagrant/plugin/v1/plugin.rb +++ b/lib/vagrant/plugin/v1/plugin.rb @@ -103,6 +103,24 @@ module Vagrant data[:command] end + # Defines additional communicators to be available. Communicators + # should be returned by a block passed to this method. This is done + # to ensure that the class is lazy loaded, so if your class inherits + # from or uses any Vagrant internals specific to Vagrant 1.0, then + # the plugin can still be defined without breaking anything in future + # versions of Vagrant. + # + # @param [String] name Communicator name. + def self.communicator(name=UNSET_VALUE, &block) + data[:communicator] ||= Registry.new + + # Register a new communicator class only if a name was given. + data[:communicator].register(name.to_sym, &block) if name != UNSET_VALUE + + # Return the registry + data[:communicator] + end + # Defines additional configuration keys to be available in the # Vagrantfile. The configuration class should be returned by a # block passed to this method. This is done to ensure that the class diff --git a/test/unit/vagrant/plugin/v1/plugin_test.rb b/test/unit/vagrant/plugin/v1/plugin_test.rb index <HASH>..<HASH> 100644 --- a/test/unit/vagrant/plugin/v1/plugin_test.rb +++ b/test/unit/vagrant/plugin/v1/plugin_test.rb @@ -100,6 +100,34 @@ describe Vagrant::Plugin::V1::Plugin do end end + describe "communicators" do + it "should register communicator classes" do + plugin = Class.new(described_class) do + communicator("foo") { "bar" } + end + + plugin.communicator[:foo].should == "bar" + end + + it "should lazily register communicator classes" do + # Below would raise an error if the value of the class was + # evaluated immediately. By asserting that this does not raise an + # error, we verify that the value is actually lazily loaded + plugin = nil + expect { + plugin = Class.new(described_class) do + communicator("foo") { raise StandardError, "FAIL!" } + end + }.to_not raise_error + + # Now verify when we actually get the configuration key that + # a proper error is raised. + expect { + plugin.communicator[:foo] + }.to raise_error(StandardError) + end + end + describe "configuration" do it "should register configuration classes" do plugin = Class.new(described_class) do
Allow the definition of communicators in plugins
hashicorp_vagrant
train
e2396706ee14b3e48bba7015437817b33352623c
diff --git a/src/Purl/Url.php b/src/Purl/Url.php index <HASH>..<HASH> 100644 --- a/src/Purl/Url.php +++ b/src/Purl/Url.php @@ -310,9 +310,7 @@ class Url extends AbstractPart { $this->initialize(); - $parts = array_map(function($value) { - return (string) $value; - }, $this->data); + $parts = array_map('strval', $this->data); if(!$this->isAbsolute()) { return self::httpBuildRelativeUrl($parts);
Optimize Url::getUrl It's more simple and effective
jwage_purl
train
ae0263de2b4ba084f62a43211af8e0e941ed0d2a
diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php index <HASH>..<HASH> 100644 --- a/lib/db/upgrade.php +++ b/lib/db/upgrade.php @@ -3787,5 +3787,16 @@ function xmldb_main_upgrade($oldversion) { // Automatically generated Moodle v3.8.0 release upgrade line. // Put any upgrade step following this. + if ($oldversion < 2019120500.01) { + // Delete any tool_cohortroles mappings for roles which no longer exist. + $DB->delete_records_select('tool_cohortroles', "roleid NOT IN (SELECT id FROM {role})"); + + // Delete any role assignments for roles which no longer exist. + $DB->delete_records_select('role_assignments', "roleid NOT IN (SELECT id FROM {role})"); + + // Main savepoint reached. + upgrade_main_savepoint(true, 2019120500.01); + } + return true; } diff --git a/version.php b/version.php index <HASH>..<HASH> 100644 --- a/version.php +++ b/version.php @@ -29,7 +29,7 @@ defined('MOODLE_INTERNAL') || die(); -$version = 2019120500.00; // YYYYMMDD = weekly release date of this DEV branch. +$version = 2019120500.01; // YYYYMMDD = weekly release date of this DEV branch. // RR = release increments - 00 in DEV branches. // .XX = incremental changes. $release = '3.9dev (Build: 20191205)'; // Human-friendly version name
MDL-<I> core: removing stale cohortroles and role assignments
moodle_moodle
train
c8edf42aa0b06cc57195981fecf30198580acde0
diff --git a/app/scripts/Inset.js b/app/scripts/Inset.js index <HASH>..<HASH> 100644 --- a/app/scripts/Inset.js +++ b/app/scripts/Inset.js @@ -15,20 +15,17 @@ const getBaseRes = tilesetInfo => ( export default class Inset { constructor( uid, - dataPos, remotePos, + renderedPos, dataConfig, tilesetInfo, options, mouseHandler, - dataType + dataType, ) { this.uid = uid; - this.dataX1 = dataPos[0]; - this.dataX2 = dataPos[1]; - this.dataY1 = dataPos[2]; - this.dataY2 = dataPos[3]; this.remotePos = remotePos; + this.renderedPos = renderedPos || this.remotePos; this.dataConfig = dataConfig; this.tilesetInfo = tilesetInfo; this.options = options; @@ -107,8 +104,8 @@ export default class Inset { const xEndId = isBedpe ? 2 : 1; const yStartId = isBedpe ? 4 : 2; const yEndId = isBedpe ? 5 : 3; - const absXLen = this.remotePos[xEndId] - this.remotePos[xStartId]; - const absYLen = this.remotePos[yEndId] - this.remotePos[yStartId]; + const absXLen = this.renderedPos[xEndId] - this.renderedPos[xStartId]; + const absYLen = this.renderedPos[yEndId] - this.renderedPos[yStartId]; this.remoteSize = Math.max(absXLen, absYLen); const entry = resolutionCustomLocSorted[bisectLeft( @@ -534,7 +531,7 @@ export default class Inset { ) { // Scale the image down from its raw resolution to the inset's pixel size this.imScale = ( - Math.max(this.width, this.height) / + Math.max(width, height) / this.scaleBase / Math.max(this.data.width, this.data.height) ); diff --git a/app/scripts/Insets2dTrack.js b/app/scripts/Insets2dTrack.js index <HASH>..<HASH> 100644 --- a/app/scripts/Insets2dTrack.js +++ b/app/scripts/Insets2dTrack.js @@ -11,7 +11,7 @@ import { create } from './services/pub-sub'; // Utils import { - absToChr, base64ToCanvas, colorToHex, flatten, tileToCanvas + absToChr, base64ToCanvas, colorToHex, flatten, latToY, lngToX, tileToCanvas } from './utils'; const BASE_MIN_SIZE = 12; @@ -82,7 +82,7 @@ export default class Insets2dTrack extends PixiTrack { this.dataFetcher.tilesetInfo((tilesetInfo) => { if (tilesetInfo.error) { console.error( - 'Error retrieving tileset info:', dataConfig, this.tilesetInfo.error + 'Error retrieving tileset info:', dataConfig, tilesetInfo.error ); } this.tilesetInfo = tilesetInfo; @@ -105,14 +105,14 @@ export default class Insets2dTrack extends PixiTrack { } createFetchRenderInset( - uid, x, y, w, h, sx, sy, swh, shh, dX1, dX2, dY1, dY2, remotePos + uid, x, y, w, h, sx, sy, swh, shh, dX1, dX2, dY1, dY2, remotePos, renderedPos ) { const inset = ( this.insets[uid] || this.initInset( uid, - [dX1, dX2, dY1, dY2], - remotePos + remotePos, + renderedPos ) ); @@ -145,6 +145,15 @@ export default class Insets2dTrack extends PixiTrack { return [dX1, dX2, dY1, dY2]; } + dataToOsmPos(dX1, dX2, dY1, dY2) { + return [ + lngToX(dX1, 19) * this.tilesetInfo.tile_size, + lngToX(dX2, 19) * this.tilesetInfo.tile_size, + latToY(dY1, 19) * this.tilesetInfo.tile_size, + latToY(dY2, 19) * this.tilesetInfo.tile_size, + ]; + } + drawInset(inset) { if (this.dataType === 'cooler') { if (!this.fetchChromInfo) return Promise.reject('This is truly odd!'); @@ -158,6 +167,14 @@ export default class Insets2dTrack extends PixiTrack { )); } + if (this.dataType === 'osm-image') { + return this.createFetchRenderInset( + ...inset, + [inset[9], inset[10], inset[11], inset[12]], + this.dataToOsmPos(inset[9], inset[10], inset[11], inset[12]) + ); + } + return this.createFetchRenderInset( ...inset, this.dataToImPos(inset[9], inset[10], inset[11], inset[12])
Add support for osm-image snippets
higlass_higlass
train
db375c097660362f937cc9aecc16be6c42e39d38
diff --git a/src/LumenGenerator/Console/TinkerCommand.php b/src/LumenGenerator/Console/TinkerCommand.php index <HASH>..<HASH> 100644 --- a/src/LumenGenerator/Console/TinkerCommand.php +++ b/src/LumenGenerator/Console/TinkerCommand.php @@ -67,9 +67,13 @@ class TinkerCommand extends Command $config->getPresenter()->addCasters( $this->getCasters() ); - + $shell = new Shell($config); - $shell->setIncludes([$this->argument('include')]); + + $include = $this->argument('include'); + if (file_exists($include)) { + $shell->setIncludes([$include]); + } $shell->run(); }
fix: artisan tinker command error PHP Warning: include(): Filename cannot be empty on line <I> bug #<I>
flipboxstudio_lumen-generator
train
738d9d01faa05f105349ef78bf2424d6dc9171aa
diff --git a/src/PhpPackages/Container/Container.php b/src/PhpPackages/Container/Container.php index <HASH>..<HASH> 100644 --- a/src/PhpPackages/Container/Container.php +++ b/src/PhpPackages/Container/Container.php @@ -20,8 +20,8 @@ class Container $reflector = new \ReflectionClass($class); - $isInstantiable = - $reflector->getConstructor()->isPublic() or is_null($reflector->getConstructor()); + $isInstantiable = ! is_null($reflector->getConstructor()) and + $reflector->getConstructor()->isPublic(); if ($reflector->isAbstract() or ! $isInstantiable) { throw new Exceptions\ClassIsNotInstantiableException($class); diff --git a/stubs/NotInstantiableClass.php b/stubs/NotInstantiableClass.php index <HASH>..<HASH> 100644 --- a/stubs/NotInstantiableClass.php +++ b/stubs/NotInstantiableClass.php @@ -2,8 +2,4 @@ abstract class NotInstantiableClass { - - private function __construct() - { - } }
Fix for isInstantiable flag.
php-packages_container
train
0892b66cc9a2760e9b44d87d88ab83dd39637df0
diff --git a/lib/pkgcloud/openstack/cdn/client/base.js b/lib/pkgcloud/openstack/cdn/client/base.js index <HASH>..<HASH> 100644 --- a/lib/pkgcloud/openstack/cdn/client/base.js +++ b/lib/pkgcloud/openstack/cdn/client/base.js @@ -25,7 +25,7 @@ exports.getHomeDocument = function(callback) { return; } - callback(null, body); + callback(err, body); }); }; diff --git a/lib/pkgcloud/openstack/cdn/client/flavors.js b/lib/pkgcloud/openstack/cdn/client/flavors.js index <HASH>..<HASH> 100644 --- a/lib/pkgcloud/openstack/cdn/client/flavors.js +++ b/lib/pkgcloud/openstack/cdn/client/flavors.js @@ -37,7 +37,7 @@ exports.getFlavor = function (flavor, callback) { callback(new Error('Unexpected empty response')); } else { - callback(null, new cdn.Flavor(self, body)); + callback(err, new cdn.Flavor(self, body)); } }); }; @@ -69,7 +69,7 @@ exports.getFlavors = function getFlavors(options, callback) { return; } - callback(null, body.flavors.map(function(flavor) { + callback(err, body.flavors.map(function(flavor) { return new cdn.Flavor(self, flavor); })); }); diff --git a/lib/pkgcloud/openstack/cdn/client/services.js b/lib/pkgcloud/openstack/cdn/client/services.js index <HASH>..<HASH> 100644 --- a/lib/pkgcloud/openstack/cdn/client/services.js +++ b/lib/pkgcloud/openstack/cdn/client/services.js @@ -88,7 +88,7 @@ exports.getServices = function getServices(options, callback) { return; } - callback(null, body.services.map(function(service) { + callback(err, body.services.map(function(service) { return new cdn.Service(self, service); })); }); @@ -210,7 +210,7 @@ exports.updateService = function (service, callback) { return callback(err); } - callback(null, service); + callback(err, service); }); }); }; @@ -305,7 +305,7 @@ _getService = function (self, service, callback) { callback(new Error('Unexpected empty response')); } else { - callback(null, new cdn.Service(self, body)); + callback(err, new cdn.Service(self, body)); } }); };
Always pass err to callback.
pkgcloud_pkgcloud
train
613b3daddd9234452d53f28567151ef22445a79b
diff --git a/liquibase-core/src/main/java/liquibase/snapshot/JdbcDatabaseSnapshot.java b/liquibase-core/src/main/java/liquibase/snapshot/JdbcDatabaseSnapshot.java index <HASH>..<HASH> 100755 --- a/liquibase-core/src/main/java/liquibase/snapshot/JdbcDatabaseSnapshot.java +++ b/liquibase-core/src/main/java/liquibase/snapshot/JdbcDatabaseSnapshot.java @@ -551,7 +551,7 @@ public class JdbcDatabaseSnapshot extends DatabaseSnapshot { sql += " and TABLE_NAME='" + database.correctObjectName(tableName, Table.class) + "'"; } } else if (database instanceof OracleDatabase) { - sql = "select uc.constraint_name, uc.table_name,uc.status,uc.deferrable,uc.deferred,ui.tablespace_name from all_constraints uc, all_indexes ui " + sql = "select uc.constraint_name, uc.table_name,uc.status,uc.deferrable,uc.deferred,ui.tablespace_name, ui.index_name, ui.owner as INDEX_CATALOG from all_constraints uc, all_indexes ui " + "where uc.constraint_type='U' and uc.index_name = ui.index_name " + "and uc.owner = '" + jdbcSchemaName + "' " + "and ui.table_owner = '" + jdbcSchemaName + "' "; diff --git a/liquibase-core/src/main/java/liquibase/snapshot/jvm/IndexSnapshotGenerator.java b/liquibase-core/src/main/java/liquibase/snapshot/jvm/IndexSnapshotGenerator.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/snapshot/jvm/IndexSnapshotGenerator.java +++ b/liquibase-core/src/main/java/liquibase/snapshot/jvm/IndexSnapshotGenerator.java @@ -184,7 +184,7 @@ public class IndexSnapshotGenerator extends JdbcSnapshotGenerator { // if (foundObject instanceof PrimaryKey) { // ((PrimaryKey) foundObject).setBackingIndex(new Index().setTable(((PrimaryKey) foundObject).getTable()).setName(foundObject.getName())); // } - if (foundObject instanceof UniqueConstraint && !(snapshot.getDatabase() instanceof DB2Database)&& !(snapshot.getDatabase() instanceof DerbyDatabase)) { + if (foundObject instanceof UniqueConstraint && ((UniqueConstraint) foundObject).getBackingIndex() == null && !(snapshot.getDatabase() instanceof DB2Database)&& !(snapshot.getDatabase() instanceof DerbyDatabase)) { Index exampleIndex = new Index().setTable(((UniqueConstraint) foundObject).getTable()); exampleIndex.getColumns().addAll(((UniqueConstraint) foundObject).getColumns()); ((UniqueConstraint) foundObject).setBackingIndex(exampleIndex); diff --git a/liquibase-core/src/main/java/liquibase/snapshot/jvm/UniqueConstraintSnapshotGenerator.java b/liquibase-core/src/main/java/liquibase/snapshot/jvm/UniqueConstraintSnapshotGenerator.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/snapshot/jvm/UniqueConstraintSnapshotGenerator.java +++ b/liquibase-core/src/main/java/liquibase/snapshot/jvm/UniqueConstraintSnapshotGenerator.java @@ -43,6 +43,7 @@ public class UniqueConstraintSnapshotGenerator extends JdbcSnapshotGenerator { UniqueConstraint constraint = new UniqueConstraint(); constraint.setTable(table); constraint.setName(example.getName()); + constraint.setBackingIndex(exampleConstraint.getBackingIndex()); for (Map<String, ?> col : metadata) { constraint.getColumns().add(new Column((String) col.get("COLUMN_NAME")).setRelation(table)); } @@ -74,6 +75,9 @@ public class UniqueConstraintSnapshotGenerator extends JdbcSnapshotGenerator { for (CachedRow constraint : metadata) { UniqueConstraint uq = new UniqueConstraint().setName(cleanNameFromDatabase((String) constraint.get("CONSTRAINT_NAME"), database)).setTable(table); + if (constraint.containsColumn("INDEX_NAME")) { + uq.setBackingIndex(new Index((String) constraint.get("INDEX_NAME"), (String) constraint.get("INDEX_CATALOG"), null, table.getName())); + } if (seenConstraints.add(uq.getName())) { table.getUniqueConstraints().add(uq); }
CORE-<I> Ability to save snapshot for later comparison Oracle unique constraints can share indexes with a different column order if one is already defined.
liquibase_liquibase
train
adc8070d3013317ece6fc7eeef01a43516732e71
diff --git a/drools-planner-examples/src/main/java/org/drools/planner/examples/tsp/swingui/TspWorldPanel.java b/drools-planner-examples/src/main/java/org/drools/planner/examples/tsp/swingui/TspWorldPanel.java index <HASH>..<HASH> 100644 --- a/drools-planner-examples/src/main/java/org/drools/planner/examples/tsp/swingui/TspWorldPanel.java +++ b/drools-planner-examples/src/main/java/org/drools/planner/examples/tsp/swingui/TspWorldPanel.java @@ -18,6 +18,7 @@ package org.drools.planner.examples.tsp.swingui; import java.awt.Color; import java.awt.Dimension; +import java.awt.Font; import java.awt.Graphics; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; @@ -147,6 +148,9 @@ public class TspWorldPanel extends JPanel { g.setColor(TangoColors.PLUM_2); g.fillRect(6, (int) height - 9, 3, 3); g.drawString("Visit", 15, (int) height - 5); + g.setColor(TangoColors.ALUMINIUM_5); + String clickString = "Click anywhere in the map to add a visit."; + g.drawString(clickString, (int) width - 5 - g.getFontMetrics().stringWidth(clickString),(int) height - 5); repaint(); }
tsp label "click anywhere to add a visit"
kiegroup_optaplanner
train
6f6f09fe4e1403de4bfee28d5396a7c7e5942647
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -39,6 +39,24 @@ var execQuery = function(query) { } }; +var execSave = function (model) { + return function(cb) { + model.save(function(err, model) { + if (err) + return cb(restifyError(err)); + else + cb(null, model); + }); + }; +}; + +var setLocationHeader = function (req, res) { + return function(model, cb) { + res.header('Location', req.url + '/' + model._id); + cb(null, model); + }; +} + var buildProjections = function(req, projection) { return function(models, cb) { var iterator = function (model, cb) { @@ -142,19 +160,16 @@ Resource.prototype.detail = function (options) { Resource.prototype.insert = function () { var self = this; - var emitInsert = emitEvent(self, 'insert'); return function(req, res, next) { - self.Model.create(req.body, function (err, model) { - if (err) { - return onError(err, next); - } - - res.header('Location', req.url + '/' + model._id); - res.send(200, model); - - emitInsert(model, next); - }); + var model = new self.Model(req.body); + async.waterfall([ + execSave(model), + setLocationHeader(req, res), + emitEvent(self, 'insert'), + sendData(res) + ], next); + }; };
Updated insert to use async.waterfall All operations except insert and update are using aync.waterfall to run command in succession.
saintedlama_restify-mongoose
train
28b5331658aa55c69a587535b34de795abfea966
diff --git a/uproot/tree.py b/uproot/tree.py index <HASH>..<HASH> 100644 --- a/uproot/tree.py +++ b/uproot/tree.py @@ -1713,7 +1713,10 @@ def lazyarrays(path, treepath, branches=None, outputtype=dict, limitbytes=1024** cache[LazyArray._cachekey(uuids[0], treepath)] = tree def chunksize(branch): - return max(branch.basket_numentries(i) for i in range(branch.numbaskets)) + if branch.numbaskets == 0: + return 0 + else: + return max(branch.basket_numentries(i) for i in range(branch.numbaskets)) if outputtype == namedtuple: outputtype = namedtuple("Arrays", [branch.name.decode("ascii") for branch, interpretation in branches]) @@ -1739,7 +1742,7 @@ class LazyArray(object): self._uuids = (None,) self._treepath = None self._branchname = onlybranch.name - self._chunksize = max(onlybranch.basket_numentries(i) for i in range(onlybranch.numbaskets)) + self._chunksize = max(onlybranch.basket_numentries(i) for i in range(onlybranch.numbaskets)) if onlybranch.numbaskets > 0 else 1 self._interpretation = interpretation self._globalentryoffset = numpy.array([0, onlybranch.numentries], dtype=numpy.int64) self._cache = cache diff --git a/uproot/version.py b/uproot/version.py index <HASH>..<HASH> 100644 --- a/uproot/version.py +++ b/uproot/version.py @@ -30,7 +30,7 @@ import re -__version__ = "2.9.6" +__version__ = "2.9.7" version = __version__ version_info = tuple(re.split(r"[-\.]", __version__))
fixes #<I>: protect max against empty sequence
scikit-hep_uproot
train
d5466f82aeabbfe1ba8ac2f7ed6e08bb48116b72
diff --git a/zpar/__init__.py b/zpar/__init__.py index <HASH>..<HASH> 100644 --- a/zpar/__init__.py +++ b/zpar/__init__.py @@ -46,8 +46,6 @@ class ZPar(object): _unload_models.argtypes = [c.c_void_p] self.libptr.unload_models(self._zpar_session_obj) - sys.stderr.write('Done unloading\n') - # clean up the data structures on the python side if self.tagger: self.tagger.cleanup()
Removed extraneous print statement.
EducationalTestingService_python-zpar
train
f3bcb2688a66efe586da517faafca83a283be72d
diff --git a/src/Event/DBALSchemaEventSubscriber.php b/src/Event/DBALSchemaEventSubscriber.php index <HASH>..<HASH> 100644 --- a/src/Event/DBALSchemaEventSubscriber.php +++ b/src/Event/DBALSchemaEventSubscriber.php @@ -60,6 +60,13 @@ class DBALSchemaEventSubscriber implements EventSubscriber public function postConnect(ConnectionEventArgs $args) { if ($this->postConnectCalled) { + // Allows multiple postConnect calls for the same connection + // instance. This is done by MasterSlaveConnection for example when + // switching master/slave connections. + if ($this->connection === $args->getConnection()) { + return; + } + throw new \LogicException( sprintf( 'It looks like you have registered the %s to more than one connection. Please register one instance per connection.', diff --git a/tests/AbstractFunctionalTestCase.php b/tests/AbstractFunctionalTestCase.php index <HASH>..<HASH> 100644 --- a/tests/AbstractFunctionalTestCase.php +++ b/tests/AbstractFunctionalTestCase.php @@ -76,19 +76,22 @@ abstract class AbstractFunctionalTestCase extends AbstractTestCase } } + protected function _getDbParams() + { + return array( + 'driver' => $GLOBALS['db_type'], + 'user' => $GLOBALS['db_username'], + 'password' => $GLOBALS['db_password'], + 'host' => $GLOBALS['db_host'], + 'dbname' => $GLOBALS['db_name'], + 'port' => $GLOBALS['db_port'], + ); + } + protected function _getConnection() { if (!isset(self::$_conn)) { - $dbParams = array( - 'driver' => $GLOBALS['db_type'], - 'user' => $GLOBALS['db_username'], - 'password' => $GLOBALS['db_password'], - 'host' => $GLOBALS['db_host'], - 'dbname' => $GLOBALS['db_name'], - 'port' => $GLOBALS['db_port'], - ); - - self::$_conn = DriverManager::getConnection($dbParams, new Configuration()); + self::$_conn = DriverManager::getConnection($this->_getDbParams(), new Configuration()); self::$_conn->getEventManager()->addEventSubscriber(new ORMSchemaEventSubscriber()); diff --git a/tests/Event/DBALSchemaEventSubscriberTest.php b/tests/Event/DBALSchemaEventSubscriberTest.php index <HASH>..<HASH> 100644 --- a/tests/Event/DBALSchemaEventSubscriberTest.php +++ b/tests/Event/DBALSchemaEventSubscriberTest.php @@ -2,6 +2,8 @@ namespace Jsor\Doctrine\PostGIS\Event; +use Doctrine\DBAL\Connections\MasterSlaveConnection; +use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Schema\ColumnDiff; use Doctrine\DBAL\Types\Type; use Jsor\Doctrine\PostGIS\AbstractFunctionalTestCase; @@ -121,6 +123,49 @@ class DBALSchemaEventSubscriberTest extends AbstractFunctionalTestCase return $table; } + public function testSubscriberThrowsWhenRegisteredOnMultipleConnections() + { + $this->setExpectedException( + '\LogicException', + 'It looks like you have registered the Jsor\Doctrine\PostGIS\Event\DBALSchemaEventSubscriber to more than one connection. Please register one instance per connection.' + ); + + $subscriber = new DBALSchemaEventSubscriber(); + + $conn1 = DriverManager::getConnection($this->_getDbParams()); + $conn1->getEventManager()->addEventSubscriber($subscriber); + + $dbParams = array( + 'driver' => 'pdo_pgsql', + ); + $conn2 = DriverManager::getConnection($dbParams); + $conn2->getEventManager()->addEventSubscriber($subscriber); + + $conn1->connect(); + $conn2->connect(); + } + + public function testSubscriberDoesNotThrowWhenRegisteredOnMasterSlaveConnectionAndConnectionSwitches() + { + $subscriber = new DBALSchemaEventSubscriber(); + + $dbParams = $this->_getDbParams(); + + $conn = DriverManager::getConnection(array( + 'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection', + 'driver' => $dbParams['driver'], + 'master' => $dbParams, + 'slaves' => array( + $dbParams + ) + )); + + $conn->getEventManager()->addEventSubscriber($subscriber); + + $conn->connect('slave'); + $conn->connect('master'); + } + public function testListTableColumns() { $columns = $this->sm->listTableColumns('points');
Allow multiple postConnect calls for the same connection instance This is done by MasterSlaveConnection for example when switching master/slave connections.
jsor_doctrine-postgis
train
770778a502327a8876d20e57407dbbe09eae09a2
diff --git a/mod/choice/lib.php b/mod/choice/lib.php index <HASH>..<HASH> 100644 --- a/mod/choice/lib.php +++ b/mod/choice/lib.php @@ -243,7 +243,7 @@ function choice_user_submit_response($formanswer, $choice, $userid, $courseid, $ if ($countanswers) { $countans = 0; foreach ($countanswers as $ca) { //only return enrolled users. - if (has_capability('mod/choice:choose', $context)) { + if (has_capability('mod/choice:choose', $context, $ca->userid, false)) { $countans = $countans+1; } }
missed one line. Fix for MDL-<I> and MDL-<I> Problem with number of Responses in choice wrong, and displayed users incorrect on results.
moodle_moodle
train
101378e05caa87b8d2c969eb9675c40667eb0639
diff --git a/src/lib/getputdelete.js b/src/lib/getputdelete.js index <HASH>..<HASH> 100644 --- a/src/lib/getputdelete.js +++ b/src/lib/getputdelete.js @@ -8,7 +8,7 @@ define( var defaultContentType = 'application/octet-stream'; - function doCall(method, url, body, mimeType, token) { + function realDoCall(method, url, body, mimeType, token) { return util.makePromise(function(promise) { logger.debug(method, url); var platformObj = { @@ -60,6 +60,43 @@ define( }); } + var inProgress = 0; + var maxInProgress = 10; + var pendingQueue = []; + + function doCall() { + var args = util.toArray(arguments); + function finishOne() { + inProgress--; + if(pendingQueue.length > 0) { + var c = pendingQueue.shift(); + logger.info('SHIFT', c.a); + doCall.apply(this, c.a).then(c.p.fulfill.bind(c.p), c.p.fail.bind(c.p)); + } else { + logger.info('QUEUE EMPTY'); + } + } + if(inProgress < maxInProgress) { + logger.info('PROCESS', args); + inProgress++; + return realDoCall.apply(this, arguments).then(function(data, mimeType) { + finishOne(); + return util.makePromise(function(p) { p.fulfill(data, mimeType); }); + }, function(error) { + finishOne(); + throw error; + }); + } else { + logger.info('ENQUEUE', args); + return util.makePromise(function(p) { + pendingQueue.push({ + a: args, + p: p + }); + }); + } + } + function get(url, token) { return doCall('GET', url, null, null, token); }
limit requests in getputdelete
remotestorage_remotestorage.js
train
13ced30224d962c8cde4c994332a0b45023e23e2
diff --git a/src/components/Editor/index.js b/src/components/Editor/index.js index <HASH>..<HASH> 100644 --- a/src/components/Editor/index.js +++ b/src/components/Editor/index.js @@ -207,9 +207,9 @@ class Editor extends Component { style={style} spellCheck="false" contentEditable={contentEditable} - onKeyDown={contentEditable && this.onKeyDown} - onKeyUp={contentEditable && this.onKeyUp} - onClick={contentEditable && this.onClick} + onKeyDown={contentEditable ? this.onKeyDown : undefined} + onKeyUp={contentEditable ? this.onKeyUp : undefined} + onClick={contentEditable ? this.onClick : undefined} dangerouslySetInnerHTML={{ __html: html }} /> )
Remove boolean values from non-boolean attributes React <I> warns and ignores boolean values in non-boolean attributes. React <I> converted these to strings and passed through. Replacing logical operators with ternary in attributes removes the warning. <URL>
FormidableLabs_react-live
train
a9578e8b51c70929b3687f57028699d403aafa84
diff --git a/Sami/Console/Command/Command.php b/Sami/Console/Command/Command.php index <HASH>..<HASH> 100644 --- a/Sami/Console/Command/Command.php +++ b/Sami/Console/Command/Command.php @@ -55,7 +55,7 @@ abstract class Command extends BaseCommand $config = getcwd().'/'.$config; } - if (!file_exists($config)) { + if (!is_file($config)) { throw new \InvalidArgumentException(sprintf('Configuration file "%s" does not exist.', $config)); }
fixed CLI when passing a directory as a config file
FriendsOfPHP_Sami
train
7a38d9f501ee1d97a718bbd9a0e70953d2a561f6
diff --git a/go/minterm/minterm.go b/go/minterm/minterm.go index <HASH>..<HASH> 100644 --- a/go/minterm/minterm.go +++ b/go/minterm/minterm.go @@ -7,10 +7,11 @@ package minterm import ( "errors" "fmt" - "github.com/keybase/go-crypto/ssh/terminal" "io" "os" "strings" + + "github.com/keybase/go-crypto/ssh/terminal" ) // MinTerm is a minimal terminal interface. @@ -20,6 +21,8 @@ type MinTerm struct { closeTermOut bool width int height int + raw bool + oldState *terminal.State } var ErrPromptInterrupted = errors.New("prompt interrupted") @@ -37,6 +40,7 @@ func New() (*MinTerm, error) { // Shutdown closes the terminal. func (m *MinTerm) Shutdown() error { + m.restore() // this can hang waiting for newline, so do it in a goroutine. // application shutting down, so will get closed by os anyway... if m.termIn != nil { @@ -79,27 +83,38 @@ func (m *MinTerm) PromptPassword(prompt string) (string, error) { func (m *MinTerm) fdIn() int { return int(m.termIn.Fd()) } func (m *MinTerm) readLine() (string, error) { - fd := int(m.fdIn()) - oldState, err := terminal.MakeRaw(fd) - if err != nil { - return "", err - } - defer terminal.Restore(fd, oldState) - var ret string - ret, err = terminal.NewTerminal(m.getReadWriter(), "").ReadLine() + m.makeRaw() + defer m.restore() + ret, err := terminal.NewTerminal(m.getReadWriter(), "").ReadLine() return ret, convertErr(err) } func (m *MinTerm) readSecret() (string, error) { + m.makeRaw() + defer m.restore() + ret, err := terminal.NewTerminal(m.getReadWriter(), "").ReadPassword("") + return ret, convertErr(err) +} + +func (m *MinTerm) makeRaw() error { fd := int(m.fdIn()) oldState, err := terminal.MakeRaw(fd) if err != nil { - return "", err + return err } - defer terminal.Restore(fd, oldState) - var ret string - ret, err = terminal.NewTerminal(m.getReadWriter(), "").ReadPassword("") - return ret, convertErr(err) + m.raw = true + m.oldState = oldState + return nil +} + +func (m *MinTerm) restore() { + if !m.raw { + return + } + fd := int(m.fdIn()) + terminal.Restore(fd, m.oldState) + m.raw = false + m.oldState = nil } func convertErr(e error) error {
Restore out of raw mode on shutdown
keybase_client
train
7f0b1c9591323951d788cb65aa1d8c7b8c3249c9
diff --git a/scdl/scdl.py b/scdl/scdl.py index <HASH>..<HASH> 100755 --- a/scdl/scdl.py +++ b/scdl/scdl.py @@ -97,7 +97,7 @@ url = { 'all': ('https://api-v2.soundcloud.com/profile/soundcloud:users:{0}?' 'limit=200'), 'playlists': ('https://api.soundcloud.com/users/{0}/playlists?' - 'limit=200'), + 'limit=5'), 'resolve': ('https://api.soundcloud.com/resolve?url={0}'), 'trackinfo': ('https://api.soundcloud.com/tracks/{0}'), 'user': ('https://api.soundcloud.com/users/{0}'), @@ -557,7 +557,7 @@ def download_track(track, playlist_name=None, playlist_file=None): def can_convert(filename): ext = os.path.splitext(filename)[1] - return ext == 'wav' or ext in 'aif' + return 'wav' in ext or 'aif' in ext def already_downloaded(track, title, filename): """ @@ -672,21 +672,21 @@ def set_metadata(track, filename, album=None): a = mutagen.File(filename) if track['description']: - if a.__class__ is mutagen.flac.FLAC: + if a.__class__ == mutagen.flac.FLAC: a['description'] = track['description'] - elif a.__class__ is mutagen.mp3.MP3: + elif a.__class__ == mutagen.mp3.MP3: a['COMM'] = mutagen.id3.COMM( encoding=3, lang=u'ENG', text=track['description'] ) if artwork_url: - if a.__class__ is mutagen.flac.FLAC: + if a.__class__ == mutagen.flac.FLAC: p = mutagen.flac.Picture() p.data = out_file.read() p.width = 500 p.height = 500 p.type = mutagen.id3.PictureType.COVER_FRONT a.add_picture(p) - elif a.__class__ is mutagen.mp3.MP3: + elif a.__class__ == mutagen.mp3.MP3: a['APIC'] = mutagen.id3.APIC( encoding=3, mime='image/jpeg', type=3, desc='Cover', data=out_file.read()
Small fix to avoid <I> server error due to too much tracks
flyingrub_scdl
train
a28b0fa4c6491ea90170a375b77e2fc7ae24ad6a
diff --git a/src/FondOfSpryker/Zed/ConditionalAvailability/Persistence/ConditionalAvailabilityRepository.php b/src/FondOfSpryker/Zed/ConditionalAvailability/Persistence/ConditionalAvailabilityRepository.php index <HASH>..<HASH> 100644 --- a/src/FondOfSpryker/Zed/ConditionalAvailability/Persistence/ConditionalAvailabilityRepository.php +++ b/src/FondOfSpryker/Zed/ConditionalAvailability/Persistence/ConditionalAvailabilityRepository.php @@ -21,6 +21,7 @@ use Spryker\Zed\Kernel\Persistence\AbstractRepository; class ConditionalAvailabilityRepository extends AbstractRepository implements ConditionalAvailabilityRepositoryInterface { public const VIRTUAL_COLUMN_SKU = 'sku'; + protected const RELATION_ALIAS_FOS_CONDITIONAL_AVAILABILITY_PERIOD = 'FosConditionalAvailabilityPeriod'; /** * @param int $idConditionalAvailability @@ -34,6 +35,7 @@ class ConditionalAvailabilityRepository extends AbstractRepository implements Co ->useFosConditionalAvailabilityPeriodQuery() ->addAscendingOrderByColumn(FosConditionalAvailabilityPeriodTableMap::COL_START_AT) ->endUse() + ->with(static::RELATION_ALIAS_FOS_CONDITIONAL_AVAILABILITY_PERIOD) ->filterByIdConditionalAvailability($idConditionalAvailability) ->findOne(); @@ -54,7 +56,7 @@ class ConditionalAvailabilityRepository extends AbstractRepository implements Co public function findConditionalAvailabilityPeriodsByFkConditionalAvailability( int $fkConditionalAvailability ): ConditionalAvailabilityPeriodCollectionTransfer { - $fosConditionalAvailabilities = $this->getFactory() + $fosConditionalAvailabilityPeriods = $this->getFactory() ->createConditionalAvailabilityPeriodQuery() ->filterByFkConditionalAvailability($fkConditionalAvailability) ->addAscendingOrderByColumn(FosConditionalAvailabilityPeriodTableMap::COL_START_AT) @@ -62,10 +64,10 @@ class ConditionalAvailabilityRepository extends AbstractRepository implements Co $conditionalAvailabilityPeriodCollectionTransfer = new ConditionalAvailabilityPeriodCollectionTransfer(); - foreach ($fosConditionalAvailabilities as $fosConditionalAvailability) { + foreach ($fosConditionalAvailabilityPeriods as $fosConditionalAvailabilityPeriod) { $conditionalAvailabilityPeriodTransfer = $this->getFactory() ->createConditionalAvailabilityPeriodMapper() - ->mapEntityToTransfer($fosConditionalAvailability, new ConditionalAvailabilityPeriodTransfer()); + ->mapEntityToTransfer($fosConditionalAvailabilityPeriod, new ConditionalAvailabilityPeriodTransfer()); $conditionalAvailabilityPeriodCollectionTransfer ->addConditionalAvailabilityPeriod($conditionalAvailabilityPeriodTransfer); @@ -131,6 +133,8 @@ class ConditionalAvailabilityRepository extends AbstractRepository implements Co ->endUse(); } + $fosConditionalAvailabilityQuery->with(static::RELATION_ALIAS_FOS_CONDITIONAL_AVAILABILITY_PERIOD); + if ($conditionalAvailabilityCriteriaFilterTransfer->getIsAccessible() !== null) { $fosConditionalAvailabilityQuery->filterByIsAccessible( $conditionalAvailabilityCriteriaFilterTransfer->getIsAccessible()
Add required relation with method 'with' (#9)
fond-of_spryker-conditional-availability
train
b10961873c0e04713f5c06dca06c1b0f97f5de44
diff --git a/code/forms/GridFieldSortableRows.php b/code/forms/GridFieldSortableRows.php index <HASH>..<HASH> 100644 --- a/code/forms/GridFieldSortableRows.php +++ b/code/forms/GridFieldSortableRows.php @@ -107,6 +107,7 @@ class GridFieldSortableRows implements GridField_HTMLProvider, GridField_ActionP $className=$gridField->getModelClass(); $ownerClass=$gridField->Form->Controller()->class; + $controllerID=$gridField->Form->Controller()->ID; $many_many=GridFieldSortableObject::is_sortable_many_many($className); if($many_many) { @@ -131,7 +132,7 @@ class GridFieldSortableRows implements GridField_HTMLProvider, GridField_ActionP for($sort=0;$sort<count($data['Items']);$sort++) { $id=intval($data['Items'][$sort]); if($many_many) { - DB::query("UPDATE \"$table\" SET \"SortOrder\" = $sort WHERE \"{$className}ID\" = $id"); + DB::query("UPDATE \"$table\" SET \"SortOrder\" = $sort WHERE \"{$className}ID\" = $id AND \"{$ownerClass}ID\" = $controllerID"); }else { $obj=DataObject::get_by_id($className, $id); $obj->SortOrder=$sort;
Better handling of many_many relationship sorting
UndefinedOffset_SortableGridField
train
d40a712f727d59dfd358e402b913c7b30758a28e
diff --git a/app/models/manager_refresh/dto_collection.rb b/app/models/manager_refresh/dto_collection.rb index <HASH>..<HASH> 100644 --- a/app/models/manager_refresh/dto_collection.rb +++ b/app/models/manager_refresh/dto_collection.rb @@ -29,7 +29,7 @@ module ManagerRefresh def process_strategy_local_db_cache_all self.saved = true - selected = [:id] + manager_ref + selected = [:id] + manager_ref selected << :type if model_class.new.respond_to? :type parent.send(association).select(selected).find_each do |record| self.data_index[object_index(record)] = record @@ -89,8 +89,8 @@ module ManagerRefresh presence_validators = model_class.validators.detect { |x| x.kind_of? ActiveRecord::Validations::PresenceValidator } # Attributes that has to be always on the entity, so attributes making unique indec of the record + attributes # that have presence validation - fixed_attributes = manager_ref - fixed_attributes += presence_validators.attributes unless presence_validators.blank? + fixed_attributes = manager_ref + fixed_attributes += presence_validators.attributes unless presence_validators.blank? fixed_dependencies = Set.new dependency_attributes.each do |key, value| @@ -113,7 +113,7 @@ module ManagerRefresh def blacklist_attributes!(attributes) @attributes_blacklist += attributes - dependency_attributes.delete_if {|key, _value| attributes.include?(key) } + dependency_attributes.delete_if { |key, _value| attributes.include?(key) } end def to_s @@ -128,12 +128,16 @@ module ManagerRefresh def actualize_dependencies(dto) dto.data.each do |key, value| - if value.kind_of? ::ManagerRefresh::DtoLazy + if is_dependency?(value) (dependency_attributes[key] ||= Set.new) << value.dto_collection - elsif value.kind_of?(Array) && value.any? { |x| x.kind_of? ::ManagerRefresh::DtoLazy } - (dependency_attributes[key] ||= Set.new) << value.detect { |x| x.kind_of? ::ManagerRefresh::DtoLazy }.dto_collection + elsif value.kind_of?(Array) && value.any? { |x| is_dependency?(x) } + (dependency_attributes[key] ||= Set.new) << value.detect { |x| is_dependency?(x) }.dto_collection end end end + + def is_dependency?(value) + value.kind_of?(::ManagerRefresh::DtoLazy) || value.kind_of?(::ManagerRefresh::Dto) + end end end
Both Dto and DtoLazy are causing a dependency Both Dto and DtoLazy are causing a dependency (transferred from ManageIQ/manageiq@1f<I>e<I>a4b<I>e6f6ac<I>ab4f6fc<I>be)
ManageIQ_inventory_refresh
train
ddadab09673707309c70afc86b232a6a3fb59979
diff --git a/src/main/java/net/finmath/marketdata/model/curves/CurveInterpolation.java b/src/main/java/net/finmath/marketdata/model/curves/CurveInterpolation.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/finmath/marketdata/model/curves/CurveInterpolation.java +++ b/src/main/java/net/finmath/marketdata/model/curves/CurveInterpolation.java @@ -453,6 +453,19 @@ public class CurveInterpolation extends AbstractCurve implements Serializable, C public List<Point> getPoints() { return Collections.unmodifiableList(points); } + + /** + * Returns the interpolation times (the x-values). + * + * The method creates a defensive copy. + * + * @return Array of interpolation times (the x-values). + */ + public double[] getTimes() { + double[] times = new double[points.size()]; + for(int i=0; i<points.size(); i++) times[i] = points.get(i).time; + return times; + } protected int getTimeIndex(final double time) { final Point point = new Point(time, Double.NaN, false);
Added method to get times vector.
finmath_finmath-lib
train
1757a4eabb837a5a657aa8913d49877128cedbe4
diff --git a/Brocfile.js b/Brocfile.js index <HASH>..<HASH> 100755 --- a/Brocfile.js +++ b/Brocfile.js @@ -7,19 +7,35 @@ var pickFiles = require('broccoli-static-compiler'); var concat = require('broccoli-concat'); var select = require('broccoli-select'); var moveFile = require('broccoli-file-mover'); -var writeFile = require('broccoli-file-creator'); var env = require('broccoli-env').getEnv(); -var pkg = require('./package.json'); -var banner = '/**\n' + - ' * ' + pkg.name + '\n' + - ' * @version v' + pkg.version + ' - ' + new Date().toISOString().substr(0, 10) + '\n' + - ' * @link ' + pkg.homepage + '\n' + - ' * @author ' + pkg.author.name + ' (' + pkg.author.email + ')\n' + - ' * @license MIT License, http://www.opensource.org/licenses/MIT\n' + - ' */\n'; +// Add banner to file -banner = writeFile('banner.js', banner); +function concatBanner(tree, options) { + var writeFile = require('broccoli-file-creator'); + var pkg = require('./package.json'); + + var banner = '/**\n' + + ' * ' + pkg.name + '\n' + + ' * @version v' + pkg.version + ' - ' + new Date().toISOString().substr(0, 10) + '\n' + + ' * @link ' + pkg.homepage + '\n' + + ' * @author ' + pkg.author.name + ' (' + pkg.author.email + ')\n' + + ' * @license MIT License, http://www.opensource.org/licenses/MIT\n' + + ' */\n'; + + banner = writeFile('banner.js', banner); + + options.inputFiles.forEach(function(inputFile) { + + var resultTree = concat(mergeTrees([tree, banner]), { + inputFiles: ['banner.js', inputFile], + outputFile: '/' + inputFile + }); + + tree = mergeTrees([tree, resultTree], { overwrite: true }); + }); + return tree; +} // Library @@ -32,11 +48,6 @@ var libJs = concat(lib, { outputFile: '/ember-strap.js' }); -libJs = concat(mergeTrees([libJs, banner]), { - inputFiles: ['banner.js', 'ember-strap.js'], - outputFile: '/ember-strap.js' -}); - var minLibJs = moveFile(libJs, { srcFile: 'ember-strap.js', destFile: 'ember-strap.min.js', @@ -52,13 +63,12 @@ minLibJs = uglifyJavaScript(minLibJs, { // compress: false }); -minLibJs = concat(mergeTrees([minLibJs, banner]), { - inputFiles: ['banner.js', 'ember-strap.min.js'], - outputFile: '/ember-strap.min.js' -}); - libJs = mergeTrees([libJs, minLibJs]); +libJs = concatBanner(libJs, { + inputFiles: ['ember-strap.js', 'ember-strap.min.js'] +}); + // Documentation
small brocfile refactoring
pierrickrouxel_ember-strap
train
c1f77cb00f9a407d2336dcb7275624839a84b18c
diff --git a/tests/phpunit/unit/Form/Resolver/ChoiceTest.php b/tests/phpunit/unit/Form/Resolver/ChoiceTest.php index <HASH>..<HASH> 100644 --- a/tests/phpunit/unit/Form/Resolver/ChoiceTest.php +++ b/tests/phpunit/unit/Form/Resolver/ChoiceTest.php @@ -321,6 +321,69 @@ class ChoiceTest extends TestCase $this->assertSame($expect, $result); } + public function testGetEntitySorted() + { + $values = 'contenttype/field_1,field_2'; + $contentType1 = new ContentType('koala', [ + 'fields' => [ + 'select_array' => [ + 'type' => 'select', + 'values' => $values, + 'sort' => 'field_1', + ], + ], + ]); + + $contentType2 = new ContentType('koala', [ + 'fields' => [ + 'select_array' => [ + 'type' => 'select', + 'values' => $values, + 'sort' => '-field_2', + ], + ], + ]); + + $mockRepo = $this->getMockBuilder(ContentRepository::class) + ->disableOriginalConstructor() + ->setMethods(['findBy']) + ->getMock() + ; + + $mockRepo->expects($this->at(0)) + ->method('findBy') + ->with([], ['field_1', 'ASC'], null) + ; + $mockRepo->expects($this->at(1)) + ->method('findBy') + ->with([], ['field_2', 'DESC'], null) + ; + + $mockEntityManager = $this->getMockBuilder(EntityManager::class) + ->disableOriginalConstructor() + ->setMethods(['getRepository']) + ->getMock() + ; + + $mockEntityManager + ->expects($this->any()) + ->method('getRepository') + ->willReturn($mockRepo) + ; + + $mockQuery = $this->getMockBuilder(Query::class) + ->disableOriginalConstructor() + ->setMethods(['getContent']) + ->getMock() + ; + + $resolver = new Choice($mockEntityManager, $mockQuery); + $resolver->get($contentType1, []); + $resolver->get($contentType2, []); + + } + + public function testGetTemplateFieldsSelect() { @@ -338,6 +401,7 @@ class ChoiceTest extends TestCase $this->assertSame(['templatefields' => ['select_array' => $values]], $result); } + /** * @return Content[] */
add test to check correct sorting gets applied
bolt_bolt
train
686e2975994da382f2d3ec5f7e1bc06abb395359
diff --git a/src/Resources/Recipe.php b/src/Resources/Recipe.php index <HASH>..<HASH> 100644 --- a/src/Resources/Recipe.php +++ b/src/Resources/Recipe.php @@ -56,10 +56,11 @@ class Recipe extends Resource /** * Run the given recipe. * + * @param array $data * @return void */ - public function run() + public function run(array $data) { - return $this->forge->runRecipe($this->id); + return $this->forge->runRecipe($this->id, $data); } -} \ No newline at end of file +}
Update ->run() method on Recipe to new signature
themsaid_forge-sdk
train
6a181fee2a56c85927a6684999f5d1b5013825e0
diff --git a/src/Api/ApiSubAccount.php b/src/Api/ApiSubAccount.php index <HASH>..<HASH> 100644 --- a/src/Api/ApiSubAccount.php +++ b/src/Api/ApiSubAccount.php @@ -42,7 +42,7 @@ class ApiSubAccount extends ApiBase public function findOneById($appUserId, $id) { $url = sprintf('users/%s/subaccounts/%s', $appUserId, $id); - return $this->getOne($url, $this->subAccountClassName); + return $this->getOne($url, $this->entityClassName); } /** @@ -83,4 +83,4 @@ class ApiSubAccount extends ApiBase $url = sprintf('users/%s/subaccounts/%s', $appUserId, $subAccount->getAppAccountId()); return $this->updateObject($url, $subAccount); } -} \ No newline at end of file +}
Fix sub account api wrong class name
picoss_SMoney
train
00cc734b678d2a08839ee2e35904e0b0e46c479d
diff --git a/mux.go b/mux.go index <HASH>..<HASH> 100644 --- a/mux.go +++ b/mux.go @@ -206,17 +206,16 @@ func (mx *Mux) NotFound(handlerFn http.HandlerFunc) { func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc) { // Build MethodNotAllowed handler chain m := mx - hFn := handlerFn + h := Chain(mx.middlewares...).HandlerFunc(handlerFn).ServeHTTP if mx.inline && mx.parent != nil { m = mx.parent - hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP } // Update the methodNotAllowedHandler from this point forward - m.methodNotAllowedHandler = hFn + m.methodNotAllowedHandler = h m.updateSubRoutes(func(subMux *Mux) { if subMux.methodNotAllowedHandler == nil { - subMux.MethodNotAllowed(hFn) + subMux.MethodNotAllowed(h) } }) }
router with empty routes but MethodNotAllowed is still valid
go-chi_chi
train
519efbf1793dc91bc484b33aa16b687005bd4c5c
diff --git a/tests/helpers/formats_helper.rb b/tests/helpers/formats_helper.rb index <HASH>..<HASH> 100644 --- a/tests/helpers/formats_helper.rb +++ b/tests/helpers/formats_helper.rb @@ -48,7 +48,8 @@ module Shindo format.delete(key) case value when Array - valid &&= datum.is_a?(Array) || p("#{key.inspect} not Array: #{datum.inspect}") + p("#{key.inspect} not Array: #{datum.inspect}") unless datum.is_a?(Array) + valid &&= datum.is_a?(Array) if datum.is_a?(Array) && !value.empty? for element in datum type = value.first @@ -60,7 +61,8 @@ module Shindo end end when Hash - valid &&= datum.is_a?(Hash) || p("#{key.inspect} not Hash: #{datum.inspect}") + p("#{key.inspect} not Hash: #{datum.inspect}") unless datum.is_a?(Hash) + valid &&= datum.is_a?(Hash) valid &&= formats_kernel(datum, value, false, strict) else p "#{key.inspect} not #{value.inspect}: #{datum.inspect}" unless datum.is_a?(value) diff --git a/tests/helpers/formats_helper_tests.rb b/tests/helpers/formats_helper_tests.rb index <HASH>..<HASH> 100644 --- a/tests/helpers/formats_helper_tests.rb +++ b/tests/helpers/formats_helper_tests.rb @@ -40,6 +40,15 @@ Shindo.tests('test_helper', 'meta') do !formats_kernel({}, {:a => String}) end + test('when an array is expected but another data type is found') do + !formats_kernel({:a => 'not an array'}, {:a => []}) + end + + test('when a hash is expected but another data type is found') do + !formats_kernel({:a => 'not a hash'}, {:a => {}}, true, false) + end + + test('non strict extra data') do !formats_kernel({:a => :b, :b => :c}, {:z => Symbol}, true, false) end
[Core] fix format_helper assuming p returns nil on ruby <I> it returns the printed string so x = foo || p("foo was false") always evaluates to something truthy
fog_fog
train
a12aa8434966ae50e46fa8dc6d697f27ee54b32a
diff --git a/enforcer/datapath_tcp.go b/enforcer/datapath_tcp.go index <HASH>..<HASH> 100644 --- a/enforcer/datapath_tcp.go +++ b/enforcer/datapath_tcp.go @@ -342,8 +342,8 @@ func (d *Datapath) processApplicationSynAckPacket(tcpPacket *packet.Packet, cont ) } - err1 := d.netOrigConnectionTracker.Remove(tcpPacket.L4FlowHash()) - err2 := d.appReplyConnectionTracker.Remove(tcpPacket.L4ReverseFlowHash()) + err1 := d.netOrigConnectionTracker.Remove(tcpPacket.L4ReverseFlowHash()) + err2 := d.appReplyConnectionTracker.Remove(tcpPacket.L4FlowHash()) if err1 != nil || err2 != nil { zap.L().Debug("Failed to remove cache entries") diff --git a/enforcer/lookup/lookup_test.go b/enforcer/lookup/lookup_test.go index <HASH>..<HASH> 100644 --- a/enforcer/lookup/lookup_test.go +++ b/enforcer/lookup/lookup_test.go @@ -47,6 +47,24 @@ var ( Operator: policy.KeyNotExists, } + vulnerKey = policy.KeyValueOperator{ + Key: "vulnerability", + Value: []string{"high"}, + Operator: policy.Equal, + } + + vulnerLowKey = policy.KeyValueOperator{ + Key: "vulnerability", + Value: []string{"low"}, + Operator: policy.Equal, + } + + namespaceKey = policy.KeyValueOperator{ + Key: "namespace", + Value: []string{"/a/b/*"}, + Operator: policy.Equal, + } + appEqWebAndenvEqDemo = policy.TagSelector{ Clause: []policy.KeyValueOperator{appEqWeb, envEqDemo}, Policy: &policy.FlowPolicy{Action: policy.Accept}, @@ -77,6 +95,16 @@ var ( Policy: &policy.FlowPolicy{Action: policy.Accept}, } + vulnTagPolicy = policy.TagSelector{ + Clause: []policy.KeyValueOperator{vulnerKey}, + Policy: &policy.FlowPolicy{Action: policy.Accept}, + } + + policyNamespace = policy.TagSelector{ + Clause: []policy.KeyValueOperator{namespaceKey, vulnerLowKey}, + Policy: &policy.FlowPolicy{Action: policy.Accept}, + } + domainParent = policy.KeyValueOperator{ Key: "domain", Value: []string{"com.example.*", "com.*", "com.longexample.*", "com.ex.*"}, @@ -196,6 +224,8 @@ func TestFuncSearch(t *testing.T) { // policy7: domain IN ("com.*", "com.example.*") // policy8: domain=com.example.web // policy9: env doesn't exist + // policy10: vulnerability=high + // policy11: namespace=/a/b/* and vulnerability=low Convey("Given an empty policyDB", t, func() { policyDB := NewPolicyDB() @@ -209,6 +239,8 @@ func TestFuncSearch(t *testing.T) { index7 := policyDB.AddPolicy(policyDomainParent) index8 := policyDB.AddPolicy(policyDomainFull) index9 := policyDB.AddPolicy(policyEnvDoesNotExist) + index10 := policyDB.AddPolicy(vulnTagPolicy) + index11 := policyDB.AddPolicy(policyNamespace) So(index1, ShouldEqual, 1) So(index2, ShouldEqual, 2) @@ -218,6 +250,36 @@ func TestFuncSearch(t *testing.T) { So(index6, ShouldEqual, 6) So(index9, ShouldEqual, 9) + Convey("The vulnerability tag policy should match", func() { + tags := policy.NewTagStore() + tags.AppendKeyValue("vulnerability", "high") + + index, action := policyDB.Search(tags) + So(index, ShouldEqual, index10) + So(action.(*policy.FlowPolicy).Action, ShouldEqual, policy.Accept) + }) + + Convey("A policy that matches only the namespace, shoud not match", func() { + tags := policy.NewTagStore() + tags.AppendKeyValue("namespace", "/a/b/c/d") + tags.AppendKeyValue("env", "privatedemo") + + index, action := policyDB.Search(tags) + So(action, ShouldBeNil) + So(index, ShouldEqual, -1) + }) + + Convey("A policy that matches namespace and vulnerability low, shoud match", func() { + tags := policy.NewTagStore() + tags.AppendKeyValue("namespace", "/a/b/c/d") + tags.AppendKeyValue("vulnerability", "low") + tags.AppendKeyValue("env", "privatedemo") + + index, action := policyDB.Search(tags) + So(action, ShouldNotBeNil) + So(index, ShouldEqual, index11) + }) + Convey("Given that I search for a single matching that matches the equal rules, it should return the correct index,", func() { tags := policy.NewTagStore() tags.AppendKeyValue("app", "web")
Fix: cleaning the wrong cache, and improve lookup tests (#<I>) * Fix: cleaning the wrong cache, and improve lookup tests
aporeto-inc_trireme-lib
train
c64ce932245a2d025560ef865120dfe38a5a59cb
diff --git a/src/components/Calendar.js b/src/components/Calendar.js index <HASH>..<HASH> 100644 --- a/src/components/Calendar.js +++ b/src/components/Calendar.js @@ -129,7 +129,7 @@ class Calendar extends React.Component { type='caret-left' /> <div> - {moment(this.state.currentDate, 'X').format('MMMM YYYY')} + {moment.unix(this.state.currentDate).format('MMMM YYYY')} </div> <Icon elementProps={{ diff --git a/src/components/DateRangePicker/Selector.js b/src/components/DateRangePicker/Selector.js index <HASH>..<HASH> 100644 --- a/src/components/DateRangePicker/Selector.js +++ b/src/components/DateRangePicker/Selector.js @@ -78,7 +78,7 @@ class MonthSelector extends React.Component { return ( <Selector {...this.props} - currentDate={moment(this.props.currentDate, 'X').format('MMMM')} + currentDate={moment.unix(this.props.currentDate).format('MMMM')} handleNextClick={this._handleNextClick} handlePreviousClick={this._handlePreviousClick} style={styles.monthSelector} @@ -117,7 +117,7 @@ class YearSelector extends React.Component { return ( <Selector {...this.props} - currentDate={moment(this.props.currentDate, 'X').format('YYYY')} + currentDate={moment.unix(this.props.currentDate).format('YYYY')} handleNextClick={this._handleNextClick} handlePreviousClick={this._handlePreviousClick} />
Remove old moment instantiations. They don't work when the default timezone is UTC.
mxenabled_mx-react-components
train
b1381eec8d09b71ec653733b9135edfc648885bd
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -91,7 +91,7 @@ http://<thumbor-server>/300x200/smart/s.glbimg.com/et/bb/f/original/2011/03/24/V }, install_requires=[ - "tornado>=2.1.1,<3.2.0", + "tornado>=2.1.1,<3.3.0", "pyCrypto>=2.1.0", "pycurl>=7.19.0,<7.20.0", "Pillow>=2.1.0,<2.4.0",
Updated tornado to the latest version. Fixes #<I>.
thumbor_thumbor
train
85717fb33d9781c3576260f60aebfa2184aee52e
diff --git a/library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadUtils.java b/library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadUtils.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadUtils.java +++ b/library/src/main/java/com/liulishuo/filedownloader/util/FileDownloadUtils.java @@ -39,6 +39,7 @@ import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; +import java.net.URLDecoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; @@ -393,11 +394,12 @@ public class FileDownloadUtils { + INTERNAL_DOCUMENT_NAME, OLD_FILE_CONVERTED_FILE_NAME); } - private static final Pattern CONTENT_DISPOSITION_QUOTED_PATTERN = - Pattern.compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\""); + // note on https://tools.ietf.org/html/rfc5987 + private static final Pattern CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN = + Pattern.compile("attachment;\\s*filename\\*\\s*=\\s*\"*([^\"]*)'\\S*'([^\"]*)\"*"); // note on http://www.ietf.org/rfc/rfc1806.txt - private static final Pattern CONTENT_DISPOSITION_NON_QUOTED_PATTERN = - Pattern.compile("attachment;\\s*filename\\s*=\\s*(.*)"); + private static final Pattern CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN = + Pattern.compile("attachment;\\s*filename\\s*=\\s*\"*([^\"\\n]*)\"*"); public static long parseContentRangeFoInstanceLength(String contentRange) { if (contentRange == null) return -1; @@ -429,16 +431,18 @@ public class FileDownloadUtils { } try { - Matcher m = CONTENT_DISPOSITION_QUOTED_PATTERN.matcher(contentDisposition); + Matcher m = CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN.matcher(contentDisposition); if (m.find()) { - return m.group(1); + String charset = m.group(1); + String encodeFileName = m.group(2); + return URLDecoder.decode(encodeFileName, charset); } - m = CONTENT_DISPOSITION_NON_QUOTED_PATTERN.matcher(contentDisposition); + m = CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN.matcher(contentDisposition); if (m.find()) { return m.group(1); } - } catch (IllegalStateException ex) { + } catch (IllegalStateException | UnsupportedEncodingException ignore) { // This function is defined as returning null when it can't parse the header } return null; diff --git a/library/src/test/java/com/liulishuo/filedownloader/util/FileDownloadUtilsTest.java b/library/src/test/java/com/liulishuo/filedownloader/util/FileDownloadUtilsTest.java index <HASH>..<HASH> 100644 --- a/library/src/test/java/com/liulishuo/filedownloader/util/FileDownloadUtilsTest.java +++ b/library/src/test/java/com/liulishuo/filedownloader/util/FileDownloadUtilsTest.java @@ -43,6 +43,20 @@ public class FileDownloadUtilsTest { filename = FileDownloadUtils .parseContentDisposition("attachment; filename=genome.jpeg\nabc"); assertThat(filename).isEqualTo("genome.jpeg"); + filename = FileDownloadUtils + .parseContentDisposition( + "attachment; filename*=\"gb2312''%d4%b4%ce%c4%bc%fe.mp3\""); + assertThat(filename).isEqualTo("源文件.mp3"); + filename = FileDownloadUtils + .parseContentDisposition("attachment; filename*=gb2312''%d4%b4%ce%c4%bc%fe.mp3"); + assertThat(filename).isEqualTo("源文件.mp3"); + filename = FileDownloadUtils + .parseContentDisposition( + "attachment; filename*=\"UTF-8''%e6%ba%90%e6%96%87%e4%bb%b6.mp3\""); + assertThat(filename).isEqualTo("源文件.mp3"); + filename = FileDownloadUtils + .parseContentDisposition("attachment;filename*=\"UTF8''1.mp3\""); + assertThat(filename).isEqualTo("1.mp3"); } @Test @@ -70,7 +84,8 @@ public class FileDownloadUtilsTest { assertThat(length).isEqualTo(-1); } - @Rule public ExpectedException thrown = ExpectedException.none(); + @Rule + public ExpectedException thrown = ExpectedException.none(); @Test public void findFilename_securityIssue() throws FileDownloadSecurityException {
refactor: support character set and language Encoding for Content-Disposition refer to <URL>
lingochamp_FileDownloader
train
359f9c0643b4ec26b7c308e6b45d9c8f170728c2
diff --git a/lib/pluckers/base.rb b/lib/pluckers/base.rb index <HASH>..<HASH> 100644 --- a/lib/pluckers/base.rb +++ b/lib/pluckers/base.rb @@ -51,7 +51,7 @@ module Pluckers build_results # And return the results - @results + @results.values end ## @@ -60,8 +60,9 @@ module Pluckers # in adding some behaviour. def configure_query @query_to_pluck = @records - @attributes_to_pluck = [] - @results = [] + @attributes_to_pluck = [{ name: @query_to_pluck.primary_key.to_sym, sql: @query_to_pluck.primary_key }] + @results = {} + @klass_reflections = @query_to_pluck.reflections.with_indifferent_access end ## @@ -92,8 +93,8 @@ module Pluckers # :title=>"Test title 1", :text=>"Test text 1"} attributes_to_return = Hash[names_to_pluck.zip(record)] - # Now we store it in the results array - @results << attributes_to_return + # Now we store it in the results hash + @results[attributes_to_return[:id]] = attributes_to_return end end diff --git a/test/pluckers/simple_attributes_test.rb b/test/pluckers/simple_attributes_test.rb index <HASH>..<HASH> 100644 --- a/test/pluckers/simple_attributes_test.rb +++ b/test/pluckers/simple_attributes_test.rb @@ -40,6 +40,7 @@ class SimpleAttributesTest < Minitest::Test must pluck Proc.new {|p| { + id: p.id, text: p.text } }
Changes required for being able to handle relationships The include storing the reflections for the plucker and plucking ids by default
simplelogica_pluckers
train
84b1198d780b1b539802f8f8bfa092888aa7c03c
diff --git a/scripts/constants.py b/scripts/constants.py index <HASH>..<HASH> 100644 --- a/scripts/constants.py +++ b/scripts/constants.py @@ -15,10 +15,10 @@ import sys # Kubernetes branch to get the OpenAPI spec from. -KUBERNETES_BRANCH = "release-1.12" +KUBERNETES_BRANCH = "release-1.13" # client version for packaging and releasing. -CLIENT_VERSION = "8.0.0-snapshot" +CLIENT_VERSION = "9.0.0-snapshot" # Name of the release package PACKAGE_NAME = "kubernetes"
Update version constants for k8s <I> release snapshot
kubernetes-client_python
train
6244095c81e631b45b8617a414a43f7096aaa89b
diff --git a/languagetool-dev/src/main/java/org/languagetool/dev/diff/RuleMatchDiffFinder.java b/languagetool-dev/src/main/java/org/languagetool/dev/diff/RuleMatchDiffFinder.java index <HASH>..<HASH> 100644 --- a/languagetool-dev/src/main/java/org/languagetool/dev/diff/RuleMatchDiffFinder.java +++ b/languagetool-dev/src/main/java/org/languagetool/dev/diff/RuleMatchDiffFinder.java @@ -194,7 +194,14 @@ public class RuleMatchDiffFinder { String title = "Comparing " + file1.getName() + " to " + file2.getName(); System.out.println(title); List<RuleMatchDiff> diffs = getDiffs(l1, l2); - diffs.sort(Comparator.comparing(this::getFullId)); + diffs.sort((k, j) -> { + int idDiff = getFullId(k).compareTo(getFullId(j)); + if (idDiff == 0) { + return k.getStatus().compareTo(j.getStatus()); + } + return idDiff; + } + ); System.out.println("Total diffs found: " + diffs.size()); Map<String, List<RuleMatchDiff>> keyToDiffs = groupDiffs(diffs); List<OutputFile> outputFiles = new ArrayList<>();
sort result by ADD/MOD/REM to improve readability
languagetool-org_languagetool
train
f587631d14fd9398b932a7095fd2cfa730ee1cbd
diff --git a/identity.go b/identity.go index <HASH>..<HASH> 100644 --- a/identity.go +++ b/identity.go @@ -94,15 +94,18 @@ func GetActiveIdentityKeysAtHeight(chainID string, height int64) ([]string, erro } var activeKeys []*IdentityKey - retiredKeys := make(map[[32]byte]bool) + allKeys := make(map[string]bool) for _, pubString := range identityInfo.InitialKeys { if IdentityKeyStringType(pubString) != IDPub { return nil, fmt.Errorf("invalid identity public key string in first entry: %s", pubString) + } else if _, present := allKeys[pubString]; present { + continue } pub := base58.Decode(pubString) k := NewIdentityKey() copy(k.Pub[:], pub[IDKeyPrefixLength:IDKeyBodyLength]) activeKeys = append(activeKeys, k) + allKeys[pubString] = true } for _, e := range entries { @@ -129,8 +132,8 @@ func GetActiveIdentityKeysAtHeight(chainID string, height int64) ([]string, erro b = base58.Decode(newPubString) copy(newKey[:], b[IDKeyPrefixLength:IDKeyBodyLength]) - // Disallow putting old keys back into rotation - if _, present := retiredKeys[newKey]; present { + // Disallow re-adding retired or currently active keys + if _, present := allKeys[newPubString]; present { continue } @@ -157,7 +160,7 @@ func GetActiveIdentityKeysAtHeight(chainID string, height int64) ([]string, erro } if key.PubString() == signerPubString && ed.Verify(key.Pub, message, &signature) { activeKeys[levelToReplace].Pub = &newKey - retiredKeys[oldKey] = true + allKeys[newPubString] = true break } }
FD-<I> add explicit rule that no identity key can be exist within the key hierarchy more than once
FactomProject_factom
train
1d338a95ec23037d2e147215e227764889a4fc29
diff --git a/lib/elastomer/client/multi_percolate.rb b/lib/elastomer/client/multi_percolate.rb index <HASH>..<HASH> 100644 --- a/lib/elastomer/client/multi_percolate.rb +++ b/lib/elastomer/client/multi_percolate.rb @@ -80,8 +80,7 @@ module Elastomer # # Returns this MultiPercolate instance. def percolate(doc, header = {}) - merged = @params.merge(header) - add_to_actions(:percolate => merged) + add_to_actions(:percolate => @params.merge(header)) add_to_actions(:doc => doc) end @@ -94,8 +93,7 @@ module Elastomer # # Returns this MultiPercolate instance. def count(doc, header = {}) - merged = @params.merge(header) - add_to_actions(:count => merged) + add_to_actions(:count => @params.merge(header)) add_to_actions(:doc => doc) end
post-review update: group params merge into add_to_action calls
github_elastomer-client
train
c061b2b610564c9322175a188c8ff2536b874ed9
diff --git a/holoviews/plotting/bokeh/chart.py b/holoviews/plotting/bokeh/chart.py index <HASH>..<HASH> 100644 --- a/holoviews/plotting/bokeh/chart.py +++ b/holoviews/plotting/bokeh/chart.py @@ -959,6 +959,7 @@ class BoxWhiskerPlot(CompositeElementPlot, ColorbarPlot, LegendPlot): else: factors = [tuple(d.pprint_value(v) for d, v in zip(element.kdims, key)) for key in element.groupby(element.kdims).data.keys()] + factors = [f[0] if len(f) == 1 else f for f in factors] if self.invert_axes: return [], factors else: @@ -1008,6 +1009,8 @@ class BoxWhiskerPlot(CompositeElementPlot, ColorbarPlot, LegendPlot): for d, v in zip(element.kdims, key)]) else: label = tuple(d.pprint_value(v) for d, v in zip(element.kdims, key)) + if len(label) == 1: + label = label[0] else: label = key
Fix for bokeh BoxWhiskerPlot category factor handling (#<I>)
pyviz_holoviews
train
f6dbde40de409898a2a38c7ed87350fc7a18a06d
diff --git a/src/tabris/Device.js b/src/tabris/Device.js index <HASH>..<HASH> 100644 --- a/src/tabris/Device.js +++ b/src/tabris/Device.js @@ -9,10 +9,6 @@ export default class Device extends NativeObject { } } - _setProperty() { - // prevent overwriting properties - } - _listen(name, listening) { if (name === 'change:orientation') { this._nativeListen('orientationchange', listening); @@ -36,16 +32,16 @@ export default class Device extends NativeObject { } NativeObject.defineProperties(Device.prototype, { - model: 'any', - platform: 'any', - version: 'any', - language: 'any', - orientation: 'any', - screenWidth: 'any', - screenHeight: 'any', - scaleFactor: 'any', - win_keyboardPresent: 'any', - win_primaryInput: 'any' + model: {type: 'any', readonly: true}, + platform: {type: 'any', readonly: true}, + version: {type: 'any', readonly: true}, + language: {type: 'any', readonly: true}, + orientation: {type: 'any', readonly: true}, + screenWidth: {type: 'any', readonly: true}, + screenHeight: {type: 'any', readonly: true}, + scaleFactor: {type: 'any', readonly: true}, + win_keyboardPresent: {type: 'any', readonly: true}, + win_primaryInput: {type: 'any', readonly: true} }); export function create() { diff --git a/src/tabris/NativeObject.js b/src/tabris/NativeObject.js index <HASH>..<HASH> 100644 --- a/src/tabris/NativeObject.js +++ b/src/tabris/NativeObject.js @@ -17,10 +17,10 @@ export default class NativeObject extends EventsClass { target['$prop_' + name] = normalizeProperty(definition); Object.defineProperty(target, name, { set(value) { - this._setProperty(name, value); + this.$setProperty(name, value); }, get() { - return this._getProperty(name); + return this.$getProperty(name); } }); } @@ -61,17 +61,17 @@ export default class NativeObject extends EventsClass { return this[name]; } - _getProperty(name) { + $getProperty(name) { if (this._isDisposed) { console.warn('Cannot get property "' + name + '" on disposed object'); return; } - let getter = this._getPropertyGetter(name) || this._getStoredProperty; + let getter = this.$getPropertyGetter(name) || this._getStoredProperty; let value = getter.call(this, name); return this._decodeProperty(this._getTypeDef(name), value); } - _setProperty(name, value) { + $setProperty(name, value) { if (this._isDisposed) { console.warn('Cannot set property "' + name + '" on disposed object'); return; @@ -84,7 +84,7 @@ export default class NativeObject extends EventsClass { console.warn(this + ': Ignored unsupported value for property "' + name + '": ' + ex.message); return; } - let setter = this._getPropertySetter(name) || this._storeProperty; + let setter = this.$getPropertySetter(name) || this._storeProperty; setter.call(this, name, encodedValue); } @@ -130,12 +130,12 @@ export default class NativeObject extends EventsClass { return (typeDef && typeDef.decode) ? typeDef.decode(value) : value; } - _getPropertyGetter(name) { + $getPropertyGetter(name) { let prop = this['$prop_' + name]; return prop ? prop.get : undefined; } - _getPropertySetter(name) { + $getPropertySetter(name) { let prop = this['$prop_' + name]; return prop ? prop.set : undefined; }
Properly define device properties read-only Instead of overwriting the internal method _setProperty(), add the readonly flag to the property definitions. Prefix _getProperties() and _setProperties() methods in NativeOject with `$` to mark them as private. They are not used anywhere else. Change-Id: I<I>edfd<I>bb<I>c<I>e<I>f<I>e9ee3e<I>
eclipsesource_tabris-js
train
a854ce5fb0647ff68b1f3cdeadcea9e52842ec04
diff --git a/lib/catalogs.py b/lib/catalogs.py index <HASH>..<HASH> 100644 --- a/lib/catalogs.py +++ b/lib/catalogs.py @@ -349,10 +349,17 @@ class UserCatalog(Catalog): def set_colnames(self): self.colnames = [] + + cnum = 1 for cname in self.COLNAMES: - if cname not in self.pars: - break - self.colnames.append(self.pars[cname]) + if cname in self.pars and not util.is_blank(self.pars[cname]): + self.colnames.append(self.pars[cname]) + else: + # Insure that at least x and y columns had default values + if 'fluxcol' not in cname: + self.colnames.append(str(cnum)) + cnum += 1 + # count the number of columns self.numcols = len(self.colnames) diff --git a/lib/pars/tweakreg.cfgspc b/lib/pars/tweakreg.cfgspc index <HASH>..<HASH> 100644 --- a/lib/pars/tweakreg.cfgspc +++ b/lib/pars/tweakreg.cfgspc @@ -19,8 +19,8 @@ outwcs = string_kw(default='shifts_wcs.fits',comment="Filename of shiftfile refe [COORDINATE FILE DESCRIPTION] catfile = string_kw(default="", triggers="_section_switch_", comment="File containing coordinate filenames for input files") -xcol = string_kw(default="", comment= "Column name for X positions") -ycol = string_kw(default="", comment= "Column name for Y positions") +xcol = string_kw(default="c1", comment= "Column name for X positions") +ycol = string_kw(default="c2", comment= "Column name for Y positions") fluxcol = string_kw(default="", comment= "Column name for source flux/mag values") fluxmax = float_or_none_kw(default=None,comment="Maximum flux value for valid objects") fluxmin = float_or_none_kw(default=None,comment="Minimum flux value for valid objects") diff --git a/lib/tweakutils.py b/lib/tweakutils.py index <HASH>..<HASH> 100644 --- a/lib/tweakutils.py +++ b/lib/tweakutils.py @@ -191,7 +191,7 @@ def read_ASCII_cols(infile,cols=[1,2,3,4]): cname = colname colnums.append(int(cname)-1) c = [] - if colnums[1] - colnums[0] > 1: + if (colnums[1] - colnums[0]) > 1: cnum = range(colnums[0],colnums[1]) c.extend(cnum) cnum = range(colnums[1],colnums[1]+(colnums[1]-colnums[0])) diff --git a/lib/updatehdr.py b/lib/updatehdr.py index <HASH>..<HASH> 100644 --- a/lib/updatehdr.py +++ b/lib/updatehdr.py @@ -124,10 +124,8 @@ def updatewcs_with_shift(image,reference,wcsname=None,rot=0.0,scale=1.0,xsh=0.0, fimg.close() update_refchip_with_shift(chip_wcs,wref,rot=rot,scale=scale,xsh=xsh,ysh=ysh) - if wcsname is None or wcsname == 'TWEAK': - wcsname = 'TWEAK_'+fileutil.getDate() - elif wcsname == '': - wcsname = ' ' + if wcsname in [None,' ','','INDEF']: + wcsname = 'TWEAK' # step 8 # Update the 'O' WCS (OPUS generated values) in the header
Default values for X and Y columns were implemented for 'tweakreg' user catalogs. The default value in .cfgspc for these parameter was also reset from '' to 'c1' and 'c2'. Finally, when 'wcsname' is not provided (blank or INDEF), a default of 'TWEAK' gets defined for use. git-svn-id: <URL>
spacetelescope_drizzlepac
train
97e38bddc882799426b0495cb01c754935362f06
diff --git a/cmd/util.go b/cmd/util.go index <HASH>..<HASH> 100644 --- a/cmd/util.go +++ b/cmd/util.go @@ -50,8 +50,11 @@ func currentBackend() (backend.Backend, error) { func commandContext() context.Context { ctx := context.Background() - if cmdutil.TracingRootSpan != nil { - ctx = opentracing.ContextWithSpan(ctx, cmdutil.TracingRootSpan) + if cmdutil.IsTracingEnabled() { + if cmdutil.TracingRootSpan != nil { + ctx = opentracing.ContextWithSpan(ctx, cmdutil.TracingRootSpan) + } + ctx = backend.ContextWithTracingOptions(ctx, backend.TracingOptions{PropagateSpans: true}) } return ctx } diff --git a/pkg/backend/backend.go b/pkg/backend/backend.go index <HASH>..<HASH> 100644 --- a/pkg/backend/backend.go +++ b/pkg/backend/backend.go @@ -115,3 +115,25 @@ type CancellationScopeSource interface { // NewScope creates a new cancellation scope. NewScope(events chan<- engine.Event, isPreview bool) CancellationScope } + +// tracingOptionsKey is the value used as the context key for TracingOptions. +var tracingOptionsKey struct{} + +// TracingOptions describes the set of options available for configuring tracing on a per-request basis. +type TracingOptions struct { + // PropagateSpans indicates that spans should be propagated from the client to the Pulumi service when making API + // calls. + PropagateSpans bool +} + +// ContextWithTracingOptions returns a new context.Context with the indicated tracing options. +func ContextWithTracingOptions(ctx context.Context, opts TracingOptions) context.Context { + return context.WithValue(ctx, tracingOptionsKey, opts) +} + +// TracingOptionsFromContext retrieves any tracing options present in the given context. If no options are present, +// this function returns the zero value. +func TracingOptionsFromContext(ctx context.Context) TracingOptions { + opts, _ := ctx.Value(tracingOptionsKey).(TracingOptions) + return opts +} diff --git a/pkg/backend/cloud/client/api.go b/pkg/backend/cloud/client/api.go index <HASH>..<HASH> 100644 --- a/pkg/backend/cloud/client/api.go +++ b/pkg/backend/cloud/client/api.go @@ -18,6 +18,7 @@ import ( "github.com/pkg/errors" "github.com/pulumi/pulumi/pkg/apitype" + "github.com/pulumi/pulumi/pkg/backend" "github.com/pulumi/pulumi/pkg/util/contract" "github.com/pulumi/pulumi/pkg/util/httputil" "github.com/pulumi/pulumi/pkg/version" @@ -137,6 +138,14 @@ func pulumiAPICall(ctx context.Context, cloudAPI, method, path string, body []by req.Header.Set("Authorization", fmt.Sprintf("%s %s", tok.Kind(), tok.String())) } + tracingOptions := backend.TracingOptionsFromContext(requestContext) + if tracingOptions.PropagateSpans { + carrier := opentracing.HTTPHeadersCarrier(req.Header) + if err = requestSpan.Tracer().Inject(requestSpan.Context(), opentracing.HTTPHeaders, carrier); err != nil { + glog.Errorf("injecting tracing headers: %v", err) + } + } + glog.V(7).Infof("Making Pulumi API call: %s", url) if glog.V(9) { glog.V(9).Infof("Pulumi API call details (%s): headers=%v; body=%v", url, req.Header, string(body)) diff --git a/pkg/util/cmdutil/trace.go b/pkg/util/cmdutil/trace.go index <HASH>..<HASH> 100644 --- a/pkg/util/cmdutil/trace.go +++ b/pkg/util/cmdutil/trace.go @@ -16,6 +16,10 @@ var TracingRootSpan opentracing.Span var traceCloser io.Closer +func IsTracingEnabled() bool { + return TracingEndpoint != "" +} + // InitTracing initializes tracing func InitTracing(name, rootSpanName, tracingEndpoint string) { // If no tracing endpoint was provided, just return. The default global tracer is already a no-op tracer. @@ -57,7 +61,7 @@ func InitTracing(name, rootSpanName, tracingEndpoint string) { // CloseTracing ensures that all pending spans have been flushed. It should be called before process exit. func CloseTracing() { - if TracingEndpoint == "" { + if !IsTracingEnabled() { return }
Enable distributed tracing. These changes add support for injecting client tracing spans into HTTP requests to the Pulumi API. The server can then rematerialize these span references and attach its own spans for distributed tracing.
pulumi_pulumi
train
a97f299b2c70146ed57ad4c69ed7685b43c5f1b7
diff --git a/src/main/java/com/authlete/common/dto/TokenResponse.java b/src/main/java/com/authlete/common/dto/TokenResponse.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/authlete/common/dto/TokenResponse.java +++ b/src/main/java/com/authlete/common/dto/TokenResponse.java @@ -996,13 +996,16 @@ public class TokenResponse extends ApiResponse /** - * Get the resources specified by the {@code resource} request parameters. + * Get the resources specified by the {@code resource} request parameters + * in the token request. + * + * <p> * See <i>"Resource Indicators for OAuth 2.0"</i> for details. + * </p> * * @return - * Target resources. - * - * @see #getAccessTokenResources() + * Resources specified by the {@code resource} request parameters + * in the token request. * * @since 2.62 */ @@ -1013,13 +1016,16 @@ public class TokenResponse extends ApiResponse /** - * Set the resources specified by the {@code resource} request parameters. + * Set the resources specified by the {@code resource} request parameters + * in the token request. + * + * <p> * See <i>"Resource Indicators for OAuth 2.0"</i> for details. + * </p> * * @param resources - * Target resources. - * - * @see #setAccessTokenResources(URI[]) + * Resources specified by the {@code resource} request parameters + * in the token request. * * @since 2.62 */ @@ -1030,27 +1036,7 @@ public class TokenResponse extends ApiResponse /** - * Get the target resources of the access token. - * - * <p> - * The target resources returned by this method may be the same as or - * different from the ones returned by {@link #getResources()}. - * </p> - * - * <p> - * In some flows, the initial request and the subsequent token request - * are sent to different endpoints. Example flows are the Authorization - * Code Flow, the Refresh Token Flow, the CIBA Ping Mode, the CIBA Poll - * Mode and the Device Flow. In these flows, not only the initial request - * but also the subsequent token request can include the {@code resource} - * request parameters. The purpose of the {@code resource} request - * parameters in the token request is to narrow the range of the target - * resources from the original set of target resources requested by the - * preceding initial request. If narrowing down is performed, the target - * resources returned by {@link #getResources()} and the ones returned by - * this method are different. This method returns the narrowed set of - * target resources. - * </p> + * Get the target resources of the access token being issued. * * <p> * See "Resource Indicators for OAuth 2.0" for details. @@ -1059,8 +1045,6 @@ public class TokenResponse extends ApiResponse * @return * The target resources of the access token. * - * @see #getResources() - * * @since 2.62 */ public URI[] getAccessTokenResources() @@ -1070,18 +1054,15 @@ public class TokenResponse extends ApiResponse /** - * Set the target resources of the access token. + * Set the target resources of the access token being issued. * * <p> - * See the description of {@link #getAccessTokenResources()} for details - * about the target resources of the access token. + * See "Resource Indicators for OAuth 2.0" for details. * </p> * * @param resources * The target resources of the access token. * - * @see #setResources(URI[]) - * * @since 2.62 */ public void setAccessTokenResources(URI[] resources)
Fixed JavaDoc of TokenResponse class.
authlete_authlete-java-common
train
a0a0bea427e96781397bddbf5012198c23747005
diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java index <HASH>..<HASH> 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java @@ -101,8 +101,7 @@ public class LdapAutoConfigurationTests { @Test public void templateExists() { this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:389") - .run(context -> assertThat( - context.getBeanNamesForType(LdapTemplate.class)).hasSize(1)); + .run(context -> assertThat(context).hasSingleBean(LdapTemplate.class)); } }
Polish "Improve LDAP auto-configuration" Closes gh-<I>
spring-projects_spring-boot
train
1f92958e1f2cf5f6836a9efa7df1a3f0bfe02935
diff --git a/errors/components/header.php b/errors/components/header.php index <HASH>..<HASH> 100644 --- a/errors/components/header.php +++ b/errors/components/header.php @@ -1,14 +1,12 @@ <h1> <?php - $paths = array(); + if (!isset($paths)) { - if (defined('FCPATH') && defined('BASE_URL')) { + $paths = array(); + } - $paths[] = array( - FCPATH . 'assets/img/error_fatal.png', - BASE_URL . 'assets/img/error_fatal.png' - ); + if (defined('FCPATH') && defined('BASE_URL')) { $paths[] = array( FCPATH . 'assets/img/logo.png', diff --git a/errors/error_404.php b/errors/error_404.php index <HASH>..<HASH> 100644 --- a/errors/error_404.php +++ b/errors/error_404.php @@ -15,6 +15,15 @@ <div id="container"> <?php + if (defined('FCPATH') && defined('BASE_URL')) { + + $paths = array(); + $paths[] = array( + FCPATH . 'assets/img/errors/404.png', + BASE_URL . 'assets/img/errors/404.png' + ); + } + include NAILS_COMMON_PATH . 'errors/components/header.php'; echo $message; diff --git a/errors/error_db.php b/errors/error_db.php index <HASH>..<HASH> 100644 --- a/errors/error_db.php +++ b/errors/error_db.php @@ -15,6 +15,15 @@ <div id="container"> <?php + if (defined('FCPATH') && defined('BASE_URL')) { + + $paths = array(); + $paths[] = array( + FCPATH . 'assets/img/errors/db.png', + BASE_URL . 'assets/img/errors/db.png' + ); + } + include NAILS_COMMON_PATH . 'errors/components/header.php'; echo $message; diff --git a/errors/error_fatal.php b/errors/error_fatal.php index <HASH>..<HASH> 100644 --- a/errors/error_fatal.php +++ b/errors/error_fatal.php @@ -15,6 +15,15 @@ <div id="container"> <?php + if (defined('FCPATH') && defined('BASE_URL')) { + + $paths = array(); + $paths[] = array( + FCPATH . 'assets/img/errors/fatal.png', + BASE_URL . 'assets/img/errors/fatal.png' + ); + } + include NAILS_COMMON_PATH . 'errors/components/header.php'; ?> diff --git a/errors/error_general.php b/errors/error_general.php index <HASH>..<HASH> 100644 --- a/errors/error_general.php +++ b/errors/error_general.php @@ -15,6 +15,15 @@ <div id="container"> <?php + if (defined('FCPATH') && defined('BASE_URL')) { + + $paths = array(); + $paths[] = array( + FCPATH . 'assets/img/errors/general.png', + BASE_URL . 'assets/img/errors/general.png' + ); + } + include NAILS_COMMON_PATH . 'errors/components/header.php'; echo $message; diff --git a/errors/startup_error.php b/errors/startup_error.php index <HASH>..<HASH> 100644 --- a/errors/startup_error.php +++ b/errors/startup_error.php @@ -15,6 +15,15 @@ <div id="container"> <?php + if (defined('FCPATH') && defined('BASE_URL')) { + + $paths = array(); + $paths[] = array( + FCPATH . 'assets/img/errors/startup.png', + BASE_URL . 'assets/img/errors/startup.png' + ); + } + include NAILS_COMMON_PATH . 'errors/components/header.php'; echo '<p>';
Error page updates Individual error pages can (and do) define image search paths.
nails_common
train
c997c100b60e55d8ad2c51013e68683d04ca1b83
diff --git a/src/mixins/event-handlers.js b/src/mixins/event-handlers.js index <HASH>..<HASH> 100644 --- a/src/mixins/event-handlers.js +++ b/src/mixins/event-handlers.js @@ -1,5 +1,5 @@ 'use strict'; -import {getTrackCSS, getTrackLeft} from './trackHelper'; +import {getTrackCSS, getTrackLeft, getTrackAnimateCSS} from './trackHelper'; import assign from 'object-assign'; var EventHandlers = { @@ -120,7 +120,15 @@ var EventHandlers = { this.slideHandler(this.state.currentSlide); } } else { - this.slideHandler(this.state.currentSlide); + // Adjust the track back to it's original position. + var currentLeft = getTrackLeft(assign({ + slideIndex: this.state.currentSlide, + trackRef: this.refs.track + }, this.props, this.state)); + + this.setState({ + trackStyle: getTrackAnimateCSS(assign({left: currentLeft}, this.props, this.state)) + }); } } };
:bug: fix slides not snap back when swipe doesn't cross threshold fixes #<I>
akiran_react-slick
train
38615687bd8d52d27caf4750e940b73245638cfc
diff --git a/example/image-classification/common/fit.py b/example/image-classification/common/fit.py index <HASH>..<HASH> 100644 --- a/example/image-classification/common/fit.py +++ b/example/image-classification/common/fit.py @@ -145,7 +145,8 @@ def fit(args, network, data_loader, **kwargs): optimizer_params = { 'learning_rate': lr, 'momentum' : args.mom, - 'wd' : args.wd} + 'wd' : args.wd, + 'lr_scheduler': lr_scheduler} monitor = mx.mon.Monitor(args.monitor, pattern=".*") if args.monitor > 0 else None @@ -178,4 +179,5 @@ def fit(args, network, data_loader, **kwargs): aux_params = aux_params, batch_end_callback = batch_end_callbacks, epoch_end_callback = checkpoint, + allow_missing = True, monitor = monitor)
add back lr_scheduler in classification example (#<I>)
apache_incubator-mxnet
train
84bdedccd287375690779105c00e2fddd4fed7d3
diff --git a/lib/voteable/voteable.rb b/lib/voteable/voteable.rb index <HASH>..<HASH> 100644 --- a/lib/voteable/voteable.rb +++ b/lib/voteable/voteable.rb @@ -1,11 +1,13 @@ module Voteable - def is_voteable(options = {}, &block) - has n, :votes, 'Voteable::Vote', :as => :voteable, :child_key => [ :voteable_id ] + def is_voteable(options = {}) + has n, :votes, 'Voteable::Vote', as: :voteable, child_key: [ :voteable_id ] - #if !options[:every_x_days].nil? - # Vote.instance_eval { @@x_days = 0; def x_days; @@x_days; end; def x_days=(value); @@x_days = (value); end } - # Vote.x_days = options[:every_x_days] - #end + if (!options[:time_between_votes].nil? && options[:time_between_votes].class == Proc) + class << self + attr_accessor :time_between_votes + end + self.time_between_votes = options[:time_between_votes] + end include Voteable::InstanceMethods end
Change interface for setting the time between interface. Now accept a proc.
brianp_dm-is-voteable
train
74d48481bfa77c073025258fd86d9d0de49a26bc
diff --git a/components/utils/scripts/elation.js b/components/utils/scripts/elation.js index <HASH>..<HASH> 100644 --- a/components/utils/scripts/elation.js +++ b/components/utils/scripts/elation.js @@ -1935,10 +1935,13 @@ elation.extend('require.batch', function(type, webroot) { return modname; } this.getnode = function(module) { - if (!this.nodes[module]) { - this.nodes[module] = new elation.require.node(module); + var mod = this.nodes[module]; + if (!module || module == 'CALLBACK') { + mod = new elation.require.node(module); + } else if (!this.nodes[module]) { + mod = this.nodes[module] = new elation.require.node(module); } - return this.nodes[module]; + return mod; } this.addrequires = function(requires, callback) { var modname = this.getcurrentmodule() || 'CALLBACK'; @@ -2066,6 +2069,13 @@ elation.extend('require.node', function(name, callback) { } this.init(); }); +elation.extend('require.debug', function() { + elation.require(['graph.d3', 'graph.force', 'ui.window'], function() { + this.debuggraph = elation.graph.force({}); + this.debuggraph.update(elation.requireactivebatchjs.batchnode); + this.debugwin = elation.ui.window({append: document.body, title: 'dependencies', content: this.debuggraph}); + }); +}); elation.extend("utils.escapeHTML", function(str) { var div = document.createElement('div');
Added elation.require.debug(), attempt to fix bad graph from reused nodes
jbaicoianu_elation
train
f68dc05dbd3c934409b18f7ad9084876ab2ec125
diff --git a/concrete/src/Attribute/Category/AbstractCategory.php b/concrete/src/Attribute/Category/AbstractCategory.php index <HASH>..<HASH> 100644 --- a/concrete/src/Attribute/Category/AbstractCategory.php +++ b/concrete/src/Attribute/Category/AbstractCategory.php @@ -4,14 +4,17 @@ namespace Concrete\Core\Attribute\Category; use Concrete\Core\Application\Application; use Concrete\Core\Attribute\AttributeValueInterface; +use Concrete\Core\Attribute\Category\SearchIndexer\StandardSearchIndexer; use Concrete\Core\Attribute\Category\SearchIndexer\StandardSearchIndexerInterface; use Concrete\Core\Attribute\Key\ImportLoader\StandardImportLoader; use Concrete\Core\Attribute\Key\RequestLoader\StandardRequestLoader; use Concrete\Core\Attribute\SetFactory; +use Concrete\Core\Attribute\TypeFactory; use Concrete\Core\Entity\Attribute\Key\Key; use Concrete\Core\Entity\Attribute\Type as AttributeType; use Concrete\Core\Entity\Package; use Doctrine\ORM\EntityManager; +use SimpleXMLElement; use Symfony\Component\HttpFoundation\Request; /** @@ -87,7 +90,7 @@ abstract class AbstractCategory implements CategoryInterface, StandardSearchInde */ public function getSearchIndexer() { - $indexer = $this->application->make('Concrete\Core\Attribute\Category\SearchIndexer\StandardSearchIndexer'); + $indexer = $this->application->make(StandardSearchIndexer::class); return $indexer; } @@ -207,7 +210,9 @@ abstract class AbstractCategory implements CategoryInterface, StandardSearchInde public function add($type, $key, $settings = null, $pkg = null) { if (is_string($type)) { - $type = \Concrete\Core\Attribute\Type::getByHandle($type); + $typeFactory = $this->application->make(TypeFactory::class); + /* @var TypeFactory $typeFactory */ + $type = $typeFactory->getByHandle($type); } // Legacy array support for $key @@ -226,7 +231,7 @@ abstract class AbstractCategory implements CategoryInterface, StandardSearchInde // Legacy support for third parameter which used to be package if ($settings instanceof Package || $settings instanceof \Concrete\Core\Package\Package) { $pkg = $settings; - unset($settings); + $settings = null; } if (!$settings) { @@ -262,7 +267,7 @@ abstract class AbstractCategory implements CategoryInterface, StandardSearchInde $manager = $this->getSetManager(); $factory = new SetFactory($this->entityManager); $set = $factory->getByID($asID); - if (is_object($set)) { + if ($set !== null) { $manager->addKey($set, $key); } } @@ -301,12 +306,12 @@ abstract class AbstractCategory implements CategoryInterface, StandardSearchInde * Import a new attribute key from a SimpleXMLElement instance. * * @param AttributeType $type the type of the attribute key to be created - * @param \SimpleXMLElement $element the SimpleXMLElement instance containing the data of the attribute key to be created + * @param SimpleXMLElement $element the SimpleXMLElement instance containing the data of the attribute key to be created * @param Package|null $package the entity of the package that's creating the attribute key (if applicable) * * @return \Concrete\Core\Entity\Attribute\Key\Key */ - public function import(AttributeType $type, \SimpleXMLElement $element, Package $package = null) + public function import(AttributeType $type, SimpleXMLElement $element, Package $package = null) { $key = $this->createAttributeKey(); $loader = $this->getImportLoader(); @@ -394,13 +399,15 @@ abstract class AbstractCategory implements CategoryInterface, StandardSearchInde */ public function deleteValue(AttributeValueInterface $attributeValue) { + /* @var \Concrete\Core\Entity\Attribute\Value\AbstractValue $attributeValue */ + // Handle legacy attributes with these three lines. $controller = $attributeValue->getAttributeKey()->getController(); $controller->setAttributeValue($attributeValue); $controller->deleteValue(); $genericValue = $attributeValue->getGenericValue(); - if (is_object($genericValue)) { + if ($genericValue !== null) { $genericValues = $this->getAttributeValueRepository()->findBy(['generic_value' => $genericValue]); if (count($genericValues) == 1) { $value = $attributeValue->getValueObject();
Avoid facade calls, avoid accessing unset variables, move to "use" statements the used classes
concrete5_concrete5
train
6a9839f4ed0bddfd14fb474756dcc5aba872fdbe
diff --git a/lib/template/config/initializers/database.rb b/lib/template/config/initializers/database.rb index <HASH>..<HASH> 100644 --- a/lib/template/config/initializers/database.rb +++ b/lib/template/config/initializers/database.rb @@ -2,7 +2,7 @@ database_setup_proc = lambda do |conn| # identify postgres connections coming from this process in pg_stat_activity process_identifier = ENV["DYNO"] || File.basename($0).gsub(/\W+/, "_") conn.execute "SET statement_timeout = '#{Config.database_timeout}s'" - conn.execute "SET application_name = #{process_identifier}" + conn.execute "SET application_name = '#{process_identifier}'" end Sequel.connect(Config.database_url,
have to wrap this in quotes too otherwise having issues with heroku dyno identifiers like web<I>
interagent_pliny
train
2727935078092801f36e11cef02e4e9c4ffecc71
diff --git a/openquake/engine/calculators/hazard/scenario/core.py b/openquake/engine/calculators/hazard/scenario/core.py index <HASH>..<HASH> 100644 --- a/openquake/engine/calculators/hazard/scenario/core.py +++ b/openquake/engine/calculators/hazard/scenario/core.py @@ -127,7 +127,10 @@ class ScenarioHazardCalculator(haz_general.BaseHazardCalculator): latter piece basically defines the work to be done in the `execute` phase.) """ - # if you don't use a transaction, errors will be eaten + # if you don't use a transaction, errors will be masked + # i.e. from wrong queries you could get errors such as + # "cannot rollback" "failed transaction" instead of the + # real error message with transaction.commit_on_success(using='job_init'): self.parse_risk_models() with transaction.commit_on_success(using='job_init'):
Improved another comment Former-commit-id: f<I>a<I>edf<I>f7d<I>ed<I>a9d<I>c5df
gem_oq-engine
train
0a21cee1565c459c1157f088e3c9fbf0e409b5df
diff --git a/src/victory-util/style.js b/src/victory-util/style.js index <HASH>..<HASH> 100644 --- a/src/victory-util/style.js +++ b/src/victory-util/style.js @@ -54,6 +54,6 @@ export default { blue: ["#002C61", "#004B8F", "#006BC9", "#3795E5", "#65B4F4"], green: ["#354722", "#466631", "#649146", "#8AB25C", "#A9C97E"] }; - return name ? scales[name] : scales.greyscale; + return name ? scales[name] : scales.grayscale; } };
Fix victory-util/style.js typo Spelling of property 'grayscale' incrorrectly referenced as 'greyscale' in return statement of getColorScale function
FormidableLabs_victory
train
ea373f9f4c0b4e13936e16f8ae642b05a4ce21c8
diff --git a/tests/test_transport.py b/tests/test_transport.py index <HASH>..<HASH> 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -245,7 +245,7 @@ class TransportTest(unittest.TestCase): self.assertEqual(True, self.tc.is_authenticated()) self.assertEqual(True, self.ts.is_authenticated()) - def testa_long_banner(self): + def test_long_banner(self): """ verify that a long banner doesn't mess up the handshake. """ @@ -339,7 +339,7 @@ class TransportTest(unittest.TestCase): self.assertEqual("This is on stderr.\n", f.readline()) self.assertEqual("", f.readline()) - def testa_channel_can_be_used_as_context_manager(self): + def test_channel_can_be_used_as_context_manager(self): """ verify that exec_command() does something reasonable. """
Weird typos introduced 2 years ago, bah Test currently passes on my workstation tho
paramiko_paramiko
train
c23bf7ee6f8fb11f07de9c1d3e092b688ecada15
diff --git a/molgenis-data-semanticsearch/pom.xml b/molgenis-data-semanticsearch/pom.xml index <HASH>..<HASH> 100644 --- a/molgenis-data-semanticsearch/pom.xml +++ b/molgenis-data-semanticsearch/pom.xml @@ -15,7 +15,7 @@ </dependency> <dependency> <groupId>org.molgenis</groupId> - <artifactId>molgenis-ontology-core</artifactId> + <artifactId>molgenis-ontology</artifactId> <version>${project.version}</version> </dependency> </dependencies> diff --git a/molgenis-data-semanticsearch/src/main/java/org/molgenis/data/semantic/OntologyTagService.java b/molgenis-data-semanticsearch/src/main/java/org/molgenis/data/semantic/OntologyTagService.java index <HASH>..<HASH> 100644 --- a/molgenis-data-semanticsearch/src/main/java/org/molgenis/data/semantic/OntologyTagService.java +++ b/molgenis-data-semanticsearch/src/main/java/org/molgenis/data/semantic/OntologyTagService.java @@ -17,9 +17,9 @@ import org.molgenis.data.meta.AttributeMetaDataMetaData; import org.molgenis.data.meta.PackageMetaData; import org.molgenis.data.meta.TagMetaData; import org.molgenis.data.support.QueryImpl; -import org.molgenis.ontology.Ontology; -import org.molgenis.ontology.OntologyService; -import org.molgenis.ontology.OntologyTerm; +import org.molgenis.ontology.beans.Ontology; +import org.molgenis.ontology.beans.OntologyTerm; +import org.molgenis.ontology.matching.OntologyService; import com.google.common.collect.Lists; diff --git a/molgenis-data-semanticsearch/src/main/java/org/molgenis/data/semantic/TagService.java b/molgenis-data-semanticsearch/src/main/java/org/molgenis/data/semantic/TagService.java index <HASH>..<HASH> 100644 --- a/molgenis-data-semanticsearch/src/main/java/org/molgenis/data/semantic/TagService.java +++ b/molgenis-data-semanticsearch/src/main/java/org/molgenis/data/semantic/TagService.java @@ -3,8 +3,8 @@ package org.molgenis.data.semantic; import org.molgenis.data.AttributeMetaData; import org.molgenis.data.EntityMetaData; import org.molgenis.data.Package; -import org.molgenis.ontology.Ontology; -import org.molgenis.ontology.OntologyTerm; +import org.molgenis.ontology.beans.Ontology; +import org.molgenis.ontology.beans.OntologyTerm; /** * Service that administrates tags on attributes, entities and packages of a particular code system. diff --git a/molgenis-data-semanticsearch/src/test/java/org/molgenis/data/semantic/OntologyTagServiceTest.java b/molgenis-data-semanticsearch/src/test/java/org/molgenis/data/semantic/OntologyTagServiceTest.java index <HASH>..<HASH> 100644 --- a/molgenis-data-semanticsearch/src/test/java/org/molgenis/data/semantic/OntologyTagServiceTest.java +++ b/molgenis-data-semanticsearch/src/test/java/org/molgenis/data/semantic/OntologyTagServiceTest.java @@ -19,11 +19,11 @@ import org.molgenis.data.meta.TagMetaData; import org.molgenis.data.support.DefaultAttributeMetaData; import org.molgenis.data.support.DefaultEntityMetaData; import org.molgenis.data.support.MapEntity; -import org.molgenis.ontology.Ontology; -import org.molgenis.ontology.OntologyService; -import org.molgenis.ontology.OntologyTerm; +import org.molgenis.ontology.beans.Ontology; import org.molgenis.ontology.beans.OntologyImpl; +import org.molgenis.ontology.beans.OntologyTerm; import org.molgenis.ontology.beans.OntologyTermImpl; +import org.molgenis.ontology.matching.OntologyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
removed the ontology-core reference and added ontology reference
molgenis_molgenis
train
878ca17fd53e46f3c99faeee46b3611902852951
diff --git a/libhttpserver/content_type_utils.go b/libhttpserver/content_type_utils.go index <HASH>..<HASH> 100644 --- a/libhttpserver/content_type_utils.go +++ b/libhttpserver/content_type_utils.go @@ -29,12 +29,13 @@ func (w *contentTypeOverridingResponseWriter) calculateOverride( ty := strings.ToLower(mimeType) switch { // First anything textual as text/plain. - // Includes javascript, html, xml. (note that the type may be e.g. application/xhtml+xml) + case strings.HasPrefix(ty, "text/"): + return "text/plain", "inline" + // Rest of javascript, html, xml. (note that the type may be e.g. application/xhtml+xml) case strings.Contains(ty, "javascript") || strings.Contains(ty, "xml") || - strings.Contains(ty, "html") || - strings.HasPrefix(ty, "text/"): - return "text/plain", "inline" + strings.Contains(ty, "html"): + return "text/plain", "attachment" // Pass multimedia types through, and pdf too. case strings.HasPrefix(ty, "audio/") || strings.HasPrefix(ty, "image/") ||
libhttpserver: Display less things inline (fix xlsx bug)
keybase_client
train
bd3641c4ea5988abd5d861aa2315778a83472384
diff --git a/asteval/asteval.py b/asteval/asteval.py index <HASH>..<HASH> 100644 --- a/asteval/asteval.py +++ b/asteval/asteval.py @@ -717,6 +717,7 @@ class Interpreter(object): for tline in hnd.body: self.run(tline) break + break if no_errors and hasattr(node, 'orelse'): for tnode in node.orelse: self.run(tnode) diff --git a/tests/test_asteval.py b/tests/test_asteval.py index <HASH>..<HASH> 100644 --- a/tests/test_asteval.py +++ b/tests/test_asteval.py @@ -618,6 +618,16 @@ class TestEval(TestCase): """)) self.isvalue('x', -1) + self.interp(textwrap.dedent(""" + x = 15 + try: + raise Exception() + x = 20 + except: + pass + """)) + self.isvalue('x', 15) + def test_tryelsefinally(self): self.interp(textwrap.dedent("""
don't continue a try block after an error is caught
newville_asteval
train
64509c6b5612df316adb6f9c3b1d9e2965dee138
diff --git a/lib/modules/apostrophe-pieces/public/js/manager-modal.js b/lib/modules/apostrophe-pieces/public/js/manager-modal.js index <HASH>..<HASH> 100644 --- a/lib/modules/apostrophe-pieces/public/js/manager-modal.js +++ b/lib/modules/apostrophe-pieces/public/js/manager-modal.js @@ -496,10 +496,12 @@ apos.define('apostrophe-pieces-manager-modal', { }).get(); if ($checkboxes.filter(':checked').length === $checkboxes.length) { $checkboxes.prop('checked', false); + $checkboxes.parents('[data-focus-'+ options.name +']').removeClass('apos-focus'); self.$el.find('input[type="checkbox"][name="select-all"]').prop('checked', false); self.choices = _.difference(self.choices, ids); } else { $checkboxes.prop('checked', true); + $checkboxes.parents('[data-focus-'+ options.name +']').addClass('apos-focus'); self.$el.find('input[type="checkbox"][name="select-all"]').prop('checked', true); self.choices = _.union(self.choices, ids); }
select all checkbox affects grid view properly
apostrophecms_apostrophe
train
bf66e9a529fed3d6c460bcdbbd0a60bc167866a4
diff --git a/cmd/iam.go b/cmd/iam.go index <HASH>..<HASH> 100644 --- a/cmd/iam.go +++ b/cmd/iam.go @@ -458,7 +458,7 @@ func reloadEtcdUsers(prefix string, usersMap map[string]auth.Credentials, policy // prefix := "config/iam/users/" // v := trim(trim(key, prefix), base(key)) == "newuser" // - user := strings.TrimSuffix(strings.TrimSuffix(string(kv.Key), prefix), path.Base(string(kv.Key))) + user := path.Clean(strings.TrimSuffix(strings.TrimPrefix(string(kv.Key), prefix), path.Base(string(kv.Key)))) if !users.Contains(user) { users.Add(user) } @@ -497,7 +497,7 @@ func reloadEtcdUsers(prefix string, usersMap map[string]auth.Credentials, policy if err = json.Unmarshal(pdata, &policyName); err != nil { return err } - policyMap[path.Base(prefix)] = policyName + policyMap[user] = policyName } } return nil @@ -521,11 +521,11 @@ func reloadEtcdPolicies(prefix string, cannedPolicyMap map[string]iampolicy.Poli // then strip off the remaining basename to obtain the prefix // value, usually in the following form. // - // key := "config/iam/policys/newpolicy/identity.json" - // prefix := "config/iam/policys/" + // key := "config/iam/policies/newpolicy/identity.json" + // prefix := "config/iam/policies/" // v := trim(trim(key, prefix), base(key)) == "newpolicy" // - policyName := strings.TrimSuffix(strings.TrimSuffix(string(kv.Key), prefix), path.Base(string(kv.Key))) + policyName := path.Clean(strings.TrimSuffix(strings.TrimPrefix(string(kv.Key), prefix), path.Base(string(kv.Key)))) if !policies.Contains(policyName) { policies.Add(policyName) } @@ -542,7 +542,7 @@ func reloadEtcdPolicies(prefix string, cannedPolicyMap map[string]iampolicy.Poli if err = json.Unmarshal(pdata, &p); err != nil { return err } - cannedPolicyMap[path.Base(prefix)] = p + cannedPolicyMap[policyName] = p } return nil }
Reload etcd users and policies properly (#<I>) Currently there was a bug in how we reload users and policies which leads to users/policies going missing due to wrong path construction. Fixes #<I>
minio_minio
train
be1256a349b188da2e2aef58ef022ed5bc2feb19
diff --git a/leveldb/bench_test.go b/leveldb/bench_test.go index <HASH>..<HASH> 100644 --- a/leveldb/bench_test.go +++ b/leveldb/bench_test.go @@ -11,7 +11,7 @@ import ( "fmt" "math/rand" "os" - "path" + "path/filepath" "runtime" "testing" @@ -61,7 +61,7 @@ func (v *valueGen) get(n int) []byte { return v.src[v.pos-n : v.pos] } -var benchDB = path.Join(os.TempDir(), fmt.Sprintf("goleveldbbench-%d", os.Getuid())) +var benchDB = filepath.Join(os.TempDir(), fmt.Sprintf("goleveldbbench-%d", os.Getuid())) type dbBench struct { b *testing.B diff --git a/leveldb/storage/file_storage.go b/leveldb/storage/file_storage.go index <HASH>..<HASH> 100644 --- a/leveldb/storage/file_storage.go +++ b/leveldb/storage/file_storage.go @@ -10,7 +10,7 @@ import ( "bytes" "fmt" "os" - "path" + "path/filepath" "runtime" "sync" "time" @@ -36,7 +36,7 @@ func OpenFile(dbpath string) (d *FileStorage, err error) { return } - lock, err := os.OpenFile(path.Join(dbpath, "LOCK"), os.O_RDWR|os.O_CREATE, 0644) + lock, err := os.OpenFile(filepath.Join(dbpath, "LOCK"), os.O_RDWR|os.O_CREATE, 0644) if err != nil { return } @@ -52,8 +52,8 @@ func OpenFile(dbpath string) (d *FileStorage, err error) { return } - os.Rename(path.Join(dbpath, "LOG"), path.Join(dbpath, "LOG.old")) - log, err := os.OpenFile(path.Join(dbpath, "LOG"), os.O_WRONLY|os.O_CREATE, 0644) + os.Rename(filepath.Join(dbpath, "LOG"), filepath.Join(dbpath, "LOG.old")) + log, err := os.OpenFile(filepath.Join(dbpath, "LOG"), os.O_WRONLY|os.O_CREATE, 0644) if err != nil { setFileLock(lock, false) return @@ -149,7 +149,7 @@ func (d *FileStorage) GetFiles(t FileType) (r []File) { // GetManifest get manifest file. func (d *FileStorage) GetManifest() (f File, err error) { - pth := path.Join(d.path, "CURRENT") + pth := filepath.Join(d.path, "CURRENT") rw, err := os.OpenFile(pth, os.O_RDONLY, 0) if err != nil { err = err.(*os.PathError).Err @@ -175,7 +175,7 @@ func (d *FileStorage) SetManifest(f File) (err error) { if !ok { return ErrInvalidFile } - pth := path.Join(d.path, "CURRENT") + pth := filepath.Join(d.path, "CURRENT") pthTmp := fmt.Sprintf("%s.%d", pth, p.num) rw, err := os.OpenFile(pthTmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { @@ -260,7 +260,7 @@ func (p *file) name() string { } func (p *file) path() string { - return path.Join(p.stor.path, p.name()) + return filepath.Join(p.stor.path, p.name()) } func (p *file) parse(name string) bool { diff --git a/leveldb/storage/file_storage_test.go b/leveldb/storage/file_storage_test.go index <HASH>..<HASH> 100644 --- a/leveldb/storage/file_storage_test.go +++ b/leveldb/storage/file_storage_test.go @@ -9,7 +9,7 @@ package storage import ( "fmt" "os" - "path" + "path/filepath" "testing" ) @@ -86,7 +86,7 @@ func TestFileStorage_InvalidFileName(t *testing.T) { } func TestFileStorage_Flock(t *testing.T) { - pth := path.Join(os.TempDir(), fmt.Sprintf("goleveldbtestfd-%d", os.Getuid())) + pth := filepath.Join(os.TempDir(), fmt.Sprintf("goleveldbtestfd-%d", os.Getuid())) _, err := os.Stat(pth) if err == nil {
leveldb: uses path/filepath package for paths manipulation
FactomProject_goleveldb
train
52229b1578e14b11f31b2c6b82f0c37cbeec7b81
diff --git a/rtv/mime_parsers.py b/rtv/mime_parsers.py index <HASH>..<HASH> 100644 --- a/rtv/mime_parsers.py +++ b/rtv/mime_parsers.py @@ -77,7 +77,7 @@ class GfycatMIMEParser(BaseMIMEParser): @staticmethod def get_mimetype(url): - parts = url.split('/') + parts = url.replace('gifs/detail/', '').split('/') api_url = '/'.join(parts[:-1] + ['cajax', 'get'] + parts[-1:]) resp = requests.get(api_url) image_url = resp.json()['gfyItem']['webmUrl']
expand gfycat mime parser for more urls
michael-lazar_rtv
train
baab4d324e936ee87326ba5cc921f62778d22229
diff --git a/lib/gradient/version.rb b/lib/gradient/version.rb index <HASH>..<HASH> 100644 --- a/lib/gradient/version.rb +++ b/lib/gradient/version.rb @@ -1,3 +1,3 @@ module Gradient - VERSION = "0.2.4" + VERSION = "0.3.0" end
Bump to version <I> - Changed the API for `Gradient::Map` to be invoked by using an array of `Gradient::Point` rather two arrays of `Gradient::ColorPoint` and `Gradient::OpacityPoint` - Introduced `Gradient::PointMerger` to take on the previous responsibility of `Gradient::Map`
zeeraw_gradient
train
627c08c306342884a53f44608ad4bc737fe67e6b
diff --git a/bokeh/core/state.py b/bokeh/core/state.py index <HASH>..<HASH> 100644 --- a/bokeh/core/state.py +++ b/bokeh/core/state.py @@ -136,7 +136,7 @@ class State(object): def autoadd(self): return self._autoadd - @property.setter + @autoadd.setter def autoadd(self, val): self._autoadd = val
added setter for curdoc.autoadd
bokeh_bokeh
train
564339d630d18f99e43812ce977136f2d1217300
diff --git a/mock.py b/mock.py index <HASH>..<HASH> 100644 --- a/mock.py +++ b/mock.py @@ -1091,8 +1091,8 @@ call = _Call() -def _spec_signature(spec, spec_set=False, inherit=False, - _parent=None, _name=None, _ids=None): +def _spec_signature(spec, spec_set=False, inherit=False, _parent=None, + _name=None, _ids=None, _instance=False): if _ids is None: _ids = {} is_type = False @@ -1102,6 +1102,8 @@ def _spec_signature(spec, spec_set=False, inherit=False, _type = spec if type(spec) == list: + # can't use _type because restriction only applies to list *instances* + # passing in 'list' (the type) as a spec is fine. raise TypeError( "spec must be a class or an instance not a list" ) @@ -1110,8 +1112,7 @@ def _spec_signature(spec, spec_set=False, inherit=False, if spec_set: kwargs = {'spec_set': spec} - - if id(spec) in _ids: + if id(spec) in _ids and not _instance: mock = _ids[id(spec)][0] return mock @@ -1125,6 +1126,10 @@ def _spec_signature(spec, spec_set=False, inherit=False, if _parent is not None: _parent._mock_children[_name] = mock + if is_type and inherit and not _instance: + mock.return_value = _spec_signature(spec, spec_set, inherit, _ids=_ids, + _instance=True) + for entry in dir(spec): if _is_magic(entry): continue diff --git a/tests/testhelpers.py b/tests/testhelpers.py index <HASH>..<HASH> 100644 --- a/tests/testhelpers.py +++ b/tests/testhelpers.py @@ -299,11 +299,6 @@ class SpecSignatureTest(unittest2.TestCase): def test_spec_inheritance_for_classes(self): - # when inheritance is on we could mock classes __init__ and callable - # object signatures with mocksignature - # how does mocksignature on a class with no __init__ method work? - # (i.e. will inherit object.__init__ that takes no args but implemented - # in C.) class Foo(object): def a(self): pass @@ -318,15 +313,28 @@ class SpecSignatureTest(unittest2.TestCase): for this_mock in class_mock, class_mock(): this_mock.a() this_mock.a.assert_called_with() - self.assertRaises(TypeError, this_mock.assert_called_with, 'foo') + self.assertRaises(TypeError, this_mock.a, 'foo') + self.assertRaises(AttributeError, getattr, this_mock, 'b') + + self.assertIs(class_mock.Bar, class_mock().Bar) + self.assertIsNot(class_mock.a, class_mock().a) instance_mock = _spec_signature(Foo(), inherit=True) instance_mock.a() instance_mock.a.assert_called_with() - self.assertRaises(TypeError, instance_mock.assert_called_with, 'foo') + self.assertRaises(TypeError, instance_mock.a, 'foo') + self.assertRaises(AttributeError, getattr, instance_mock, 'b') # The return value isn't created with a spec because the spec is an # instance and not a class. The spec isn't inherited by return value. instance_mock().a(1, 2, 3) instance_mock().a.assert_called_with(1, 2, 3) + + def test_spec_inheritance_callables(self): + # with spec inheritance we could mock classes __init__ and callable + # object signatures with mocksignature. + # how does mocksignature on a class with no __init__ method work? + # (i.e. will inherit object.__init__ that takes no args but implemented + # in C.) + pass
id cache shared by _spec_signature for return values of mocked classes
testing-cabal_mock
train
302f12430551c33b9642ba9748b385b72db53bf3
diff --git a/protocol/src/main/java/org/jboss/as/protocol/ProtocolChannelClient.java b/protocol/src/main/java/org/jboss/as/protocol/ProtocolChannelClient.java index <HASH>..<HASH> 100644 --- a/protocol/src/main/java/org/jboss/as/protocol/ProtocolChannelClient.java +++ b/protocol/src/main/java/org/jboss/as/protocol/ProtocolChannelClient.java @@ -24,9 +24,10 @@ package org.jboss.as.protocol; import static org.jboss.as.protocol.ProtocolMessages.MESSAGES; import static org.xnio.Options.SASL_POLICY_NOANONYMOUS; import static org.xnio.Options.SASL_POLICY_NOPLAINTEXT; - import java.io.Closeable; import java.io.IOException; +import java.net.InetAddress; +import java.net.NetworkInterface; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; @@ -64,6 +65,7 @@ import org.xnio.OptionMap.Builder; * @version $Revision: 1.1 $ */ public class ProtocolChannelClient<T extends ProtocolChannel> implements Closeable { + private static final String JBOSS_LOCAL_USER = "JBOSS-LOCAL-USER"; private final boolean startedEndpoint; private final Endpoint endpoint; private final Registration providerRegistration; @@ -114,6 +116,9 @@ public class ProtocolChannelClient<T extends ProtocolChannel> implements Closeab Builder builder = OptionMap.builder(); builder.set(SASL_POLICY_NOANONYMOUS, Boolean.FALSE); builder.set(SASL_POLICY_NOPLAINTEXT, Boolean.FALSE); + if (isLocal() == false) { + builder.set(Options.SASL_DISALLOWED_MECHANISMS, Sequence.of(JBOSS_LOCAL_USER)); + } List<Property> tempProperties = new ArrayList<Property>(saslOptions != null ? saslOptions.size() : 1); tempProperties.add(Property.of("jboss.sasl.local-user.quiet-auth", "true")); if (saslOptions != null) { @@ -137,6 +142,18 @@ public class ProtocolChannelClient<T extends ProtocolChannel> implements Closeab return connection; } + private boolean isLocal() { + try { + String hostName = uri.getHost(); + InetAddress address = InetAddress.getByName(hostName); + NetworkInterface nic = NetworkInterface.getByInetAddress(address); + + return address.isLoopbackAddress() || nic != null; + } catch (Exception e) { + return false; + } + } + public T openChannel(String channelName) throws IOException { if (connection == null) { throw MESSAGES.notConnected();
[AS7-<I>] Disable the JBOSS-LOCAL-USER mechanism on clients that already know this is a remote call.
wildfly_wildfly
train
22761a9b4d80323894595ba7dab90ada983cf979
diff --git a/tests/test_cookiecutters.py b/tests/test_cookiecutters.py index <HASH>..<HASH> 100644 --- a/tests/test_cookiecutters.py +++ b/tests/test_cookiecutters.py @@ -12,6 +12,7 @@ TestJQuery.test_cookiecutter_jquery from __future__ import unicode_literals import os +import sys import subprocess import pytest @@ -37,14 +38,16 @@ def remove_additional_dirs(request): def bake_data(): pypackage_data = ( 'git clone https://github.com/audreyr/cookiecutter-pypackage.git', - 'cookiecutter --no-input cookiecutter-pypackage/', + '{0} -m cookiecutter.cli --no-input cookiecutter-pypackage/'.format( + sys.executable), 'cookiecutter-pypackage', 'boilerplate/README.rst' ) jquery_data = ( 'git clone https://github.com/audreyr/cookiecutter-jquery.git', - 'cookiecutter --no-input cookiecutter-jquery/', + '{0} -m cookiecutter.cli --no-input cookiecutter-jquery/'.format( + sys.executable), 'cookiecutter-jquery', 'boilerplate/README.md' ) diff --git a/tests/test_more_cookiecutters.py b/tests/test_more_cookiecutters.py index <HASH>..<HASH> 100644 --- a/tests/test_more_cookiecutters.py +++ b/tests/test_more_cookiecutters.py @@ -12,6 +12,7 @@ TestExamplesRepoArg.test_cookiecutter_pypackage_git from __future__ import unicode_literals import os +import sys import subprocess import pytest @@ -39,7 +40,8 @@ def remove_additional_dirs(request): def test_git_branch(): pypackage_git = 'https://github.com/audreyr/cookiecutter-pypackage.git' proc = subprocess.Popen( - 'cookiecutter -c console-script {0}'.format(pypackage_git), + '{0} -m cookiecutter.cli -c console-script {1}'.format(sys.executable, + pypackage_git), stdin=subprocess.PIPE, shell=True ) @@ -56,7 +58,8 @@ def test_git_branch(): @pytest.mark.usefixtures('clean_system', 'remove_additional_dirs') def test_cookiecutter_pypackage_git(): proc = subprocess.Popen( - 'cookiecutter https://github.com/audreyr/cookiecutter-pypackage.git', + '{0} -m cookiecutter.cli https://github.com/audreyr/' + 'cookiecutter-pypackage.git'.format(sys.executable), stdin=subprocess.PIPE, shell=True )
Make tests work without installing cookiecutter When running tests without installing cookiecutter, some of them fail because they try to invoke cookiecutter. Moreover, if cookiecutter is installed on the system, the tests would use the installed version instead of the one in the build tree. To solve both issues, use `python -m cookiecutter.cli` instead of `cookiecutter`.
audreyr_cookiecutter
train
5598961d2c2ddc4d4f46b1f43570e525a2353ef3
diff --git a/src/components/View/index.js b/src/components/View/index.js index <HASH>..<HASH> 100644 --- a/src/components/View/index.js +++ b/src/components/View/index.js @@ -1,3 +1,5 @@ +import '../../modules/injectResponderEventPlugin'; + import applyLayout from '../../modules/applyLayout'; import applyNativeMethods from '../../modules/applyNativeMethods'; import BaseComponentPropTypes from '../../propTypes/BaseComponentPropTypes'; diff --git a/src/core.js b/src/core.js index <HASH>..<HASH> 100644 --- a/src/core.js +++ b/src/core.js @@ -1,5 +1,3 @@ -import './modules/injectResponderEventPlugin'; - import findNodeHandle from './modules/findNodeHandle'; import ReactDOM from 'react-dom'; import ReactDOMServer from 'react-dom/server'; diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,3 @@ -import './modules/injectResponderEventPlugin'; - import findNodeHandle from './modules/findNodeHandle'; import ReactDOM from 'react-dom'; import ReactDOMServer from 'react-dom/server';
Move ResponderEventPlugin injection to View
necolas_react-native-web
train
20b572f7f8b5d03c7fcfceca1812bd8045d02441
diff --git a/api/app/app.go b/api/app/app.go index <HASH>..<HASH> 100644 --- a/api/app/app.go +++ b/api/app/app.go @@ -76,7 +76,7 @@ func NewApp(name string, framework string, teams []string) (App, error) { if err != nil { return a, err } - err = NewEnviron(a.Name, a.KeystoneEnv.AccessKey, a.KeystoneEnv.secretKey) + err = newEnviron(&a) if err != nil { return a, err } diff --git a/api/app/env.go b/api/app/env.go index <HASH>..<HASH> 100644 --- a/api/app/env.go +++ b/api/app/env.go @@ -140,7 +140,7 @@ func newJujuEnv(access, secret string) (JujuEnv, error) { }, nil } -func NewEnviron(name, access, secret string) error { +func newEnviron(a *App) error { envs := map[string]map[string]JujuEnv{} file, err := filesystem().OpenFile(EnvironConfPath, syscall.O_CREAT|syscall.O_RDWR, 0600) if err != nil { @@ -158,11 +158,11 @@ func NewEnviron(name, access, secret string) error { if _, ok := envs["environments"]; !ok { envs["environments"] = map[string]JujuEnv{} } - jujuEnv, err := newJujuEnv(access, secret) + jujuEnv, err := newJujuEnv(a.KeystoneEnv.AccessKey, a.KeystoneEnv.secretKey) if err != nil { return err } - envs["environments"][name] = jujuEnv + envs["environments"][a.Name] = jujuEnv data, err := goyaml.Marshal(&envs) _, err = file.Write(data) return err diff --git a/api/app/env_test.go b/api/app/env_test.go index <HASH>..<HASH> 100644 --- a/api/app/env_test.go +++ b/api/app/env_test.go @@ -90,7 +90,14 @@ func (s *S) TestNewEnviron(c *C) { defer func() { fsystem = s.rfs }() - err = NewEnviron("name", "access", "secret") + a := App{ + Name: "name", + KeystoneEnv: KeystoneEnv{ + AccessKey: "access", + secretKey: "secret", + }, + } + err = newEnviron(&a) c.Assert(err, IsNil) c.Assert(rfs.HasAction("openfile "+EnvironConfPath+" with mode 0600"), Equals, true) file, err := rfs.Open(EnvironConfPath) @@ -121,7 +128,14 @@ func (s *S) TestNewEnvironShouldKeepExistentsEnvirons(c *C) { defer func() { fsystem = s.rfs }() - err = NewEnviron("name", "access", "secret") + a := App{ + Name: "name", + KeystoneEnv: KeystoneEnv{ + AccessKey: "access", + secretKey: "secret", + }, + } + err = newEnviron(&a) c.Assert(err, IsNil) c.Assert(rfs.HasAction("openfile "+EnvironConfPath+" with mode 0600"), Equals, true) file, err := rfs.Open(EnvironConfPath)
api/app: refactoring newEnviron 1. Unexport the function 2. Make it receive an app instead of three strings
tsuru_tsuru
train
18a7b3d1fdb2d5f852083b1a0622edc5fd80eac9
diff --git a/src/client/api.js b/src/client/api.js index <HASH>..<HASH> 100644 --- a/src/client/api.js +++ b/src/client/api.js @@ -24,8 +24,8 @@ export function weacast (config) { } api.configure(feathers.authentication({ storage: window.localStorage, - cookie: 'weacast-jwt', - storageKey: 'weacast-jwt', + cookie: config.apiJwt || 'weacast-jwt', + storageKey: config.apiJwt || 'weacast-jwt', path: config.apiPath + '/authentication' }))
feat: allow to configure JWT name on client side
weacast_weacast-core
train
47e807672fabf6b8696da8132ed12e60ee361724
diff --git a/packages/react-bootstrap-table2/src/bootstrap-table.js b/packages/react-bootstrap-table2/src/bootstrap-table.js index <HASH>..<HASH> 100644 --- a/packages/react-bootstrap-table2/src/bootstrap-table.js +++ b/packages/react-bootstrap-table2/src/bootstrap-table.js @@ -4,12 +4,14 @@ import cs from 'classnames'; import Header from './header'; import Body from './body'; -import storeBase from './store/base'; +import Store from './store/base'; +import PropsBaseResolver from './props-resolver'; -class BootstrapTable extends storeBase(Component) { +class BootstrapTable extends PropsBaseResolver(Component) { constructor(props) { super(props); this.validateProps(); + this.store = new Store(props); } render() { @@ -34,7 +36,7 @@ class BootstrapTable extends storeBase(Component) { <table className={ tableClass }> <Header columns={ columns } /> <Body - data={ this.data } + data={ this.store.data } keyField={ keyField } columns={ columns } /> diff --git a/packages/react-bootstrap-table2/src/props-resolver/column-resolver.js b/packages/react-bootstrap-table2/src/props-resolver/column-resolver.js index <HASH>..<HASH> 100644 --- a/packages/react-bootstrap-table2/src/props-resolver/column-resolver.js +++ b/packages/react-bootstrap-table2/src/props-resolver/column-resolver.js @@ -1,3 +1,6 @@ -export function columnSize(columns) { - return columns.length; -} +export default ExtendBase => + class ColumnResolver extends ExtendBase { + columnSize() { + return this.props.columns.length; + } + }; diff --git a/packages/react-bootstrap-table2/src/props-resolver/index.js b/packages/react-bootstrap-table2/src/props-resolver/index.js index <HASH>..<HASH> 100644 --- a/packages/react-bootstrap-table2/src/props-resolver/index.js +++ b/packages/react-bootstrap-table2/src/props-resolver/index.js @@ -1,13 +1,13 @@ -import { columnSize } from './column-resolver'; +import ColumnResolver from './column-resolver'; export default ExtendBase => - class TableResolver extends ExtendBase { + class TableResolver extends ColumnResolver(ExtendBase) { validateProps() { const { columns, keyField } = this.props; if (!keyField) { throw new Error('Please specify a field as key via keyField'); } - if (columnSize(columns) <= 0) { + if (this.columnSize(columns) <= 0) { throw new Error('No any visible columns detect'); } } diff --git a/packages/react-bootstrap-table2/src/store/base.js b/packages/react-bootstrap-table2/src/store/base.js index <HASH>..<HASH> 100644 --- a/packages/react-bootstrap-table2/src/store/base.js +++ b/packages/react-bootstrap-table2/src/store/base.js @@ -1,10 +1,6 @@ -import TableResolver from '../props-resolver'; - -export default ExtendBase => - class Store extends TableResolver(ExtendBase) { - constructor(props) { - super(props); - const { data } = this.props; - this.data = data ? data.slice() : []; - } - }; +export default class Store { + constructor(props) { + const { data } = props; + this.data = data ? data.slice() : []; + } +}
refine the relation for props resolver and internal store
react-bootstrap-table_react-bootstrap-table2
train
47111dfa1ab96b3d5d063c4e1c1555f7e12e546f
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## 0.1.1 * Added `json_show_attrs` and `json_index_attrs` to specialize attributes for json. These methods default to `show_attrs` and `index_attrs`. +* Fixed Iord::OutputHelper.image and its call in Iord::Field ## 0.1.0 * Added JSON support, can be enabled by including Iord::Json module. diff --git a/lib/iord/fields.rb b/lib/iord/fields.rb index <HASH>..<HASH> 100644 --- a/lib/iord/fields.rb +++ b/lib/iord/fields.rb @@ -123,7 +123,7 @@ module Iord attr[:format].call(resource, attr[:value]) end elsif attr.has_key? :image - o.image_tag resource.public_send(*attr[:image]), attr[:params] + o.image resource.public_send(*attr[:image]), attr[:params] elsif attr.has_key? :link o.link_to attr[:label], attr[:url], attr[:params] else diff --git a/lib/iord/output_helper.rb b/lib/iord/output_helper.rb index <HASH>..<HASH> 100644 --- a/lib/iord/output_helper.rb +++ b/lib/iord/output_helper.rb @@ -84,6 +84,7 @@ module Iord end def image(url, hash) + hash ||= {} v.image_tag(url, hash) end end
Fixed Iord::OutputHelper.image and its call in Iord::Field
Aethelflaed_iord
train
f17d16da2d3ee2e7871872c2549e81d704b3ba70
diff --git a/examples/FasterRCNN/modeling/model_cascade.py b/examples/FasterRCNN/modeling/model_cascade.py index <HASH>..<HASH> 100644 --- a/examples/FasterRCNN/modeling/model_cascade.py +++ b/examples/FasterRCNN/modeling/model_cascade.py @@ -3,7 +3,7 @@ import tensorflow as tf from tensorpack.tfutils import get_current_tower_context from config import config as cfg -from utils.box_ops import pairwise_iou +from utils.box_ops import pairwise_iou, area as tf_area from .model_box import clip_boxes from .model_frcnn import BoxProposals, FastRCNNHead, fastrcnn_outputs @@ -27,8 +27,8 @@ class CascadeRCNNHead(object): self.num_cascade_stages = len(cfg.CASCADE.IOUS) - self.is_training = get_current_tower_context().is_training - if self.is_training: + self.training = get_current_tower_context().is_training + if self.training: @tf.custom_gradient def scale_gradient(x): return x, lambda dy: dy * (1.0 / self.num_cascade_stages) @@ -72,6 +72,8 @@ class CascadeRCNNHead(object): refined_boxes = head.decoded_output_boxes_class_agnostic() refined_boxes = clip_boxes(refined_boxes, self.image_shape2d) + if self.training: + refined_boxes = tf.boolean_mask(refined_boxes, tf_area(refined_boxes) > 0) return head, tf.stop_gradient(refined_boxes, name='output_boxes') def match_box_with_gt(self, boxes, iou_threshold): @@ -81,7 +83,7 @@ class CascadeRCNNHead(object): Returns: BoxProposals """ - if self.is_training: + if self.training: with tf.name_scope('match_box_with_gt_{}'.format(iou_threshold)): iou = pairwise_iou(boxes, self.gt_boxes) # NxM max_iou_per_box = tf.reduce_max(iou, axis=1) # N
[Cascade R-CNN] only train with nonempty boxes
tensorpack_tensorpack
train
a4720080d98ce44e87e24a68c660b43353d81c1b
diff --git a/lib/esvg/svg.rb b/lib/esvg/svg.rb index <HASH>..<HASH> 100644 --- a/lib/esvg/svg.rb +++ b/lib/esvg/svg.rb @@ -56,12 +56,16 @@ module Esvg found = find_files if found.size > 0 - found = found.sort_by{ |f| File.mtime(f) } - @mtime = File.mtime(found.last) + last = found.sort_by{ |f| File.mtime(f) }.last + @mtime = File.mtime(last) + end - found.each do |f| - @files[File.basename(f, ".*")] = read(f) - end + found.each do |f| + @files[File.basename(f, ".*")] = read(f) + end + + if @files.empty? && config[:verbose] + puts "No icons found at #{config[:path]}" end end diff --git a/lib/esvg/version.rb b/lib/esvg/version.rb index <HASH>..<HASH> 100644 --- a/lib/esvg/version.rb +++ b/lib/esvg/version.rb @@ -1,3 +1,3 @@ module Esvg - VERSION = "2.2.0" + VERSION = "2.2.1" end
Added logging message for no icons found
imathis_esvg
train
6ef90fdef995f0674b2b0937c5e11d159c939860
diff --git a/question/type/calculated/datasetdefinitions_form.php b/question/type/calculated/datasetdefinitions_form.php index <HASH>..<HASH> 100644 --- a/question/type/calculated/datasetdefinitions_form.php +++ b/question/type/calculated/datasetdefinitions_form.php @@ -98,8 +98,7 @@ class question_dataset_dependent_definitions_form extends moodleform { list($options, $selected) = $this->qtypeobj->dataset_options($this->question, $datasetname); unset($options['0']); // Mandatory... - $label = get_string('wildcard', 'qtype_calculated'). - " <strong>$datasetname</strong> "; + $label = get_string('wildcard', 'qtype_calculated', $datasetname); $mform->addElement('select', "dataset[$key]", $label, $options); if (isset($datadefscat[$datasetname])) { $mform->addElement('static', "there is a category", @@ -118,8 +117,7 @@ class question_dataset_dependent_definitions_form extends moodleform { if (!isset($datasetmenus[$datasetname])) { list($options, $selected) = $this->qtypeobj->dataset_options( $this->question, $datasetname, false); - $label = get_string('wildcard', 'qtype_calculated') . - " <strong>$datasetname</strong> "; + $label = get_string('wildcard', 'qtype_calculated', $datasetname); $mform->addElement('select', "dataset[$key]", $label, $options); if (isset($datadefscat[$datasetname])) { $mform->addElement('static', "there is a category", diff --git a/question/type/calculated/datasetitems_form.php b/question/type/calculated/datasetitems_form.php index <HASH>..<HASH> 100644 --- a/question/type/calculated/datasetitems_form.php +++ b/question/type/calculated/datasetitems_form.php @@ -131,7 +131,7 @@ class question_dataset_dependent_items_form extends moodleform { $j = (($this->noofitems) * count($this->datasetdefs))+1; foreach ($this->datasetdefs as $defkey => $datasetdef) { if ($datasetdef->category |= 0 ) { - $name = get_string('sharedwildcardname', 'qtype_calculated', $datasetdef->name); + $name = get_string('sharedwildcard', 'qtype_calculated', $datasetdef->name); } else { $name = get_string('wildcard', 'qtype_calculated', $datasetdef->name); } @@ -283,7 +283,7 @@ class question_dataset_dependent_items_form extends moodleform { get_string('wildcard', 'qtype_calculated', $datasetdef->name)); } else { $mform->addElement('text', "number[$j]", get_string( - 'sharedwildcardname', 'qtype_calculated', $datasetdef->name)); + 'sharedwildcard', 'qtype_calculated', $datasetdef->name)); } } else { diff --git a/question/type/calculated/lang/en/qtype_calculated.php b/question/type/calculated/lang/en/qtype_calculated.php index <HASH>..<HASH> 100644 --- a/question/type/calculated/lang/en/qtype_calculated.php +++ b/question/type/calculated/lang/en/qtype_calculated.php @@ -119,7 +119,7 @@ $string['questiondatasets_help'] = 'Question datasets of wild cards that will be $string['questionstoredname'] ='Question stored name'; $string['replacewithrandom'] = 'Replace with a random value'; $string['reuseifpossible'] = 'reuse previous value if available'; -$string['sharedwildcard']='Shared wild card <strong>{$a}</strong>'; +$string['sharedwildcard']='Shared wild card {<strong>{$a}</strong>}'; $string['sharedwildcardname']='Shared wild card '; $string['sharedwildcards']='Shared wild cards'; $string['significantfigures'] = 'with {$a}';
MDL-<I> qtype calculated, bad display of placeholder names on the editing form.
moodle_moodle
train
6371483b76bf2a45117bd5f0f091fb501f968db5
diff --git a/src/main/java/net/samuelcampos/usbdrivedectector/USBDeviceDetectorManager.java b/src/main/java/net/samuelcampos/usbdrivedectector/USBDeviceDetectorManager.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/samuelcampos/usbdrivedectector/USBDeviceDetectorManager.java +++ b/src/main/java/net/samuelcampos/usbdrivedectector/USBDeviceDetectorManager.java @@ -36,23 +36,38 @@ public class USBDeviceDetectorManager { private static final Logger logger = Logger .getLogger(USBDeviceDetectorManager.class); - private static final long defaultPoolingInterval = 10 * 1000; + private static final long DEFAULT_POLLING_INTERVAL = 10 * 1000; + + private static long currentPollingInterval = DEFAULT_POLLING_INTERVAL; private Set<USBStorageDevice> connectedDevices; private List<IUSBDriveListener> listeners; private Timer timer; public USBDeviceDetectorManager() { - this(defaultPoolingInterval); + this(DEFAULT_POLLING_INTERVAL); } - public USBDeviceDetectorManager(long poolingInterval) { + public USBDeviceDetectorManager(long pollingInterval) { listeners = new ArrayList<IUSBDriveListener>(); connectedDevices = new HashSet<USBStorageDevice>(); + } + + public synchronized void start() { + if (timer != null) { + timer.cancel(); + } timer = new Timer(); - timer.scheduleAtFixedRate(new ListenerTask(), poolingInterval, poolingInterval); + timer.scheduleAtFixedRate(new ListenerTask(), currentPollingInterval, currentPollingInterval); + + } + + public synchronized void stop() { + if (timer != null) { + timer.cancel(); + } } public synchronized boolean addDriveListener(IUSBDriveListener listener) {
Fixed typo from 'pooling' to 'polling', changed the static variable name to follow standard Java naming conventions. Changed the timer from being started automatically to being started manually (per java best practices don't start a new thread in a constructor)), added a stop() method to cancel the timer so you don't need a System.Exit() call to kill the timer..
samuelcampos_usbdrivedetector
train
c5b72069bf9f3f0ce220bea62afbbb91d728e3e7
diff --git a/quick_server/quick_server.py b/quick_server/quick_server.py index <HASH>..<HASH> 100644 --- a/quick_server/quick_server.py +++ b/quick_server/quick_server.py @@ -79,6 +79,10 @@ from http.server import SimpleHTTPRequestHandler import http.server as http_server import socketserver +try: + import pyarrow # avoid pyarrow atexit error +except (ModuleNotFoundError, ImportError) as _: + pass WorkerArgs = Dict[str, Any] TokenObj = Dict[str, Any] @@ -157,7 +161,7 @@ def get_time() -> float: return time.monotonic() -__version__ = "0.7.14" +__version__ = "0.7.15" def _getheader_fallback(obj: Any, key: str) -> Any: diff --git a/quick_server/worker.js b/quick_server/worker.js index <HASH>..<HASH> 100644 --- a/quick_server/worker.js +++ b/quick_server/worker.js @@ -17,7 +17,7 @@ export const CONFIG = { // animation: ['/', '-', '\\', '|'], animationTime: 300, }; -export const VERSION = '0.7.14'; +export const VERSION = '0.7.15'; export class Worker { constructor() { diff --git a/quick_server/worker.legacy.js b/quick_server/worker.legacy.js index <HASH>..<HASH> 100644 --- a/quick_server/worker.legacy.js +++ b/quick_server/worker.legacy.js @@ -18,7 +18,7 @@ window.CONFIG = { // animation: ['/', '-', '\\', '|'], animationTime: 300, }; -window.VERSION = '0.7.14'; +window.VERSION = '0.7.15'; class Worker { constructor() { diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -41,7 +41,7 @@ with open(path.join(here, 'README.rst'), encoding='utf-8') as f: setup( name='quick_server', - version='0.7.14', + version='0.7.15', description='QuickServer is a quick to use and ' + 'easy to set up server implementation.', long_description=long_description,
changes pyarrow error (#<I>)
JosuaKrause_quick_server
train
b8ef85352b0264ff41fd898e3126da670c08c97d
diff --git a/wfe2/wfe.go b/wfe2/wfe.go index <HASH>..<HASH> 100644 --- a/wfe2/wfe.go +++ b/wfe2/wfe.go @@ -175,6 +175,13 @@ func (wfe *WebFrontEndImpl) HandleFunc(mux *http.ServeMux, pattern string, h web logEvent.AddError("unable to make nonce: %s", err) } } + // Per section 7.1 "Resources": + // The "index" link relation is present on all resources other than the + // directory and indicates the URL of the directory. + if pattern != directoryPath { + directoryURL := web.RelativeEndpoint(request, "index") + response.Header().Add("Link", link(directoryURL, "index")) + } logEvent.Endpoint = pattern if request.URL != nil { diff --git a/wfe2/wfe_test.go b/wfe2/wfe_test.go index <HASH>..<HASH> 100644 --- a/wfe2/wfe_test.go +++ b/wfe2/wfe_test.go @@ -448,6 +448,7 @@ func TestHandleFunc(t *testing.T) { {[]string{"GET"}, "POST", false, false, "/test"}, {[]string{"GET"}, "OPTIONS", false, true, "/test"}, {[]string{"GET"}, "MAKE-COFFEE", false, false, "/test"}, // 405, or 418? + {[]string{"GET"}, "GET", true, true, directoryPath}, } { runWrappedHandler(&http.Request{Method: c.reqMethod}, c.pattern, c.allowed...) test.AssertEquals(t, stubCalled, c.shouldCallStub) @@ -469,6 +470,14 @@ func TestHandleFunc(t *testing.T) { test.AssertNotEquals(t, nonce, "") lastNonce = nonce } + linkHeader := rw.Header().Get("Link") + if c.pattern != directoryPath { + // If the pattern wasn't the directory there should be a Link header for the index + test.AssertEquals(t, linkHeader, `<http://localhost/index>;rel="index"`) + } else { + // The directory resource shouldn't get a link header + test.AssertEquals(t, linkHeader, "") + } } // Disallowed method returns error JSON in body
WFE2: Always send Link header for directory URL. (#<I>) All HTTP responses for requests to resources (other than the directory resource) should get a `Link` header with the `"index"` relation that points to the ACME directory URL. See <URL>
letsencrypt_boulder
train