hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
712b5e46c539096fd204535e61c568e455f4c604
diff --git a/context_test.go b/context_test.go index <HASH>..<HASH> 100644 --- a/context_test.go +++ b/context_test.go @@ -7,7 +7,6 @@ import ( "encoding/xml" "errors" "fmt" - "github.com/labstack/gommon/log" "io" "math" "mime/multipart" @@ -19,6 +18,7 @@ import ( "text/template" "time" + "github.com/labstack/gommon/log" testify "github.com/stretchr/testify/assert" ) diff --git a/middleware/cors_test.go b/middleware/cors_test.go index <HASH>..<HASH> 100644 --- a/middleware/cors_test.go +++ b/middleware/cors_test.go @@ -73,7 +73,7 @@ func TestCORS(t *testing.T) { c = e.NewContext(req, rec) req.Header.Set(echo.HeaderOrigin, "http://aaa.example.com") cors = CORSWithConfig(CORSConfig{ - AllowOrigins: []string{"http://*.example.com"}, + AllowOrigins: []string{"http://*.example.com"}, }) h = cors(echo.NotFoundHandler) h(c) diff --git a/middleware/jwt.go b/middleware/jwt.go index <HASH>..<HASH> 100644 --- a/middleware/jwt.go +++ b/middleware/jwt.go @@ -25,7 +25,7 @@ type ( // ErrorHandler defines a function which is executed for an invalid token. // It may be used to define a custom JWT error. ErrorHandler JWTErrorHandler - + // ErrorHandlerWithContext is almost identical to ErrorHandler, but it's passed the current context. ErrorHandlerWithContext JWTErrorHandlerWithContext @@ -74,7 +74,7 @@ type ( // JWTErrorHandlerWithContext is almost identical to JWTErrorHandler, but it's passed the current context. JWTErrorHandlerWithContext func(error, echo.Context) error - + jwtExtractor func(echo.Context) (string, error) ) @@ -183,7 +183,7 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc { if config.ErrorHandler != nil { return config.ErrorHandler(err) } - + if config.ErrorHandlerWithContext != nil { return config.ErrorHandlerWithContext(err, c) } @@ -210,7 +210,7 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc { return config.ErrorHandler(err) } if config.ErrorHandlerWithContext != nil { - return config.ErrorHandlerWithContext(err, c) + return config.ErrorHandlerWithContext(err, c) } return &echo.HTTPError{ Code: http.StatusUnauthorized, diff --git a/middleware/jwt_test.go b/middleware/jwt_test.go index <HASH>..<HASH> 100644 --- a/middleware/jwt_test.go +++ b/middleware/jwt_test.go @@ -205,7 +205,7 @@ func TestJWT(t *testing.T) { req.Header.Set(echo.HeaderCookie, tc.hdrCookie) c := e.NewContext(req, res) - if tc.reqURL == "/" + token { + if tc.reqURL == "/"+token { c.SetParamNames("jwt") c.SetParamValues(token) }
format code (gofmt + trim trailing space) (#<I>)
labstack_echo
train
0f582476799f4bd169e0c8236e40c0efd778a465
diff --git a/km3modules/plot.py b/km3modules/plot.py index <HASH>..<HASH> 100644 --- a/km3modules/plot.py +++ b/km3modules/plot.py @@ -173,8 +173,8 @@ class IntraDOMCalibrationPlotter(kp.Module): ) sorted_dom_ids = sorted( calibration.keys(), - key=lambda d: - str(self.db.doms.via_dom_id(dom_id=d, det_id=self.det_oid)) + key=lambda d: self.db.doms. + via_dom_id(dom_id=d, det_id=self.det_oid).omkey ) # by DU and FLOOR, note that DET OID is needed! for ax, dom_id in zip(axes.flatten(), sorted_dom_ids): calib = calibration[dom_id]
Use omkey property to sort
tamasgal_km3pipe
train
41441d2e06c1f012c58fce10615ee414ad263196
diff --git a/spec/dfeojm_spec.rb b/spec/dfeojm_spec.rb index <HASH>..<HASH> 100644 --- a/spec/dfeojm_spec.rb +++ b/spec/dfeojm_spec.rb @@ -2,30 +2,38 @@ require 'dfeojm' describe DFEOJM do it "provides usage information by default" do - result = %x[dfeojm 2>&1] + output = `dfeojm 2>&1` + result = $?.exitstatus - result.should match /Error: hostname must be present/ - result.should_not match /is up/ - result.should_not match /looks down/ + output.should match /Error: hostname must be present/ + output.should_not match /is up/ + output.should_not match /looks down/ + result.should_not be 0 end it "provides version information" do - result = %x[dfeojm -v 2>/dev/null] + output = `dfeojm -v 2>/dev/null` + result = $?.exitstatus - result.should match /[0-9]+\.[0-9]+/ + output.should match /[0-9]+\.[0-9]+/ + result.should be 0 end it "shows that www.google.com should usually be up" do - result = %x[dfeojm www.google.com 2>/dev/null] + output = `dfeojm www.google.com 2>/dev/null` + result = $?.exitstatus - result.should match /is up/ - result.should_not match /looks down/ + output.should match /is up/ + output.should_not match /looks down/ + result.should be 0 end it "shows that www.thiswillneverexist.com should usually be down" do - result = %x[dfeojm www.thiswillneverexist.com 2>/dev/null] + output = `dfeojm www.thiswillneverexist.com 2>/dev/null` + result = $?.exitstatus - result.should match /looks down/ - result.should_not match /is up/ + output.should match /looks down/ + output.should_not match /is up/ + result.should_not be 0 end end
reorganized spec and checked exit codes
steakknife_dfeojm
train
66cb17ec07c2fa146b4cd0984095b74ed1722b66
diff --git a/satpy/readers/fci_l1c_fdhsi.py b/satpy/readers/fci_l1c_fdhsi.py index <HASH>..<HASH> 100644 --- a/satpy/readers/fci_l1c_fdhsi.py +++ b/satpy/readers/fci_l1c_fdhsi.py @@ -182,8 +182,7 @@ class FCIFDHSIFileHandler(NetCDF4FileHandler): def calc_area_extent(self, key): """Calculate area extent for a dataset. - - Cache results between channels""" + """ # Calculate the area extent of the swath based on start line and column # information, total number of segments and channel resolution # numbers from PUG, Table 3
FCI reader, adapt docstring to reality
pytroll_satpy
train
98d9f0c410588ce9240638f9f1c2e6c380ff721f
diff --git a/oct/core/hq.py b/oct/core/hq.py index <HASH>..<HASH> 100644 --- a/oct/core/hq.py +++ b/oct/core/hq.py @@ -18,6 +18,7 @@ class HightQuarter(object): :param str topic: topic for external publishing socket :param bool with_forwarder: tell HQ if it should connects to forwarder, default False :param bool with_streamer: tell HQ if ti should connects to streamer, default False + :param str streamer_address: streamer address to connect with form : <ip>:<port> """ def __init__(self, output_dir, config, topic, master=True, *args, **kwargs): self.context = zmq.Context() @@ -35,10 +36,25 @@ class HightQuarter(object): self.started = False self.messages = 0 + with_streamer = kwargs.get('with_streamer', False) + streamer_address = None + if with_streamer: + streamer_address = kwargs.get('streamer_address', "127.0.0.1:{}".format(config.get('external_publisher'))) + + self._configure_external_publisher(config, with_streamer, streamer_address) + # waiting for init sockets print("Warmup") time.sleep(1) + def _configure_external_publisher(self, config, with_streamer=False, streamer_address=None): + external_publisher = config.get('external_publisher', 5002) if not streamer_address else streamer_address + + if with_streamer: + self.external_publisher.connect("tcp://{}".format(external_publisher)) + else: + self.external_publisher.bind("tcp://*:{}".format(external_publisher)) + def _configure_sockets(self, config, with_streamer=False, with_forwarder=False): """Configure sockets for HQ @@ -47,13 +63,10 @@ class HightQuarter(object): :param bool with_forwarder: tell if we need to connect to forwarder or simply bind """ rc_port = config.get('rc_port', 5001) - external_publisher = config.get('external_publisher', 5002) self.result_collector.set_hwm(0) self.result_collector.bind("tcp://*:{}".format(rc_port)) - self.external_publisher.bind("tcp://*:{}".format(external_publisher)) - self.poller.register(self.result_collector, zmq.POLLIN) def _process_socks(self, socks):
prepare hq for forwarder #<I>
TheGhouls_oct
train
7e65b453a26bb21f83b35f8411cae3a3b1d5afd2
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,5 +1,7 @@ require 'simplecov' -SimpleCov.start +SimpleCov.start do + add_filter "/spec/" +end require 'bini' require 'bini/optparser'
Filtered out my specs from my coverage, still have <I>%.
erniebrodeur_bini
train
5483ae6df014a6ba35a07754c1996752532684f2
diff --git a/app/src/Gruntfile.js b/app/src/Gruntfile.js index <HASH>..<HASH> 100644 --- a/app/src/Gruntfile.js +++ b/app/src/Gruntfile.js @@ -9,6 +9,7 @@ module.exports = function(grunt) { path: { tmp: 'tmp', pages: 'tmp/pages', + sourcemaps: '../view/maps', doc: { js: 'docs/js', php: 'docs/php' diff --git a/app/src/grunt/uglify.js b/app/src/grunt/uglify.js index <HASH>..<HASH> 100644 --- a/app/src/grunt/uglify.js +++ b/app/src/grunt/uglify.js @@ -9,6 +9,7 @@ module.exports = { options: { preserveComments: 'some', sourceMap: '<%= sourcemap.js %>', + sourceMapName: '<%= path.sourcemaps %>/lib.js.map', sourceMapIncludeSources: true }, files: [{ @@ -108,6 +109,7 @@ module.exports = { prepareBootstrapJs: { options: { sourceMap: '<%= sourcemap.js %>', + sourceMapName: '<%= path.sourcemaps %>/bootstrap.js.map', sourceMapIncludeSources: true }, files: { @@ -131,7 +133,7 @@ module.exports = { options: { banner: '<%= banner.boltJs %>', sourceMap: '<%= sourcemap.js %>', - sourceMapName: '<%= path.dest.js %>/maps/bolt.min.js.map' + sourceMapName: '<%= path.sourcemaps %>/bolt.js.map' }, files: { '<%= path.dest.js %>/bolt.min.js': '<%= files.boltJs %>'
Now generate js souremaps in view/maps
bolt_bolt
train
be0b37f28cdc829b7351988d360dba88c391b71a
diff --git a/lib/from.js b/lib/from.js index <HASH>..<HASH> 100644 --- a/lib/from.js +++ b/lib/from.js @@ -220,8 +220,17 @@ return (function () { var delay = function (func) { setTimeout(func, 0) }; + // For API consistency with `from.thisDirectory`, `from.thisPath` returns a + // `Promise`. There’s no *actual* async operations occuring, feel free to + // `wait()` on it for a sync return value. var thisPath; // = undefined; - from['thisPath'] = function () { return thisPath }; + var thisPathGetter = function () { + var getter = new(process.Promise); + + delay(function () { getter.emitSuccess(thisPath) }); + + return getter; + }; from['thisPath'] = thisPathGetter; var thisDirectory = function (relativeTo) { var getter = new(process.Promise),
`from.thisPath` is now an async getter
ELLIOTTCABLE_from
train
d5667b2dcafc1094126ec897aee1f1543fa673e8
diff --git a/ui/src/side_nav/components/UserNavBlock.js b/ui/src/side_nav/components/UserNavBlock.js index <HASH>..<HASH> 100644 --- a/ui/src/side_nav/components/UserNavBlock.js +++ b/ui/src/side_nav/components/UserNavBlock.js @@ -3,7 +3,7 @@ import {Link} from 'react-router' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' -import Authorized, {SUPERADMIN_ROLE} from 'src/auth/Authorized' +import Authorized, {ADMIN_ROLE, SUPERADMIN_ROLE} from 'src/auth/Authorized' import classnames from 'classnames' @@ -41,11 +41,6 @@ class UserNavBlock extends Component { {me.name} </div> <Authorized requiredRole={SUPERADMIN_ROLE}> - <Link className="sidebar-menu--item" to={`${sourcePrefix}/users`}> - Manage Users - </Link> - </Authorized> - <Authorized requiredRole={SUPERADMIN_ROLE}> <Link className="sidebar-menu--item" to={`${sourcePrefix}/organizations`} @@ -53,6 +48,11 @@ class UserNavBlock extends Component { Manage Organizations </Link> </Authorized> + <Authorized requiredRole={ADMIN_ROLE}> + <Link className="sidebar-menu--item" to={`${sourcePrefix}/users`}> + Manage Users + </Link> + </Authorized> <a className="sidebar-menu--item" href={logoutLink}> Logout </a>
Only show Manage Organizations to SuperAdmin
influxdata_influxdb
train
37ebafc5926101a60a82c6716eb264ce26b398b1
diff --git a/TeamComp/tier.py b/TeamComp/tier.py index <HASH>..<HASH> 100644 --- a/TeamComp/tier.py +++ b/TeamComp/tier.py @@ -25,16 +25,28 @@ class Tier(Enum): silver = 5 bronze = 6 + def __lt__(self,other): + return self.value > other.value + + def __le__(self,other): + return self.value >= self.value + + def __gt__(self,other): + return self.value <= other.value + + def __ge__(self,other): + return self.value <= other.value + + def __eq__(self,other): + return self.value == other.value + + def __ne__(self,other): + return self.value != other.value + @unique class Maps(Enum): SUMMONERS_RIFT = 11 -def tier_to_int(tier): - return Tier[tier].value - -def int_to_tier(int): - return Tier(int) - def leagues_by_summoner_ids(summoner_ids, queue=Queue.RANKED_SOLO_5x5): summoners_league = defaultdict(set) for start, end in slice(0, len(summoner_ids), 10): @@ -45,13 +57,13 @@ def leagues_by_summoner_ids(summoner_ids, queue=Queue.RANKED_SOLO_5x5): return summoners_league def update_participants(tier_seed, participantsIdentities, queue=Queue.RANKED_SOLO_5x5, minimum_tier=Tier.bronze): - match_tier = Tier.challenger.value + match_tier = Tier.challenger leagues = leagues_by_summoner_ids([p.player.summonerId for p in participantsIdentities], queue) for league, ids in leagues.items(): - if league.value <= minimum_tier.value: + if league >= minimum_tier: tier_seed[league].update(ids) - match_tier = max(match_tier, league.value) - return int_to_tier(match_tier) + match_tier = min(match_tier, league.value) + return match_tier def summoner_names_to_id(summoners): ids = {}
Overloeaded the comparison function for Tier
MakersF_LoLScraper
train
1f00da5f083ec7d68c56dc4958d3d415fc77b4a6
diff --git a/example1.py b/example1.py index <HASH>..<HASH> 100644 --- a/example1.py +++ b/example1.py @@ -27,6 +27,11 @@ def func2(q1, q2): """ a = q1/q2 + + if q2 == 5: + z = 7 + IPS() + return a @@ -46,10 +51,9 @@ z = func1(x) - 5 u = y**2 + z**2# should be an array full of 1.0 - - b1 = func2(1.0, 2.0) -b2 = func2(1.0, 0) # ZeroDivisionError -> start interactive debugger +#b2 = func2(1.0, 0) # ZeroDivisionError -> start interactive debugger +b2 = func2(1.0, 5) # start IPS inside func2 -IPS() +#IPS() # start IPS on top level diff --git a/ipHelp.py b/ipHelp.py index <HASH>..<HASH> 100644 --- a/ipHelp.py +++ b/ipHelp.py @@ -6,7 +6,7 @@ import new import inspect -__version__ = "0.4.1" +__version__ = "0.4.1.1" @@ -149,6 +149,12 @@ try: config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell + + # these two lines prevent problems in related to the initialization + # of ultratb.FormattedTB below + InteractiveShellEmbed.clear_instance() + InteractiveShellEmbed._instance = None + shell = InteractiveShellEmbed.instance() shell(header=custom_header, stack_depth=2)
Bugfix (configurable.MultipleInstanceError was triggered probably by some update)
cknoll_ipydex
train
496b5659e127a5bf0e51fa8a7a78d9c068020a8b
diff --git a/flac/decode.go b/flac/decode.go index <HASH>..<HASH> 100644 --- a/flac/decode.go +++ b/flac/decode.go @@ -21,11 +21,7 @@ func Decode(rc io.ReadCloser) (s beep.StreamSeekCloser, format beep.Format, err d.rc.Close() } }() - rsc, ok := rc.(io.ReadSeeker) - if !ok { - panic(fmt.Errorf("%T does not implement io.Seeker", rc)) - } - d.stream, err = flac.New(rsc) + d.stream, err = flac.New(rc) if err != nil { return nil, beep.Format{}, errors.Wrap(err, "flac") } @@ -139,7 +135,7 @@ func (d *decoder) Position() int { } func (d *decoder) Seek(p int) error { - panic("not yet implemented") + return errors.New("flac.decoder.Seek: not yet implemented") } func (d *decoder) Close() error {
flac: remove ReadSeeker assertion The underlying flac library does not yet support seeking, and when that support is added, this should be done more gracefully in beep so that users can still use streaming data not implementing io.Seeker Fixes #<I>.
faiface_beep
train
860a8fb7a6981c5f68408a389b5639fc5110a7b1
diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/subscription/SubscriptionInterceptorLoader.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/subscription/SubscriptionInterceptorLoader.java index <HASH>..<HASH> 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/subscription/SubscriptionInterceptorLoader.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/subscription/SubscriptionInterceptorLoader.java @@ -37,6 +37,7 @@ import java.util.Set; public class SubscriptionInterceptorLoader { private static final Logger ourLog = LoggerFactory.getLogger(SubscriptionInterceptorLoader.class); + // TODO KHS remove side-effects of autowiring these beans private SubscriptionMatcherInterceptor mySubscriptionMatcherInterceptor; private SubscriptionActivatingInterceptor mySubscriptionActivatingInterceptor; @@ -52,11 +53,16 @@ public class SubscriptionInterceptorLoader { if (!supportedSubscriptionTypes.isEmpty()) { loadSubscriptions(); - + if (mySubscriptionActivatingInterceptor == null) { + mySubscriptionActivatingInterceptor = myAppicationContext.getBean(SubscriptionActivatingInterceptor.class); + } ourLog.info("Registering subscription activating interceptor"); myDaoConfig.registerInterceptor(mySubscriptionActivatingInterceptor); } if (myDaoConfig.isSubscriptionMatchingEnabled()) { + if (mySubscriptionMatcherInterceptor == null) { + mySubscriptionMatcherInterceptor = myAppicationContext.getBean(SubscriptionMatcherInterceptor.class); + } ourLog.info("Registering subscription matcher interceptor"); myDaoConfig.registerInterceptor(mySubscriptionMatcherInterceptor); } @@ -67,14 +73,6 @@ public class SubscriptionInterceptorLoader { // Load subscriptions into the SubscriptionRegistry myAppicationContext.getBean(SubscriptionLoader.class); ourLog.info("...{} subscriptions loaded", mySubscriptionRegistry.size()); - - // Once subscriptions have been loaded, now - if (mySubscriptionActivatingInterceptor == null) { - mySubscriptionActivatingInterceptor = myAppicationContext.getBean(SubscriptionActivatingInterceptor.class); - } - if (mySubscriptionMatcherInterceptor == null) { - mySubscriptionMatcherInterceptor = myAppicationContext.getBean(SubscriptionMatcherInterceptor.class); - } } @VisibleForTesting
Emergency fix. Normally I'd write a test for this, but this startup behaviour is changing in my next PR.
jamesagnew_hapi-fhir
train
2811fb562b961c406cf483d6bd8a2e7c89132680
diff --git a/lib/ps4socket.js b/lib/ps4socket.js index <HASH>..<HASH> 100644 --- a/lib/ps4socket.js +++ b/lib/ps4socket.js @@ -32,8 +32,7 @@ const PacketFactory = require('./packets.js'); const { delayMillis } = require('./util'); const DEFAULT_PORT = 997; -const DEFAULT_LOGIN_TIMEOUT = 5000; -const LOGIN_RETRY_DELAY = 2000; +const SERVER_RESPONSE_TIMEOUT = 60000; let KnownPackets; @@ -86,7 +85,6 @@ function Ps4Socket(config) { this.packets = new PacketFactory(); this.loggedIn = false; this._loginResult = null; - this._loginRetryTimer = null; // eslint-disable-next-line if (this.config.host) { @@ -100,6 +98,7 @@ Ps4Socket.prototype.connect = function(host, port) { const creds = { 'user-credential': this.config.accountId }; const device = { address: host }; + this._lastConnect = { host, port }; const udp = ps4lib.udpSocket(); udp.bind(async () => { @@ -160,12 +159,6 @@ Ps4Socket.prototype._cleanup = function() { this.client = null; this.loggedIn = false; this._loginResult = null; - - // just in case - if (this._loginRetryTimer) { - clearTimeout(this._loginRetryTimer); - this._loginRetryTimer = null; - } }; /** @@ -197,8 +190,6 @@ Ps4Socket.prototype.isLoggedIn = function() { * { * passCode: // the (optional) passcode * , pinCode: // the (optional) pincode - * , timeout: // milliseconds after which to give up - * , retries: // number of times to retry on timeout * } * @param callback Optional; if provided, will be * called when we get the login_result event @@ -223,8 +214,6 @@ Ps4Socket.prototype.login = function(pinCodeOrConfig, callback) { config = { pinCode: '', - timeout: DEFAULT_LOGIN_TIMEOUT, - retries: 3, ...config, }; @@ -253,23 +242,12 @@ Ps4Socket.prototype.login = function(pinCodeOrConfig, callback) { }; loginTimeout = setTimeout(() => { - debug(`Login timed out; ${config.retries} retries remaining`); + debug('Login timed out'); this.removeListener('login_result', onLoginResult); - config.retries -= 1; - if (config.retries > 0) { - // try again after a short delay - debug(`Retry login in ${LOGIN_RETRY_DELAY}`); - this.emit('login_retry', this); - this._loginRetryTimer = setTimeout(() => { - this.login(config, cb); - }, LOGIN_RETRY_DELAY); - return; - } - this.emit('login_result', { error_code: -1, error: 'Timeout' }); cb(new Error('Timeout logging in')); - }, config.timeout); + }, SERVER_RESPONSE_TIMEOUT); this.once('login_result', onLoginResult); } @@ -310,7 +288,7 @@ Ps4Socket.prototype.logout = function(callback) { debug('Logout timeout'); this.removeListener('login_result', onLogoutResult); callback(new Error('Timeout waiting for logout result')); - }, 15000); + }, SERVER_RESPONSE_TIMEOUT); this.once('logout_result', onLogoutResult); }; @@ -471,11 +449,6 @@ KnownPackets = { packet.result = result; debug('<<< LOGIN_RESULT', result); - if (this._loginRetryTimer) { - clearTimeout(this._loginRetryTimer); - this._loginRetryTimer = null; - } - if (result !== 0) { packet.error = 'LOGIN_FAILED'; packet.error_code = result;
Disable login retry in favor of a longer timeout This seems more in line with what the app does; it just has a blanket server timeout of <I>s. This approach not only simplifies things, but eliminates another possible candidate for the LOGIN_MGR_BUSY issue (see #<I>). Sadly, it does not actually solve the issue, however.
dhleong_ps4-waker
train
a82d018e722899948981e6cbeac9dac8fe5087e2
diff --git a/lib/cli/file-set.js b/lib/cli/file-set.js index <HASH>..<HASH> 100644 --- a/lib/cli/file-set.js +++ b/lib/cli/file-set.js @@ -236,12 +236,22 @@ function add(file) { 'fileSet': self }; - filePipeline.run(context, function (err) { - if (err) { - file.fail(err); - } + /* + * Force an asynchronous operation. + * This ensures that files which fall through + * the file pipeline quicker that expected (e.g., + * when already fatally failed) still queue up + * correctly. + */ + + setImmediate(function () { + filePipeline.run(context, function (err) { + if (err) { + file.fail(err); + } - one(self); + one(self); + }); }); return self;
Fix premature reporting A bug was recently introduced where, when the first file had failed before it was passed to the file pipeline, it could cause the file queue to flush.
remarkjs_remark
train
a6dbccd29b8cb6f6c18f7c636588d634ead3f341
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -11,9 +11,9 @@ ], "require": { "php": ">=5.3.2", - "precore/precore": "~1.0", + "precore/precore": "~1.3", "doctrine/annotations": "~1.1", - "trf4php/trf4php": "~1.1", + "trf4php/trf4php": "~1.2", "lf4php/lf4php": "~4.0", "ocramius/lazy-map": "~1.0" }, diff --git a/src/predaddy/commandhandling/DirectCommandForwarder.php b/src/predaddy/commandhandling/DirectCommandForwarder.php index <HASH>..<HASH> 100644 --- a/src/predaddy/commandhandling/DirectCommandForwarder.php +++ b/src/predaddy/commandhandling/DirectCommandForwarder.php @@ -58,7 +58,7 @@ class DirectCommandForwarder extends Object */ public function forwardCommand(DirectCommand $command) { - $class = new ObjectClass($command->getAggregateClass()); + $class = ObjectClass::forName($command->getAggregateClass()); $repository = $this->repositoryRepository->getRepository($class); $aggregateId = $command->getAggregateIdentifier(); if ($aggregateId === null) { diff --git a/src/predaddy/domain/impl/LazyEventSourcedRepositoryRepository.php b/src/predaddy/domain/impl/LazyEventSourcedRepositoryRepository.php index <HASH>..<HASH> 100644 --- a/src/predaddy/domain/impl/LazyEventSourcedRepositoryRepository.php +++ b/src/predaddy/domain/impl/LazyEventSourcedRepositoryRepository.php @@ -51,7 +51,7 @@ class LazyEventSourcedRepositoryRepository implements RepositoryRepository $this->map = new CallbackLazyMap( function ($aggregateClass) use ($eventBus, $eventStore, $snapshotStrategy) { return new EventSourcingRepository( - new ObjectClass($aggregateClass), + ObjectClass::forName($aggregateClass), $eventBus, $eventStore, $snapshotStrategy diff --git a/src/predaddy/domain/impl/doctrine/DoctrineOrmEventStore.php b/src/predaddy/domain/impl/doctrine/DoctrineOrmEventStore.php index <HASH>..<HASH> 100644 --- a/src/predaddy/domain/impl/doctrine/DoctrineOrmEventStore.php +++ b/src/predaddy/domain/impl/doctrine/DoctrineOrmEventStore.php @@ -138,7 +138,7 @@ class DoctrineOrmEventStore implements SnapshotEventStore /* @var $aggregateRoot EventSourcedAggregateRoot */ $aggregateRoot = $this->loadSnapshot($aggregateRootClass, $aggregateId); if ($aggregateRoot === null) { - $objectClass = new ObjectClass($aggregateRootClass); + $objectClass = ObjectClass::forName($aggregateRootClass); $aggregateRoot = $objectClass->newInstanceWithoutConstructor(); } $aggregateRoot->loadFromHistory($events); @@ -168,7 +168,7 @@ class DoctrineOrmEventStore implements SnapshotEventStore /* @var $snapshot Snapshot */ $snapshot = $this->findSnapshot($aggregateRootClass, $aggregateId); if ($snapshot !== null) { - $reflectionClass = new ObjectClass($aggregateRootClass); + $reflectionClass = ObjectClass::forName($aggregateRootClass); $aggregateRoot = $this->serializer->deserialize($snapshot->getAggregateRoot(), $reflectionClass); } return $aggregateRoot;
removed inline ObjectClass instantiations
szjani_predaddy
train
00d137edec47992e2c6ce4c9f5ece1b4854785f5
diff --git a/go/vt/proto/query/query.pb.go b/go/vt/proto/query/query.pb.go index <HASH>..<HASH> 100644 --- a/go/vt/proto/query/query.pb.go +++ b/go/vt/proto/query/query.pb.go @@ -3629,7 +3629,7 @@ type StreamHealthResponse struct { // realtime_stats contains information about the tablet status. // It is only filled in if the information is about a tablet. RealtimeStats *RealtimeStats `protobuf:"bytes,4,opt,name=realtime_stats,json=realtimeStats,proto3" json:"realtime_stats,omitempty"` - // tablet_alias is the alias of the sending tablet. The discovery/legacy_healthcheck.go + // tablet_alias is the alias of the sending tablet. The discovery/healthcheck.go // code uses it to verify that it's talking to the correct tablet and that it // hasn't changed in the meantime e.g. due to tablet restarts where ports or // ips have been reused but assigned differently. diff --git a/go/vt/vtgate/tabletgateway.go b/go/vt/vtgate/tabletgateway.go index <HASH>..<HASH> 100644 --- a/go/vt/vtgate/tabletgateway.go +++ b/go/vt/vtgate/tabletgateway.go @@ -200,19 +200,18 @@ func (gw *TabletGateway) withRetry(ctx context.Context, target *querypb.Target, } gw.shuffleTablets(gw.localCell, tablets) - var tabletLastUsed string var th *discovery.TabletHealth // skip tablets we tried before for _, t := range tablets { - tabletLastUsed = topoproto.TabletAliasString(t.Tablet.Alias) - if _, ok := invalidTablets[tabletLastUsed]; !ok { + tabletLastUsed = t.Tablet + if _, ok := invalidTablets[topoproto.TabletAliasString(tabletLastUsed.Alias)]; !ok { th = t break } else { - tabletLastUsed = "" + tabletLastUsed = nil } } - if tabletLastUsed == "" { + if tabletLastUsed == nil { // do not override error from last attempt. if err == nil { err = vterrors.New(vtrpcpb.Code_UNAVAILABLE, "no available connection") @@ -223,7 +222,7 @@ func (gw *TabletGateway) withRetry(ctx context.Context, target *querypb.Target, // execute if th.Conn == nil { err = vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "no connection for tablet %v", tabletLastUsed) - invalidTablets[tabletLastUsed] = true + invalidTablets[topoproto.TabletAliasString(tabletLastUsed.Alias)] = true continue } @@ -232,7 +231,7 @@ func (gw *TabletGateway) withRetry(ctx context.Context, target *querypb.Target, canRetry, err = inner(ctx, target, th.Conn) gw.updateStats(target, startTime, err) if canRetry { - invalidTablets[tabletLastUsed] = true + invalidTablets[topoproto.TabletAliasString(tabletLastUsed.Alias)] = true continue } break
healthcheck: update protobuf generated sources, fix shadowing bug which results in incomplete error information
vitessio_vitess
train
8adac7586bb1ca264ae47ee3f599d43fe5dcb8cd
diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,6 @@ { "version": "0.0.0", "name": "haul", - "version": "0.0.1", "description": "Haul is a new command line tools for React Native", "bin": "./src/cli", "scripts": { diff --git a/src/cli/start/index.js b/src/cli/start/index.js index <HASH>..<HASH> 100644 --- a/src/cli/start/index.js +++ b/src/cli/start/index.js @@ -21,7 +21,8 @@ function start() { { port: 8081, dev: true, - platform: "ios" + platform: "ios", + cwd: process.cwd(), } ); diff --git a/src/utils/makeReactNativeConfig.js b/src/utils/makeReactNativeConfig.js index <HASH>..<HASH> 100644 --- a/src/utils/makeReactNativeConfig.js +++ b/src/utils/makeReactNativeConfig.js @@ -16,6 +16,7 @@ const PLATFORMS = ["ios", "android"]; type ConfigOptions = { port: number, platform: "ios" | "android", + cwd: string, dev: boolean }; @@ -31,7 +32,7 @@ type WebpackConfigFactory = /** * Returns default config based on environment */ -const getDefaultConfig = ({ platform, dev, port }): WebpackConfig => ({ +const getDefaultConfig = ({ platform, cwd, dev, port }): WebpackConfig => ({ // Default polyfills and entry-point setup entry: [require.resolve("./polyfillEnvironment.js")], // Built-in loaders @@ -65,7 +66,7 @@ const getDefaultConfig = ({ platform, dev, port }): WebpackConfig => ({ // Default resolve resolve: { alias: findProvidesModule([ - path.resolve(process.cwd(), "node_modules/react-native") + path.resolve(cwd, "node_modules/react-native") ]), extensions: [`.${platform}.js`, ".js"] },
Pass cwd to config getter
callstack_haul
train
01c4f63c2ba66ca260c64841ad05f3f35df2bd52
diff --git a/lib/asciidoctor/rouge.rb b/lib/asciidoctor/rouge.rb index <HASH>..<HASH> 100644 --- a/lib/asciidoctor/rouge.rb +++ b/lib/asciidoctor/rouge.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true +require 'asciidoctor' require 'asciidoctor/extensions' require 'asciidoctor/rouge/constants' require 'asciidoctor/rouge/docinfo_processor' diff --git a/lib/asciidoctor/rouge/docinfo_processor.rb b/lib/asciidoctor/rouge/docinfo_processor.rb index <HASH>..<HASH> 100644 --- a/lib/asciidoctor/rouge/docinfo_processor.rb +++ b/lib/asciidoctor/rouge/docinfo_processor.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true require 'asciidoctor/rouge/constants' +require 'asciidoctor' require 'asciidoctor/extensions' require 'rouge' diff --git a/lib/asciidoctor/rouge/passthroughs_substitutor.rb b/lib/asciidoctor/rouge/passthroughs_substitutor.rb index <HASH>..<HASH> 100644 --- a/lib/asciidoctor/rouge/passthroughs_substitutor.rb +++ b/lib/asciidoctor/rouge/passthroughs_substitutor.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true -require 'asciidoctor/substitutors' +require 'asciidoctor' require 'asciidoctor/rouge/constants' module Asciidoctor::Rouge diff --git a/lib/asciidoctor/rouge/treeprocessor.rb b/lib/asciidoctor/rouge/treeprocessor.rb index <HASH>..<HASH> 100644 --- a/lib/asciidoctor/rouge/treeprocessor.rb +++ b/lib/asciidoctor/rouge/treeprocessor.rb @@ -3,6 +3,7 @@ require 'asciidoctor/rouge/constants' require 'asciidoctor/rouge/callouts_substitutor' require 'asciidoctor/rouge/html_formatter' require 'asciidoctor/rouge/passthroughs_substitutor' +require 'asciidoctor' require 'asciidoctor/extensions' require 'rouge'
Fix compatibility with asciidoctor <I>
jirutka_asciidoctor-rouge
train
edb9904138ce4e20c7597ff04f6c480997ad095d
diff --git a/mqemitter-redis.js b/mqemitter-redis.js index <HASH>..<HASH> 100644 --- a/mqemitter-redis.js +++ b/mqemitter-redis.js @@ -77,6 +77,7 @@ function MQEmitterRedis (opts) { MQEmitter.call(this, opts) this._opts.regexWildcardOne = new RegExp(this._opts.wildcardOne.replace(/([/,!\\^${}[\]().*+?|<>\-&])/g, '\\$&'), 'g') + this._opts.regexWildcardSome = new RegExp((this._opts.matchEmptyLevels ? this._opts.separator.replace(/([/,!\\^${}[\]().*+?|<>\-&])/g, '\\$&') + '?' : '') + this._opts.wildcardSome.replace(/([/,!\\^${}[\]().*+?|<>\-&])/g, '\\$&'), 'g') } inherits(MQEmitterRedis, MQEmitter) @@ -115,7 +116,7 @@ MQEmitterRedis.prototype.close = function (cb) { MQEmitterRedis.prototype._subTopic = function (topic) { return topic .replace(this._opts.regexWildcardOne, '*') - .replace((this._opts.matchEmptyLevels ? this._opts.separator : '') + this._opts.wildcardSome, '*') + .replace(this._opts.regexWildcardSome, '*') } MQEmitterRedis.prototype.on = function on (topic, cb, done) {
fix: Wildcard some to work with # (#<I>) * fix: Wildcard some to work with # * check if matchEmptyLevels is enabled
mcollina_mqemitter-redis
train
e13fe724557d225149de7e1ec442f8a66afbdd60
diff --git a/opal/corelib/string/unpack.rb b/opal/corelib/string/unpack.rb index <HASH>..<HASH> 100644 --- a/opal/corelib/string/unpack.rb +++ b/opal/corelib/string/unpack.rb @@ -1,3 +1,4 @@ +require 'base64' require 'corelib/pack_unpack/format_string_parser' class String @@ -234,23 +235,7 @@ class String function base64Decode(callback) { return function(data) { - var string = callback(data); - if (typeof(atob) === 'function') { - // Browser - return atob(string); - } else if (typeof(Buffer) === 'function') { - // Node - if (typeof(Buffer.from) === 'function') { - // Node 5.10+ - return Buffer.from(string, 'base64').toString(); - } else { - return new Buffer(string, 'base64').toString(); - } - } else if (#{defined?(Base64)}) { - return #{Base64.decode64(`string`)}; - } else { - #{raise "To use String#unpack('m'), you must first require 'base64'."} - } + return #{Base64.decode64(`callback(data)`)}; } } diff --git a/stdlib/base64.rb b/stdlib/base64.rb index <HASH>..<HASH> 100644 --- a/stdlib/base64.rb +++ b/stdlib/base64.rb @@ -6,7 +6,7 @@ module Base64 // encoder // [https://gist.github.com/999166] by [https://github.com/nignag] - encode = Opal.global.btoa || function (input) { + encode = function (input) { var str = String(input); /* jshint ignore:start */ for ( @@ -31,7 +31,7 @@ module Base64 // decoder // [https://gist.github.com/1020396] by [https://github.com/atk] - decode = Opal.global.atob || function (input) { + decode = function (input) { var str = String(input).replace(/=+$/, ''); if (str.length % 4 == 1) { #{raise ArgumentError, 'invalid base64 (failed: The string to be decoded is not correctly encoded.)'};
Use a single implementation for Base<I> Previously the behavior was buggy on some platforms.
opal_opal
train
969873441ec42f1790b3b601f04e46d9493a64d8
diff --git a/src/js/ripple/transaction.js b/src/js/ripple/transaction.js index <HASH>..<HASH> 100644 --- a/src/js/ripple/transaction.js +++ b/src/js/ripple/transaction.js @@ -529,7 +529,7 @@ Transaction.prototype.setFlags = function(flags) { Transaction.prototype.accountSet = function(src) { if (typeof src === 'object') { var options = src; - src = options.source || options.from; + src = options.source || options.from || options.account; } if (!UInt160.is_valid(src)) { @@ -538,6 +538,7 @@ Transaction.prototype.accountSet = function(src) { this.tx_json.TransactionType = 'AccountSet'; this.tx_json.Account = UInt160.json_rewrite(src); + return this; }; @@ -547,7 +548,7 @@ Transaction.prototype.claim = function(src, generator, public_key, signature) { signature = options.signature; public_key = options.public_key; generator = options.generator; - src = options.source || options.from; + src = options.source || options.from || options.account; } this.tx_json.TransactionType = 'Claim'; @@ -561,7 +562,7 @@ Transaction.prototype.offerCancel = function(src, sequence) { if (typeof src === 'object') { var options = src; sequence = options.sequence; - src = options.source || options.from; + src = options.source || options.from || options.account; } if (!UInt160.is_valid(src)) { @@ -571,6 +572,7 @@ Transaction.prototype.offerCancel = function(src, sequence) { this.tx_json.TransactionType = 'OfferCancel'; this.tx_json.Account = UInt160.json_rewrite(src); this.tx_json.OfferSequence = Number(sequence); + return this; }; @@ -585,7 +587,7 @@ Transaction.prototype.offerCreate = function(src, taker_pays, taker_gets, expira expiration = options.expiration; taker_gets = options.taker_gets || options.sell; taker_pays = options.taker_pays || options.buy; - src = options.source || options.from; + src = options.source || options.from || options.account; } if (!UInt160.is_valid(src)) { @@ -629,6 +631,7 @@ Transaction.prototype.passwordFund = function(src, dst) { this.tx_json.TransactionType = 'PasswordFund'; this.tx_json.Destination = UInt160.json_rewrite(dst); + return this; }; @@ -639,7 +642,7 @@ Transaction.prototype.passwordSet = function(src, authorized_key, generator, pub public_key = options.public_key; generator = options.generator; authorized_key = options.authorized_key; - src = options.source || options.from; + src = options.source || options.from || options.account; } if (!UInt160.is_valid(src)) { @@ -651,6 +654,7 @@ Transaction.prototype.passwordSet = function(src, authorized_key, generator, pub this.tx_json.Generator = generator; this.tx_json.PublicKey = public_key; this.tx_json.Signature = signature; + return this; }; @@ -676,10 +680,11 @@ Transaction.prototype.payment = function(src, dst, amount) { var options = src; amount = options.amount; dst = options.destination || options.to; - src = options.source || options.from; - if (options.invoiceID) { - this.invoiceID(options.invoiceID); - } + src = options.source || options.from || options.account; + } + + if (options.invoiceID) { + this.invoiceID(options.invoiceID); } if (!UInt160.is_valid(src)) { @@ -709,7 +714,7 @@ Transaction.prototype.rippleLineSet = function(src, limit, quality_in, quality_o quality_out = options.quality_out; quality_in = options.quality_in; limit = options.limit; - src = options.source || options.from; + src = options.source || options.from || options.account; } if (!UInt160.is_valid(src)) { @@ -743,7 +748,7 @@ Transaction.prototype.walletAdd = function(src, amount, authorized_key, public_k public_key = options.public_key; authorized_key = options.authorized_key; amount = options.amount; - src = options.source || options.from; + src = options.source || options.from || options.account; } if (!UInt160.is_valid(src)) { @@ -755,6 +760,7 @@ Transaction.prototype.walletAdd = function(src, amount, authorized_key, public_k this.tx_json.RegularKey = authorized_key; this.tx_json.PublicKey = public_key; this.tx_json.Signature = signature; + return this; };
Recognize account option as equivalent to source in transaction construction
ChainSQL_chainsql-lib
train
923f8893bc7d378bb4853a9fc57b3c620b4ca928
diff --git a/ibis/backends/base/sql/alchemy/datatypes.py b/ibis/backends/base/sql/alchemy/datatypes.py index <HASH>..<HASH> 100644 --- a/ibis/backends/base/sql/alchemy/datatypes.py +++ b/ibis/backends/base/sql/alchemy/datatypes.py @@ -1,5 +1,7 @@ +from __future__ import annotations + import functools -from typing import Iterable, Optional +from typing import Iterable import sqlalchemy as sa from sqlalchemy.dialects import mysql, postgresql, sqlite @@ -31,7 +33,7 @@ class StructType(UserDefinedType): return f"STRUCT({pairs})" -def table_from_schema(name, meta, schema, database: Optional[str] = None): +def table_from_schema(name, meta, schema, database: str | None = None): # Convert Ibis schema to SQLA table columns = []
chore: pyupgrade and add annotations from future
ibis-project_ibis
train
9a77af6cde50a70bf8e351c3e314ed4d505e6d1b
diff --git a/test/jade.test.js b/test/jade.test.js index <HASH>..<HASH> 100644 --- a/test/jade.test.js +++ b/test/jade.test.js @@ -272,6 +272,10 @@ module.exports = { err.message); }, + 'test html 5 mode': function(assert){ + assert.equal('<!DOCTYPE html>\n<input type="checked" checked>', render('!!! 5\ninput(type="checkbox", checked)')); + }, + 'test attrs': function(assert){ assert.equal('<img src="&lt;script&gt;" />', render('img(src="<script>")'), 'Test attr escaping');
Added a test for html 5 mode
pugjs_then-pug
train
73fc6e859d7b0d800dc01a21d32cd458c3a60205
diff --git a/pkg/policy/api/ingress.go b/pkg/policy/api/ingress.go index <HASH>..<HASH> 100644 --- a/pkg/policy/api/ingress.go +++ b/pkg/policy/api/ingress.go @@ -30,12 +30,9 @@ import ( // the effects of any Requires field in any rule will apply to all other // rules as well. // -// - For now, combining ToPorts, FromCIDR, and FromEndpoints in the same rule -// is not supported and any such rules will be rejected. In the future, this -// will be supported and if multiple members of this structure are specified, -// then all members must match in order for the rule to take effect. The -// exception to this rule is the Requires field, the effects of any Requires -// field in any rule will apply to all other rules as well. +// - FromEndpoints, FromCIDR, FromCIDRSet and FromEntities are mutually +// exclusive. Only one of these members may be present within an individual +// rule. type IngressRule struct { // FromEndpoints is a list of endpoints identified by an // EndpointSelector which are allowed to communicate with the endpoint diff --git a/pkg/policy/api/rule_validation.go b/pkg/policy/api/rule_validation.go index <HASH>..<HASH> 100644 --- a/pkg/policy/api/rule_validation.go +++ b/pkg/policy/api/rule_validation.go @@ -111,12 +111,6 @@ func (i *IngressRule) sanitize() error { "FromCIDRSet": len(i.FromCIDRSet), "FromEntities": len(i.FromEntities), } - l3DependentL4Support := map[interface{}]bool{ - "FromEndpoints": true, - "FromCIDR": false, - "FromCIDRSet": false, - "FromEntities": true, - } l7Members := countL7Rules(i.ToPorts) l7IngressSupport := map[string]bool{ "DNS": false, @@ -131,11 +125,6 @@ func (i *IngressRule) sanitize() error { } } } - for member := range l3Members { - if l3Members[member] > 0 && len(i.ToPorts) > 0 && !l3DependentL4Support[member] { - return fmt.Errorf("Combining %s and ToPorts is not supported yet", member) - } - } if len(l7Members) > 0 && !option.Config.EnableL7Proxy { return errors.New("L7 policy is not supported since L7 proxy is not enabled")
policy: Allow CIDR-dependent L4 support on ingress This allows policies such as FromCIDR + ToPorts on ingress.
cilium_cilium
train
903b1dfd50f5b740d28a7bc8d933e037aa95776e
diff --git a/telebot/__init__.py b/telebot/__init__.py index <HASH>..<HASH> 100644 --- a/telebot/__init__.py +++ b/telebot/__init__.py @@ -909,9 +909,10 @@ class TeleBot: def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None): return apihelper.answer_pre_checkout_query(self.token, pre_checkout_query_id, ok, error_message) - def edit_message_caption(self, caption, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): + def edit_message_caption(self, caption, chat_id=None, message_id=None, inline_message_id=None, + parse_mode=None, reply_markup=None): result = apihelper.edit_message_caption(self.token, caption, chat_id, message_id, inline_message_id, - reply_markup) + parse_mode, reply_markup) if type(result) == bool: return result return types.Message.de_json(result) diff --git a/telebot/apihelper.py b/telebot/apihelper.py index <HASH>..<HASH> 100644 --- a/telebot/apihelper.py +++ b/telebot/apihelper.py @@ -616,7 +616,8 @@ def edit_message_text(token, text, chat_id=None, message_id=None, inline_message return _make_request(token, method_url, params=payload) -def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): +def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_message_id=None, + parse_mode=None, reply_markup=None): method_url = r'editMessageCaption' payload = {'caption': caption} if chat_id: @@ -625,6 +626,8 @@ def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_m payload['message_id'] = message_id if inline_message_id: payload['inline_message_id'] = inline_message_id + if parse_mode: + payload['parse_mode'] = parse_mode if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) return _make_request(token, method_url, params=payload)
added parse_mode in edit_message_caption
eternnoir_pyTelegramBotAPI
train
a4f2240aa582d032aa1d22983a834a83d2e1df74
diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/OElement.java b/core/src/main/java/com/orientechnologies/orient/core/record/OElement.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/OElement.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/OElement.java @@ -20,6 +20,7 @@ package com.orientechnologies.orient.core.record; import com.orientechnologies.orient.core.metadata.schema.OClass; +import com.orientechnologies.orient.core.metadata.schema.OType; import java.util.Optional; import java.util.Set; @@ -51,6 +52,20 @@ public interface OElement extends ORecord{ public void setProperty(String name, Object value); /** + * Sets a property value + * @param name the property name + * @param value the property value + * @param fieldType Forced type (not auto-determined) + */ + public void setProperty(String name, Object value, OType... fieldType); + + /** + * Remove a property + * @param name the property name + */ + public <RET> RET removeProperty(String name); + + /** * Returns an instance of OVertex representing current element * @return An OVertex that represents the current element. An empty optional if the current element is not a vertex */ diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java @@ -470,7 +470,7 @@ import java.util.stream.Collectors; } } - public Object removeProperty(final String iFieldName) { + public <RET> RET removeProperty(final String iFieldName) { checkForLoading(); checkForFields(); @@ -502,7 +502,7 @@ import java.util.stream.Collectors; if (oldValue instanceof ORidBag) ((ORidBag) oldValue).setOwner(null); setDirty(); - return oldValue; + return (RET) oldValue; } protected static void validateField(ODocument iRecord, OImmutableProperty p) throws OValidationException { diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/OEdgeDelegate.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/OEdgeDelegate.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/OEdgeDelegate.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/OEdgeDelegate.java @@ -28,6 +28,7 @@ import com.orientechnologies.orient.core.exception.ORecordNotFoundException; import com.orientechnologies.orient.core.exception.OSerializationException; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.metadata.schema.OClass; +import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.OEdge; import com.orientechnologies.orient.core.record.OElement; import com.orientechnologies.orient.core.record.ORecord; @@ -126,6 +127,14 @@ public class OEdgeDelegate implements OEdge { element.setProperty(name, value); } + @Override + public void setProperty(String name, Object value, OType... fieldType) { + if (element == null) { + promoteToRegularEdge(); + } + element.setProperty(name, value,fieldType); + } + private void promoteToRegularEdge() { ODatabase db = getDatabase(); OVertexDelegate from = (OVertexDelegate) getFrom(); @@ -138,6 +147,11 @@ public class OEdgeDelegate implements OEdge { this.vIn = null; } + @Override + public <RET> RET removeProperty(String name) { + return element.removeProperty(name); + } + @Override public Optional<OVertex> asVertex() { return Optional.empty(); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/OVertexDelegate.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/OVertexDelegate.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/OVertexDelegate.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/OVertexDelegate.java @@ -234,6 +234,16 @@ public class OVertexDelegate implements OVertex { element.setProperty(name, value); } + @Override + public void setProperty(String name, Object value, OType... fieldType) { + element.setProperty(name,value,fieldType); + } + + @Override + public <RET> RET removeProperty(String name) { + return element.removeProperty(name); + } + @Override public Optional<OVertex> asVertex() { return Optional.of(this); }
Added removeProperty and setProperty with type in OElement
orientechnologies_orientdb
train
1a48a1b83fb10aa44e9bb02f89eedc0fd93588cb
diff --git a/src/client/utils/ua.js b/src/client/utils/ua.js index <HASH>..<HASH> 100644 --- a/src/client/utils/ua.js +++ b/src/client/utils/ua.js @@ -1,5 +1,6 @@ -const ua = typeof navigator === 'undefined'? '' : navigator.userAgent; +const ua = typeof navigator === 'undefined'? '' : navigator.userAgent, + platform = typeof navigator === 'undefined'? '' : navigator.platform; export const isTrident = ua.indexOf('Trident') > -1; export const isEdge = ua.indexOf('Edge') > -1; -export const isIos = /iPad|iPhone|iPod/.test(ua) && typeof MSStream === 'undefined'; +export const isIos = /iPad|iPhone|iPod/.test(platform);
Use navigator.platform to detect ios in desktop mode
dfilatov_vidom
train
6b42b45685715aa92efaa3e818f826e3bc3b7b55
diff --git a/test/java-callStaticMethod-test.js b/test/java-callStaticMethod-test.js index <HASH>..<HASH> 100644 --- a/test/java-callStaticMethod-test.js +++ b/test/java-callStaticMethod-test.js @@ -12,6 +12,12 @@ exports['Java - Call Static Method'] = nodeunit.testCase({ }); }, + "callStaticMethod without a callback": function(test) { + var result = java.callStaticMethod("Test", "staticMethod"); + console.log("callStaticMethod without a callback result message", result); + test.done(); + }, + "callStaticMethodSync": function(test) { var result = java.callStaticMethodSync("Test", "staticMethod"); test.ok(result);
test case for [issue #<I>]
joeferner_node-java
train
0fe520de5636de0e3223b3c7e36b9a001072edde
diff --git a/src/xPDO/xPDO.php b/src/xPDO/xPDO.php index <HASH>..<HASH> 100644 --- a/src/xPDO/xPDO.php +++ b/src/xPDO/xPDO.php @@ -1101,11 +1101,15 @@ class xPDO { if (!$criteria instanceof Om\xPDOCriteria) { $this->log(xPDO::LOG_LEVEL_WARN, "Invalid criteria object of class {$type} encountered.", '', __METHOD__, __FILE__, __LINE__); $type = null; + } elseif ($criteria instanceof Om\xPDOQuery) { + $type = 'xPDOQuery'; + } else { + $type = 'xPDOCriteria'; } } return $type; } - +0 /** * Add criteria when requesting a derivative class row automatically. * diff --git a/test/xPDO/Test/xPDOTest.php b/test/xPDO/Test/xPDOTest.php index <HASH>..<HASH> 100644 --- a/test/xPDO/Test/xPDOTest.php +++ b/test/xPDO/Test/xPDOTest.php @@ -151,6 +151,17 @@ class xPDOTest extends TestCase } /** + * Verify xPDO::getCriteriaType returns "xPDOQuery" + */ + public function testGetCriteriaType() + { + $criteria = $this->xpdo->newQuery('xPDO\\Test\\Sample\\Person'); + $criteriaType = $this->xpdo->getCriteriaType($criteria); + $success = $criteriaType === 'xPDOQuery'; + $this->assertTrue($success, 'Unexpected criteriaType ' . $criteriaType); + } + + /** * Tests xPDO::getAncestry and make sure it returns an array of the correct * data. *
Modify getCriteriaType to return xPDOQuery|xPDOCriteria After refactoring xPDO into the \xPDO namespace, getCriteriaType returns the fully-qualified class name which breaks a feature of xPDOIterator that depends on methods of xPDOQuery derivatives.
modxcms_xpdo
train
8c0ce827b725ee42ba0f1cf8e4db8e904b052905
diff --git a/src/molecules/formfields/DateField/index.js b/src/molecules/formfields/DateField/index.js index <HASH>..<HASH> 100644 --- a/src/molecules/formfields/DateField/index.js +++ b/src/molecules/formfields/DateField/index.js @@ -9,20 +9,19 @@ function DateField(props) { className, children, label, - focused, - error + meta } = props; const baseClassName = classnames( styles['datefield'], - { [styles.focused]: focused }, - { [styles.hasError]: !!error }, + { [styles.focused]: meta && meta.active }, + { [styles.hasError]: meta && meta.touched && meta.error && !meta.active }, className ); const childClassName = classnames( styles['datefield-input'], - { [styles['datefield-input-focused']]: focused } + { [styles['datefield-input-focused']]: meta && meta.active } ); return ( @@ -38,8 +37,8 @@ function DateField(props) { )} </div> </div> - {error && - <div className={styles.error}>{ error }</div> + {meta && meta.touched && meta.error && + <div className={styles.error}>{ meta.error }</div> } </div> ); @@ -56,13 +55,9 @@ DateField.propTypes = { */ label: PropTypes.string, /** - * Whether or not the date field is focused + * Meta object is passed from reduxForm */ - focused: PropTypes.bool, - /** - * Any errors for the date form - */ - error: PropTypes.string + meta: PropTypes.object }; export default DateField;
change DateField to work with Field
policygenius_athenaeum
train
2040c7caa55c53bfb5285825f120785ef0e032c2
diff --git a/tests/unit/grains/core_test.py b/tests/unit/grains/core_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/grains/core_test.py +++ b/tests/unit/grains/core_test.py @@ -247,6 +247,7 @@ class CoreGrainsTestCase(TestCase): self.assertEqual(os_grains.get('oscodename'), os_release_map['oscodename']) self.assertEqual(os_grains.get('osrelease'), os_release_map['osrelease']) self.assertListEqual(list(os_grains.get('osrelease_info')), os_release_map['osrelease_info']) + self.assertEqual(os_grains.get('osmajorrelease'), os_release_map['osmajorrelease']) @skipIf(not salt.utils.is_linux(), 'System is not Linux') def test_suse_os_grains_sles11sp3(self): @@ -262,6 +263,7 @@ PATCHLEVEL = 3 'osfullname': "SLES", 'osrelease': '11.3', 'osrelease_info': [11, 3], + 'osmajorrelease': 11, 'files': ["/etc/SuSE-release"], } self._run_suse_os_grains_tests(_os_release_map) @@ -285,6 +287,7 @@ PATCHLEVEL = 3 'osfullname': "SLES", 'osrelease': '11.4', 'osrelease_info': [11, 4], + 'osmajorrelease': 11, 'files': ["/etc/os-release"], } self._run_suse_os_grains_tests(_os_release_map) @@ -308,6 +311,7 @@ PATCHLEVEL = 3 'osfullname': "SLES", 'osrelease': '12', 'osrelease_info': [12], + 'osmajorrelease': 12, 'files': ["/etc/os-release"], } self._run_suse_os_grains_tests(_os_release_map) @@ -331,6 +335,7 @@ PATCHLEVEL = 3 'osfullname': "SLES", 'osrelease': '12.1', 'osrelease_info': [12, 1], + 'osmajorrelease': 12, 'files': ["/etc/os-release"], } self._run_suse_os_grains_tests(_os_release_map) @@ -354,6 +359,7 @@ PATCHLEVEL = 3 'osfullname': "Leap", 'osrelease': '42.1', 'osrelease_info': [42, 1], + 'osmajorrelease': 42, 'files': ["/etc/os-release"], } self._run_suse_os_grains_tests(_os_release_map) @@ -377,6 +383,7 @@ PATCHLEVEL = 3 'osfullname': "Tumbleweed", 'osrelease': '20160504', 'osrelease_info': [20160504], + 'osmajorrelease': 20160504, 'files': ["/etc/os-release"], } self._run_suse_os_grains_tests(_os_release_map)
Add unit test for osmajorrelease grain
saltstack_salt
train
09a47651a4a90239a0c23720fbbb3593599dfaf4
diff --git a/test/api.js b/test/api.js index <HASH>..<HASH> 100644 --- a/test/api.js +++ b/test/api.js @@ -14,7 +14,11 @@ function apiCreator(options) { options.powerAssert = true; options.projectDir = options.projectDir || ROOT_DIR; options.resolveTestsFrom = options.resolveTestsFrom || options.projectDir; - return new Api(options); + const instance = new Api(options); + if (!options.precompileHelpers) { + instance._precompileHelpers = () => Promise.resolve(); + } + return instance; } generateTests('Without Pool: ', options => apiCreator(options || {})); @@ -76,9 +80,12 @@ function generateTests(prefix, apiCreator) { test(`${prefix} precompile helpers`, t => { t.plan(1); - const api = apiCreator(); + const api = apiCreator({ + precompileHelpers: true, + resolveTestsFrom: path.join(__dirname, 'fixture/precompile-helpers') + }); - return api.run([path.join(__dirname, 'fixture/precompile-helpers/test/test.js')]) + return api.run() .then(result => { t.is(result.passCount, 1); });
Avoid helper compilation during API tests We're ending up compiling all helper-like files in AVA's test/ directory, which is unnecessary.
andywer_ava-ts
train
4247fdcace34196bb1801bcb25162b5fcf9b2c83
diff --git a/glances/glances.py b/glances/glances.py index <HASH>..<HASH> 100755 --- a/glances/glances.py +++ b/glances/glances.py @@ -43,6 +43,12 @@ gettext.install(__appname__) import json import collections +# Somes libs depends of OS +is_Bsd = sys.platform.endswith('bsd') +is_Linux = sys.platform.startswith('linux') +is_Mac = sys.platform.startswith('darwin') +is_Windows = sys.platform.startswith('win') + try: # For Python v2.x from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler @@ -59,7 +65,6 @@ except ImportError: # For Python v3.x from xmlrpc.client import ServerProxy -is_Windows = sys.platform.startswith('win') if not is_Windows: # Only import curses for non Windows OS # Curses did not exist on Windows OS (shame on it) @@ -91,7 +96,6 @@ except Exception: else: psutil_get_cpu_percent_tag = True -is_Linux = sys.platform.startswith('linux') try: # get_io_counter method only available with PsUtil 0.2.1+ psutil.Process(os.getpid()).get_io_counters() @@ -523,8 +527,14 @@ class GlancesGrabProcesses: self.processcount = {'total': 0, 'running': 0, 'sleeping': 0} for proc in psutil.process_iter(): + procstat = self.__get_process_stats__(proc) + # Ignore the 'idle' process on Windows or Bsd + # Waiting upstream patch from PsUtil + if ((is_Windows or is_Bsd) + and (procstat['cmdline'] == 'idle')): + continue # Update processlist - self.processlist.append(self.__get_process_stats__(proc)) + self.processlist.append(procstat) # Update processcount try: self.processcount[str(proc.status)] += 1
Filter and hide idle processes on Windows and FreeBSD
nicolargo_glances
train
add2360a37c493f75626ed6f39deee0e1f935abe
diff --git a/src/org/jgroups/util/FixedSizeBitSet.java b/src/org/jgroups/util/FixedSizeBitSet.java index <HASH>..<HASH> 100644 --- a/src/org/jgroups/util/FixedSizeBitSet.java +++ b/src/org/jgroups/util/FixedSizeBitSet.java @@ -119,7 +119,7 @@ public class FixedSizeBitSet { */ public void clear(int from, int to) { if(from < 0 || to < 0 || to < from || to >= size) - throw new IndexOutOfBoundsException("from=" + from + ", to=" + to); + return; int startWordIndex = wordIndex(from); int endWordIndex = wordIndex(to);
FixedSizeBitSet.clear(): return rather than throw exception when bounds are incorrect (<URL>)
belaban_JGroups
train
272725188d65d2a292c7737f97176e92e6ffe103
diff --git a/base.php b/base.php index <HASH>..<HASH> 100644 --- a/base.php +++ b/base.php @@ -2270,7 +2270,7 @@ final class Base extends Prefab implements ArrayAccess { session_cache_limiter(''); call_user_func_array('session_set_cookie_params', $jar=[ - 'expire'=>time(), + 'expire'=>0, 'path'=>$base?:'/', 'domain'=>is_int(strpos($_SERVER['SERVER_NAME'],'.')) && !filter_var($_SERVER['SERVER_NAME'],FILTER_VALIDATE_IP)?
Rework initial reference for cookie expiry
bcosca_fatfree-core
train
33978b93f7751b7852ce70552e1bfb8f4e4efd26
diff --git a/lib/plugins/bash_build_actions.rb b/lib/plugins/bash_build_actions.rb index <HASH>..<HASH> 100644 --- a/lib/plugins/bash_build_actions.rb +++ b/lib/plugins/bash_build_actions.rb @@ -7,10 +7,17 @@ module BashBuildActions class Bash < CxActionsPluginBase extend Cmd def cmd(bash_cmd) - run bash_cmd do | stdout, stderr, _thread| + result = run bash_cmd do | stdout, stderr, _thread| inf "#{stdout}" if stdout err "#{stderr}" if stderr end + + unless result.exitstatus == 0 + cx_exit "Command '#{bash_cmd}' failed with exitstatus #{result.exitstatus}", + result.exitstatus + end + + result end end end diff --git a/spec/plugins/bash_build_actions_spec.rb b/spec/plugins/bash_build_actions_spec.rb index <HASH>..<HASH> 100644 --- a/spec/plugins/bash_build_actions_spec.rb +++ b/spec/plugins/bash_build_actions_spec.rb @@ -31,5 +31,25 @@ describe BashBuildActions::Bash do expect(formatter).to have_received(:err).with("Message2 to stderr") end end + + context "given a passing exitstatus" do + subject { bash.cmd "exit 0" } + + it "exits successfully" do + expect(subject.exitstatus).to eq(0) + end + end + + context "given a failing exitstatus" do + subject { bash.cmd "exit 1" } + + it "exits with failure exitstatus and logs message" do + begin + subject + rescue SystemExit => e + expect(e.status).to eq(1) + end + end + end end end
CX #<I> exit cx build when it returns failure exitstatus This allow us to chain cx commands together and break the chain on a failure, which in this case would stop broken code being submitted.
imaginatelabs_radial
train
ab088537f212b36823dd78fdf3d836559d28ef22
diff --git a/lib/wed/modes/generic/generic_tr.js b/lib/wed/modes/generic/generic_tr.js index <HASH>..<HASH> 100644 --- a/lib/wed/modes/generic/generic_tr.js +++ b/lib/wed/modes/generic/generic_tr.js @@ -52,10 +52,21 @@ function Registry(editor) { data.element_name); - var $container = (editor.mode._options.autoinsert) ? - _fillRecursively($new, editor) : $new; - - editor.setDataCaret($container[0], 0); + if (editor.mode._options.autoinsert) { + _fill($new, editor); + + // Move the caret to the deepest first child. + var new_ = $new[0]; + while(new_) { + var child = new_.firstChild; + if (!child) + break; + new_ = child; + } + editor.setDataCaret(new_, 0); + } + else + editor.setDataCaret($new[0], 0); }.bind(this))); @@ -136,11 +147,7 @@ function Registry(editor) { })); } -function _fillRecursively($new, editor) { - var $ret = $new; - - var first = true; - +function _fill($new, editor) { while(true) { var errors = editor.validator.getErrorsFor($new[0]); @@ -177,18 +184,7 @@ function _fillRecursively($new, editor) { locations[0]), element_name: name }); - - var $child = $($new[0].childNodes[locations[0]]); - - var $container = _fillRecursively($child, editor); - - if (first) { - $ret = $container; - first = false; - } } - - return $ret; } oop.inherit(Registry, transformation.TransformationRegistry);
There is no need to fill recursively when using transformations.
mangalam-research_wed
train
1472eb3adec030b0499a3d3d6c3bbaab67fdb3da
diff --git a/jax/scipy/sparse/linalg.py b/jax/scipy/sparse/linalg.py index <HASH>..<HASH> 100644 --- a/jax/scipy/sparse/linalg.py +++ b/jax/scipy/sparse/linalg.py @@ -82,6 +82,10 @@ def cg(A, b, x0=None, *, tol=1e-5, atol=0.0, maxiter=None, M=None): need to supply the linear operator ``A`` as a function instead of a sparse matrix or ``LinearOperator``. + Derivatives of ``cg`` are implemented via implicit differentiation with + another ``cg`` solve, rather than by differentiating _through_ the solver. + They will be accurate only if both solves converge. + Parameters ---------- A : function @@ -121,6 +125,7 @@ def cg(A, b, x0=None, *, tol=1e-5, atol=0.0, maxiter=None, M=None): See also -------- scipy.sparse.linalg.cg + jax.lax.custom_linear_solve """ if x0 is None: x0 = tree_map(jnp.zeros_like, b)
DOC: note how derivatives are computed for CG (#<I>)
tensorflow_probability
train
69b1c0e58b80e6db74a7984ba9ceeaaa0e7c1914
diff --git a/lib/Account.js b/lib/Account.js index <HASH>..<HASH> 100644 --- a/lib/Account.js +++ b/lib/Account.js @@ -20,14 +20,14 @@ Account.prototype.sign = function sign(request, cb) { hash = hash.update(request.toString()).digest() request.headers["x-amzn-authorization"] = "AWS3 " + [ - "AWSAccessKeyId=" + session.credentials.accessKeyId, + "AWSAccessKeyId=" + session.tokenCredentials.accessKeyId, "Algorithm=HmacSHA256", "SignedHeaders=host;x-amz-date;x-amz-security-token;x-amz-target", - "Signature=" + session.credentials.sign(hash) + "Signature=" + session.tokenCredentials.sign(hash) ] cb(null, request) }) } -module.exports = Account \ No newline at end of file +module.exports = Account diff --git a/lib/Session.js b/lib/Session.js index <HASH>..<HASH> 100644 --- a/lib/Session.js +++ b/lib/Session.js @@ -3,16 +3,18 @@ var https = require("https") , Credentials = require("./Credentials") function Session(attrs) { - this.credentials = new Credentials(attrs) + this.sessionCredentials = new Credentials(attrs) + this.tokenCredentials = null this.listeners = [] } Session.prototype = { duration: 60 * 60 * 1000, + refreshPadding: 60 * 1000, //refresh 1 minute ahead of time consumedCapacity: 0, fetch: function(cb) { - if (this.expiration > new Date) return cb(null, this) + if ((this.expiration - this.refreshPadding) > new Date) return cb(null, this) this.listeners.push(cb) > 1 || this.refresh() }, @@ -21,15 +23,15 @@ Session.prototype = { var req = new Request req.query.DurationSeconds = 0 | this.duration / 1000 - req.query.AWSAccessKeyId = this.credentials.accessKeyId - req.query.Signature = this.credentials.sign(req.toString(), "sha256", "base64") + req.query.AWSAccessKeyId = this.sessionCredentials.accessKeyId + req.query.Signature = this.sessionCredentials.sign(req.toString(), "sha256", "base64") req.send(function(err, data) { var listeners = this.listeners.splice(0) if (!err) { this.expiration = new Date(data.expiration) - this.credentials = new Credentials(data) + this.tokenCredentials = new Credentials(data) this.token = data.sessionToken } @@ -116,4 +118,4 @@ function Response(xml) { Request.Query = Query Session.Request = Request Session.Response = Response -module.exports = Session \ No newline at end of file +module.exports = Session
fix session refresh bug security token requests need to be signed with the 'original' credentials, not the credentials from the previous security token
jed_dynamo
train
5717bd3fc32816b8520d54acaa3dfb32204a83a6
diff --git a/src/Behat/Behat/Gherkin/Loader/FeatureSuiteLoader.php b/src/Behat/Behat/Gherkin/Loader/FeatureSuiteLoader.php index <HASH>..<HASH> 100644 --- a/src/Behat/Behat/Gherkin/Loader/FeatureSuiteLoader.php +++ b/src/Behat/Behat/Gherkin/Loader/FeatureSuiteLoader.php @@ -65,6 +65,7 @@ class FeatureSuiteLoader extends AbstractFileLoader $iterator = Finder::create() ->depth(0) + ->followLinks() ->sortByName() ->in($this->featuresPath) ;
Follow symlinks (closes #<I>)
Behat_Behat
train
d1cf268be959eda318963e0a4969489d009c1141
diff --git a/synapse/tests/test_lib_ingest.py b/synapse/tests/test_lib_ingest.py index <HASH>..<HASH> 100644 --- a/synapse/tests/test_lib_ingest.py +++ b/synapse/tests/test_lib_ingest.py @@ -516,7 +516,7 @@ class IngTest(SynTest): gest = s_ingest.Ingest(info) gest.ingest(core,data=data) - self.nn( core.getTufoByProp('inet:fqdn','vertex.link') ) + self.none( core.getTufoByProp('inet:fqdn','vertex.link') ) def test_ingest_condtag(self):
tweak unit test for correct conditional behavior
vertexproject_synapse
train
93722b81dff6322eaeb171564f18afc9dbbbd2b2
diff --git a/src/Rules/ModelRuleHelper.php b/src/Rules/ModelRuleHelper.php index <HASH>..<HASH> 100644 --- a/src/Rules/ModelRuleHelper.php +++ b/src/Rules/ModelRuleHelper.php @@ -18,10 +18,10 @@ final class ModelRuleHelper { public function findModelReflectionFromType(Type $type): ?ClassReflection { - if ((new ObjectType(Builder::class))->isSuperTypeOf($type)->no() && - (new ObjectType(EloquentBuilder::class))->isSuperTypeOf($type)->no() && - (new ObjectType(Relation::class))->isSuperTypeOf($type)->no() && - (new ObjectType(Model::class))->isSuperTypeOf($type)->no() + if (! (new ObjectType(Builder::class))->isSuperTypeOf($type)->yes() && + ! (new ObjectType(EloquentBuilder::class))->isSuperTypeOf($type)->yes() && + ! (new ObjectType(Relation::class))->isSuperTypeOf($type)->yes() && + ! (new ObjectType(Model::class))->isSuperTypeOf($type)->yes() ) { return null; }
fix: inverted check in the ModelRuleHelper (#<I>)
nunomaduro_larastan
train
7179e30fc9593b74261dac176cd8e74a1d418f5e
diff --git a/lib/wrappers/sync-angular.js b/lib/wrappers/sync-angular.js index <HASH>..<HASH> 100644 --- a/lib/wrappers/sync-angular.js +++ b/lib/wrappers/sync-angular.js @@ -14,8 +14,8 @@ angular.module('wfm.sync.service', []) sync.init($fh, mediator, syncOptions); } - syncService.manage = function(datasetId) { - managerPromise = $q.when(sync.manage(datasetId)); + syncService.manage = function(datasetId, options, queryParams, metaData) { + managerPromise = $q.when(sync.manage(datasetId, options, queryParams, metaData)); return managerPromise; }; diff --git a/lib/wrappers/sync-mediator.js b/lib/wrappers/sync-mediator.js index <HASH>..<HASH> 100644 --- a/lib/wrappers/sync-mediator.js +++ b/lib/wrappers/sync-mediator.js @@ -15,8 +15,8 @@ function wrapper(mediator) { }, 0); }); - mediator.subscribe('sync:manage', function(datasetId) { - sync.manage(datasetId).then(function(_manager) { + mediator.subscribe('sync:manage', function(datasetId, options, queryParams, metaData) { + sync.manage(datasetId, options, queryParams, metaData).then(function(_manager) { manager = _manager; setupListeners(datasetId); mediator.publish('done:sync:manage:'+datasetId, manager);
Added the extra manage params to the angular and mediator wrappers
raincatcher-beta_raincatcher-sync
train
1017903e46d9f263f9f99fb8706843f99bf8a8b9
diff --git a/slither/core/declarations/contract.py b/slither/core/declarations/contract.py index <HASH>..<HASH> 100644 --- a/slither/core/declarations/contract.py +++ b/slither/core/declarations/contract.py @@ -21,7 +21,7 @@ class Contract(ChildSlither, SourceMapping): self._id = None self._inheritance = [] self._immediate_inheritance = [] - self._base_constructor_contracts_called = [] + self._explicit_base_constructor_calls = [] self._enums = {} self._structures = {} @@ -79,7 +79,7 @@ class Contract(ChildSlither, SourceMapping): def setInheritance(self, inheritance, immediate_inheritance, called_base_constructor_contracts): self._inheritance = inheritance self._immediate_inheritance = immediate_inheritance - self._base_constructor_contracts_called = called_base_constructor_contracts + self._explicit_base_constructor_calls = called_base_constructor_contracts @property def derived_contracts(self): @@ -143,27 +143,16 @@ class Contract(ChildSlither, SourceMapping): return [f for f in self.functions if f.visibility in ['public', 'external']] @property - def base_constructors_called(self): + def explicit_base_constructor_calls(self): """ - list(Function): List of the base constructors invoked by this contract definition, not via - this contract's constructor definition. + list(Function): List of the base constructors called explicitly by this contract definition. - NOTE: Base constructors can also be called from the constructor definition! + Base constructors called by any constructor definition will not be included. + Base constructors implicitly called by the contract definition (without + parenthesis) will not be included. """ - return [c.constructor for c in self._base_constructor_contracts_called if c.constructor] - - @property - def all_base_constructors_called(self): - """ - list(Function): List of the base constructors invoked by this contract definition, or the - underlying constructor definition. They should be in order of declaration, - starting first with contract definition's base constructor calls, then the - constructor definition's base constructor calls. - - NOTE: Duplicates may occur if the same base contracts are called in both - the contract and constructor definition. - """ - return self.base_constructors_called + self.constructor.base_constructors_called + # This is a list of contracts internally, so we convert it to a list of constructor functions. + return [c.constructor for c in self._explicit_base_constructor_calls if c.constructor] @property def modifiers(self): diff --git a/slither/core/declarations/function.py b/slither/core/declarations/function.py index <HASH>..<HASH> 100644 --- a/slither/core/declarations/function.py +++ b/slither/core/declarations/function.py @@ -56,7 +56,7 @@ class Function(ChildContract, SourceMapping): self._expression_calls = [] self._expression_modifiers = [] self._modifiers = [] - self._base_constructor_contracts_called = [] + self._explicit_base_constructor_calls = [] self._payable = False self._contains_assembly = False @@ -200,14 +200,15 @@ class Function(ChildContract, SourceMapping): return list(self._modifiers) @property - def base_constructors_called(self): + def explicit_base_constructor_calls(self): """ - list(Function): List of the base constructors invoked by this presumed constructor by definition, not via - calls within the function body. + list(Function): List of the base constructors called explicitly by this presumed constructor definition. - NOTE: Base constructors can also be called from the contract definition! + Base constructors implicitly or explicitly called by the contract definition will not be + included. """ - return [c.constructor for c in self._base_constructor_contracts_called if c.constructor] + # This is a list of contracts internally, so we convert it to a list of constructor functions. + return [c.constructor for c in self._explicit_base_constructor_calls if c.constructor] def __str__(self): return self._name diff --git a/slither/solc_parsing/declarations/function.py b/slither/solc_parsing/declarations/function.py index <HASH>..<HASH> 100644 --- a/slither/solc_parsing/declarations/function.py +++ b/slither/solc_parsing/declarations/function.py @@ -773,7 +773,7 @@ class FunctionSolc(Function): if isinstance(m, Function): self._modifiers.append(m) elif isinstance(m, Contract): - self._base_constructor_contracts_called.append(m) + self._explicit_base_constructor_calls.append(m) def analyze_params(self):
Refactored property/field names for improved accuracy.
crytic_slither
train
3f630d8ad7c162d7cac8fedfb32b35f0cc7240ff
diff --git a/pkg/kubelet/kubelet.go b/pkg/kubelet/kubelet.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/kubelet.go +++ b/pkg/kubelet/kubelet.go @@ -2657,7 +2657,7 @@ func readyPodCondition(isPodReady bool, reason, message string) []api.PodConditi } // getPodReadyCondition returns ready condition if all containers in a pod are ready, else it returns an unready condition. -func getPodReadyCondition(spec *api.PodSpec, containerStatuses []api.ContainerStatus) []api.PodCondition { +func getPodReadyCondition(spec *api.PodSpec, containerStatuses []api.ContainerStatus, podPhase api.PodPhase) []api.PodCondition { // Find if all containers are ready or not. if containerStatuses == nil { return readyPodCondition(false, "UnknownContainerStatuses", "") @@ -2673,6 +2673,12 @@ func getPodReadyCondition(spec *api.PodSpec, containerStatuses []api.ContainerSt unknownContainers = append(unknownContainers, container.Name) } } + + // In case of unexist unknowContainers, If pod has derminated successed and it has unreadyContainers, just return PodCompleted + if podPhase == api.PodSucceeded && len(unknownContainers) == 0 { + return readyPodCondition(false, fmt.Sprint("PodCompleted"), "") + } + unreadyMessages := []string{} if len(unknownContainers) > 0 { unreadyMessages = append(unreadyMessages, fmt.Sprintf("containers with unknown status: %s", unknownContainers)) @@ -2734,7 +2740,7 @@ func (kl *Kubelet) generatePodStatus(pod *api.Pod) (api.PodStatus, error) { podStatus.Phase = GetPhase(spec, podStatus.ContainerStatuses) kl.probeManager.UpdatePodStatus(pod.UID, podStatus) - podStatus.Conditions = append(podStatus.Conditions, getPodReadyCondition(spec, podStatus.ContainerStatuses)...) + podStatus.Conditions = append(podStatus.Conditions, getPodReadyCondition(spec, podStatus.ContainerStatuses, podStatus.Phase)...) if !kl.standaloneMode { hostIP, err := kl.GetHostIP() diff --git a/pkg/kubelet/kubelet_test.go b/pkg/kubelet/kubelet_test.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/kubelet_test.go +++ b/pkg/kubelet/kubelet_test.go @@ -1875,16 +1875,19 @@ func TestGetPodReadyCondition(t *testing.T) { tests := []struct { spec *api.PodSpec containerStatuses []api.ContainerStatus + podPhase api.PodPhase expected []api.PodCondition }{ { spec: nil, containerStatuses: nil, + podPhase: api.PodRunning, expected: getReadyCondition(api.ConditionFalse, "UnknownContainerStatuses", ""), }, { spec: &api.PodSpec{}, containerStatuses: []api.ContainerStatus{}, + podPhase: api.PodRunning, expected: getReadyCondition(api.ConditionTrue, "", ""), }, { @@ -1894,6 +1897,7 @@ func TestGetPodReadyCondition(t *testing.T) { }, }, containerStatuses: []api.ContainerStatus{}, + podPhase: api.PodRunning, expected: getReadyCondition(api.ConditionFalse, "ContainersNotReady", "containers with unknown status: [1234]"), }, { @@ -1907,6 +1911,7 @@ func TestGetPodReadyCondition(t *testing.T) { getReadyStatus("1234"), getReadyStatus("5678"), }, + podPhase: api.PodRunning, expected: getReadyCondition(api.ConditionTrue, "", ""), }, { @@ -1919,6 +1924,7 @@ func TestGetPodReadyCondition(t *testing.T) { containerStatuses: []api.ContainerStatus{ getReadyStatus("1234"), }, + podPhase: api.PodRunning, expected: getReadyCondition(api.ConditionFalse, "ContainersNotReady", "containers with unknown status: [5678]"), }, { @@ -1932,12 +1938,25 @@ func TestGetPodReadyCondition(t *testing.T) { getReadyStatus("1234"), getNotReadyStatus("5678"), }, + podPhase: api.PodRunning, expected: getReadyCondition(api.ConditionFalse, "ContainersNotReady", "containers with unready status: [5678]"), }, + { + spec: &api.PodSpec{ + Containers: []api.Container{ + {Name: "1234"}, + }, + }, + containerStatuses: []api.ContainerStatus{ + getNotReadyStatus("1234"), + }, + podPhase: api.PodSucceeded, + expected: getReadyCondition(api.ConditionFalse, "PodCompleted", ""), + }, } for i, test := range tests { - condition := getPodReadyCondition(test.spec, test.containerStatuses) + condition := getPodReadyCondition(test.spec, test.containerStatuses, test.podPhase) if !reflect.DeepEqual(condition, test.expected) { t.Errorf("On test case %v, expected:\n%+v\ngot\n%+v\n", i, test.expected, condition) }
when pod has successed, update condition to PodCompleted
kubernetes_kubernetes
train
6541519acb31c1fb835f668e442e3284fec84606
diff --git a/Classes/Service/CompileService.php b/Classes/Service/CompileService.php index <HASH>..<HASH> 100644 --- a/Classes/Service/CompileService.php +++ b/Classes/Service/CompileService.php @@ -37,7 +37,7 @@ class CompileService { /** * @param string $file */ - public function getCompiledFile($file) { + public static function getCompiledFile($file) { $file = GeneralUtility::getFileAbsFileName($file); $pathParts = pathinfo($file); if($pathParts['extension'] === 'less'){ @@ -80,4 +80,4 @@ class CompileService { return $variables; } -} \ No newline at end of file +}
[TASK] Make getCompiledFile a static method - fixes #<I> #<I> TYPO3 sets the deprecation strategy to the strictest possible when in Development mode. That includes hard Exceptions on PHP <I>. This patch makes the method static which shouldnt harm anyone.
benjaminkott_bootstrap_package
train
f89f00444580c5a7b900c91b25b98cff3d76011d
diff --git a/fhir/fhir_requests.go b/fhir/fhir_requests.go index <HASH>..<HASH> 100644 --- a/fhir/fhir_requests.go +++ b/fhir/fhir_requests.go @@ -48,7 +48,7 @@ func GetPatientConditions(fullFhirUrl string, ts time.Time) ([]models.Condition, c, ok := resource.Resource.(models.Condition) if ok { cStart := getConditionStart(c) - if cStart == nil || cStart.Time.Before(ts) { + if cStart == nil || cStart.Time.Before(ts) || cStart.Time.Equal(ts) { conditions = append(conditions, c) } } @@ -83,7 +83,7 @@ func GetPatientMedicationStatements(fullFhirUrl string, ts time.Time) ([]models. ms, ok := resource.Resource.(models.MedicationStatement) if ok { msStart := getMedicationStatementStart(ms) - if msStart == nil || msStart.Time.Before(ts) { + if msStart == nil || msStart.Time.Before(ts) || msStart.Time.Equal(ts) { medicationStatements = append(medicationStatements, ms) } }
When filtering for events to include in the risk assessment, be sure to include events before *and at* the reference time
intervention-engine_riskservice
train
52141aae7f073fe917c841ddbb4531a9beb04ddc
diff --git a/version.py b/version.py index <HASH>..<HASH> 100644 --- a/version.py +++ b/version.py @@ -21,7 +21,7 @@ Every version number class implements the following interface: an equivalent string -- ie. one that will generate an equivalent version number instance) * __repr__ generates Python code to recreate the version number instance - * __cmp__ compares the current instance with either another instance + * _cmp compares the current instance with either another instance of the same class or a string (which will be parsed to an instance of the same class, thus must follow the same rules) """ @@ -32,7 +32,7 @@ class Version: """Abstract base class for version numbering classes. Just provides constructor (__init__) and reproducer (__repr__), because those seem to be the same for all version numbering classes; and route - rich comparisons to __cmp__. + rich comparisons to _cmp. """ def __init__ (self, vstring=None): @@ -43,37 +43,37 @@ class Version: return "%s ('%s')" % (self.__class__.__name__, str(self)) def __eq__(self, other): - c = self.__cmp__(other) + c = self._cmp(other) if c is NotImplemented: return c return c == 0 def __ne__(self, other): - c = self.__cmp__(other) + c = self._cmp(other) if c is NotImplemented: return c return c != 0 def __lt__(self, other): - c = self.__cmp__(other) + c = self._cmp(other) if c is NotImplemented: return c return c < 0 def __le__(self, other): - c = self.__cmp__(other) + c = self._cmp(other) if c is NotImplemented: return c return c <= 0 def __gt__(self, other): - c = self.__cmp__(other) + c = self._cmp(other) if c is NotImplemented: return c return c > 0 def __ge__(self, other): - c = self.__cmp__(other) + c = self._cmp(other) if c is NotImplemented: return c return c >= 0 @@ -91,7 +91,7 @@ class Version: # (if not identical to) the string supplied to parse # __repr__ (self) - generate Python code to recreate # the instance -# __cmp__ (self, other) - compare two version numbers ('other' may +# _cmp (self, other) - compare two version numbers ('other' may # be an unparsed version string, or another # instance of your version class) @@ -169,30 +169,39 @@ class StrictVersion (Version): return vstring - def __cmp__ (self, other): + def _cmp (self, other): if isinstance(other, str): other = StrictVersion(other) - compare = cmp(self.version, other.version) - if (compare == 0): # have to compare prerelease - - # case 1: neither has prerelease; they're equal - # case 2: self has prerelease, other doesn't; other is greater - # case 3: self doesn't have prerelease, other does: self is greater - # case 4: both have prerelease: must compare them! + if self.version != other.version: + # numeric versions don't match + # prerelease stuff doesn't matter + if self.version < other.version: + return -1 + else: + return 1 - if (not self.prerelease and not other.prerelease): + # have to compare prerelease + # case 1: neither has prerelease; they're equal + # case 2: self has prerelease, other doesn't; other is greater + # case 3: self doesn't have prerelease, other does: self is greater + # case 4: both have prerelease: must compare them! + + if (not self.prerelease and not other.prerelease): + return 0 + elif (self.prerelease and not other.prerelease): + return -1 + elif (not self.prerelease and other.prerelease): + return 1 + elif (self.prerelease and other.prerelease): + if self.prerelease == other.prerelease: return 0 - elif (self.prerelease and not other.prerelease): + elif self.prerelease < other.prerelease: return -1 - elif (not self.prerelease and other.prerelease): + else: return 1 - elif (self.prerelease and other.prerelease): - return cmp(self.prerelease, other.prerelease) - - else: # numeric versions don't match -- - return compare # prerelease stuff doesn't matter - + else: + assert False, "never get here" # end class StrictVersion @@ -325,7 +334,7 @@ class LooseVersion (Version): return "LooseVersion ('%s')" % str(self) - def __cmp__ (self, other): + def _cmp (self, other): if isinstance(other, str): other = LooseVersion(other)
Issue #<I>: Remove cmp. Stage 1: remove all uses of cmp and __cmp__ from the standard library and tests.
pypa_setuptools
train
217e28db56402c9fb30ec6db34af74049ec398f0
diff --git a/src/Bartlett/Reflect/PhpParser/NodeProcessor.php b/src/Bartlett/Reflect/PhpParser/NodeProcessor.php index <HASH>..<HASH> 100644 --- a/src/Bartlett/Reflect/PhpParser/NodeProcessor.php +++ b/src/Bartlett/Reflect/PhpParser/NodeProcessor.php @@ -33,7 +33,7 @@ interface NodeProcessor * * @return void */ - public function push($callback); + public function push(callable $callback); /** * Gets list of processors that will check pre-conditions. diff --git a/src/Bartlett/Reflect/PhpParser/NodeProcessorAbstract.php b/src/Bartlett/Reflect/PhpParser/NodeProcessorAbstract.php index <HASH>..<HASH> 100644 --- a/src/Bartlett/Reflect/PhpParser/NodeProcessorAbstract.php +++ b/src/Bartlett/Reflect/PhpParser/NodeProcessorAbstract.php @@ -33,11 +33,9 @@ class NodeProcessorAbstract implements NodeProcessor /** * {@inheritdoc} */ - public function push($callback) + public function push(callable $callback) { - if (is_callable($callback)) { - array_push($this->processors, $callback); - } + array_push($this->processors, $callback); } /**
Force TypeHint constraint and simplify code
llaville_php-reflect
train
2a31759dcf793c13c290e19d8f8fb40e9d63f4ae
diff --git a/libkbfs/config_local.go b/libkbfs/config_local.go index <HASH>..<HASH> 100644 --- a/libkbfs/config_local.go +++ b/libkbfs/config_local.go @@ -1,6 +1,8 @@ package libkbfs import ( + "fmt" + "github.com/keybase/client/go/libkb" "github.com/keybase/client/go/logger" keybase1 "github.com/keybase/client/go/protocol" @@ -49,6 +51,10 @@ type ConfigLocal struct { maxNameBytes uint32 maxDirBytes uint64 rekeyQueue RekeyQueue + + // allKnownConfigs is used for testing, and contains all created + // Config objects in this test. + allKnownConfigsForTesting *[]Config } var _ Config = (*ConfigLocal)(nil) @@ -460,6 +466,20 @@ func (c *ConfigLocal) SetMetricsRegistry(r metrics.Registry) { // Shutdown implements the Config interface for ConfigLocal. func (c *ConfigLocal) Shutdown() error { + if c.CheckStateOnShutdown() { + // Before we do anything, wait for all archiving to finish. + for _, config := range *c.allKnownConfigsForTesting { + kbfsOps, ok := config.KBFSOps().(*KBFSOpsStandard) + if !ok { + return fmt.Errorf("No KBFSOps Standard!") + } + for _, fbo := range kbfsOps.ops { + lState := makeFBOLockState() + fbo.waitForArchives(lState) + } + } + } + err := c.KBFSOps().Shutdown() // Continue with shutdown regardless of err. c.RekeyQueue().Clear() diff --git a/libkbfs/folder_branch_ops.go b/libkbfs/folder_branch_ops.go index <HASH>..<HASH> 100644 --- a/libkbfs/folder_branch_ops.go +++ b/libkbfs/folder_branch_ops.go @@ -4978,6 +4978,12 @@ func (fbo *folderBranchOps) Rekey(ctx context.Context, tlf TlfID) (err error) { }) } +func (fbo *folderBranchOps) waitForArchives(lState *lockState) { + fbo.mdWriterLock.Lock(lState) + defer fbo.mdWriterLock.Unlock(lState) + fbo.archiveGroup.Wait() +} + func (fbo *folderBranchOps) SyncFromServer( ctx context.Context, folderBranch FolderBranch) (err error) { fbo.log.CDebugf(ctx, "SyncFromServer") @@ -5023,10 +5029,7 @@ func (fbo *folderBranchOps) SyncFromServer( // Wait for all the asynchronous block archiving to hit the block // server. - fbo.mdWriterLock.Lock(lState) - defer fbo.mdWriterLock.Unlock(lState) - fbo.archiveGroup.Wait() - + fbo.waitForArchives(lState) return nil } diff --git a/libkbfs/test_common.go b/libkbfs/test_common.go index <HASH>..<HASH> 100644 --- a/libkbfs/test_common.go +++ b/libkbfs/test_common.go @@ -156,6 +156,9 @@ func MakeTestConfigOrBust(t logger.TestLogBackend, // turn off background flushing by default during tests config.noBGFlush = true + configs := []Config{config} + config.allKnownConfigsForTesting = &configs + return config } @@ -222,6 +225,10 @@ func ConfigAsUser(config *ConfigLocal, loggedInUser libkb.NormalizedUsername) *C c.SetMDServer(mdServer) c.SetKeyServer(keyServer) + // Keep track of all the other configs in a shared slice. + c.allKnownConfigsForTesting = config.allKnownConfigsForTesting + *c.allKnownConfigsForTesting = append(*c.allKnownConfigsForTesting, c) + return c }
test_common: all FBOs must finish archiving before checking state Issue: KBFS-<I>
keybase_client
train
230d769a9755a0a0d43771349d1c12d63f8baf26
diff --git a/dist/piano.js b/dist/piano.js index <HASH>..<HASH> 100644 --- a/dist/piano.js +++ b/dist/piano.js @@ -39,7 +39,7 @@ var blackKeyMap = { }; var convertAccidental = function(keyName) { - return keyName.replace('s', '\u0023').replace('b', '\u266D'); + return keyName.replace('s', '#'); } var octaves = [0,1,2,3,4,5,6,7,8,9,10]; diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -38,7 +38,7 @@ var blackKeyMap = { }; var convertAccidental = function(keyName) { - return keyName.replace('s', '\u0023').replace('b', '\u266D'); + return keyName.replace('s', '#'); } var octaves = [0,1,2,3,4,5,6,7,8,9,10]; diff --git a/styles.css b/styles.css index <HASH>..<HASH> 100644 --- a/styles.css +++ b/styles.css @@ -143,5 +143,4 @@ d content: attr(data-keyname); position: absolute; bottom: 8px; - left: -2px; }
use simple chars for sharps and flats
musicjs_beautiful-piano
train
d312c30847c4755ad673939ee2801c372644fea6
diff --git a/pkg/api/validation/validation.go b/pkg/api/validation/validation.go index <HASH>..<HASH> 100644 --- a/pkg/api/validation/validation.go +++ b/pkg/api/validation/validation.go @@ -397,9 +397,9 @@ func validateSource(source *api.VolumeSource) errs.ValidationErrorList { return allErrs } -func validateHostPathVolumeSource(hostDir *api.HostPathVolumeSource) errs.ValidationErrorList { +func validateHostPathVolumeSource(hostPath *api.HostPathVolumeSource) errs.ValidationErrorList { allErrs := errs.ValidationErrorList{} - if hostDir.Path == "" { + if hostPath.Path == "" { allErrs = append(allErrs, errs.NewFieldRequired("path")) } return allErrs
fix the change of hostDir to hostPath
kubernetes_kubernetes
train
6ce9973341aa07c1ca5a7445b4e28f33907fc8ad
diff --git a/test/utils.py b/test/utils.py index <HASH>..<HASH> 100644 --- a/test/utils.py +++ b/test/utils.py @@ -1078,7 +1078,7 @@ class Vtctld(object): if python: from vtctl import grpc_vtctl_client rpc_port = self.grpc_port - return (protocol, 'localhost:%d' % rpc_port) + return (protocol, '%s:%d' % (socket.getfqdn(), rpc_port)) def process_args(self): return ['-vtctld_addr', 'http://localhost:%d/' % self.port] diff --git a/test/worker.py b/test/worker.py index <HASH>..<HASH> 100755 --- a/test/worker.py +++ b/test/worker.py @@ -242,18 +242,30 @@ class TestBaseSplitClone(unittest.TestCase): keyspace_id: the value of `keyspace_id` column. """ k = '%d' % keyspace_id - values_str = '' - for i in xrange(num_values): - if i != 0: - values_str += ',' - values_str += "(%d, '%s', 0x%x)" % (id_offset + i, msg, keyspace_id) - tablet.mquery( - 'vt_test_keyspace', [ - 'begin', - 'insert into worker_test(id, msg, keyspace_id) values%s ' - '/* EMD keyspace_id:%s*/' % (values_str, k), - 'commit'], - write=True) + + # For maximum performance, multiple values are inserted in one statement. + # However, when the statements are too long, queries will timeout and + # vttablet will kill them. Therefore, we chunk it into multiple statements. + def chunks(full_list, n): + """Yield successive n-sized chunks from full_list.""" + for i in xrange(0, len(full_list), n): + yield full_list[i:i+n] + + max_chunk_size = 100*1000 + for chunk in chunks(range(1, num_values+1), max_chunk_size): + logging.debug('Inserting values for range [%d, %d].', chunk[0], chunk[-1]) + values_str = '' + for i in chunk: + if i != chunk[0]: + values_str += ',' + values_str += "(%d, '%s', 0x%x)" % (id_offset + i, msg, keyspace_id) + tablet.mquery( + 'vt_test_keyspace', [ + 'begin', + 'insert into worker_test(id, msg, keyspace_id) values%s ' + '/* EMD keyspace_id:%s*/' % (values_str, k), + 'commit'], + write=True) def insert_values( self, tablet, num_values, num_shards, offset=0, keyspace_id_range=2**64):
Exporting internal changes back to open-source. NOTE: Changes were already LGTM'd internally.
vitessio_vitess
train
90b4ea2f3d98ab26f8996fd1e6f90f68bde2cbcd
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -106,7 +106,7 @@ module.exports = { }, included: function(){ - this._super.apply(this, arguments); + this._super.included.apply(this, arguments); // We cannot use ember-cli to import velocity as an AMD module here, because we always need the shim in FastBoot // to not break any module imports (as velocity/velocity.js has a FastBoot guard, so FastBoot does not see any
Fix `_super` in included hook
ember-animation_liquid-fire
train
409d8fad2b76035fd7651ea56bbad0fbe5f8561d
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -47,13 +47,15 @@ function normalizePaths(paths) { return objects; } -function findAll(patterns) { +function findAll(cwd, patterns) { // Glob patterns and normalize returned paths - return normalizePaths(glob.sync(patterns)); + return normalizePaths(glob.sync(patterns, { + cwd: cwd + })); } -function requireModule(file) { - file = path.resolve(process.cwd(), file); +function requireModule(cwd, file) { + file = path.resolve(cwd, file); // Clear cached module, if any delete require.cache[require.resolve(file)]; @@ -62,23 +64,23 @@ function requireModule(file) { return require(file); } -function registerModule(method, file) { +function registerModule(method, cwd, file) { /*jshint validthis: true */ var extension, name, - module = requireModule(file.oldValue); + fileModule = requireModule(cwd, file.oldValue); - if (!module) { + if (!fileModule) { return; } - if (typeof module.register === 'function') { - module.register(this); + if (typeof fileModule.register === 'function') { + fileModule.register(this); return; } - if (typeof module === 'function') { + if (typeof fileModule === 'function') { extension = path.extname(file.value); name = file.value.slice(0, -extension.length); @@ -92,12 +94,12 @@ function registerModule(method, file) { name = name.replace(pathSepPattern, '-'); } - this[method](name, module); + this[method](name, fileModule); return; } - this[method](module); + this[method](fileModule); } /** @@ -106,6 +108,7 @@ function registerModule(method, file) { * @type {Function} * @param {Object} handlebars Handlebars instance. * @param {Object} options Plugin options. + * @param {String} options.cwd Current working directory. Defaults to `process.cwd()`. * @param {String|Array.<String>} options.helpers One or more glob strings matching helpers. * @param {String|Array.<String>} options.partials One or more glob strings matching partials. * @return {Object} Handlebars instance. @@ -113,15 +116,25 @@ function registerModule(method, file) { function registrar(handlebars, options) { options = options || {}; - var helpers = options.helpers, + var register, + cwd = options.cwd || process.cwd(), + helpers = options.helpers, partials = options.partials; if (helpers) { - findAll(helpers).forEach(registerModule.bind(handlebars, 'registerHelper')); + // Setup helper regsiter method + register = registerModule.bind(handlebars, 'registerHelper', cwd); + + // Register helpers + findAll(cwd, helpers).forEach(register); } if (partials) { - findAll(partials).forEach(registerModule.bind(handlebars, 'registerPartial')); + // Setup partial regsiter method + register = registerModule.bind(handlebars, 'registerPartial', cwd); + + // Register partials + findAll(cwd, partials).forEach(register); } return handlebars; diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "handlebars-registrar", - "version": "1.0.3", + "version": "1.1.0", "description": "Effortless wiring of Handlebars helpers and partials.", "keywords": [ "handlebars", diff --git a/test/handlebars-registrar.spec.js b/test/handlebars-registrar.spec.js index <HASH>..<HASH> 100644 --- a/test/handlebars-registrar.spec.js +++ b/test/handlebars-registrar.spec.js @@ -89,4 +89,25 @@ describe('handlebars-registrar e2e', function () { expect(hb.partials.item).to.be.a('string'); expect(hb.partials.link).to.be.a('string'); }); + + it('should allow setting the cwd', function () { + var hb = handlebars.create(); + + handlebarsRegistrar(hb, { + cwd: __dirname, + helpers: 'fixtures/helpers/function/**/*.js', + partials: 'fixtures/partials/raw/**/*.hbs' + }); + + expect(hb.helpers.lower).to.be.a('function'); + expect(hb.helpers.upper).to.be.a('function'); + expect(hb.helpers['flow-lest']).to.be.a('function'); + expect(hb.helpers['flow-when']).to.be.a('function'); + expect(hb.helpers.empty).to.be(undefined); + + expect(hb.partials.layout).to.be.a('function'); + expect(hb.partials['layout-2col']).to.be.a('function'); + expect(hb.partials['components/item']).to.be.a('function'); + expect(hb.partials['components/link']).to.be.a('function'); + }); });
Added ability to set `cwd`. Bumped minor version.
shannonmoeller_handlebars-wax
train
68cde93f09d6bea392f28f54e766db37bcdad84d
diff --git a/telemetry/telemetry/page/page.py b/telemetry/telemetry/page/page.py index <HASH>..<HASH> 100644 --- a/telemetry/telemetry/page/page.py +++ b/telemetry/telemetry/page/page.py @@ -23,10 +23,16 @@ class Page(object): self.credentials = None self.disabled = False self.wait_time_after_navigate = 2 + self._attributes = attributes - if attributes: - for k, v in attributes.iteritems(): - setattr(self, k, v) + def __getattr__(self, name): + if name in self._attributes: + return self._attributes[name] + + if self.page_set and hasattr(self.page_set, name): + return getattr(self._page_set, name) + + raise AttributeError() # NOTE: This assumes the page_set file uses 'file:///' instead of 'file://', # otherwise the '/' will be missing between page_set.base_dir and
[telemetry] Page set-level attributes. Page attributes cascade from page sets, with the page attribute having priority. This small change can eliminate most of the redundancy in the page sets. R=<EMAIL>,<EMAIL> BUG=None. TEST=None. Review URL: <URL>
catapult-project_catapult
train
c26bf0cdd4a91af05086878ebfd3554fdaf63d4f
diff --git a/src/components/DateRangePicker.js b/src/components/DateRangePicker.js index <HASH>..<HASH> 100644 --- a/src/components/DateRangePicker.js +++ b/src/components/DateRangePicker.js @@ -162,6 +162,7 @@ class DateRangePicker extends React.Component { return { currentDate: date, focusedDay: date, + selectedDefaultRange: '', selectedBox: isLargeOrMediumWindowSize ? this._getToggledSelectBox(state.selectedBox) : state.selectedBox, selectedStartDate: modifiedRangeCompleteButDatesInversed ? endDate : startDate, selectedEndDate: modifiedRangeCompleteButDatesInversed ? startDate : endDate,
Set the selectedDefaultRange back to an empty string when selecting a date from the calendar (#<I>)
mxenabled_mx-react-components
train
3a94538af1f0c1d5c8f4ab87b504a64e4baac80b
diff --git a/src/redis_lock/__init__.py b/src/redis_lock/__init__.py index <HASH>..<HASH> 100644 --- a/src/redis_lock/__init__.py +++ b/src/redis_lock/__init__.py @@ -332,8 +332,6 @@ class Lock(object): * Use ``Lock("name", id=id_from_other_place).release()`` * Use ``Lock("name").reset()`` """ - if not self._held: - raise NotAcquired("This Lock instance didn't acquire the lock.") if self._lock_renewal_thread is not None: self._stop_lock_renewer() logger.debug("Releasing %r.", self._name)
Remove un-necessary check. Ref #<I>.
ionelmc_python-redis-lock
train
d67184bfd4bd241439a86cf3f9e9d975409b00ee
diff --git a/src/Sylius/Bundle/ResourceBundle/spec/Sylius/Bundle/ResourceBundle/Doctrine/ORM/EntityRepository.php b/src/Sylius/Bundle/ResourceBundle/spec/Sylius/Bundle/ResourceBundle/Doctrine/ORM/EntityRepository.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/ResourceBundle/spec/Sylius/Bundle/ResourceBundle/Doctrine/ORM/EntityRepository.php +++ b/src/Sylius/Bundle/ResourceBundle/spec/Sylius/Bundle/ResourceBundle/Doctrine/ORM/EntityRepository.php @@ -109,7 +109,7 @@ class EntityRepository extends ObjectBehavior { foreach ($criteria as $property => $value) { $queryBuilder - ->andWhere('foo.'.$property.' = :'.$property) + ->andWhere('o.'.$property.' = :'.$property) ->shouldBeCalled() ->willReturn($queryBuilder) ;
Update spec, as we reverted the alias generation
Sylius_Sylius
train
9276c6fec314f1ad95f85cdccafbc14a3516ba82
diff --git a/packages/selenium-ide/src/neo/models/Command.js b/packages/selenium-ide/src/neo/models/Command.js index <HASH>..<HASH> 100644 --- a/packages/selenium-ide/src/neo/models/Command.js +++ b/packages/selenium-ide/src/neo/models/Command.js @@ -211,9 +211,9 @@ export const ArgTypes = { }, variableName: { name: "variable name", - description: "The name of the variable you'd like to either store an \ - expression's result in or reference in a check with \ - 'assert' or 'verify'." + description: "The name of a variable (without brackets). Used to either store an \ + expression's result in or reference for a check (e.g., \ + with 'assert' or 'verify')." }, waitTime: { name: "wait time",
Updated reference copy for variable name description to make it clear what input is accepted (per #<I>).
SeleniumHQ_selenium-ide
train
c5bd2f942bdac98870c5fceab1baf6acedb21294
diff --git a/opengrid/library/regression.py b/opengrid/library/regression.py index <HASH>..<HASH> 100644 --- a/opengrid/library/regression.py +++ b/opengrid/library/regression.py @@ -477,48 +477,28 @@ class MultiVarLinReg(Analysis): and decompose it into a dictionary. This dictionary is stored in the list 'formulas', one dict per fit. - Of course we have to remove the fit.model.formula entirely, it is built-up again + Finally we have to remove each fit entirely (not just the formula), it is built-up again from self.formulas in the __setstate__ method. """ - d = self.__dict__ d['formulas'] = [] for fit in self.list_of_fits: d['formulas'].append(self._modeldesc_to_dict(fit.model.formula)) - delattr(fit.model, 'formula') + #delattr(fit.model, 'formula') + d.pop('list_of_fits') + d.pop('fit') print("Pickling... Removing the 'formula' from each fit.model.\n\ - You have to unpickle your object or run __setstate__ to restore them.".format(d)) + You have to unpickle your object or run __setstate__(self.__dict__) to restore them.".format(d)) return d def __setstate__(self, state): """Restore the attributes that cannot be pickled""" - for fit, formula in zip(self.list_of_fits, state['formulas']): - fit.model.formula = self._modeldesc_from_dict(formula) - delattr(self, 'formulas') - - - -class TestPickle(object): - """ - Examples - -------- - >>> from opengrid.library.regression import TestPickle - >>> import pickle - >>> tp = TestPickle('test') - >>> pickle.dump(tp, open('test.pkl', 'wb')) - """ - def __init__(self, x): - setattr(self, 'x', [Term([LookupFactor('endog')])]) - - def __getstate__(self): - d = self.__dict__ - d['temp'] = self.x[0].factors[0].name() - d.pop('x') - print("pickling, d={}".format(d)) - return d - - def __setstate__(self, state): - setattr(self, 'x', [Term([LookupFactor(state['temp'])])]) - + for k,v in state.items(): + if k is not 'formulas': + setattr(self, k, v) + self.list_of_fits = [] + for formula in state['formulas']: + self.list_of_fits.append(fm.ols(self._modeldesc_from_dict(formula), data=self.df).fit()) + self.fit = self.list_of_fits[-1]
Remove all fits from a MultiVarLinReg object to allow pickling. They are restored during unpickling
opengridcc_opengrid
train
afa909d32f6b5fa1017fe92533bf38d348a401a0
diff --git a/coordination/src/main/java/io/atomix/coordination/state/LeaderElectionState.java b/coordination/src/main/java/io/atomix/coordination/state/LeaderElectionState.java index <HASH>..<HASH> 100644 --- a/coordination/src/main/java/io/atomix/coordination/state/LeaderElectionState.java +++ b/coordination/src/main/java/io/atomix/coordination/state/LeaderElectionState.java @@ -20,8 +20,8 @@ import io.atomix.copycat.server.Commit; import io.atomix.copycat.server.StateMachine; import io.atomix.copycat.server.StateMachineExecutor; -import java.util.ArrayList; -import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; /** * Leader election state machine. @@ -29,9 +29,8 @@ import java.util.List; * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ public class LeaderElectionState extends StateMachine { - private Session leader; - private long epoch; - private final List<Commit<LeaderElectionCommands.Listen>> listeners = new ArrayList<>(); + private Commit<LeaderElectionCommands.Listen> leader; + private final Map<Long, Commit<LeaderElectionCommands.Listen>> listeners = new LinkedHashMap<>(); @Override public void configure(StateMachineExecutor executor) { @@ -42,13 +41,17 @@ public class LeaderElectionState extends StateMachine { @Override public void close(Session session) { - if (leader != null && leader.equals(session)) { + if (leader != null && leader.session().equals(session)) { + leader.clean(); leader = null; if (!listeners.isEmpty()) { - Commit<LeaderElectionCommands.Listen> leader = listeners.remove(0); - this.leader = leader.session(); - this.epoch = leader.index(); - this.leader.publish("elect", this.epoch); + leader = listeners.entrySet().iterator().next().getValue(); + this.leader.session().publish("elect", this.leader.index()); + } + } else { + Commit<LeaderElectionCommands.Listen> listener = listeners.remove(session.id()); + if (listener != null) { + listener.clean(); } } } @@ -58,12 +61,10 @@ public class LeaderElectionState extends StateMachine { */ protected void listen(Commit<LeaderElectionCommands.Listen> commit) { if (leader == null) { - leader = commit.session(); - epoch = commit.index(); - leader.publish("elect", epoch); - commit.clean(); - } else { - listeners.add(commit); + leader = commit; + leader.session().publish("elect", leader.index()); + } else if (!listeners.containsKey(commit.session().id())) { + listeners.put(commit.session().id(), commit); } } @@ -71,16 +72,20 @@ public class LeaderElectionState extends StateMachine { * Applies listen commits. */ protected void unlisten(Commit<LeaderElectionCommands.Unlisten> commit) { - if (leader != null && leader.equals(commit.session())) { - leader = null; - if (!listeners.isEmpty()) { - Commit<LeaderElectionCommands.Listen> leader = listeners.remove(0); - this.leader = leader.session(); - this.epoch = commit.index(); - this.leader.publish("elect", epoch); - leader.clean(); + try { + if (leader != null && leader.session().equals(commit.session())) { + leader = null; + if (!listeners.isEmpty()) { + leader = listeners.entrySet().iterator().next().getValue(); + leader.session().publish("elect", leader.index()); + } + } else { + Commit<LeaderElectionCommands.Listen> listener = listeners.remove(commit.session().id()); + if (listener != null) { + listener.clean(); + } } - } else { + } finally { commit.clean(); } } @@ -89,7 +94,7 @@ public class LeaderElectionState extends StateMachine { * Applies an isLeader query. */ protected boolean isLeader(Commit<LeaderElectionCommands.IsLeader> commit) { - return leader != null && leader.equals(commit.session()) && epoch == commit.operation().epoch(); + return leader != null && leader.session().equals(commit.session()) && leader.index() == commit.operation().epoch(); } }
Clean up leader election state machine to ensure commits are properly cleaned.
atomix_atomix
train
e7a0322f4f2298c7faf13ac88460403afe129779
diff --git a/interop/src/test/java/zipkin/cassandra/CassandraTestGraph.java b/interop/src/test/java/zipkin/cassandra/CassandraTestGraph.java index <HASH>..<HASH> 100644 --- a/interop/src/test/java/zipkin/cassandra/CassandraTestGraph.java +++ b/interop/src/test/java/zipkin/cassandra/CassandraTestGraph.java @@ -26,13 +26,16 @@ enum CassandraTestGraph { } final Lazy<CassandraStorage> storage = new Lazy<CassandraStorage>() { + AssumptionViolatedException ex = null; + @Override protected CassandraStorage compute() { + if (ex != null) throw ex; CassandraStorage result = new CassandraStorage.Builder().keyspace("test_zipkin").build(); try { result.spanStore().getServiceNames(); return result; } catch (NoHostAvailableException e) { - throw new AssumptionViolatedException(e.getMessage()); + throw ex = new AssumptionViolatedException(e.getMessage()); } } }; diff --git a/interop/src/test/java/zipkin/elasticsearch/ElasticsearchTestGraph.java b/interop/src/test/java/zipkin/elasticsearch/ElasticsearchTestGraph.java index <HASH>..<HASH> 100755 --- a/interop/src/test/java/zipkin/elasticsearch/ElasticsearchTestGraph.java +++ b/interop/src/test/java/zipkin/elasticsearch/ElasticsearchTestGraph.java @@ -25,13 +25,16 @@ enum ElasticsearchTestGraph { } final Lazy<ElasticsearchStorage> storage = new Lazy<ElasticsearchStorage>() { + public AssumptionViolatedException ex; + @Override protected ElasticsearchStorage compute() { + if (ex != null) throw ex; ElasticsearchStorage result = new ElasticsearchStorage.Builder().build(); try { result.spanStore().getServiceNames(); return result; } catch (NoNodeAvailableException e) { - throw new AssumptionViolatedException(e.getMessage()); + throw ex = new AssumptionViolatedException(e.getMessage()); } } }; diff --git a/zipkin-storage/cassandra/src/test/java/zipkin/cassandra/CassandraTestGraph.java b/zipkin-storage/cassandra/src/test/java/zipkin/cassandra/CassandraTestGraph.java index <HASH>..<HASH> 100644 --- a/zipkin-storage/cassandra/src/test/java/zipkin/cassandra/CassandraTestGraph.java +++ b/zipkin-storage/cassandra/src/test/java/zipkin/cassandra/CassandraTestGraph.java @@ -26,13 +26,16 @@ enum CassandraTestGraph { } final Lazy<CassandraStorage> storage = new Lazy<CassandraStorage>() { + AssumptionViolatedException ex = null; + @Override protected CassandraStorage compute() { + if (ex != null) throw ex; CassandraStorage result = new CassandraStorage.Builder().keyspace("test_zipkin").build(); try { result.spanStore().getServiceNames(); return result; } catch (NoHostAvailableException e) { - throw new AssumptionViolatedException(e.getMessage()); + throw ex = new AssumptionViolatedException(e.getMessage()); } } }; diff --git a/zipkin-storage/elasticsearch/src/test/java/zipkin/elasticsearch/ElasticsearchTestGraph.java b/zipkin-storage/elasticsearch/src/test/java/zipkin/elasticsearch/ElasticsearchTestGraph.java index <HASH>..<HASH> 100755 --- a/zipkin-storage/elasticsearch/src/test/java/zipkin/elasticsearch/ElasticsearchTestGraph.java +++ b/zipkin-storage/elasticsearch/src/test/java/zipkin/elasticsearch/ElasticsearchTestGraph.java @@ -25,13 +25,16 @@ enum ElasticsearchTestGraph { } final Lazy<ElasticsearchStorage> storage = new Lazy<ElasticsearchStorage>() { + public AssumptionViolatedException ex; + @Override protected ElasticsearchStorage compute() { + if (ex != null) throw ex; ElasticsearchStorage result = new ElasticsearchStorage.Builder().build(); try { result.spanStore().getServiceNames(); return result; } catch (NoNodeAvailableException e) { - throw new AssumptionViolatedException(e.getMessage()); + throw ex = new AssumptionViolatedException(e.getMessage()); } } };
Skip faster when test dependencies are missing By caching an exception attempting to connect to storage, tests skip <I> minutes faster!
apache_incubator-zipkin
train
dfbb5d61e6ea9608469a102856688dc16085a31f
diff --git a/spec/unit/multi_select_spec.rb b/spec/unit/multi_select_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/multi_select_spec.rb +++ b/spec/unit/multi_select_spec.rb @@ -3,6 +3,24 @@ RSpec.describe TTY::Prompt do let(:symbols) { TTY::Prompt::Symbols.symbols } + def output_helper(prompt, choices, active, selected, + hint: "Use arrow keys, press Space to select and Enter to finish", + init: false) + if init + out = "\e[?25l#{prompt} \e[90m(#{hint})\e[0m\n" + else + out = "#{prompt} #{selected.join(", ")}\n" + end + out << choices.map do |c| + prefix = (c == active) ? "#{symbols[:pointer]} " : " " + prefix += (selected.include?(c)) ? "\e[32m#{symbols[:radio_on]}\e[0m" : "#{symbols[:radio_off]}" + "#{prefix} #{c}" + end.join("\n") + out << "\e[2K\e[1G\e[1A" * choices.count + out << "\e[2K\e[1G" + out + end + it "selects nothing when return pressed immediately" do prompt = TTY::TestPrompt.new choices = %w(vodka beer wine whisky bourbon) @@ -316,4 +334,41 @@ RSpec.describe TTY::Prompt do "What letter? \e[32mA\e[0m\n\e[?25h", ].join) end + + it "doesn't cycle by default" do + prompt = TTY::TestPrompt.new + choices = %w(A B C) + prompt.on(:keypress) { |e| prompt.trigger(:keydown) if e.value == "j" } + prompt.input << "j" << "j" << "j" << " " << "\r" + prompt.input.rewind + value = prompt.multi_select("What letter?", choices) + expect(value).to eq(["C"]) + expect(prompt.output.string).to eq( + output_helper("What letter?", choices, "A", [], init: true) + + output_helper("What letter?", choices, "B", []) + + output_helper("What letter?", choices, "C", []) + + output_helper("What letter?", choices, "C", []) + + output_helper("What letter?", choices, "C", ["C"]) + + "What letter? \e[32mC\e[0m\n\e[?25h" + ) + end + + it "cycles when configured to do so" do + prompt = TTY::TestPrompt.new + choices = %w(A B C) + prompt.on(:keypress) { |e| prompt.trigger(:keydown) if e.value == "j" } + prompt.input << "j" << "j" << "j" << " " << "\r" + prompt.input.rewind + value = prompt.multi_select("What letter?", choices, cycle: true) + expect(value).to eq(["A"]) + expect(prompt.output.string).to eq( + output_helper("What letter?", choices, "A", [], init: true) + + output_helper("What letter?", choices, "B", []) + + output_helper("What letter?", choices, "C", []) + + output_helper("What letter?", choices, "A", []) + + output_helper("What letter?", choices, "A", ["A"]) + + "What letter? \e[32mA\e[0m\n\e[?25h" + ) + end + end
Add specs for mutli_select
piotrmurach_tty-prompt
train
5899175be1c18e470d20d0a049b35c9b57452869
diff --git a/h2o-algos/src/main/java/hex/DataInfo.java b/h2o-algos/src/main/java/hex/DataInfo.java index <HASH>..<HASH> 100644 --- a/h2o-algos/src/main/java/hex/DataInfo.java +++ b/h2o-algos/src/main/java/hex/DataInfo.java @@ -440,6 +440,8 @@ public class DataInfo extends Keyed<DataInfo> { res._fold = false; res._responses = 0; res._valid = true; + res._interactions=_interactions; + res._interactionVecs=_interactionVecs; return res; } @@ -482,6 +484,7 @@ public class DataInfo extends Keyed<DataInfo> { _valid = false; _numOffsets = dinfo._numOffsets; _interactions = dinfo._interactions; + _interactionVecs=dinfo._interactionVecs; assert dinfo._predictor_transform != null; assert dinfo._response_transform != null; _predictor_transform = dinfo._predictor_transform; @@ -667,7 +670,13 @@ public class DataInfo extends Keyed<DataInfo> { } } - public boolean isInteractionVec(int colid) { return _adaptedFrame.vec(colid) instanceof InteractionWrappedVec; } + public boolean isInteractionVec(int colid) { + if( null==_interactions || null==_interactionVecs ) return false; + if( _adaptedFrame!=null ) + return _adaptedFrame.vec(colid) instanceof InteractionWrappedVec; + else + return Arrays.binarySearch(_interactionVecs,colid) > 0; + } /** *
null check for isInteractionVec
h2oai_h2o-3
train
48bd04b83a2c957c869ac5a134ab7c6cdb82cc32
diff --git a/uportal-impl/src/main/java/org/jasig/portal/ChannelManager.java b/uportal-impl/src/main/java/org/jasig/portal/ChannelManager.java index <HASH>..<HASH> 100644 --- a/uportal-impl/src/main/java/org/jasig/portal/ChannelManager.java +++ b/uportal-impl/src/main/java/org/jasig/portal/ChannelManager.java @@ -1021,7 +1021,7 @@ public class ChannelManager implements LayoutEventListener { } //If the channel object has changed (likely now an error channel) return immediatly - if (originalChannel != ch) { + if (originalChannel != null && originalChannel != ch) { return false; }
UP-<I> Check for a null originalChannel before checking if it does not equal the channel to act on, happens when first request is an action git-svn-id: <URL>
Jasig_uPortal
train
6f1fdb09a296763da231350a85ae4d09bfe4a08c
diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructors.java b/core/src/main/java/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructors.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructors.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructors.java @@ -25,12 +25,11 @@ import com.sun.tools.javac.code.Symbol; /** * @author [email protected] (Steven Goldfeder) */ -@BugPattern(name = "InjectAssistedInjectAndInjectOnConstructors", +@BugPattern(name = "AssistedInjectAndInjectOnConstructors", summary = "@AssistedInject and @Inject should not be used on different constructors " + "in the same class.", - explanation = - "Mixing @Inject and @AssistedInject leads to confusing code and the documentation specifies " - + "not to do it. See " + explanation = "Mixing @Inject and @AssistedInject leads to confusing code and the " + + "documentation specifies not to do it. See " + "http://google-guice.googlecode.com/git/javadoc/com/google/inject/assistedinject/AssistedInject.html", category = INJECT, severity = WARNING, maturity = EXPERIMENTAL) public class InjectAssistedInjectAndInjectOnConstructors extends BugChecker diff --git a/core/src/test/resources/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructorsNegativeCases.java b/core/src/test/resources/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructorsNegativeCases.java index <HASH>..<HASH> 100644 --- a/core/src/test/resources/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructorsNegativeCases.java +++ b/core/src/test/resources/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructorsNegativeCases.java @@ -47,4 +47,17 @@ public class InjectAssistedInjectAndInjectOnConstructorsNegativeCases { @AssistedInject public TestClass5() {} } + + /** + * Class has a constructor annotated with @javax.inject.Inject and another constructor annotated + * with @AssistedInject. The warning is suppressed. + */ + @SuppressWarnings("AssistedInjectAndInjectOnConstructors") + public class TestClass6 { + @javax.inject.Inject + public TestClass6() {} + + @AssistedInject + public TestClass6(int n) {} + } } diff --git a/core/src/test/resources/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructorsPositiveCases.java b/core/src/test/resources/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructorsPositiveCases.java index <HASH>..<HASH> 100644 --- a/core/src/test/resources/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructorsPositiveCases.java +++ b/core/src/test/resources/com/google/errorprone/bugpatterns/InjectAssistedInjectAndInjectOnConstructorsPositiveCases.java @@ -19,6 +19,7 @@ public class InjectAssistedInjectAndInjectOnConstructorsPositiveCases { @AssistedInject public TestClass1(int n) {} } + /** * Class has a constructor annotated with @com.google.inject.Inject and another constructor * annotated with @AssistedInject. @@ -32,6 +33,7 @@ public class InjectAssistedInjectAndInjectOnConstructorsPositiveCases { @AssistedInject public TestClass2(int n) {} } + /** * Class has a constructor annotated with @com.google.inject.Inject, another constructor * annotated with @AssistedInject, and a third constructor with no annotation.
added suppression test, removed prefix from suppression string, other nits
google_error-prone
train
cded040cb6211b113289d06b880c2a7fd5ee5b7d
diff --git a/elem/elem.gen.go b/elem/elem.gen.go index <HASH>..<HASH> 100644 --- a/elem/elem.gen.go +++ b/elem/elem.gen.go @@ -334,7 +334,7 @@ func Form(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { // is the highest section level and <h6> is the lowest. // // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements -func Header1(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { +func Heading1(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { return vecty.Tag("h1", markup...) } @@ -342,7 +342,7 @@ func Header1(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { // is the highest section level and <h6> is the lowest. // // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements -func Header2(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { +func Heading2(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { return vecty.Tag("h2", markup...) } @@ -350,7 +350,7 @@ func Header2(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { // is the highest section level and <h6> is the lowest. // // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements -func Header3(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { +func Heading3(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { return vecty.Tag("h3", markup...) } @@ -358,7 +358,7 @@ func Header3(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { // is the highest section level and <h6> is the lowest. // // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements -func Header4(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { +func Heading4(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { return vecty.Tag("h4", markup...) } @@ -366,7 +366,7 @@ func Header4(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { // is the highest section level and <h6> is the lowest. // // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements -func Header5(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { +func Heading5(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { return vecty.Tag("h5", markup...) } @@ -374,7 +374,7 @@ func Header5(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { // is the highest section level and <h6> is the lowest. // // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements -func Header6(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { +func Heading6(markup ...vecty.MarkupOrComponentOrHTML) *vecty.HTML { return vecty.Tag("h6", markup...) } diff --git a/elem/generate.go b/elem/generate.go index <HASH>..<HASH> 100644 --- a/elem/generate.go +++ b/elem/generate.go @@ -37,12 +37,12 @@ var elemNameMap = map[string]string{ "em": "Emphasis", "fieldset": "FieldSet", "figcaption": "FigureCaption", - "h1": "Header1", - "h2": "Header2", - "h3": "Header3", - "h4": "Header4", - "h5": "Header5", - "h6": "Header6", + "h1": "Heading1", + "h2": "Heading2", + "h3": "Heading3", + "h4": "Heading4", + "h5": "Heading5", + "h6": "Heading6", "hgroup": "HeadingsGroup", "hr": "HorizontalRule", "i": "Italic", diff --git a/examples/todomvc/components/pageview.go b/examples/todomvc/components/pageview.go index <HASH>..<HASH> 100644 --- a/examples/todomvc/components/pageview.go +++ b/examples/todomvc/components/pageview.go @@ -71,7 +71,7 @@ func (p *PageView) renderHeader() *vecty.HTML { return elem.Header( prop.Class("header"), - elem.Header1( + elem.Heading1( vecty.Text("todos"), ), elem.Form(
elem: Rename h1-h6 elements from Header to Heading. Update todomvc example to use new name. Fixes #<I>.
gopherjs_vecty
train
07522152c3db280e23f4064cf45103689baf3a34
diff --git a/stage0/run.go b/stage0/run.go index <HASH>..<HASH> 100644 --- a/stage0/run.go +++ b/stage0/run.go @@ -41,6 +41,7 @@ import ( "github.com/coreos/rkt/common" "github.com/coreos/rkt/common/apps" "github.com/coreos/rkt/pkg/aci" + "github.com/coreos/rkt/pkg/fileutil" "github.com/coreos/rkt/pkg/sys" "github.com/coreos/rkt/store" "github.com/coreos/rkt/version" @@ -413,7 +414,13 @@ func prepareStage1Image(cfg PrepareConfig, img types.Hash, cdir string, useOverl } if !useOverlay { - if err := aci.RenderACIWithImageID(img, s1, cfg.Store); err != nil { + if err := writeManifest(cfg.CommonConfig, img, s1); err != nil { + return fmt.Errorf("error writing manifest: %v", err) + } + + destRootfs := filepath.Join(s1, "rootfs") + cachedTreePath := cfg.Store.GetTreeStoreRootFS(img.String()) + if err := fileutil.CopyTree(cachedTreePath, destRootfs); err != nil { return fmt.Errorf("error rendering ACI: %v", err) } } @@ -440,6 +447,26 @@ func setupStage1Image(cfg RunConfig, img types.Hash, cdir string, useOverlay boo return nil } +// writeManifest takes an img ID and writes the corresponding manifest in dest +func writeManifest(cfg CommonConfig, img types.Hash, dest string) error { + manifest, err := cfg.Store.GetImageManifest(img.String()) + if err != nil { + return err + } + + mb, err := json.Marshal(manifest) + if err != nil { + return fmt.Errorf("error marshalling image manifest: %v", err) + } + + log.Printf("Writing image manifest") + if err := ioutil.WriteFile(filepath.Join(dest, "manifest"), mb, 0700); err != nil { + return fmt.Errorf("error writing pod manifest: %v", err) + } + + return nil +} + // overlayRender renders the image that corresponds to the given hash using the // overlay filesystem. // It writes the manifest in the specified directory and mounts an overlay
stage0: copy stage1 image from tree cache instead of extracting it Since we render the stage1 image anyway, if we don't use overlay fs, we copy its rootfs from the tree cache instead of extracting it every single time.
rkt_rkt
train
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
diff --git a/lib/ice_cube/validations/hour_of_day.rb b/lib/ice_cube/validations/hour_of_day.rb index <HASH>..<HASH> 100644 --- a/lib/ice_cube/validations/hour_of_day.rb +++ b/lib/ice_cube/validations/hour_of_day.rb @@ -23,7 +23,7 @@ module IceCube first_hour = Array(validations[:hour_of_day]).min_by(&:value) time = TimeUtil::TimeWrapper.new(start_time, false) - if freq > 1 + if freq > 1 && base_interval_validation.type == :hour offset = first_hour.validate(opening_time, start_time) time.add(:hour, offset - freq) else diff --git a/spec/examples/weekly_rule_spec.rb b/spec/examples/weekly_rule_spec.rb index <HASH>..<HASH> 100644 --- a/spec/examples/weekly_rule_spec.rb +++ b/spec/examples/weekly_rule_spec.rb @@ -338,6 +338,26 @@ module IceCube end end end + + # August 2018 + # Su Mo Tu We Th Fr Sa + # 1 2 3 4 + # 5 6 7 8 9 10 11 + # 12 13 14 15 16 17 18 + # 19 20 21 22 23 24 25 + # 26 27 28 29 30 31 + context 'when day of start_time does not align with specified day rule' do + let(:start_time) { Time.utc(2018, 8, 7, 10, 0, 0) } + let(:end_time) { Time.utc(2018, 8, 7, 15, 0, 0) } + let(:biweekly) { IceCube::Rule.weekly(2).day(:saturday).hour_of_day(10) } + let(:schedule) { IceCube::Schedule.new(start_time, end_time: end_time) { |s| s.rrule biweekly } } + let(:range) { [Time.utc(2018, 8, 11, 7, 0, 0), Time.utc(2018, 8, 12, 6, 59, 59)] } + let(:expected_date) { Time.utc(2018, 8, 11, 10, 0, 0) } + + it 'should align to the correct day with the spans option' do + expect(schedule.occurrences_between(range.first, range.last, spans: true)).to include expected_date + end + end end describe "using occurs_between with a weekly schedule" do
Fix offset bug when day of start_time does not align with specified day rule (#<I>) This combination needs to apply the right offset for advancing to the first occurrence: - Weekly with frequency > 1 (biweekly, etc.) - with a weekday validation (e.g. Saturday) - declared as starting on a different weekday (e.g. Friday) - with an hour of day validation (even when declared to start on the expected hour)
seejohnrun_ice_cube
train
170442069713792a98f2b0fa543ff76e0d8ff840
diff --git a/pyrogram/types/bots_and_keyboards/callback_query.py b/pyrogram/types/bots_and_keyboards/callback_query.py index <HASH>..<HASH> 100644 --- a/pyrogram/types/bots_and_keyboards/callback_query.py +++ b/pyrogram/types/bots_and_keyboards/callback_query.py @@ -252,7 +252,7 @@ class CallbackQuery(Object, Update): Raises: RPCError: In case of a Telegram RPC error. """ - return await self.edit_message_text(caption, parse_mode, reply_markup) + return await self.edit_message_text(caption, parse_mode, reply_markup=reply_markup) async def edit_message_media( self,
Fix wrongly passed positional arguments (#<I>) Since CallbackQuery.edit_message_text takes 4 arguments and CallbackQuery.edit_message_caption only 3, the reply_markup ends up to be the disable_web_page_preview one. Resolve this by specifying the argument name
pyrogram_pyrogram
train
cb96183df287a3bb27fb02527ca1f626a7b09824
diff --git a/bundles/org.eclipse.orion.client.core/web/orion/nlsutil.js b/bundles/org.eclipse.orion.client.core/web/orion/nlsutil.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.core/web/orion/nlsutil.js +++ b/bundles/org.eclipse.orion.client.core/web/orion/nlsutil.js @@ -13,7 +13,7 @@ define([], function() { function urlExists(url) { var http = new XMLHttpRequest(); - http.open('HEAD', url, false); + http.open('GET', url, false); http.send(); return http.status!=404; } diff --git a/bundles/org.eclipse.orion.client.editor/web/orion/textview/util.js b/bundles/org.eclipse.orion.client.editor/web/orion/textview/util.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.editor/web/orion/textview/util.js +++ b/bundles/org.eclipse.orion.client.editor/web/orion/textview/util.js @@ -18,7 +18,7 @@ define([], function() { function urlExists(url) { var http = new XMLHttpRequest(); - http.open('HEAD', url, false); + http.open('GET', url, false); http.send(); return http.status!=404; }
Bug <I> -Orion client nls bundles format cannot be consumed by Babel - remove HEAD method
eclipse_orion.client
train
e57d866ded7ca25c630d3ef697c9f9ca9c38586c
diff --git a/PlugIns/Camera/CameraHardwareSource.py b/PlugIns/Camera/CameraHardwareSource.py index <HASH>..<HASH> 100644 --- a/PlugIns/Camera/CameraHardwareSource.py +++ b/PlugIns/Camera/CameraHardwareSource.py @@ -285,12 +285,14 @@ class CameraFrameParameters(object): self.exposure_ms = d.get("exposure_ms", 125) self.binning = d.get("binning", 1) self.processing = d.get("processing") + self.integration_count = d.get("integration_count") def as_dict(self): return { "exposure_ms": self.exposure_ms, "binning": self.binning, "processing": self.processing, + "integration_count": self.integration_count, } @@ -437,6 +439,16 @@ class Camera(abc.ABC): """ ... + def set_integration_count(self, integration_count: int, mode_id: str) -> None: + """Set the integration code for the mode. + + Integration count can be ignored, in which case integration is performed by higher level code. + + Setting the integration count for the currently live mode (if there is one) should update acquisition as soon + as possible, which may be immediately or may be the next frame. + """ + pass + @property @abc.abstractmethod def exposure_ms(self) -> float: @@ -509,6 +521,10 @@ class Camera(abc.ABC): The 'data' may point to memory allocated in low level code, but it must remain valid and unmodified until released (Python reference count goes to zero). + + If integration_count is non-zero and is handled directly in this method, the 'properties' should also contain + a 'integration_count' value to indicate how many frames were integrated. If the value is missing, a default + value of 1 is assumed. """ ... @@ -583,10 +599,23 @@ class CameraAdapterAcquisitionTask: frame_parameters = self.__frame_parameters exposure_ms = frame_parameters.exposure_ms binning = frame_parameters.binning - data_element = self.__camera.acquire_image() + integration_count = frame_parameters.integration_count if frame_parameters.integration_count else 1 + cumulative_frame_count = 0 # used for integration_count + cumulative_data = None + data_element = None # avoid use-before-set warning + while cumulative_frame_count < integration_count: + data_element = self.__camera.acquire_image() + frames_acquired = data_element["properties"].get("integration_count", 1) + if cumulative_data is None: + cumulative_data = data_element["data"] + else: + cumulative_data += data_element["data"] + cumulative_frame_count += frames_acquired + assert cumulative_frame_count <= integration_count if self.__stop_after_acquire: self.__camera.stop_live() - sub_area = (0, 0), data_element["data"].shape + sub_area = (0, 0), cumulative_data.shape + data_element["data"] = cumulative_data data_element["version"] = 1 data_element["sub_area"] = sub_area data_element["state"] = "complete" @@ -617,6 +646,7 @@ class CameraAdapterAcquisitionTask: data_element["properties"]["binning"] = binning data_element["properties"]["valid_rows"] = sub_area[0][0] + sub_area[1][0] data_element["properties"]["frame_index"] = data_element["properties"]["frame_number"] + data_element["properties"]["integration_count"] = cumulative_frame_count return [data_element] def __activate_frame_parameters(self): @@ -625,6 +655,7 @@ class CameraAdapterAcquisitionTask: mode_id = self.__camera.mode self.__camera.set_exposure_ms(self.__frame_parameters.exposure_ms, mode_id) self.__camera.set_binning(self.__frame_parameters.binning, mode_id) + self.__camera.set_integration_count(self.__frame_parameters.integration_count, mode_id) class CameraAdapter: diff --git a/PlugIns/Camera/test/CameraControl_test.py b/PlugIns/Camera/test/CameraControl_test.py index <HASH>..<HASH> 100644 --- a/PlugIns/Camera/test/CameraControl_test.py +++ b/PlugIns/Camera/test/CameraControl_test.py @@ -565,6 +565,21 @@ class TestCameraControlClass(unittest.TestCase): numpy.random.seed() random.seed() + def test_integrating_frames_updates_frame_count_by_integration_count(self): + document_controller, document_model, hardware_source, state_controller = self._setup_hardware_source() + with contextlib.closing(document_controller), contextlib.closing(state_controller): + frame_parameters = hardware_source.get_frame_parameters(0) + frame_parameters.integration_count = 4 + hardware_source.set_current_frame_parameters(frame_parameters) + hardware_source.start_playing() + try: + frame0_integration_count = hardware_source.get_next_xdatas_to_finish()[0].metadata["hardware_source"]["integration_count"] + frame1_integration_count = hardware_source.get_next_xdatas_to_finish()[0].metadata["hardware_source"]["integration_count"] + self.assertEqual(frame0_integration_count, 4) + self.assertEqual(frame1_integration_count, 4) + finally: + hardware_source.abort_playing(sync_timeout=3.0) + def test_facade_frame_parameter_methods(self): document_controller, document_model, hardware_source, state_controller = self.__setup_hardware_source() with contextlib.closing(document_controller), contextlib.closing(state_controller):
Add integration count to frame parameters and support in camera hardware source. Was svn r<I>
nion-software_nionswift-instrumentation-kit
train
2a9a2aa049d8685c2815311df6e1d29c9b5de5f1
diff --git a/franz/rabbitmq/consumer.py b/franz/rabbitmq/consumer.py index <HASH>..<HASH> 100644 --- a/franz/rabbitmq/consumer.py +++ b/franz/rabbitmq/consumer.py @@ -91,12 +91,17 @@ class Consumer: properties.correlation_id, self._queue_name, ) + + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + logging.basicConfig( format='[%(levelname)s] {correlation_id}: %(message)s'.format( correlation_id=correlation_id ), level=logging.INFO, ) + consumer_callback( correlation_id, method.routing_key,
remove before re-setting the config
carta_franz
train
be931f1b403cb7a71428dab49f1ccd8060c8bcf4
diff --git a/ELiDE/ELiDE/board/board.py b/ELiDE/ELiDE/board/board.py index <HASH>..<HASH> 100644 --- a/ELiDE/ELiDE/board/board.py +++ b/ELiDE/ELiDE/board/board.py @@ -129,6 +129,8 @@ class Board(RelativeLayout): return if not self.collide_point(*touch.pos): return + touch.push() + touch.apply_transform_2d(self.to_local) if self.selection: self.selection.hit = self.selection.collide_point(*touch.pos) if self.selection.hit: @@ -140,6 +142,7 @@ class Board(RelativeLayout): self.selection_candidates = pawns if self.selection in self.selection_candidates: self.selection_candidates.remove(self.selection) + touch.pop() return True spots = list(self.spots_at(*touch.pos)) if spots: @@ -165,13 +168,16 @@ class Board(RelativeLayout): origin=self.protodest ) self.add_widget(self.protoportal2) + touch.pop() return True if not self.selection_candidates: arrows = list(self.arrows_at(*touch.pos)) if arrows: Logger.debug("Board: hit {} arrows".format(len(arrows))) self.selection_candidates = arrows + touch.pop() return True + touch.pop() def on_touch_move(self, touch): """If an entity is selected, drag it.""" @@ -179,10 +185,14 @@ class Board(RelativeLayout): return if self.selection in self.selection_candidates: self.selection_candidates.remove(self.selection) + touch.push() + touch.apply_transform_2d(self.to_local) if self.selection: if not self.selection_candidates: self.keep_selection = True - return self.selection.dispatch('on_touch_move', touch) + ret = self.selection.dispatch('on_touch_move', touch) + touch.pop() + return ret elif self.selection_candidates: for cand in self.selection_candidates: if cand.collide_point(*touch.pos): @@ -193,7 +203,10 @@ class Board(RelativeLayout): self.selection = cand cand.hit = cand.selected = True touch.grab(cand) - return cand.dispatch('on_touch_move', touch) + ret = cand.dispatch('on_touch_move', touch) + touch.pop() + return ret + touch.pop() def portal_touch_up(self, touch): """Try to create a portal between the spots the user chose.""" @@ -244,10 +257,14 @@ class Board(RelativeLayout): if hasattr(self, '_lasttouch') and self._lasttouch == touch: return self._lasttouch = touch + touch.push() + touch.apply_transform_2d(self.to_local) if hasattr(self, 'protodest'): Logger.debug("Board: on_touch_up making a portal") touch.ungrab(self) - return self.portal_touch_up(touch) + ret = self.portal_touch_up(touch) + touch.pop() + return ret if hasattr(self.selection, 'on_touch_up'): self.selection.dispatch('on_touch_up', touch) while self.selection_candidates: @@ -281,6 +298,7 @@ class Board(RelativeLayout): self.selection = None self.keep_selection = False touch.ungrab(self) + touch.pop() return def _pull_size(self, *args):
Apply local transform to Board touches I'm not sure why this didn't cause trouble before.
LogicalDash_LiSE
train
ec32294a3daa97457ad83399f56218bf4fced04d
diff --git a/examples/example_minimum.php b/examples/example_minimum.php index <HASH>..<HASH> 100644 --- a/examples/example_minimum.php +++ b/examples/example_minimum.php @@ -34,24 +34,23 @@ //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0 $TestFeed->setImage('Testing the RSS writer class','http://www.ajaxray.com/projects/rss','http://www.rightbrainsolution.com/_resources/img/logo.png'); - //Retriving informations from database addin feeds - $db->query($query); - $result = $db->result; - - while($row = mysql_fetch_array($result, MYSQL_ASSOC)) - { - //Create an empty FeedItem - $newItem = $TestFeed->createNewItem(); - - //Add elements to the feed item - $newItem->setTitle($row['title']); - $newItem->setLink($row['link']); - $newItem->setDate($row['create_date']); - $newItem->setDescription($row['description']); - - //Now add the feed item - $TestFeed->addItem($newItem); - } + //Let's add some feed items: Create two empty FeedItem instances + $itemOne = $TestFeed->createNewItem(); + $itemTwo = $TestFeed->createNewItem(); + + //Add item details + $itemOne->setTitle('The title of the first entry.'); + $itemOne->setLink('http://www.google.de'); + $itemOne->setDate(time()); + $itemOne->setDescription('And here\'s the description of the entry.'); + $itemTwo->setTitle('Lorem ipsum'); + $itemTwo->setLink('http://www.example.com'); + $itemTwo->setDate(1234567890); + $itemTwo->setDescription('Lorem ipsum dolor sit amet, consectetur, adipisci velit'); + + //Now add the feed item + $TestFeed->addItem($itemOne); + $TestFeed->addItem($itemTwo); //OK. Everything is done. Now genarate the feed. $TestFeed->generateFeed();
Don't use a (actually not working) database for retrieving item information. The minimal example should have minimal requirements...
mibe_FeedWriter
train
ea7f239028a04aca3f92e30b0adefd9e81e31361
diff --git a/host-controller/src/main/java/org/jboss/as/host/controller/mgmt/MasterDomainControllerOperationHandlerImpl.java b/host-controller/src/main/java/org/jboss/as/host/controller/mgmt/MasterDomainControllerOperationHandlerImpl.java index <HASH>..<HASH> 100644 --- a/host-controller/src/main/java/org/jboss/as/host/controller/mgmt/MasterDomainControllerOperationHandlerImpl.java +++ b/host-controller/src/main/java/org/jboss/as/host/controller/mgmt/MasterDomainControllerOperationHandlerImpl.java @@ -262,7 +262,7 @@ public class MasterDomainControllerOperationHandlerImpl extends ManagementChanne } private String getRelativePath(final File parent, final File child) { - return child.getAbsolutePath().substring(parent.getAbsolutePath().length()); + return child.getAbsolutePath().substring(parent.getAbsolutePath().length()+1); } private void writeFile(final File localPath, final File file, final FlushableDataOutput output) throws IOException {
AS7-<I> - Fix distributed deploy for Windows DC This patch fixes problem when you have Windows DC and Linux HC File path had \ in name and that failed deployment
wildfly_wildfly
train
8761e6e06e06593ad5a8712c5ff43aa3ac8c5a16
diff --git a/indra/tools/reading/submit_reading_pipeline_aws.py b/indra/tools/reading/submit_reading_pipeline_aws.py index <HASH>..<HASH> 100644 --- a/indra/tools/reading/submit_reading_pipeline_aws.py +++ b/indra/tools/reading/submit_reading_pipeline_aws.py @@ -1,5 +1,13 @@ from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str +import boto3 +import botocore.session +from indra.literature import elsevier_client as ec + +bucket_name = 'bigmech' + +# Submit the reading job +batch_client = boto3.client('batch') def get_environment(): # Get AWS credentials @@ -60,6 +68,7 @@ def submit_run_reach(basename, pmid_list_filename, start_ix=None, end_ix=None, job_list.append({'jobId': job_info['jobId']}) return job_list + def submit_combine(basename, job_ids=None): # Get environment variables environment_vars = get_environment() @@ -78,18 +87,10 @@ def submit_combine(basename, job_ids=None): kwargs['dependsOn'] = job_ids batch_client.submit_job(**kwargs) + if __name__ == '__main__': import sys import argparse - import boto3 - import botocore.session - from indra.literature import elsevier_client as ec - - bucket_name = 'bigmech' - #job_type =sys.argv[1] - - # Submit the reading job - batch_client = boto3.client('batch') # Create the top-level parser parser = argparse.ArgumentParser('submit_reading_pipeline_aws.py',
Move imports so submit can be called from outside
sorgerlab_indra
train
64ea6f22ef41dc3769670a35b5ab84f21be953ae
diff --git a/example.js b/example.js index <HASH>..<HASH> 100644 --- a/example.js +++ b/example.js @@ -13,7 +13,7 @@ import createLogger from 'redux-logger' // Auth0 import { Auth0Provider } from 'use-auth0-hooks' import { accountLinks, getAuth0Callbacks, getAuth0Config } from './lib/util/auth' -import { AUTH0_SCOPE } from './lib/util/constants' +import { AUTH0_SCOPE, URL_ROOT } from './lib/util/constants' // import Bootstrap Grid components for layout import { Nav, Navbar, Grid, Row, Col } from 'react-bootstrap' @@ -143,7 +143,7 @@ render(auth0Config scope={AUTH0_SCOPE} domain={auth0Config.domain} clientId={auth0Config.clientId} - redirectUri={`${window.location.protocol}//${window.location.host}`} + redirectUri={URL_ROOT} {...auth0Callbacks} > {innerProvider} diff --git a/lib/components/user/nav-login-button-auth0.js b/lib/components/user/nav-login-button-auth0.js index <HASH>..<HASH> 100644 --- a/lib/components/user/nav-login-button-auth0.js +++ b/lib/components/user/nav-login-button-auth0.js @@ -1,7 +1,7 @@ import React from 'react' import { useAuth } from 'use-auth0-hooks' -import { getAuthRedirectUri } from '../../util/auth' +import { URL_ROOT } from '../../util/constants' import NavLoginButton from './nav-login-button' @@ -20,7 +20,7 @@ const NavLoginButtonAuth0 = ({ // TODO: check that URLs are whitelisted. All trip query URLs in /#/ are. const afterLoginPath = '/#/signedin' const handleLogin = () => login({ - redirect_uri: `${getAuthRedirectUri()}${afterLoginPath}`, + redirect_uri: `${URL_ROOT}${afterLoginPath}`, appState: {urlHash: window.location.hash} // The part of href from #/?, e.g. #/?ui_activeSearch=... }) diff --git a/lib/components/user/user-account-screen.js b/lib/components/user/user-account-screen.js index <HASH>..<HASH> 100644 --- a/lib/components/user/user-account-screen.js +++ b/lib/components/user/user-account-screen.js @@ -366,11 +366,6 @@ class UserAccountScreen extends Component { userData } = this.state - if (isNewAccount && !user.email_verified) { - // Check and prompt for email verification first to avoid extra user wait. - return verifyEmailScreen - } - if (!userData) { // Display a hint while fetching user data (from componentDidMount). return awaitingScreen @@ -399,7 +394,11 @@ class UserAccountScreen extends Component { <div className='otp'> {navBar} <form className='container'> - {isNewAccount ? this._renderNewAccount() : this._renderExistingAccount()} + {(isNewAccount && !user.email_verified) + // Check and prompt for email verification first to avoid extra user wait. + ? verifyEmailScreen + : (isNewAccount ? this._renderNewAccount() : this._renderExistingAccount()) + } </form> </div> ) diff --git a/lib/util/auth.js b/lib/util/auth.js index <HASH>..<HASH> 100644 --- a/lib/util/auth.js +++ b/lib/util/auth.js @@ -1,6 +1,6 @@ import { push } from 'connected-react-router' -import { PERSISTENCE_STRATEGY_OTP_MIDDLEWARE } from './constants' +import { PERSISTENCE_STRATEGY_OTP_MIDDLEWARE, URL_ROOT } from './constants' /** * Custom links under the user account dropdown. @@ -69,7 +69,7 @@ export function getAuth0Callbacks (reduxStore) { // the state just before the Auth0 operation (stored in appState.urlHash), // and prevent the URL with no search from appearing in the user's browsing history. const newUserPath = appState.urlHash.replace('#/', '#/account/welcome') - const newUserUrl = `${getAuthRedirectUri()}${newUserPath}` + const newUserUrl = `${URL_ROOT}${newUserPath}` window.location.replace(newUserUrl) } else if (appState && appState.returnTo) { diff --git a/lib/util/constants.js b/lib/util/constants.js index <HASH>..<HASH> 100644 --- a/lib/util/constants.js +++ b/lib/util/constants.js @@ -1,2 +1,5 @@ export const AUTH0_SCOPE = '' export const PERSISTENCE_STRATEGY_OTP_MIDDLEWARE = 'otp_middleware' + +// Gets the root URL, e.g. https://otp-instance.example.com:8080/, computed once for all. +export const URL_ROOT = `${window.location.protocol}//${window.location.host}`
fix(redirect, verify email): Add redirect URL_ROOT, add nav to verify email.
opentripplanner_otp-react-redux
train
8fee1e3dc0a5e053afe69bbac7a631a95de5aef7
diff --git a/src/main/java/org/ops4j/io/StreamUtils.java b/src/main/java/org/ops4j/io/StreamUtils.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/ops4j/io/StreamUtils.java +++ b/src/main/java/org/ops4j/io/StreamUtils.java @@ -18,15 +18,20 @@ package org.ops4j.io; -import org.ops4j.lang.NullArgumentException; -import org.ops4j.monitors.stream.StreamMonitor; - import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.io.BufferedReader; +import java.io.BufferedWriter; import java.net.URL; +import org.ops4j.lang.NullArgumentException; +import org.ops4j.monitors.stream.StreamMonitor; /** * @author <a href="http://www.ops4j.org">Open Particpation Software for Java</a> @@ -152,4 +157,48 @@ public class StreamUtils boolean noMoreOnIn2Either = in2.read() == -1; return noMoreOnIn2Either; } + + static public void copyReaderToWriter( Reader in, Writer out, boolean close ) + throws IOException + { + try + { + if( ! (in instanceof BufferedReader )) + { + in = new BufferedReader( in ); + } + if( ! (out instanceof BufferedWriter )) + { + out = new BufferedWriter( out ); + } + int ch = in.read(); + while( ch != -1 ) + { + out.write( ch ); + ch = in.read(); + } + out.flush(); + } finally + { + if( close ) + { + in.close(); + out.close(); + } + } + } + + static public void copyStreamToWriter( InputStream in, Writer out, String encoding, boolean close ) + throws IOException + { + InputStreamReader reader = new InputStreamReader( in, encoding ); + copyReaderToWriter( reader, out, close ); + } + + static public void copyReaderToStream( Reader in, OutputStream out, String encoding, boolean close ) + throws IOException + { + OutputStreamWriter writer = new OutputStreamWriter( out, encoding ); + copyReaderToWriter( in, writer, close ); + } } diff --git a/src/main/test/java/org/ops4j/io/StreamUtilTestCase.java b/src/main/test/java/org/ops4j/io/StreamUtilTestCase.java index <HASH>..<HASH> 100644 --- a/src/main/test/java/org/ops4j/io/StreamUtilTestCase.java +++ b/src/main/test/java/org/ops4j/io/StreamUtilTestCase.java @@ -13,14 +13,17 @@ * implied. * * See the License for the specific language governing permissions and - * limitations under the License. + * limitations under the License. */ package org.ops4j.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; import junit.framework.TestCase; +import junit.framework.ComparisonFailure; public class StreamUtilTestCase extends TestCase { @@ -160,6 +163,63 @@ public class StreamUtilTestCase extends TestCase } } + public void testCopyReaderToWriter() + throws Exception + { + String s = "HabbaZout\u4512\u1243\u9812"; + StringReader reader = new StringReader( s ); + StringWriter writer = new StringWriter(); + StreamUtils.copyReaderToWriter( reader, writer, true ); + assertEquals( s, writer.getBuffer().toString() ); + } + + public void testCopyReaderToStream() + throws Exception + { + String s = "HabbaZout\u1298\u1243\u9812"; + StringReader reader = new StringReader( s ); + ByteArrayOutputStream baos = new ByteArrayOutputStream( ); + StreamUtils.copyReaderToStream( reader, baos, "UTF-8", true ); + assertEquals( s, baos.toString() ); + + reader = new StringReader( s ); + baos = new ByteArrayOutputStream( ); + StreamUtils.copyReaderToStream( reader, baos, "ISO-8859-1", true ); + //noinspection ErrorNotRethrown + try + { + assertEquals( s, baos.toString() ); + fail( "Didn't fail incorrect encoding."); + } catch( ComparisonFailure e ) + { + // expected + } + } + + public void testCopyStreamToWriter() + throws Exception + { + String s = "HabbaZout\u1298\u1243\u9812"; + ByteArrayInputStream in = new ByteArrayInputStream( s.getBytes( "UTF-8" ) ); + StringWriter writer = new StringWriter(); + StreamUtils.copyStreamToWriter( in, writer, "UTF-8", true ); + assertEquals( s, writer.getBuffer().toString() ); + + in = new ByteArrayInputStream( s.getBytes( "ISO-8859-1" ) ); + writer = new StringWriter(); + StreamUtils.copyStreamToWriter( in, writer, "UTF-8", true ); + //noinspection ErrorNotRethrown + try + { + assertEquals( s, writer.getBuffer().toString() ); + fail( "Didn't fail incorrect encoding."); + } catch( ComparisonFailure e ) + { + // expected + } + + } + private static class MyByteArrayOutputStream extends ByteArrayOutputStream {
Added in StreamUtils support for Reader/Writer copy operations. git-svn-id: <URL>
ops4j_org.ops4j.base
train
ba6c034e5b66f385d1a1efd2b427765645b6c2a3
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -14,11 +14,12 @@ import os +import codecs from setuptools import setup, find_packages def read(*rnames): - return open(os.path.join(os.path.dirname(__file__), *rnames)).read() + return codecs.open(os.path.join(os.path.dirname(__file__), *rnames), encoding='utf-8').read() setup(
Fix utf8 file input in setup.py
knaperek_djangosaml2
train
5f076c7129c8d658234e31f17db42f9a30013bd3
diff --git a/firetv/__init__.py b/firetv/__init__.py index <HASH>..<HASH> 100644 --- a/firetv/__init__.py +++ b/firetv/__init__.py @@ -33,8 +33,7 @@ WINDOW_REGEX = re.compile(r"Window\{(?P<id>.+?) (?P<user>.+) (?P<package>.+?)(?: SCREEN_ON_CMD = r"dumpsys power | grep 'Display Power' | grep -q 'state=ON'" AWAKE_CMD = r"dumpsys power | grep mWakefulness | grep -q Awake" WAKE_LOCK_CMD = r"dumpsys power | grep Locks | grep -q 'size=0'" -AUDIO_STARTED_CMD = "dumpsys audio | grep started" -AUDIO_PAUSED_CMD = "dumpsys audio | grep paused" +AUDIO_STATE_CMD = r"dumpsys audio | grep paused && echo -e '1\c' || (dumpsys audio | grep started && echo '2\c' || echo '0\c')" CURRENT_APP_CMD = "dumpsys window windows | grep mCurrentFocus" RUNNING_APPS_CMD = "ps | grep u0_a" @@ -525,13 +524,12 @@ class FireTV: @property def audio_state(self): """Check if audio is playing, paused, or idle.""" - output = self.adb_shell(AUDIO_PAUSED_CMD + SUCCESS1_FAILURE0 + " && " + - AUDIO_STARTED_CMD + SUCCESS1_FAILURE0) + output = self.adb_shell(AUDIO_STATE_CMD) if output is None: return None - if output[0] == '1': + if output == '1': return STATE_PAUSED - if output[1] == '1': + if output == '2': return STATE_PLAYING return STATE_IDLE @@ -563,15 +561,15 @@ class FireTV: if output[3] == '1': audio_state = STATE_PAUSED - elif output[4] == '1': + elif output[3] == '2': audio_state = STATE_PLAYING else: audio_state = STATE_IDLE - if len(output) < 6: - return screen_on, awake, wake_lock, None + if len(output) < 5: + return screen_on, awake, wake_lock, audio_state, None - current_focus = output[5:].replace("\r", "") + current_focus = output[4:].replace("\r", "") matches = WINDOW_REGEX.search(current_focus) # case 1: current app was successfully found
Improve 'audio_state' property
happyleavesaoc_python-firetv
train
8eb98614b78dab2ce0c20bde3d79e0dbf4262e79
diff --git a/tests/llist_test.py b/tests/llist_test.py index <HASH>..<HASH> 100644 --- a/tests/llist_test.py +++ b/tests/llist_test.py @@ -255,6 +255,17 @@ class testDLList(unittest.TestCase): del ll[0] self.assertEqual(len(ll), 0) + def test_list_readonly_attributes(self): + ll = DLList(range(4)) + self.assertRaises(TypeError, setattr, ll, 'first', None) + self.assertRaises(TypeError, setattr, ll, 'last', None) + self.assertRaises(TypeError, setattr, ll, 'size', None) + + def test_node_readonly_attributes(self): + ll = DLListNode() + self.assertRaises(TypeError, setattr, ll, 'prev', None) + self.assertRaises(TypeError, setattr, ll, 'next', None) + def suite(): suite = unittest.TestSuite()
Added tests for read-only attributes
ajakubek_python-llist
train
1a9144034cc02e50ff69886a592c082366e5b088
diff --git a/src/jquery.smooth-scroll.js b/src/jquery.smooth-scroll.js index <HASH>..<HASH> 100644 --- a/src/jquery.smooth-scroll.js +++ b/src/jquery.smooth-scroll.js @@ -145,6 +145,7 @@ $.fn.extend({ scrollTarget: thisOpts.scrollTarget || thisHash, link: link }); + $.smoothScroll( clickOpts ); } }); @@ -232,6 +233,7 @@ $.smoothScroll = function(options, px) { $.smoothScroll.version = version; $.smoothScroll.filterPath = function(string) { + string = string || ''; return string .replace(/^\//,'') .replace(/(?:index|default).[a-zA-Z]{3,4}$/,'')
Avoid "Cannot call method 'replace' of undefined" error
kswedberg_jquery-smooth-scroll
train
4de2194fe33c82fa43d19d1e80c0487940a3a85f
diff --git a/test-support/page-object/queries/text.js b/test-support/page-object/queries/text.js index <HASH>..<HASH> 100644 --- a/test-support/page-object/queries/text.js +++ b/test-support/page-object/queries/text.js @@ -51,6 +51,22 @@ import { findElementWithAssert, map, normalizeText } from '../helpers'; * // returns 'ipsum' * assert.equal(page.text, 'ipsum'); * + * @example + * + * // <div><span>lorem</span></div> + * // <div class="scope"> + * // ipsum + * // </div> + * // <div><span>dolor</span></div> + * + * const page = PageObject.create({ + * scope: '.scope', + * text: PageObject.text('span', { normalize: false }) + * }); + * + * // returns 'ipsum' + * assert.equal(page.text, '\n ipsum\n'); + * * @public * * @param {string} selector - CSS selector of the element to check @@ -59,6 +75,7 @@ import { findElementWithAssert, map, normalizeText } from '../helpers'; * @param {number} options.at - Reduce the set of matched elements to the one at the specified index * @param {boolean} options.resetScope - Override parent's scope * @param {boolean} options.multiple - Return an array of values + * @param {boolean} options.normalize - Set to `false` to avoid text normalization * @return {Descriptor} * * @throws Will throw an error if no element matches selector @@ -70,9 +87,8 @@ export function text(selector, options = {}) { get() { const elements = findElementWithAssert(this, selector, options); - const result = map(elements, function(element) { - return normalizeText(element.text()); - }); + const avoidNormalization = options.normalize === false; + const result = map(elements, (element) => avoidNormalization ? element.text() : normalizeText(element.text())); return options.multiple ? result : result[0]; } diff --git a/tests/unit/queries/text-test.js b/tests/unit/queries/text-test.js index <HASH>..<HASH> 100644 --- a/tests/unit/queries/text-test.js +++ b/tests/unit/queries/text-test.js @@ -37,6 +37,17 @@ test('normalizes inner text of the element containing newlines', function(assert assert.equal(page.foo, 'Hello multi-line world!'); }); +test('avoid text normalization if normalize:false', function(assert) { + const denormalizedText = [' \n ', 'Hello', 'multi-line', 'world! ', '\t', '\n'].join('\n'); + fixture(`<span>${denormalizedText}</span>`); + + let page = create({ + foo: text('span', { normalize: false }) + }); + + assert.equal(page.foo, denormalizedText); +}); + test('converts &nbsp; characters into standard whitespace characters', function(assert) { fixture('<span>This&nbsp;is&nbsp;awesome.</span>');
Add option to avoid text normalization Use arrow functions Add comments
san650_ember-cli-page-object
train
0c6676d4360e33033cc19d6c8c69fdf07187693e
diff --git a/assess_add_cloud.py b/assess_add_cloud.py index <HASH>..<HASH> 100755 --- a/assess_add_cloud.py +++ b/assess_add_cloud.py @@ -103,14 +103,23 @@ def iter_clouds(clouds): yield cloud_spec('bogus-type', 'bogus-type', {'type': 'bogus'}, exception=TypeNotAccepted) for cloud_name, cloud in clouds.items(): - yield cloud_spec(cloud_name, cloud_name, cloud) + spec = cloud_spec(cloud_name, cloud_name, cloud) + if cloud['type'] == 'manual': + spec = xfail(spec, 1649721, InvalidEndpoint) + yield spec for cloud_name, cloud in clouds.items(): - yield xfail(cloud_spec('long-name-{}'.format(cloud_name), 'A' * 4096, - cloud, NameNotAccepted), 1641970, NameMismatch) - yield xfail( + spec = xfail(cloud_spec('long-name-{}'.format(cloud_name), 'A' * 4096, + cloud, NameNotAccepted), 1641970, NameMismatch) + if cloud['type'] == 'manual': + spec = xfail(spec, 1649721, InvalidEndpoint) + yield spec + spec = xfail( cloud_spec('invalid-name-{}'.format(cloud_name), 'invalid/name', cloud, NameNotAccepted), 1641981, None) + if cloud['type'] == 'manual': + spec = xfail(spec, 1649721, InvalidEndpoint) + yield spec if cloud['type'] not in ('maas', 'manual', 'vsphere'): variant = deepcopy(cloud) diff --git a/deploy_stack.py b/deploy_stack.py index <HASH>..<HASH> 100644 --- a/deploy_stack.py +++ b/deploy_stack.py @@ -1072,8 +1072,8 @@ def _deploy_job(args, charm_series, series): deploy_dummy_stack(client, charm_series, args.use_charmstore) assess_juju_relations(client) skip_juju_run = ( - (client.version < "2" and sys.platform in ("win32", "darwin")) - or charm_series.startswith(("centos", "win"))) + (client.version < "2" and sys.platform in ("win32", "darwin")) or + charm_series.startswith(("centos", "win"))) if not skip_juju_run: assess_juju_run(client) if args.upgrade: diff --git a/tests/test_assess_add_cloud.py b/tests/test_assess_add_cloud.py index <HASH>..<HASH> 100644 --- a/tests/test_assess_add_cloud.py +++ b/tests/test_assess_add_cloud.py @@ -118,13 +118,13 @@ class TestIterClouds(FakeHomeTestCase): cloud = {'type': 'manual', 'endpoint': 'http://example.com'} spec = cloud_spec('foo', 'foo', cloud) self.assertItemsEqual([ - self.bogus_type, spec, - xfail(cloud_spec('long-name-foo', 'A' * 4096, cloud), 1641970, - NameMismatch), - xfail(cloud_spec('invalid-name-foo', 'invalid/name', cloud, - exception=NameNotAccepted), 1641981, None), - make_long_endpoint(spec), - ], iter_clouds({'foo': cloud})) + self.bogus_type, xfail(spec, 1649721, InvalidEndpoint), + xfail(xfail(cloud_spec('long-name-foo', 'A' * 4096, cloud), + 1641970, NameMismatch), 1649721, InvalidEndpoint), + xfail(xfail(cloud_spec('invalid-name-foo', 'invalid/name', cloud, + exception=NameNotAccepted), 1641981, None), + 1649721, InvalidEndpoint), + make_long_endpoint(spec)], iter_clouds({'foo': cloud})) def test_vsphere(self): cloud = { diff --git a/tests/test_remote.py b/tests/test_remote.py index <HASH>..<HASH> 100644 --- a/tests/test_remote.py +++ b/tests/test_remote.py @@ -151,7 +151,7 @@ class TestRemote(tests.FakeHomeTestCase): with patch.object(client, "get_juju_output") as mock_gjo: mock_gjo.side_effect = error with self.assertRaises(subprocess.CalledProcessError) as c: - output = remote.run("cat /a/file") + remote.run("cat /a/file") self.assertIs(c.exception, error) mock_gjo.assert_called_once_with("ssh", unit, "cat /a/file", timeout=120) @@ -172,7 +172,7 @@ class TestRemote(tests.FakeHomeTestCase): with patch("remote._no_platform_ssh", autospec=True, return_value=True) as mock_nps: with self.assertRaises(subprocess.CalledProcessError) as c: - output = remote.run("cat /a/file") + remote.run("cat /a/file") self.assertIs(c.exception, error) mock_gjo.assert_called_once_with("ssh", unit, "cat /a/file", timeout=120)
Update with expected endpoint failures for manual.
juju_juju
train
8411535bc4e01a4451ac0d1205670a93c9a63b1e
diff --git a/Swat/SwatXMLRPCServer.php b/Swat/SwatXMLRPCServer.php index <HASH>..<HASH> 100644 --- a/Swat/SwatXMLRPCServer.php +++ b/Swat/SwatXMLRPCServer.php @@ -6,6 +6,12 @@ require_once 'XML/RPC2/Server.php'; /** * Base class for an XML-RPC Server * + * The XML-RPC server acts as a regular page in an application . This means + * all the regular page security features work for XML-RPC servers. + * + * Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service + * requests. + * * @package Swat * @copyright 2005 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 @@ -13,6 +19,8 @@ require_once 'XML/RPC2/Server.php'; abstract class SwatXMLRPCServer extends SwatPage { /** + * Creates a new XML-RPC server + * * @xmlrpc.hidden */ public function __construct() @@ -21,9 +29,11 @@ abstract class SwatXMLRPCServer extends SwatPage } /** - * Display the page + * Displays this page * - * This method is called by the layout to output the XML-RPC response. + * This method is called by the application's layout and creates an + * XML-RPC server and handles a request. The XML-RPC response from the + * server is output here as well. * * @xmlrpc.hidden */
More documentation. svn commit r<I>
silverorange_swat
train
c7c7268f34c08d9dfe7c085eca5f8a8b57736eab
diff --git a/IfcPlugins/src/org/bimserver/ifc/step/deserializer/IfcStepStreamingDeserializer.java b/IfcPlugins/src/org/bimserver/ifc/step/deserializer/IfcStepStreamingDeserializer.java index <HASH>..<HASH> 100644 --- a/IfcPlugins/src/org/bimserver/ifc/step/deserializer/IfcStepStreamingDeserializer.java +++ b/IfcPlugins/src/org/bimserver/ifc/step/deserializer/IfcStepStreamingDeserializer.java @@ -30,6 +30,7 @@ import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.TreeMap; +import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -97,7 +98,10 @@ public abstract class IfcStepStreamingDeserializer implements StreamingDeseriali private QueryContext reusable; private IfcHeader ifcHeader; - private static MetricCollector metricCollector = new MetricCollector(); + private static MetricCollector metricCollector = new MetricCollector(); + + // This is enabled for now so we can test more models, not decided yet whether this will be enabled in the final release + private static final boolean CONVERT_INVALID_IFC_GUIDS = true; // Use String instead of EClass, compare takes 1.7% private final Map<String, AtomicInteger> summaryMap = new TreeMap<>(); @@ -400,13 +404,10 @@ public abstract class IfcStepStreamingDeserializer implements StreamingDeseriali } else { if (!eStructuralFeature.isMany()) { Object converted = convert(eStructuralFeature, eStructuralFeature.getEType(), val); - object.setAttribute(eStructuralFeature, converted); if (eStructuralFeature.getName().equals("GlobalId")) { - try { - GuidCompressor.getGuidFromCompressedString(converted.toString(), new Guid()); - } catch (InvalidGuidException e) { - throw new DeserializeException("Invalid GUID: \"" + converted.toString() + "\": " + e.getMessage()); - } + processGuid(object, eStructuralFeature, converted); + } else { + object.setAttribute(eStructuralFeature, converted); } if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE.getEDouble()) { EStructuralFeature doubleStringFeature = eClass.getEStructuralFeature(eStructuralFeature.getName() + "AsString"); @@ -444,6 +445,31 @@ public abstract class IfcStepStreamingDeserializer implements StreamingDeseriali metricCollector.collect(line.length(), nrBytes); } } + } + + private void processGuid(VirtualObject object, EStructuralFeature eStructuralFeature, Object converted) throws BimserverDatabaseException, DeserializeException { + try { + GuidCompressor.getGuidFromCompressedString(converted.toString(), new Guid()); + object.setAttribute(eStructuralFeature, converted); + // If it's valid, we do nothing, we just store it as it was + } catch (InvalidGuidException e) { + if (CONVERT_INVALID_IFC_GUIDS) { + // The GUID is invalid according to the IFC spec, sometimes another representation is used in IFC files, which is a valid GUID, but not according to the IFC spec + // The next bit of code tries this variant, it remains to be decided what will be the final implementation for this in deserializer + try { + UUID uuid = UUID.fromString(converted.toString()); + String ifcGuid = GuidCompressor.compressGuidString(uuid.toString()); + LOGGER.warn("Invalid GUID on line " + lineNumber + " , converted from default UUID format (" + uuid.toString() + ") to IFC format (" + ifcGuid + ")"); + // If this succeeds, we convert the UUID to the IFC format, and store that, so this "changes" the model + object.setAttribute(eStructuralFeature, ifcGuid); + } catch (Exception e2) { + // We use the original exception's message, since that is most accurate + throw new DeserializeException("Invalid GUID: \"" + converted.toString() + "\": " + e.getMessage()); + } + } else { + throw new DeserializeException("Invalid GUID: \"" + converted.toString() + "\": " + e.getMessage()); + } + } } private DatabaseInterface getDatabaseInterface() {
Added experimental GUID conversion for GUIDs not defined according to IFC standard (but still valid UUID)
opensourceBIM_IfcPlugins
train
0ae3b0690077088e625824cf94305c26ce5aafb2
diff --git a/addok/helpers/search.py b/addok/helpers/search.py index <HASH>..<HASH> 100644 --- a/addok/helpers/search.py +++ b/addok/helpers/search.py @@ -1,10 +1,10 @@ from math import ceil +from addok.config import config from addok.helpers import iter_pipe def preprocess_query(s): - from addok.config import config return list(iter_pipe(s, config.QUERY_PROCESSORS + config.PROCESSORS))
No need to load the config at runtime now
addok_addok
train
c4a98145a020df4ff00f0dcc728effdb3626da92
diff --git a/docroot/modules/custom/ymca_blog_listing/src/Controller/YMCANewsEventsPageController.php b/docroot/modules/custom/ymca_blog_listing/src/Controller/YMCANewsEventsPageController.php index <HASH>..<HASH> 100644 --- a/docroot/modules/custom/ymca_blog_listing/src/Controller/YMCANewsEventsPageController.php +++ b/docroot/modules/custom/ymca_blog_listing/src/Controller/YMCANewsEventsPageController.php @@ -45,7 +45,8 @@ class YMCANewsEventsPageController extends ControllerBase { $node_storage = \Drupal::entityManager()->getStorage('node'); $nodes = $node_storage->loadMultiple($nids); foreach ($nodes as $node) { - $output['#markup'] .= render(node_view($node, 'location_blog_teaser')); + $node_view = node_view($node, 'location_blog_teaser'); + $output['#markup'] .= render($node_view); } } break;
[YMCA-<I>] replace blog listing with new logic
ymcatwincities_openy
train
bc2a57b8a3a5efd69eb26f833a61ab0ba317621a
diff --git a/app/models/manager_refresh/inventory/persister.rb b/app/models/manager_refresh/inventory/persister.rb index <HASH>..<HASH> 100644 --- a/app/models/manager_refresh/inventory/persister.rb +++ b/app/models/manager_refresh/inventory/persister.rb @@ -24,6 +24,25 @@ class ManagerRefresh::Inventory::Persister collections.keys end + def method_missing(method_name, *arguments, &block) + if inventory_collections_names.include?(method_name) + self.class.define_collections_reader(method_name) + send(method_name) + else + super + end + end + + def respond_to_missing?(method_name, _include_private = false) + inventory_collections_names.include?(method_name) || super + end + + def self.define_collections_reader(collection_key) + define_method(collection_key) do + collections.try(:[], collection_key) + end + end + protected def initialize_inventory_collections @@ -34,7 +53,7 @@ class ManagerRefresh::Inventory::Persister # # @param inventory_collection_data [Hash] Hash used for ManagerRefresh::InventoryCollection initialize def add_inventory_collection(inventory_collection_data) - data = inventory_collection_data + data = inventory_collection_data data[:parent] ||= manager if !data.key?(:delete_method) && data[:model_class]
Dynamic access of collections with Rails like method cache Dynamic access of collections with Rails like method cache, first pass goes through methods missing and looks into collections hash by creating a getter metho. So second+ pass is much faster. (transferred from ManageIQ/manageiq@c<I>f2d0b2ec<I>fa<I>cd<I>c6ca6a<I>aa4)
ManageIQ_inventory_refresh
train
c0d843ceb39be5025e95ec064ef0b35c405f97a9
diff --git a/spec/mail/network/retriever_methods/pop3_spec.rb b/spec/mail/network/retriever_methods/pop3_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mail/network/retriever_methods/pop3_spec.rb +++ b/spec/mail/network/retriever_methods/pop3_spec.rb @@ -77,6 +77,21 @@ describe "POP3 Retriever" do messages.size.should == 10 end + + it "should handle the delete_after_find option" do + Mail.find(:delete_after_find => false) + MockPOP3.popmails.each { |message| message.should_not be_deleted } + + Mail.find(:delete_after_find => true) + MockPOP3.popmails.first(10).each { |message| message.should be_deleted } + MockPOP3.popmails.last(10).each { |message| message.should_not be_deleted } + end + + it "should handle the find_and_delete method" do + Mail.find_and_delete(:count => 15) + MockPOP3.popmails.first(15).each { |message| message.should be_deleted } + MockPOP3.popmails.last(5).each { |message| message.should_not be_deleted } + end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -90,6 +90,7 @@ class MockPopMail def initialize(rfc2822, number) @rfc2822 = rfc2822 @number = number + @deleted = false end def pop @@ -103,6 +104,14 @@ class MockPopMail def to_s "#{number}: #{pop}" end + + def delete + @deleted = true + end + + def deleted? + @deleted + end end class MockPOP3 @@ -119,7 +128,7 @@ class MockPOP3 def self.popmails @@popmails.clone end - + def each_mail(*args) @@popmails.each do |popmail| yield popmail
Add specs for :delete_after_find option to the find method and the find_and_delete method itself
mikel_mail
train
e291587027b16ffd7fb0e5bdd6bf203e8ed2620f
diff --git a/doc/man_docs.go b/doc/man_docs.go index <HASH>..<HASH> 100644 --- a/doc/man_docs.go +++ b/doc/man_docs.go @@ -34,6 +34,17 @@ import ( // subcmds, `sub` and `sub-third`. And `sub` has a subcommand called `third` // it is undefined which help output will be in the file `cmd-sub-third.1`. func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error { + return GenManTreeFromOpts(cmd, GenManTreeOptions{ + Header: header, + Path: dir, + CommandSeparator: "_", + }) +} + +// GenManTreeFromOpts generates a man page for the command and all descendants. +// The pages are written to the opts.Path directory. +func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error { + header := opts.Header if header == nil { header = &GenManHeader{} } @@ -41,7 +52,7 @@ func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error { if !c.IsAvailableCommand() || c.IsHelpCommand() { continue } - if err := GenManTree(c, header, dir); err != nil { + if err := GenManTreeFromOpts(c, opts); err != nil { return err } } @@ -50,8 +61,12 @@ func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error { section = header.Section } - basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + "." + section - filename := filepath.Join(dir, basename) + separator := "_" + if opts.CommandSeparator != "" { + separator = opts.CommandSeparator + } + basename := strings.Replace(cmd.CommandPath(), " ", separator, -1) + filename := filepath.Join(opts.Path, basename + "." + section) f, err := os.Create(filename) if err != nil { return err @@ -62,6 +77,12 @@ func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error { return GenMan(cmd, &headerCopy, f) } +type GenManTreeOptions struct { + Header *GenManHeader + Path string + CommandSeparator string +} + // GenManHeader is a lot like the .TH header at the start of man pages. These // include the title, section, date, source, and manual. We will use the // current time if Date if unset and will use "Auto generated by spf13/cobra" @@ -167,10 +188,8 @@ func manPrintOptions(out io.Writer, command *cobra.Command) { } func genMan(cmd *cobra.Command, header *GenManHeader) []byte { - // something like `rootcmd subcmd1 subcmd2` - commandName := cmd.CommandPath() // something like `rootcmd-subcmd1-subcmd2` - dashCommandName := strings.Replace(commandName, " ", "-", -1) + dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1) buf := new(bytes.Buffer)
Cretea a new GenManTree function that takes an options struct.
spf13_cobra
train
04bd1ea72c1334c204762cea66589f2647e803b3
diff --git a/code/libraries/koowa/components/com_koowa/template/helper/paginator.php b/code/libraries/koowa/components/com_koowa/template/helper/paginator.php index <HASH>..<HASH> 100644 --- a/code/libraries/koowa/components/com_koowa/template/helper/paginator.php +++ b/code/libraries/koowa/components/com_koowa/template/helper/paginator.php @@ -265,7 +265,7 @@ class ComKoowaTemplateHelperPaginator extends ComKoowaTemplateHelperSelect */ protected function _bootstrap_link($page, $title) { - $url = clone KRequest::url(); + $url = $this->getObject('request')->getUrl(); $query = $url->getQuery(true); //For compatibility with Joomla use limitstart instead of offset diff --git a/code/libraries/koowa/libraries/controller/behavior/editable.php b/code/libraries/koowa/libraries/controller/behavior/editable.php index <HASH>..<HASH> 100644 --- a/code/libraries/koowa/libraries/controller/behavior/editable.php +++ b/code/libraries/koowa/libraries/controller/behavior/editable.php @@ -40,7 +40,7 @@ class KControllerBehaviorEditable extends KControllerBehaviorAbstract $this->registerCallback('after.cancel', array($this, 'unlockResource')); //Set the default redirect. - $this->setRedirect(KRequest::referrer()); + $this->setRedirect($this->getRequest()->getReferrer()); $this->_cookie_path = $config->cookie_path; } @@ -90,7 +90,7 @@ class KControllerBehaviorEditable extends KControllerBehaviorAbstract */ public function getReferrer() { - $referrer = KRequest::get('cookie.referrer', 'url'); + $referrer = $this->getRequest()->cookies->get('referrer', 'url'); if ($referrer) { @@ -109,10 +109,10 @@ class KControllerBehaviorEditable extends KControllerBehaviorAbstract */ public function setReferrer() { - if(!KRequest::has('cookie.referrer_locked')) + if(!$this->getRequest()->cookies->has('referrer_locked')) { - $request = KRequest::url(); - $referrer = KRequest::referrer(); + $request = $this->getRequest()->getUrl(); + $referrer = $this->getRequest()->getReferrer(); //Compare request url and referrer if(!isset($referrer) || ((string) $referrer == (string) $request)) @@ -219,7 +219,7 @@ class KControllerBehaviorEditable extends KControllerBehaviorAbstract if ($data instanceof KDatabaseRowInterface) { - $url = clone KRequest::url(); + $url = clone $this->getRequest()->getUrl(); if($this->getModel()->getState()->isUnique()) { diff --git a/code/libraries/koowa/libraries/view/file.php b/code/libraries/koowa/libraries/view/file.php index <HASH>..<HASH> 100644 --- a/code/libraries/koowa/libraries/view/file.php +++ b/code/libraries/koowa/libraries/view/file.php @@ -360,10 +360,8 @@ class KViewFile extends KViewAbstract // Prevent caching // Pragma and cache-control needs to be empty for IE on SSL. // See: http://support.microsoft.com/default.aspx?scid=KB;EN-US;q316431 - ; - if (preg_match('#(?:MSIE |Internet Explorer/)(?:[0-9.]+)#', $this->getObject('request')->getAgent()) - && (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') - ) { + $request = $this->getObject('request'); + if ($request->isSecure() && preg_match('#(?:MSIE |Internet Explorer/)(?:[0-9.]+)#', $request->getAgent())) { header('Pragma: '); header('Cache-Control: '); }
re #<I>: Continue taking out KRequest
timble_kodekit
train
c31fec783cb9f19904fe7d0b53a0e5637f2acb8b
diff --git a/OnBoarding/OnBoarding.php b/OnBoarding/OnBoarding.php index <HASH>..<HASH> 100644 --- a/OnBoarding/OnBoarding.php +++ b/OnBoarding/OnBoarding.php @@ -28,6 +28,9 @@ namespace OnBoarding; use Shudrum\Component\ArrayFinder\ArrayFinder; use Symfony\Component\Yaml\Yaml; +use Configuration; +use Twig_Environment; + /** * OnBoarding main class. @@ -35,14 +38,9 @@ use Symfony\Component\Yaml\Yaml; class OnBoarding { /** - * @var \Twig_Loader_Filesystem + * @var Twig_Environment */ - private $loader; - - /** - * @var \Twig_Environment - */ - private $twig; + private $twigEnvironment; /** * @var ArrayFinder @@ -62,16 +60,20 @@ class OnBoarding /** * OnBoarding constructor. * - * @param string $languageIsoCode Language ISO code + * @param Twig_Environment $twigEnvironment Twig environment needed to manage the templates + * @param string $configurationFolder Configuration folder + * @param string $languageIsoCode Language ISO code */ - public function __construct($languageIsoCode = 'en') - { - $this->loader = new \Twig_Loader_Filesystem(realpath(__DIR__.'/../views')); // TODO: A injecter - $this->twig = new \Twig_Environment($this->loader); + public function __construct( + Twig_Environment $twigEnvironment, + $configurationFolder, + $languageIsoCode = 'en' + ) { + $this->twigEnvironment = $twigEnvironment; - $this->configuration = Yaml::parse(file_get_contents(__DIR__.'/../config/configuration.yml')); + $this->configuration = Yaml::parse(file_get_contents($configurationFolder.'/configuration.yml')); - $this->loadSteps(__DIR__.'/../config', $languageIsoCode); + $this->loadSteps($configurationFolder, $languageIsoCode); } /** @@ -117,8 +119,7 @@ class OnBoarding */ public function setCurrentStep($step) { - // TODO: Find how to inject the Configuration if not done - return \Configuration::updateValue('ONBOARDINGV2_CURRENT_STEP', $step); + return Configuration::updateValue('ONBOARDINGV2_CURRENT_STEP', $step); } /** @@ -130,8 +131,7 @@ class OnBoarding */ public function setShutDown($status) { - // TODO: Find how to inject the Configuration if not done - return \Configuration::updateValue('ONBOARDINGV2_SHUT_DOWN', $status); + return Configuration::updateValue('ONBOARDINGV2_SHUT_DOWN', $status); } /** @@ -207,7 +207,7 @@ class OnBoarding */ private function getTemplateContent($templateName, $additionnalParameters = array()) // TODO: Find a better name { - return $this->twig->render($templateName.'.twig', array_merge( + return $this->twigEnvironment->render($templateName.'.twig', array_merge( $additionnalParameters, $this->localization->get() )); @@ -220,8 +220,7 @@ class OnBoarding */ private function getCurrentStep() { - // TODO: Find how to inject the Configuration if not done - return (int)\Configuration::get('ONBOARDINGV2_CURRENT_STEP'); + return (int)Configuration::get('ONBOARDINGV2_CURRENT_STEP'); } /** @@ -245,11 +244,10 @@ class OnBoarding /** * Return the shut down status. * - * @return boot Shut down status + * @return bool Shut down status */ private function isShutDown() { - // TODO: Find how to inject the Configuration if not done - return (int)\Configuration::get('ONBOARDINGV2_SHUT_DOWN'); + return (int)Configuration::get('ONBOARDINGV2_SHUT_DOWN'); } } diff --git a/onboardingv2.php b/onboardingv2.php index <HASH>..<HASH> 100644 --- a/onboardingv2.php +++ b/onboardingv2.php @@ -30,6 +30,8 @@ if (!defined('_PS_VERSION_')) require_once __DIR__.'/vendor/autoload.php'; use \OnBoarding\OnBoarding; +use \Twig_Loader_Filesystem; +use \Twig_Environment; /** * OnBoarding module entry class. @@ -59,7 +61,11 @@ class Onboardingv2 extends Module 'max' => _PS_VERSION_, ]; - $this->onBoarding = new OnBoarding('en'); // TODO: Get the language of the shop + $twigEnvironment = new Twig_Environment( + new Twig_Loader_Filesystem(__DIR__.'/views') + ); + + $this->onBoarding = new OnBoarding($twigEnvironment, __DIR__.'/config', 'en'); // TODO: Get the language of the shop if (Tools::getIsset('resetonboarding')) { $this->onBoarding->setShutDown(false);
[*] Twig is now correctly injected And the configuration folder is also a parameter.
PrestaShop_welcome
train
55d1b7f4a87f1fd674bb3015d9d5868a77275418
diff --git a/chef/lib/chef/resource.rb b/chef/lib/chef/resource.rb index <HASH>..<HASH> 100644 --- a/chef/lib/chef/resource.rb +++ b/chef/lib/chef/resource.rb @@ -50,20 +50,22 @@ class Chef raise Chef::Exceptions::InvalidResourceReference, msg end self.resource = matching_resource - rescue Chef::Exceptions::ResourceNotFound - Chef::Log.fatal(<<-FAIL) -Resource #{notifying_resource} is configured to notify resource #{resource} with action #{action}, -but #{resource} cannot be found in the resource collection. #{notifying_resource} is defined in + rescue Chef::Exceptions::ResourceNotFound => e + err = Chef::Exceptions::ResourceNotFound.new(<<-FAIL) +Resource #{notifying_resource} is configured to notify resource #{resource} with action #{action}, \ +but #{resource} cannot be found in the resource collection. #{notifying_resource} is defined in \ #{notifying_resource.source_line} FAIL - raise - rescue Chef::Exceptions::InvalidResourceSpecification - Chef::Log.fatal(<<-F) -Resource #{notifying_resource} is configured to notify resource #{resource} with action #{action}, -but #{resource} is not valid syntax to look up a resource in the resource collection. Notification + err.set_backtrace(e.backtrace) + raise err + rescue Chef::Exceptions::InvalidResourceSpecification => e + err = Chef::Exceptions::InvalidResourceSpecification.new(<<-F) +Resource #{notifying_resource} is configured to notify resource #{resource} with action #{action}, \ +but #{resource.inspect} is not valid syntax to look up a resource in the resource collection. Notification \ is defined near #{notifying_resource.source_line} F - raise + err.set_backtrace(e.backtrace) + raise err end end
improve error message clarity for notify lazy references when an error is raised when resolving a lazy reference for a notification, rewrite it with an informative message and context
chef_chef
train
7147fd37cd0743210306aed10cfa74d98e3179fe
diff --git a/src/main/java/org/whitesource/agent/dependency/resolver/ruby/RubyDependencyResolver.java b/src/main/java/org/whitesource/agent/dependency/resolver/ruby/RubyDependencyResolver.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/whitesource/agent/dependency/resolver/ruby/RubyDependencyResolver.java +++ b/src/main/java/org/whitesource/agent/dependency/resolver/ruby/RubyDependencyResolver.java @@ -100,7 +100,7 @@ public class RubyDependencyResolver extends AbstractDependencyResolver { @Override public Collection<String> getManifestFiles(){ - return Arrays.asList(GEM_FILE_LOCK); + return Arrays.asList(GEM_FILE_LOCK, GEM_FILE, GEMS_RB, GEMS_LOCKED); } @Override
Add Ruby source files to manifests list
whitesource_fs-agent
train
21408212dafc1b37e2f2d51a4c4afbcc9cef403b
diff --git a/modules/caddyhttp/replacer.go b/modules/caddyhttp/replacer.go index <HASH>..<HASH> 100644 --- a/modules/caddyhttp/replacer.go +++ b/modules/caddyhttp/replacer.go @@ -105,7 +105,7 @@ func addHTTPVarsToReplacer(repl caddy.Replacer, req *http.Request, w http.Respon case "http.request.uri.query": return req.URL.RawQuery, true case "http.request.uri.query_string": - return "?" + req.URL.Query().Encode(), true + return "?" + req.URL.RawQuery, true // original request, before any internal changes case "http.request.orig_method": @@ -130,11 +130,7 @@ func addHTTPVarsToReplacer(repl caddy.Replacer, req *http.Request, w http.Respon return or.URL.RawQuery, true case "http.request.orig_uri.query_string": or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request) - qs := or.URL.Query().Encode() - if qs != "" { - qs = "?" + qs - } - return qs, true + return "?" + or.URL.RawQuery, true } // hostname labels
http: query and query_string placeholders should use RawQuery, probably
mholt_caddy
train
d832f0d15791fc951f55d30ce13c20d5dc9e89c3
diff --git a/lib/xpay/payment.rb b/lib/xpay/payment.rb index <HASH>..<HASH> 100644 --- a/lib/xpay/payment.rb +++ b/lib/xpay/payment.rb @@ -86,19 +86,19 @@ module Xpay pares = threedsecure.add_element("PaRes") pares.text = "" @response_xml = process() - rt = REXML::XPath.first(@response_xml, "//Result").text.to_i + rt = response_code end when 2 # TWO -> do a normal AUTH request rewrite_request_block("AUTH") # Rewrite the request block as AUTH request with information from the response, deleting unused items @response_xml = process() - rt = REXML::XPath.first(@response_xml, "//Result").text.to_i + rt = response_code else # ALL other cases, payment declined - rt = REXML::XPath.first(@response_xml, "//Result").text.to_i + rt = response_code end else - rt = REXML::XPath.first(@response_xml, "//Result").text.to_i + rt = response_code end - return rt + rt end # The response_block is a hash and can have one of several values: diff --git a/lib/xpay/transaction.rb b/lib/xpay/transaction.rb index <HASH>..<HASH> 100644 --- a/lib/xpay/transaction.rb +++ b/lib/xpay/transaction.rb @@ -16,7 +16,7 @@ module Xpay end def response_code - @response_code ||= REXML::XPath.first(@response_xml, "//Result").text.to_i rescue -1 + REXML::XPath.first(@response_xml, "//Result").text.to_i rescue nil end private
removed storing in instanve variable because value can change during process
vpacher_xpay
train