hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
8feb1d2caa430f9adc49da10d728b9c0c380a64b
diff --git a/lib/fabrication/generator/base.rb b/lib/fabrication/generator/base.rb index <HASH>..<HASH> 100644 --- a/lib/fabrication/generator/base.rb +++ b/lib/fabrication/generator/base.rb @@ -100,8 +100,6 @@ class Fabrication::Generator::Base _instance.save! if _instance.respond_to?(:save!) end - def post_initialize; end - def process_attributes(attributes) self._transient_attributes = Hash.new attributes.each do |attribute|
Remove unused Generator::Base#post_initialize method [fixes #<I>]
paulelliott_fabrication
train
9108e9965a4e9e2dfccb27ce4c5fc476a5be21bd
diff --git a/collector-http.go b/collector-http.go index <HASH>..<HASH> 100644 --- a/collector-http.go +++ b/collector-http.go @@ -180,7 +180,7 @@ func (c *HTTPCollector) append(span *zipkincore.Span) (newBatchSize int) { c.batch = append(c.batch, span) if len(c.batch) > c.maxBacklog { dispose := len(c.batch) - c.maxBacklog - c.logger.Log("Backlog too long, disposing spans.", "count", dispose) + c.logger.Log("msg", "backlog too long, disposing spans.", "count", dispose) c.batch = c.batch[dispose:] } newBatchSize = len(c.batch) diff --git a/logger.go b/logger.go index <HASH>..<HASH> 100644 --- a/logger.go +++ b/logger.go @@ -11,8 +11,9 @@ import ( // not even in number var ErrMissingValue = errors.New("(MISSING)") -// Logger interface used by this package. -// This means that we accept Go kit Log compatible loggers +// Logger is the fundamental interface for all log operations. Log creates a +// log event from keyvals, a variadic sequence of alternating keys and values. +// The signature is compatible with the Go kit log package. type Logger interface { Log(keyvals ...interface{}) error }
fixed minor issue in log message. closes #<I>
openzipkin-contrib_zipkin-go-opentracing
train
cc99531d4cc6eb153812ea71f95d90e5546099b1
diff --git a/test/wpa_supplicant.js b/test/wpa_supplicant.js index <HASH>..<HASH> 100644 --- a/test/wpa_supplicant.js +++ b/test/wpa_supplicant.js @@ -29,7 +29,7 @@ describe('wpa_supplicant', function() { it('should stop the daemons', function(done) { wpa_supplicant.exec = function(command, callback) { should(command).eql( - 'kill `pgrep -f "^wpa_supplicant -i wlan0"` || true'); + 'kill `pgrep -f "wpa_supplicant .* -i wlan0"` || true'); callback(null, '', ''); }; @@ -94,4 +94,43 @@ describe('wpa_supplicant', function() { }); }) }) + + describe('wpa_supplicant.manual(options, callback)', function() { + it('should start the daemon', function(done) { + wpa_supplicant.exec = function(command, callback) { + should(command).eql([ + 'wpa_supplicant -s -B -P /run/wpa_supplicant/wlan0.pid', + '-i wlan0 -D nl80211,wext -C /run/wpa_supplicant' + ].join(' ')); + + callback(null, '', ''); + }; + + var options = { + interface: 'wlan0', + drivers: [ 'nl80211', 'wext' ] + }; + + wpa_supplicant.manual(options, function(err) { + should(err).not.be.ok; + done(); + }); + }) + + it('should handle errors', function(done) { + wpa_supplicant.exec = function(command, callback) { + callback('error'); + }; + + var options = { + interface: 'wlan0', + drivers: [ 'nl80211', 'wext' ] + }; + + wpa_supplicant.manual(options, function(err) { + should(err).eql('error'); + done(); + }); + }) + }) }) diff --git a/wpa_supplicant.js b/wpa_supplicant.js index <HASH>..<HASH> 100644 --- a/wpa_supplicant.js +++ b/wpa_supplicant.js @@ -34,7 +34,8 @@ var child_process = require('child_process'); var wpa_supplicant = module.exports = { exec: child_process.exec, disable: disable, - enable: enable + enable: enable, + manual: manual }; /** @@ -51,13 +52,13 @@ var wpa_supplicant = module.exports = { * var wpa_supplicant = require('wireless-tools/wpa_supplicant'); * * wpa_supplicant.disable('wlan0', function(err) { - * // disconnected from wireless network + * // disconnected from wireless network * }); * */ function disable(interface, callback) { - var command = 'kill `pgrep -f "^wpa_supplicant -i ' - + interface + '"` || true'; + var command = 'kill `pgrep -f "wpa_supplicant .* -i ' + + interface + '"` || true'; return this.exec(command, callback); } @@ -83,7 +84,7 @@ function disable(interface, callback) { * }; * * wpa_supplicant.enable(options, function(err) { - * // connected to the wireless network + * // connected to the wireless network * }); * */ @@ -94,5 +95,29 @@ function enable(options, callback) { + '" > ' + file + ' && wpa_supplicant -i ' + options.interface + ' -B -D ' + options.driver + ' -c ' + file + ' && rm -f ' + file; - return this.exec(command, callback); + return this.exec(command, callback); } + +/** + * launchs wpa manually (as if it were launched by ifup if interface wpa setup was done in /network/interfaces) + * /sbin/wpa_supplicant -s -B -P /run/wpa_supplicant.wlan0.pid -i wlan0 -D nl80211,wext -C /run/wpa_supplicant + * options = { + * interface: 'wlan0', + * drivers: [ 'nl80211', 'wext' ] + * } + */ +function manual(options, callback) { + var command = [ + 'wpa_supplicant -s -B -P', + [ '/run/wpa_supplicant/', options.interface, '.pid'].join(''), + '-i', + options.interface, + '-D', + options.drivers.join(), + '-C /run/wpa_supplicant' + ].join(' '); + + return this.exec(command, callback); +} + +
Kill any wpa_suplicant for this device This way will be able to kill wpa supplicants launched by other processes ifup / ifdown. Adding manual wpa_supplicant Launched in such way I can use wpa_cli to connect to wpasupplicant and send commands
bakerface_wireless-tools
train
16873b99f474dfd9d5b0970f9d5cc13411308991
diff --git a/lib/moo/model/box_data.rb b/lib/moo/model/box_data.rb index <HASH>..<HASH> 100644 --- a/lib/moo/model/box_data.rb +++ b/lib/moo/model/box_data.rb @@ -1,3 +1,4 @@ +require 'json' module Moo module Model class BoxData < Data @@ -9,6 +10,14 @@ module Moo end @colour = value end + + def to_json + { + :linkId => link_id, + :type => 'boxData', + :colour => colour.to_hash + }.to_json + end end end end diff --git a/lib/moo/model/colour.rb b/lib/moo/model/colour.rb index <HASH>..<HASH> 100644 --- a/lib/moo/model/colour.rb +++ b/lib/moo/model/colour.rb @@ -48,21 +48,25 @@ module Moo end def to_json + self.to_hash.to_json + end + + def to_hash if @type == 'RGB' - { + return { :type => 'RGB', :r => @r, :g => @g, :b => @b - }.to_json + } elsif @type == 'CMYK' - { + return { :type => 'CMYK', :c => @c, :m => @m, :y => @y, :k => @k - }.to_json + } end end diff --git a/spec/model/box_data_spec.rb b/spec/model/box_data_spec.rb index <HASH>..<HASH> 100644 --- a/spec/model/box_data_spec.rb +++ b/spec/model/box_data_spec.rb @@ -35,4 +35,31 @@ describe Moo::Model::BoxData do expect { d.colour = 'woof woof' }.should raise_error ArgumentError end end + + describe 'to_json' do + it 'should reflect the values set on the boxdata object' do + c= Colour.new + c.type = 'rgb' + c.r = 100 + c.g = 150 + c.b = 200 + + bd = BoxData.new + bd.link_id = 'woof_woof' + bd.colour = c + + expected_json = { + :linkId => 'woof_woof', + :type => 'boxData', + :colour => { + :type => 'RGB', + :r => 100, + :g => 150, + :b => 200 + } + }.to_json + + bd.to_json.should == expected_json + end + end end
added BoxData.to_json
Najaf_moo.rb
train
1c1edfcf7df3e4d89e0cc6de202c878139937887
diff --git a/lib/AbstractView.php b/lib/AbstractView.php index <HASH>..<HASH> 100644 --- a/lib/AbstractView.php +++ b/lib/AbstractView.php @@ -301,6 +301,9 @@ abstract class AbstractView extends AbstractObject } $cutting_here=false; + $cutting_output=''; + + $this->initTemplateTags(); if (isset($_GET['cut_object']) @@ -310,6 +313,11 @@ abstract class AbstractView extends AbstractObject // If we are cutting here, render childs and then we are done unset($_GET['cut_object']); $cutting_here=true; + + $this->addHook('output',function($self,$output)use(&$cutting_output) { + $cutting_output.=$output; + }); + } foreach ($this->elements as $key => $obj) { @@ -328,11 +336,11 @@ abstract class AbstractView extends AbstractObject } if ($cutting_here) { - $result=$this->owner->template->cloneRegion($this->spot)->render(); + //$result=$this->owner->template->cloneRegion($this->spot)->render(); if ($this->api->jquery) { $this->api->jquery->getJS($this); } - throw new Exception_StopRender($result); + throw new Exception_StopRender($cutting_output); } // if template wasn't cut, we move all JS chains to parent @@ -410,6 +418,8 @@ abstract class AbstractView extends AbstractObject */ function region_render() { + throw $this->exception('cut_region is now obsolete'); + if ($this->template_flush) { if ($this->api->jquery) { $this->api->jquery->getJS($this);
obsoleted cut_region, changed how cut_* is gathering output Possibly incompatibilty with PHP <I>, is that bothering anyone?
atk4_atk4
train
52d0d99a27c1afc70e290e74549db7ce72db603d
diff --git a/api/app.go b/api/app.go index <HASH>..<HASH> 100644 --- a/api/app.go +++ b/api/app.go @@ -42,8 +42,18 @@ func getApp(name string, u *auth.User) (app.App, error) { func deploy(w http.ResponseWriter, r *http.Request, t auth.Token) error { version := r.PostFormValue("version") - if version == "" { - return &errors.HTTP{Code: http.StatusBadRequest, Message: "Missing parameter version"} + archiveURL := r.PostFormValue("archive-url") + if version == "" && archiveURL == "" { + return &errors.HTTP{ + Code: http.StatusBadRequest, + Message: "you must specify either the version or the archive-url", + } + } + if version != "" && archiveURL != "" { + return &errors.HTTP{ + Code: http.StatusBadRequest, + Message: "you must specify either the version or the archive-url, but not both", + } } commit := r.PostFormValue("commit") w.Header().Set("Content-Type", "text") diff --git a/api/app_test.go b/api/app_test.go index <HASH>..<HASH> 100644 --- a/api/app_test.go +++ b/api/app_test.go @@ -169,7 +169,7 @@ func (s *S) TestCloneRepositoryShouldReturnNotFoundWhenAppDoesNotExist(c *gochec c.Assert(e, gocheck.ErrorMatches, "^App abc not found.$") } -func (s *S) TestCloneRepositoryWithoutVersion(c *gocheck.C) { +func (s *S) TestCloneRepositoryWithoutVersionAndArchiveURL(c *gocheck.C) { request, err := http.NewRequest("POST", "/apps/abc/repository/clone?:appname=abc", nil) c.Assert(err, gocheck.IsNil) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") @@ -179,7 +179,21 @@ func (s *S) TestCloneRepositoryWithoutVersion(c *gocheck.C) { e, ok := err.(*errors.HTTP) c.Assert(ok, gocheck.Equals, true) c.Assert(e.Code, gocheck.Equals, http.StatusBadRequest) - c.Assert(e.Message, gocheck.Equals, "Missing parameter version") + c.Assert(e.Message, gocheck.Equals, "you must specify either the version or the archive-url") +} + +func (s *S) TestCloneRepositoryWithVersionAndArchiveURL(c *gocheck.C) { + body := strings.NewReader("version=abcdef&archive-url=http://google.com") + request, err := http.NewRequest("POST", "/apps/abc/repository/clone?:appname=abc", body) + c.Assert(err, gocheck.IsNil) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + recorder := httptest.NewRecorder() + err = deploy(recorder, request, s.token) + c.Assert(err, gocheck.NotNil) + e, ok := err.(*errors.HTTP) + c.Assert(ok, gocheck.Equals, true) + c.Assert(e.Code, gocheck.Equals, http.StatusBadRequest) + c.Assert(e.Message, gocheck.Equals, "you must specify either the version or the archive-url, but not both") } func (s *S) TestAppList(c *gocheck.C) {
api: support version and archive-url parameters in the deploy handler It doesn't do anything yet. Related to #<I>.
tsuru_tsuru
train
eaa4c36aff234a3b9d247e189a04538162b5c1ad
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,8 @@ This is a changelog for Piwik platform developers. All changes for our HTTP API' * We fixed a bug where the API method `Sites.getPatternMatchSites` only returned a very limited number of websites by default. We now return all websites by default unless a limit is specified specifically. ### Deprecations -* The API method `SitesManager.getSitesIdWithVisits` has been deprecated and will be removed in Piwik 3.0 +* The HTTP API method `SitesManager.getSitesIdWithVisits` has been deprecated and will be removed in Piwik 3.0 +* The HTTP API method `API.getLastDate` has been deprecated and will be removed in Piwik 3.0 * The API method `\Piwik\Plugin::getListHooksRegistered()` has been deprecated and will be removed in Piwik 3.0. Use `\Piwik\Plugin::registerEvents()` instead. * The following events have been deprecated and will be removed in Piwik 3.0. Use [dimensions](http://developer.piwik.org/guides/dimensions) instead. * `Tracker.existingVisitInformation` diff --git a/plugins/API/API.php b/plugins/API/API.php index <HASH>..<HASH> 100644 --- a/plugins/API/API.php +++ b/plugins/API/API.php @@ -413,6 +413,9 @@ class API extends \Piwik\Plugin\API $language, $idGoal, $legendAppendMetric, $labelUseAbsoluteUrl); } + /** + * @deprecated + */ public function getLastDate($date, $period) { $lastDate = Range::getLastDate($date, $period); diff --git a/tests/PHPUnit/Unit/DeprecatedMethodsTest.php b/tests/PHPUnit/Unit/DeprecatedMethodsTest.php index <HASH>..<HASH> 100644 --- a/tests/PHPUnit/Unit/DeprecatedMethodsTest.php +++ b/tests/PHPUnit/Unit/DeprecatedMethodsTest.php @@ -16,6 +16,7 @@ use Piwik\Version; use ReflectionClass; /** + * @group DeprecatedMethodsTest * @group Core */ class DeprecatedMethodsTest extends \PHPUnit_Framework_TestCase @@ -70,6 +71,7 @@ class DeprecatedMethodsTest extends \PHPUnit_Framework_TestCase $this->assertDeprecatedMethodIsRemovedInPiwik3('\Piwik\Menu\MenuAbstract', 'add'); $this->assertDeprecatedMethodIsRemovedInPiwik3('\Piwik\Archive', 'getDataTableFromArchive'); $this->assertDeprecatedMethodIsRemovedInPiwik3('\Piwik\Plugin', 'getListHooksRegistered'); + $this->assertDeprecatedMethodIsRemovedInPiwik3('\Piwik\Plugins\API\API', 'getLastDate'); } private function assertDeprecatedMethodIsRemoved($className, $method, $removalDate)
Fixes #<I> Deprecate the API.getLastDate method as it is un-used in Piwik
matomo-org_matomo
train
8170abd22dab861acef13f94c0d9473ae346cf14
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -5,10 +5,10 @@ setup( description = 'Uses git for distributed active learning', author = 'Casey Law, Umaa Rebbapragada', author_email = 'caseyjlaw@gmail.com', - version = '0.37', + version = '0.38', url = 'http://github.com/caseyjlaw/activegit', packages = find_packages(), # get all python scripts in real time - install_requires=['sh', 'scikit-learn'], + install_requires=['sh'], # 'scipy', 'scikit-learn'], entry_points=''' [console_scripts] aginit=activegit.cli:initrepo
removed sklearn dep
caseyjlaw_activegit
train
a64daac6884f51dabcb6e7a058df66528816a80c
diff --git a/netmiko/base_connection.py b/netmiko/base_connection.py index <HASH>..<HASH> 100644 --- a/netmiko/base_connection.py +++ b/netmiko/base_connection.py @@ -176,7 +176,7 @@ class BaseConnection: session_log_record_writes: bool = False, session_log_file_mode: str = "write", allow_auto_change: bool = False, - encoding: str = "ascii", + encoding: str = "utf-8", sock: Optional[socket.socket] = None, auto_connect: bool = True, delay_factor_compat: bool = False, diff --git a/netmiko/channel.py b/netmiko/channel.py index <HASH>..<HASH> 100644 --- a/netmiko/channel.py +++ b/netmiko/channel.py @@ -82,7 +82,7 @@ class SSHChannel(Channel): outbuf = self.remote_conn.recv(MAX_BUFFER) if len(outbuf) == 0: raise ReadException("Channel stream closed by remote device.") - output += outbuf.decode("utf-8", "ignore") + output += outbuf.decode(self.encoding, "ignore") return output def read_channel(self) -> str: @@ -123,7 +123,7 @@ class TelnetChannel(Channel): """Read all of the available data from the channel.""" if self.remote_conn is None: raise ReadException("Attempt to read, but there is no active channel.") - return self.remote_conn.read_very_eager().decode("utf-8", "ignore") + return self.remote_conn.read_very_eager().decode(self.encoding, "ignore") class SerialChannel(Channel): @@ -150,7 +150,7 @@ class SerialChannel(Channel): raise ReadException("Attempt to read, but there is no active channel.") if self.remote_conn.in_waiting > 0: output = self.remote_conn.read(self.remote_conn.in_waiting).decode( - "utf-8", "ignore" + self.encoding, "ignore" ) assert isinstance(output, str) return output diff --git a/netmiko/utilities.py b/netmiko/utilities.py index <HASH>..<HASH> 100644 --- a/netmiko/utilities.py +++ b/netmiko/utilities.py @@ -223,16 +223,12 @@ def find_netmiko_dir() -> Tuple[str, str]: return (netmiko_base_dir, netmiko_full_dir) -def write_bytes(out_data: AnyStr, encoding: str = "ascii") -> bytes: - """Legacy for Python2 and Python3 compatible byte stream.""" - if sys.version_info[0] >= 3: - if isinstance(out_data, str): - if encoding == "utf-8": - return out_data.encode("utf-8") - else: - return out_data.encode("ascii", "ignore") - elif isinstance(out_data, bytes): - return out_data +def write_bytes(out_data: AnyStr, encoding: str = "utf-8") -> bytes: + """Ensure output is properly encoded bytes.""" + if isinstance(out_data, str): + return out_data.encode(encoding) + elif isinstance(out_data, bytes): + return out_data msg = f"Invalid value for out_data neither unicode nor byte string: {str(out_data)}" raise ValueError(msg) diff --git a/tests/unit/test_utilities.py b/tests/unit/test_utilities.py index <HASH>..<HASH> 100755 --- a/tests/unit/test_utilities.py +++ b/tests/unit/test_utilities.py @@ -224,6 +224,9 @@ def test_ntc_templates_discovery(): ntc_path = utilities.get_template_dir() for py_path in sys.path: if "site-packages" in py_path: + _, suffix = py_path.split("site-packages") + if len(suffix) > 1: # Should be "" or "/" + continue packages_dir = py_path break assert ntc_path == f"{packages_dir}/ntc_templates/templates"
Improve encoding behavior (#<I>)
ktbyers_netmiko
train
a185e57ce5a7cf55a6eed1b21a2e3285ebfba109
diff --git a/languagetool-core/src/test/java/org/languagetool/rules/WordListValidatorTest.java b/languagetool-core/src/test/java/org/languagetool/rules/WordListValidatorTest.java index <HASH>..<HASH> 100644 --- a/languagetool-core/src/test/java/org/languagetool/rules/WordListValidatorTest.java +++ b/languagetool-core/src/test/java/org/languagetool/rules/WordListValidatorTest.java @@ -37,6 +37,7 @@ public class WordListValidatorTest { "Ææ" + // English "ÍÚÑ" + // for Spanish "õș" + // for Portuguese + "ā" + // for Persian "·" + // for Catalan "'’" + "ýùźăŽČĆÅıøğåšĝÇİŞŠčžć±ą+-" + // for Dutch (inhabitants) proper names mostly @@ -64,6 +65,7 @@ public class WordListValidatorTest { "ångströms", "'Ndrangheta", "McDonald's", + "Bahrām", "µm", "µg", "µl",
[core] white list persian character for diacritics rule
languagetool-org_languagetool
train
1b9713e40963ba394b97ad76fb9c57936a3f62c2
diff --git a/salt/modules/nova.py b/salt/modules/nova.py index <HASH>..<HASH> 100644 --- a/salt/modules/nova.py +++ b/salt/modules/nova.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- ''' -Module for handling OpenStack Nova calls. +Module for handling OpenStack Nova calls :depends: - novaclient Python module :configuration: This module is not usable until the user, password, tenant, and @@ -162,6 +162,8 @@ def boot(name, flavor_id=0, image_id=0, profile=None, timeout=300): def server_by_name(name, profile=None): ''' + .. versionadded:: Helium + Returns information about one server based on the name name @@ -177,8 +179,7 @@ def server_by_name(name, profile=None): salt '*' nova.server_by_name test.example.com profile=openstack ''' - servers = server_list(profile=profile) - return servers[server_name] + return server_list(profile=profile).get(name, {}) def _volume_get(volume_id, profile=None): diff --git a/salt/states/nova.py b/salt/states/nova.py index <HASH>..<HASH> 100644 --- a/salt/states/nova.py +++ b/salt/states/nova.py @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- ''' -Using states to manage nova -============================================= +States to manage OpenStack Nova +=============================== +.. versionadded:: Helium Use this minion to do things with nova:
Fixes for nova module Fixed a NameError and potential KeyError. Also added versionadded RST directives where appropriate.
saltstack_salt
train
735492f03feb9e0edbeeab38c218e20b23d3a527
diff --git a/manager/eris-mint/evm/vm.go b/manager/eris-mint/evm/vm.go index <HASH>..<HASH> 100644 --- a/manager/eris-mint/evm/vm.go +++ b/manager/eris-mint/evm/vm.go @@ -147,6 +147,30 @@ func (vm *VM) Call(caller, callee *Account, code, input []byte, value int64, gas return } +// DelegateCall is executed by the DELEGATECALL opcode, introduced as off Ethereum Homestead. +// The intent of delegate call is to run the code of the callee in the storage context of the caller; +// while preserving the original caller to the previous callee. +// Different to the normal CALL or CALLCODE, the value does not need to be transferred to the callee. +func (vm *VM) DelegateCall(caller, callee *Account, code, input []byte, value int64, gas *int64) (output []byte, err error) { + + exception := new(string) + // fire the post call event (including exception if applicable) + defer vm.fireCallEvent(exception, &output, caller, callee, input, value, gas) + + // DelegateCall does not transfer the value to the callee. + + if len(code) > 0 { + vm.callDepth += 1 + output, err = vm.call(caller, callee, code, input, value, gas) + vm.callDepth -= 1 + if err != nil { + *exception = err.Error() + } + } + + return +} + // Try to deduct gasToUse from gasLeft. If ok return false, otherwise // set err and return true. func useGasNegative(gasLeft *int64, gasToUse int64, err *error) bool {
erismint/vm: implement DelegateCall as scoped function
hyperledger_burrow
train
c5be1c29d9e6d9e1ef798c5ec2b67875a76f6aa4
diff --git a/lib/shortline.js b/lib/shortline.js index <HASH>..<HASH> 100644 --- a/lib/shortline.js +++ b/lib/shortline.js @@ -108,41 +108,31 @@ Shortline.prototype.ask = function ask(question, options) { }); } - var result = self.prompt(fullQuestion); - - if (options.default) { - result = result.then(function applyDefault(answer) { - return answer || options.default; - }); - } + return self.prompt(fullQuestion).then(function answerToResult(answer) { + if (options.default) { + answer = answer || options.default; + } - if (options.trim) { - result = result.then(function trimAnswer(answer) { - return answer.trimRight(); - }); - } + if (options.trim) { + answer = answer.trimRight(); + } - if (options.validate) { - result = result.then(function validateAnswer(answer) { - if (!options.validate.test(answer)) { - var response = options.responses && options.responses.notValid; - if (!response) { - response = 'Your answer isn\'t valid (must match ' + - options.validate.source + ').'; - } - self._output.write(response + '\n'); - return self.ask(question, options); + if (options.validate && !options.validate.test(answer)) { + var response = options.responses && options.responses.notValid; + if (!response) { + response = 'Your answer isn\'t valid (must match ' + + options.validate.source + ').'; } + self._output.write(response + '\n'); + return self.ask(question, options); + } - return answer; - }); - } - - if (options.convert) { - result = result.then(options.convert); - } + if (options.convert) { + answer = options.convert(answer); + } - return result; + return answer; + }); }; /** Prompts the user for input without validation, retry, type conversion, or
Fix re-prompting on invalid answer Previously if the answer to a question was invalid, the conversion would be applied to the re-prompt result (which had already been converted). Fix this by removing a lot of unnecessary promise chaining.
kevinoid_travis-status
train
8ab0e510a695e1ba9d999a7be297efd188841cf4
diff --git a/src/Illuminate/Console/Scheduling/CallbackEvent.php b/src/Illuminate/Console/Scheduling/CallbackEvent.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Console/Scheduling/CallbackEvent.php +++ b/src/Illuminate/Console/Scheduling/CallbackEvent.php @@ -1,5 +1,6 @@ <?php namespace Illuminate\Console\Scheduling; +use LogicException; use InvalidArgumentException; use Illuminate\Contracts\Container\Container; @@ -47,14 +48,51 @@ class CallbackEvent extends Event { */ public function run(Container $container) { + if ($this->description) + { + touch($this->mutexPath()); + } + $response = $container->call($this->callback, $this->parameters); + @unlink($this->mutexPath()); + parent::callAfterCallbacks($container); return $response; } /** + * Do not allow the event to overlap each other. + * + * @return $this + */ + public function withoutOverlapping() + { + if ( ! isset($this->description)) + { + throw new LogicException( + "A scheduled event name is required to prevent overlapping. Use the 'name' method before 'withoutOverlapping'." + ); + } + + return $this->skip(function() + { + return file_exists($this->mutexPath()); + }); + } + + /** + * Get the mutex path for the scheduled command. + * + * @return string + */ + protected function mutexPath() + { + return storage_path().'/framework/schedule-'.md5($this->description); + } + + /** * Get the summary of the event for display. * * @return string diff --git a/src/Illuminate/Console/Scheduling/Event.php b/src/Illuminate/Console/Scheduling/Event.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Console/Scheduling/Event.php +++ b/src/Illuminate/Console/Scheduling/Event.php @@ -55,6 +55,13 @@ class Event { public $evenInMaintenanceMode = false; /** + * Indicates if the command should not overlap itself. + * + * @var bool + */ + public $withoutOverlapping = false; + + /** * The filter callback. * * @var \Closure @@ -166,12 +173,30 @@ class Event { */ public function buildCommand() { - $command = $this->command.' > '.$this->output.' 2>&1 &'; + if ($this->withoutOverlapping) + { + $command = '(touch '.$this->mutexPath().'; '.$this->command.'; rm '.$this->mutexPath().') > '.$this->output.' 2>&1 &'; + } + else + { + $command = $this->command.' > '.$this->output.' 2>&1 &'; + } + return $this->user ? 'sudo -u '.$this->user.' '.$command : $command; } /** + * Get the mutex path for the scheduled command. + * + * @return string + */ + protected function mutexPath() + { + return storage_path().'/framework/schedule-'.md5($this->expression.$this->command); + } + + /** * Determine if the given event should run based on the Cron expression. * * @param \Illuminate\Contracts\Foundation\Application $app @@ -531,6 +556,21 @@ class Event { } /** + * Do not allow the event to overlap each other. + * + * @return $this + */ + public function withoutOverlapping() + { + $this->withoutOverlapping = true; + + return $this->skip(function() + { + return file_exists($this->mutexPath()); + }); + } + + /** * Register a callback to further filter the schedule. * * @param \Closure $callback @@ -657,6 +697,17 @@ class Event { * @param string $description * @return $this */ + public function name($description) + { + return $this->description($description); + } + + /** + * Set the human-friendly description of the event. + * + * @param string $description + * @return $this + */ public function description($description) { $this->description = $description;
Add withoutOverlapping to scheduled commands.
laravel_framework
train
221bbf792e60de7cc6197612cd3fa3621893961a
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java b/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java @@ -1100,8 +1100,7 @@ public class Task implements Runnable, TaskSlotPayload, TaskActions, PartitionPr Runnable cancelWatchdog = new TaskCancelerWatchDog( executingThread, taskManagerActions, - taskCancellationTimeout, - LOG); + taskCancellationTimeout); Thread watchDogThread = new Thread( executingThread.getThreadGroup(), @@ -1508,9 +1507,6 @@ public class Task implements Runnable, TaskSlotPayload, TaskActions, PartitionPr */ private static class TaskCancelerWatchDog implements Runnable { - /** The logger to report on the fatal condition. */ - private final Logger log; - /** The executing task thread that we wait for to terminate. */ private final Thread executerThread; @@ -1523,12 +1519,10 @@ public class Task implements Runnable, TaskSlotPayload, TaskActions, PartitionPr TaskCancelerWatchDog( Thread executerThread, TaskManagerActions taskManager, - long timeoutMillis, - Logger log) { + long timeoutMillis) { checkArgument(timeoutMillis > 0); - this.log = log; this.executerThread = executerThread; this.taskManager = taskManager; this.timeoutMillis = timeoutMillis; @@ -1557,8 +1551,7 @@ public class Task implements Runnable, TaskSlotPayload, TaskActions, PartitionPr } } catch (Throwable t) { - ExceptionUtils.rethrowIfFatalError(t); - log.error("Error in Task Cancellation Watch Dog", t); + throw new FlinkRuntimeException("Error in Task Cancellation Watch Dog", t); } } }
[FLINK-<I>] Fail fatally if the TaskCancelerWatchDog encounters exception in run method If the TaskCancelerWatchDog encounters an exception in the run method, then we can no longer guarantee that it will do its job. Hence, it is best to fail fatally by letting the exception bubble up so that it is handled by the uncaught exception handler.
apache_flink
train
a8ddf7ead7f89f20f30bf5ecfd27b623d182d66a
diff --git a/src/rez/util.py b/src/rez/util.py index <HASH>..<HASH> 100644 --- a/src/rez/util.py +++ b/src/rez/util.py @@ -621,12 +621,14 @@ def convert_old_command_expansions(command): return command +""" def convert_old_environment_variable_references(input_): def repl(matchobj): return "{env.%s}" % matchobj.groupdict()['variable'] return re.sub("\$\{?(?P<variable>[a-zA-Z][_a-zA-Z0-9]*)\}?", repl, input_) +""" def convert_old_commands(commands, annotate=True): @@ -677,11 +679,11 @@ def convert_old_commands(commands, annotate=True): func = "appendenv" if idx == 0 else "prependenv" parts = parts[1:] if idx == 0 else parts[:-1] val = separator.join(parts) - val = convert_old_environment_variable_references(val) + #val = convert_old_environment_variable_references(val) loc.append("%s('%s', '%s')" % (func, var, _encode(val))) continue - value = convert_old_environment_variable_references(value) + #value = convert_old_environment_variable_references(value) loc.append("setenv('%s', '%s')" % (var, _encode(value))) elif toks[0].startswith('#'): loc.append("comment('%s')" % _encode(' '.join(toks[1:])))
-removed use of `convert_old_environment_variable_references`, addresses issue #<I>.
nerdvegas_rez
train
7555787e9b259790802f71cf0ef96245249e0c4d
diff --git a/btrfs/test_btrfs.py b/btrfs/test_btrfs.py index <HASH>..<HASH> 100644 --- a/btrfs/test_btrfs.py +++ b/btrfs/test_btrfs.py @@ -2,9 +2,13 @@ # All rights reserved # Licensed under Simplified BSD License (see LICENSE) +# 3p +from nose.plugins.attrib import attr + # project from tests.checks.common import AgentCheckTest +@attr('unix') class TestBtrfs(AgentCheckTest): """Basic Test for btrfs integration.""" CHECK_NAME = 'btrfs'
[btrfs] this is a unix test, skip on appveyor.
DataDog_integrations-core
train
66c944982830cb650b2f2d994f68de85dcd7c9bd
diff --git a/graylog2-server/src/main/java/org/graylog/security/UserContext.java b/graylog2-server/src/main/java/org/graylog/security/UserContext.java index <HASH>..<HASH> 100644 --- a/graylog2-server/src/main/java/org/graylog/security/UserContext.java +++ b/graylog2-server/src/main/java/org/graylog/security/UserContext.java @@ -18,6 +18,7 @@ package org.graylog.security; import org.apache.shiro.SecurityUtils; import org.apache.shiro.UnavailableSecurityManagerException; +import org.apache.shiro.authz.permission.AllPermission; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.graylog.grn.GRN; @@ -123,6 +124,14 @@ public class UserContext { return subject.isPermitted(GRNPermission.create(RestPermissions.ENTITY_OWN, entity)); } + /** + * Checks if the user is permitted to do everything + * @return The check result + */ + public boolean hasAllPermission() { + return subject.isPermitted(new AllPermission()); + } + public boolean isPermitted(String permission, GRN target) { return isPermitted(permission, target.entity()); }
Add hasAllPermission check to UserContext (#<I>) Checks if the user is permitted to do everything (aka admin permission)
Graylog2_graylog2-server
train
e0bcd0fc70763db5ddea8fd2972819fe16aa3007
diff --git a/src/php/wp-cli/wp-cli.php b/src/php/wp-cli/wp-cli.php index <HASH>..<HASH> 100755 --- a/src/php/wp-cli/wp-cli.php +++ b/src/php/wp-cli/wp-cli.php @@ -52,6 +52,9 @@ if ( !empty( $assoc_args['path'] ) ) { define( 'WP_ROOT', $_SERVER['PWD'] . '/' ); } +// Handle --url and --blog parameters +WP_CLI::_set_url( $assoc_args ); + if ( array( 'core', 'download' ) == $arguments ) { WP_CLI::run_command( $arguments, $assoc_args ); exit; @@ -79,9 +82,6 @@ if ( array( 'core', 'install' ) == $arguments ) { define( 'WP_INSTALLING', true ); } -// Handle --url and --blog parameters -WP_CLI::_set_url( $assoc_args ); - // Load WordPress require WP_ROOT . 'wp-load.php'; require ABSPATH . 'wp-admin/includes/admin.php';
don't ignore --url param when calling wp db create. see #<I>
wp-cli_extension-command
train
c9095ae670d9fc7244ef8ecafa0afc19d25d8d76
diff --git a/mod/data/fields.php b/mod/data/fields.php index <HASH>..<HASH> 100755 --- a/mod/data/fields.php +++ b/mod/data/fields.php @@ -30,7 +30,7 @@ $id = optional_param('id', 0, PARAM_INT); // course module id $d = optional_param('d', 0, PARAM_INT); // database id $fid = optional_param('fid', 0 , PARAM_INT); // update field id - $newtype = optional_param('fieldmenu','',PARAM_ALPHA); // type of the new field + $newtype = optional_param('newtype','',PARAM_ALPHA); // type of the new field $mode = optional_param('mode','',PARAM_ALPHA); $displaynotice = ''; //str to print after an operation, @@ -207,18 +207,13 @@ $field->display_edit_field(); } else { /// Display the main listing of all fields - - echo '<form name="fieldform" action="fields.php" method="post">'; - echo '<input name="d" type="hidden" value="'.$data->id.'" />'; - echo '<input type="hidden" name="mode" value="" />'; - echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'; - print_simple_box_start('center','50%'); - - echo '<table width="100%"><tr>'; - echo '<td>'.get_string('newfield','data').' '; - choose_from_menu($menufield,'fieldmenu','0','choose','fieldform.mode.value=\'new\';fieldform.submit();','0'); + + echo '<div class="fieldadd" align="center">'; + echo get_string('newfield','data').': '; + popup_form($CFG->wwwroot.'/mod/data/fields.php?d='.$data->id.'&amp;mode=new&amp;sesskey='. + sesskey().'&amp;newtype=', $menufield, 'fieldform', '', 'choose'); helpbutton('fields', get_string('addafield','data'), 'data'); - echo '</td></tr>'; + echo '</div>'; if (!record_exists('data_fields','dataid',$data->id)) { echo '<tr><td colspan="2">'.get_string('nofieldindatabase','data').'</td></tr>'; // nothing in database @@ -265,7 +260,6 @@ echo '</td></tr></table>'; print_simple_box_end(); - echo '</form>'; }
The menu to add fields is now more accessible
moodle_moodle
train
cfdfa0878675015a0db8abd85d22f562e3902d89
diff --git a/src/wtf/io/buffer.js b/src/wtf/io/buffer.js index <HASH>..<HASH> 100644 --- a/src/wtf/io/buffer.js +++ b/src/wtf/io/buffer.js @@ -488,11 +488,11 @@ wtf.io.Buffer.prototype.readAsciiString = function() { var offset = this.offset; var out = new Array(charCount); for (var n = 0; n < charCount; n++) { - out[n] = String.fromCharCode(data[offset++]); + out[n] = data[offset++]; } this.offset = offset; - return out.join(''); + return String.fromCharCode.apply(null, out); }; @@ -583,20 +583,19 @@ wtf.io.Buffer.prototype.readUtf8String = function() { while (c < charCount) { var c1 = data[offset++]; if (c1 < 128) { - out[c++] = String.fromCharCode(c1); + out[c++] = c1; } else if (c1 > 191 && c1 < 224) { var c2 = data[offset++]; - out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63); + out[c++] = (c1 & 31) << 6 | (c2 & 63); } else { var c2 = data[offset++]; var c3 = data[offset++]; - out[c++] = String.fromCharCode( - (c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63); + out[c++] = (c1 & 15) << 12 | (c2 & 63) << 6 | (c3 & 63); } } this.offset = offset; - return out.join(''); + return String.fromCharCode.apply(null, out); };
Fixing string parsing to do the fromCharCode at the end so that it generates better strings. This speeds up search in large dbs a bit.
google_tracing-framework
train
d8064087296a0a043dd5f37e7dd557eebe56637b
diff --git a/Rakefile b/Rakefile index <HASH>..<HASH> 100644 --- a/Rakefile +++ b/Rakefile @@ -42,6 +42,7 @@ namespace :rabbit do def create_config_file(config_file, web_port) File.open("#{config_file}.config",'w') do |f| f.puts "[" + f.puts " {rabbit, [{channel_max, 1000}]}," f.puts " {rabbitmq_management, [{listener, [{port, #{web_port}}]}]}" f.puts "]." end diff --git a/lib/beetle/configuration.rb b/lib/beetle/configuration.rb index <HASH>..<HASH> 100644 --- a/lib/beetle/configuration.rb +++ b/lib/beetle/configuration.rb @@ -55,8 +55,12 @@ module Beetle attr_accessor :user # the password to use when connectiong to the AMQP servers (defaults to <tt>"guest"</tt>) attr_accessor :password - # the maximum permissible size of a frame (in bytes). Defaults to 128 KB + # the maximum permissible size of a frame (in bytes). defaults to 128 KB attr_accessor :frame_max + # the max number of channels the publisher tries to negotiate with the server. Defaults + # to 2047, which is the RabbitMQ default in 3.7. We can't set this to 0 because of a bug + # in bunny. + attr_accessor :channel_max # In contrast to RabbitMQ 2.x, RabbitMQ 3.x preserves message order when requeing a message. This can lead to # throughput degradation (when rejected messages block the processing of other messages @@ -127,6 +131,7 @@ module Beetle self.password = "guest" self.api_port = 15672 self.frame_max = 131072 + self.channel_max = 2047 self.prefetch_count = 1 self.dead_lettering_enabled = false diff --git a/lib/beetle/publisher.rb b/lib/beetle/publisher.rb index <HASH>..<HASH> 100644 --- a/lib/beetle/publisher.rb +++ b/lib/beetle/publisher.rb @@ -166,6 +166,7 @@ module Beetle :pass => @client.config.password, :vhost => @client.config.vhost, :frame_max => @client.config.frame_max, + :channel_max => @client.config.channel_max, :socket_timeout => @client.config.publishing_timeout, :spec => '09') b.start diff --git a/test/beetle/publisher_test.rb b/test/beetle/publisher_test.rb index <HASH>..<HASH> 100644 --- a/test/beetle/publisher_test.rb +++ b/test/beetle/publisher_test.rb @@ -25,6 +25,7 @@ module Beetle :vhost => "/", :socket_timeout => 0, :frame_max => 131072, + :channel_max => 2047, :spec => '09' } Bunny.expects(:new).with(expected_bunny_options).returns(m)
publisher: fixed channel_max negotiation for servers which set channel_max
xing_beetle
train
0414620ffd58f5607b74ed8f227940cdd49f6bf2
diff --git a/rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/scan/RxBleInternalScanResult.java b/rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/scan/RxBleInternalScanResult.java index <HASH>..<HASH> 100644 --- a/rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/scan/RxBleInternalScanResult.java +++ b/rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/scan/RxBleInternalScanResult.java @@ -51,4 +51,11 @@ public class RxBleInternalScanResult implements ScanResultInterface { public String getAddress() { return bluetoothDevice.getAddress(); } + + @Override + public String getDeviceName() { + BluetoothDevice device = getBluetoothDevice(); + return device == null ? null : device.getName(); + } + } diff --git a/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanFilter.java b/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanFilter.java index <HASH>..<HASH> 100644 --- a/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanFilter.java +++ b/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanFilter.java @@ -275,7 +275,7 @@ import java.util.UUID; // Local name match. if (mDeviceName != null) { - if (!mDeviceName.equals(scanRecord.getDeviceName())) { + if (!mDeviceName.equals(scanRecord.getDeviceName()) && !mDeviceName.equals(scanResult.getDeviceName())) { return false; } } diff --git a/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanResult.java b/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanResult.java index <HASH>..<HASH> 100644 --- a/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanResult.java +++ b/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanResult.java @@ -46,6 +46,11 @@ public class ScanResult implements ScanResultInterface { return bleDevice == null ? null : bleDevice.getMacAddress(); } + public String getDeviceName() { + RxBleDevice device = getBleDevice(); + return device == null ? null : device.getName(); + } + @Override @NonNull public String toString() { diff --git a/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanResultInterface.java b/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanResultInterface.java index <HASH>..<HASH> 100644 --- a/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanResultInterface.java +++ b/rxandroidble/src/main/java/com/polidea/rxandroidble2/scan/ScanResultInterface.java @@ -7,6 +7,11 @@ public interface ScanResultInterface { String getAddress(); /** + * Get the device name from the device (not from scan record) + */ + String getDeviceName(); + + /** * Get the RSSI of the scan result */ int getRssi(); diff --git a/rxandroidble/src/test/groovy/com/polidea/rxandroidble2/scan/ScanFilterTest.groovy b/rxandroidble/src/test/groovy/com/polidea/rxandroidble2/scan/ScanFilterTest.groovy index <HASH>..<HASH> 100644 --- a/rxandroidble/src/test/groovy/com/polidea/rxandroidble2/scan/ScanFilterTest.groovy +++ b/rxandroidble/src/test/groovy/com/polidea/rxandroidble2/scan/ScanFilterTest.groovy @@ -8,14 +8,11 @@ class ScanFilterTest extends Specification { RxBleInternalScanResult mockInternalScanResult = Mock RxBleInternalScanResult - BluetoothDevice mockBluetoothDevice = Mock BluetoothDevice - ScanRecord mockScanRecord = Mock ScanRecord ScanFilter objectUnderTest def setup() { - mockInternalScanResult.getBluetoothDevice() >> mockBluetoothDevice mockInternalScanResult.getScanRecord() >> mockScanRecord } @@ -30,6 +27,17 @@ class ScanFilterTest extends Specification { objectUnderTest.matches(mockInternalScanResult) } + def "should match by device name if the name is present in BluetoothDevice"() { + + given: + String name = "xxx" + mockInternalScanResult.getDeviceName() >> name + objectUnderTest = new ScanFilter.Builder().setDeviceName(name).build() + + expect: + objectUnderTest.matches(mockInternalScanResult) + } + def "should not match by device name if the name is not present in BluetoothDevice nor ScanRecord"() { given:
Revert removal of ScanFilter match on cached device name
Polidea_RxAndroidBle
train
d28bf73c97c11cb02b5c264fe39895b7f8fadfb0
diff --git a/mr/src/main/java/org/elasticsearch/hadoop/rest/RestRepository.java b/mr/src/main/java/org/elasticsearch/hadoop/rest/RestRepository.java index <HASH>..<HASH> 100644 --- a/mr/src/main/java/org/elasticsearch/hadoop/rest/RestRepository.java +++ b/mr/src/main/java/org/elasticsearch/hadoop/rest/RestRepository.java @@ -274,7 +274,7 @@ public class RestRepository implements Closeable, StatsAware { Shard shard = new Shard(shardData); if (shard.getState().isStarted()) { Node node = nodes.get(shard.getNode()); - Assert.notNull(node, "Cannot find node with id [" + shard.getNode() + "]"); + Assert.notNull(node, String.format("Cannot find node with id [%s] (is HTTP enabled?) from shard [%s] in nodes [%s]; layout [%s]", shard.getNode(), shard, shardGroup, info)); shards.put(shard, node); break; } @@ -295,7 +295,7 @@ public class RestRepository implements Closeable, StatsAware { Shard shard = new Shard(shardData); if (shard.isPrimary()) { Node node = nodes.get(shard.getNode()); - Assert.notNull(node, "Cannot find node with id [" + shard.getNode() + "]"); + Assert.notNull(node, String.format("Cannot find node with id [%s] (is HTTP enabled?) from shard [%s] in nodes [%s]; layout [%s]", shard.getNode(), shard, shardGroup, info)); shards.put(shard, node); break; }
Improve message regarding nodes not being found
elastic_elasticsearch-hadoop
train
057c2c6bc4516ace97230465ea8f6ffafc9ba34e
diff --git a/lib/chef/knife/configure.rb b/lib/chef/knife/configure.rb index <HASH>..<HASH> 100644 --- a/lib/chef/knife/configure.rb +++ b/lib/chef/knife/configure.rb @@ -75,7 +75,7 @@ class Chef config_file = File.expand_path(config_file) if File.exist?(config_file) - confirm("Overwrite #{config_file}?") + confirm("Overwrite #{config_file}") end ::File.open(config_file, "w") do |f| f.puts <<-EOH
Remove redundant "?" in knife configure RK: Obvious fix.
chef_chef
train
1e449656a8147b00b297f1272bc0c1d4a3d07704
diff --git a/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java b/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java index <HASH>..<HASH> 100644 --- a/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java +++ b/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java @@ -322,8 +322,12 @@ public class ASTHelpers { case PARENTHESIZED: case NEW_CLASS: case MEMBER_REFERENCE: - case LAMBDA_EXPRESSION: return false; + case LAMBDA_EXPRESSION: + // Parenthesizing e.g. `x -> (y -> z)` is unnecessary but helpful + Tree parent = state.getPath().getParentPath().getLeaf(); + return parent.getKind().equals(Kind.LAMBDA_EXPRESSION) + && stripParentheses(((LambdaExpressionTree) parent).getBody()).equals(expression); default: // continue below } if (expression instanceof LiteralTree) { diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryParenthesesTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryParenthesesTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryParenthesesTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryParenthesesTest.java @@ -122,4 +122,16 @@ public class UnnecessaryParenthesesTest { "}") .doTest(); } + + @Test + public void lambdaLambda() { + helper + .addSourceLines( + "Test.java", + "import java.util.function.Function;", + "class Test {", + " Function<Void, Function<Void, Void>> r = x -> (y -> y);", + "}") + .doTest(); + } }
Allow parens around nested lambdas PiperOrigin-RevId: <I>
google_error-prone
train
4d56cbf66c67b0bb08a36057c95dbd1a9d5aa22a
diff --git a/topologies/mongos.js b/topologies/mongos.js index <HASH>..<HASH> 100644 --- a/topologies/mongos.js +++ b/topologies/mongos.js @@ -254,10 +254,10 @@ function emitSDAMEvent(self, event, description) { } const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; -function destroyServer(server, options) { +function destroyServer(server, options, callback) { options = options || {}; SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - server.destroy(options); + server.destroy(options, callback); } /** @@ -808,32 +808,43 @@ Mongos.prototype.unref = function() { * @param {boolean} [options.force=false] Force destroy the pool * @method */ -Mongos.prototype.destroy = function(options) { - var self = this; - // Transition state - stateTransition(this, DESTROYED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - // Clear out any monitoring process - if (this.haTimeoutId) clearTimeout(this.haTimeoutId); +Mongos.prototype.destroy = function(options, callback) { + if (this.haTimeoutId) { + clearTimeout(this.haTimeoutId); + } + + const proxies = this.connectedProxies.concat(this.connectingProxies); + let serverCount = proxies.length; + const serverDestroyed = () => { + serverCount--; + if (serverCount > 0) { + return; + } + + emitTopologyDescriptionChanged(this); + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); + stateTransition(this, DESTROYED); + if (typeof callback === 'function') { + callback(null, null); + } + }; + + if (serverCount === 0) { + serverDestroyed(); + return; + } // Destroy all connecting servers - proxies.forEach(function(server) { + proxies.forEach(server => { // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, + this.emit('serverClosed', { + topologyId: this.id, address: server.name }); - destroyServer(server, options); - - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, server); + destroyServer(server, options, serverDestroyed); + moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); }); - // Emit the final topology change - emitTopologyDescriptionChanged(self); - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); }; /**
refactor(mongos): support passing callback to `destroy`
mongodb_node-mongodb-native
train
f6459f1868866c95889cb290f18f5bfa5912fd4c
diff --git a/aikif/core_data.py b/aikif/core_data.py index <HASH>..<HASH> 100644 --- a/aikif/core_data.py +++ b/aikif/core_data.py @@ -15,7 +15,8 @@ def TEST(): print(e) # save a table - ev = CoreTable(fldr=os.getcwd(), tpe='Events', user='user01', header=['date', 'category', 'details']) + import aikif.config + ev = CoreTable(aikif.config.fldrs['log_folder'], tpe='Events', user='user01', header=['date', 'category', 'details']) ev.add(Event('Sales Meeting', ['2014-01-11', 'Office', 'Catchup with client'])) ev.add(Event('Sales Meeting#3', ['2015-03-11', 'Office', 'Catchup with client'])) ev.add(Event('DEV AIKIF - core data', ['2015-05-11', 'Software', 'update TEST - no test for CORE_DATA']))
core data example saves to local log folder
acutesoftware_AIKIF
train
8ea67ce0e517febf97ab4948189eb0e5fe33387e
diff --git a/src/File.php b/src/File.php index <HASH>..<HASH> 100644 --- a/src/File.php +++ b/src/File.php @@ -11,7 +11,7 @@ use TusPhp\Exception\OutOfRangeException; class File { /** @const Max chunk size */ - const CHUNK_SIZE = 8192; // 8 bytes. + const CHUNK_SIZE = 8192; // 8 kilobytes. /** @const Input stream */ const INPUT_STREAM = 'php://input';
Corrected bytes to kilobytes (#<I>)
ankitpokhrel_tus-php
train
1d3571d4c57f6087a051ac0d3422c5ee8000933a
diff --git a/lib/resolveScripts.js b/lib/resolveScripts.js index <HASH>..<HASH> 100644 --- a/lib/resolveScripts.js +++ b/lib/resolveScripts.js @@ -5,10 +5,10 @@ var versionMap = require('./version-map.json'); var defaultPaths = { 'jquery': Handlebars.compile('http://ajax.googleapis.com/ajax/libs/jquery/{{version}}/jquery.min.js'), - 'can': Handlebars.compile('http://canjs.com/release/{{version}}/can.jquery.js'), - 'ejs': Handlebars.compile('http://canjs.com/release/{{version}}/can.ejs.js'), - 'mustache': Handlebars.compile('http://canjs.com/release/{{version}}/can.view.mustache.js'), - 'stache': Handlebars.compile('http://canjs.com/release/{{version}}/can.stache.js') + 'can': Handlebars.compile('http://v2.canjs.com/release/{{version}}/can.jquery.js'), + 'ejs': Handlebars.compile('http://v2.canjs.com/release/{{version}}/can.ejs.js'), + 'mustache': Handlebars.compile('http://v2.canjs.com/release/{{version}}/can.view.mustache.system.js'), + 'stache': Handlebars.compile('http://v2.canjs.com/release/{{version}}/can.stache.js') }; var getScriptFromPath = function(scriptPath) {
Change paths in resolveScripts.js to use v2 paths Also change mustache path to the correct can.view.mustache.system.js
canjs_can-compile
train
958f7f31c0f3be586ad0cec17a0ba595d8d44bd1
diff --git a/src/sap.m/src/sap/m/library.js b/src/sap.m/src/sap/m/library.js index <HASH>..<HASH> 100644 --- a/src/sap.m/src/sap/m/library.js +++ b/src/sap.m/src/sap/m/library.js @@ -50,7 +50,7 @@ sap.ui.define([ "sap.m.BackgroundDesign", "sap.m.BarDesign", "sap.m.ButtonType", - "sap.m.CarouselArrowsAlign", + "sap.m.CarouselArrowsPlacement", "sap.m.DateTimeInputType", "sap.m.DialogType", "sap.m.DeviationIndicator", @@ -103,7 +103,7 @@ sap.ui.define([ "sap.m.SwipeDirection", "sap.m.SwitchType", "sap.m.TimePickerMaskMode", - "sap.m.TileSizeBehaviour", + "sap.m.TileSizeBehavior", "sap.m.ToolbarDesign", "sap.m.VerticalPlacementType", "sap.m.semantic.SemanticRuleSetType"
[INTERNAL][FIX] sap.m: fix names of listed types The listed types CarouselArrowsAlign and TileSizeBehaviour don't exist, the right names are CarouselArrowsPlacement and TileSizeBehaviour. Change-Id: I2f0efd8becccf<I>cf<I>e<I>fc5cbe<I>a<I>d<I>d1
SAP_openui5
train
97b8cfa2358bcc81e8e3dd10444bea7ed3a137bb
diff --git a/src/Behat/Mink/Driver/SahiDriver.php b/src/Behat/Mink/Driver/SahiDriver.php index <HASH>..<HASH> 100644 --- a/src/Behat/Mink/Driver/SahiDriver.php +++ b/src/Behat/Mink/Driver/SahiDriver.php @@ -240,7 +240,7 @@ class SahiDriver implements DriverInterface public function getCookie($name) { try { - return $this->evaluateScript(sprintf('_sahi._cookie("%s")', $name)); + return urldecode($this->evaluateScript(sprintf('_sahi._cookie("%s")', $name))); } catch (ConnectionException $e) {} }
return decoded cookie in sahi
minkphp_Mink
train
fea05c765df3b84bd229170de6ade0af8539351d
diff --git a/tests/logs_unittest.py b/tests/logs_unittest.py index <HASH>..<HASH> 100644 --- a/tests/logs_unittest.py +++ b/tests/logs_unittest.py @@ -31,8 +31,7 @@ from openquake import settings LOG_FILE_PATH = os.path.join(os.getcwd(), 'test_file_for_the_logs_module.log') -class LogsTestCase(unittest.TestCase): - +class PreserveJavaIO(object): @classmethod def setUpClass(cls): # This is safe to call even if the jvm was already running from a @@ -47,6 +46,19 @@ class LogsTestCase(unittest.TestCase): cls.old_java_out = jpype.java.lang.System.out cls.old_java_err = jpype.java.lang.System.err + @classmethod + def tearDownClass(cls): + # restore the java stdout and stderr that were trashed during this test + jpype.java.lang.System.setOut(cls.old_java_out) + jpype.java.lang.System.setErr(cls.old_java_err) + + +class LogsTestCase(PreserveJavaIO, unittest.TestCase): + + @classmethod + def setUpClass(cls): + super(LogsTestCase, cls).setUpClass() + try: os.remove(LOG_FILE_PATH) except OSError: @@ -54,9 +66,7 @@ class LogsTestCase(unittest.TestCase): @classmethod def tearDownClass(cls): - # restore the java stdout and stderr that were trashed during this test - jpype.java.lang.System.setOut(cls.old_java_out) - jpype.java.lang.System.setErr(cls.old_java_err) + super(LogsTestCase, cls).tearDownClass() try: os.remove(LOG_FILE_PATH)
Move Java stdout/stderr preservation to a separate class.
gem_oq-engine
train
39e3a34f8a3b23af7d1c64bb2a16a5a30bbc22c0
diff --git a/src/models/options/ParserOptions.js b/src/models/options/ParserOptions.js index <HASH>..<HASH> 100644 --- a/src/models/options/ParserOptions.js +++ b/src/models/options/ParserOptions.js @@ -2,6 +2,7 @@ import Immutable from 'immutable' export default class ParserOptions extends Immutable.Record({ name: 'swagger', + version: null, instance: null, isDefault: true }) { @@ -25,6 +26,10 @@ export default class ParserOptions extends Immutable.Record({ } else if (!parser.name || typeof parser.name !== 'string') { parser.name = 'swagger' + + if (typeof parser.version !== 'string') { + parser.version = null + } } else { parser.isDefault = false diff --git a/src/models/options/__tests__/ParserOptions-test.js b/src/models/options/__tests__/ParserOptions-test.js index <HASH>..<HASH> 100644 --- a/src/models/options/__tests__/ParserOptions-test.js +++ b/src/models/options/__tests__/ParserOptions-test.js @@ -46,6 +46,7 @@ export class TestParserOptions extends UnitTest { testNormalizeWithEmptyObjectOpts() { const expected = { name: 'swagger', + version: null, instance: null } @@ -58,6 +59,7 @@ export class TestParserOptions extends UnitTest { const expected = { some: 'key', name: 'swagger', + version: null, instance: null }
added version to model for parser options
luckymarmot_API-Flow
train
576229a8909cbb082f8b8aeba7a34616fc068b2a
diff --git a/indra/assemblers/pysb/assembler.py b/indra/assemblers/pysb/assembler.py index <HASH>..<HASH> 100644 --- a/indra/assemblers/pysb/assembler.py +++ b/indra/assemblers/pysb/assembler.py @@ -1052,19 +1052,14 @@ def complex_assemble_multi_way(stmt, model, agent_set, parameters): complex_assemble_default = complex_assemble_one_step # MODIFICATION ################################################### - def modification_monomers_interactions_only(stmt, agent_set): if stmt.enz is None: return enz = agent_set.get_create_base_agent(stmt.enz) - act_type = mod_acttype_map[stmt.__class__] - active_site = act_type - enz.create_site(active_site) sub = agent_set.get_create_base_agent(stmt.sub) - # See NOTE in monomers_one_step, below - mod_condition_name = stmt.__class__.__name__.lower() - sub.create_mod_site(ist.ModCondition(mod_condition_name, - stmt.residue, stmt.position)) + act_type = mod_acttype_map[stmt.__class__] + enz.create_site(act_type) + sub.create_mod_site(stmt._get_mod_condition()) def modification_monomers_one_step(stmt, agent_set): @@ -1395,27 +1390,14 @@ def phosphorylation_assemble_atp_dependent(stmt, model, parameters, agent_set): # DEMODIFICATION ##################################################### - -def demodification_monomers_interactions_only(stmt, agent_set): - if stmt.enz is None: - return - enz = agent_set.get_create_base_agent(stmt.enz) - sub = agent_set.get_create_base_agent(stmt.sub) - active_site = mod_acttype_map[stmt.__class__] - enz.create_site(active_site) - mod_condition_name = stmt.__class__.__name__.lower()[2:] - sub.create_mod_site(ist.ModCondition(mod_condition_name, - stmt.residue, stmt.position)) - +demodification_monomers_interactions_only = modification_monomers_interactions_only() def demodification_monomers_one_step(stmt, agent_set): if stmt.enz is None: return enz = agent_set.get_create_base_agent(stmt.enz) sub = agent_set.get_create_base_agent(stmt.sub) - mod_condition_name = stmt.__class__.__name__.lower()[2:] - sub.create_mod_site(ist.ModCondition(mod_condition_name, - stmt.residue, stmt.position)) + sub.create_mod_site(stmt._get_mod_condition()) def demodification_monomers_two_step(stmt, agent_set): @@ -1423,9 +1405,7 @@ def demodification_monomers_two_step(stmt, agent_set): return enz = agent_set.get_create_base_agent(stmt.enz) sub = agent_set.get_create_base_agent(stmt.sub) - mod_condition_name = stmt.__class__.__name__.lower()[2:] - sub.create_mod_site(ist.ModCondition(mod_condition_name, - stmt.residue, stmt.position)) + sub.create_mod_site(stmt._get_mod_condition()) # Create site for binding the substrate enz.create_site(get_binding_site_name(stmt.sub)) sub.create_site(get_binding_site_name(stmt.enz)) @@ -1439,10 +1419,8 @@ def demodification_assemble_interactions_only(stmt, model, agent_set, parameters sub = model.monomers[stmt.sub.name] active_site = mod_acttype_map[stmt.__class__] # See NOTE in Phosphorylation.monomers_one_step - demod_condition_name = stmt.__class__.__name__.lower() - mod_condition_name = demod_condition_name[2:] - demod_site = get_mod_site_name(mod_condition_name, - stmt.residue, stmt.position) + mc = stmt._get_mod_condition() + demod_site = get_mod_site_name(stmt._get_mod_condition()) rule_enz_str = get_agent_rule_str(stmt.enz) rule_sub_str = get_agent_rule_str(stmt.sub)
Start unifying mod and demod policies
sorgerlab_indra
train
9e1d506a8cfedef2fdd605e4cbf4bf53651ad214
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -15,9 +15,10 @@ module ActiveSupport def initialize(*addresses) addresses = addresses.flatten + options = addresses.extract_options! addresses = ["localhost"] if addresses.empty? @addresses = addresses - @data = MemCache.new(addresses) + @data = MemCache.new(addresses, options) end def read(key, options = nil) diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index <HASH>..<HASH> 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -18,6 +18,19 @@ class CacheStoreSettingTest < Test::Unit::TestCase assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) assert_equal %w(localhost), store.addresses end + + def test_mem_cache_fragment_cache_store_with_multiple_servers + store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1' + assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) + assert_equal %w(localhost 192.168.1.1), store.addresses + end + + def test_mem_cache_fragment_cache_store_with_options + store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1', :namespace => 'foo' + assert_kind_of(ActiveSupport::Cache::MemCacheStore, store) + assert_equal %w(localhost 192.168.1.1), store.addresses + assert_equal 'foo', store.instance_variable_get('@data').instance_variable_get('@namespace') + end def test_object_assigned_fragment_cache_store store = ActiveSupport::Cache.lookup_store ActiveSupport::Cache::FileStore.new("/path/to/cache/directory")
Support options passed to ActiveSupport::Cache :mem_cache_store [#<I> state:resolved]
rails_rails
train
c73d5bf59b9dc20a6b0708f4d69b6c62f95c6e79
diff --git a/src/org/zaproxy/zap/view/MainToolbarPanel.java b/src/org/zaproxy/zap/view/MainToolbarPanel.java index <HASH>..<HASH> 100644 --- a/src/org/zaproxy/zap/view/MainToolbarPanel.java +++ b/src/org/zaproxy/zap/view/MainToolbarPanel.java @@ -294,7 +294,7 @@ public class MainToolbarPanel extends JPanel { @Override public void actionPerformed(java.awt.event.ActionEvent e) { - View.getSingleton().showSessionDialog(Model.getSingleton().getSession(), null); + Control.getSingleton().getMenuFileControl().properties(); } }); }
Issue <I> - Title not updated when session name is changed through the main tool bar button "Session Properties..." Changed to show the dialogue using the method MenuFileControl#properties() (which already takes care to update the title).
zaproxy_zaproxy
train
16e2a411025c01b517020974cef6587bdbd957bf
diff --git a/tests/unit/views/oxshopcontrolTest.php b/tests/unit/views/oxshopcontrolTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/views/oxshopcontrolTest.php +++ b/tests/unit/views/oxshopcontrolTest.php @@ -347,7 +347,6 @@ class Unit_Views_oxShopControlTest extends OxidTestCase { oxTestModules::addFunction( 'oxUtils', 'isSearchEngine', '{ return false; }' ); oxTestModules::addFunction( 'oxUtils', 'setHeader', '{}' ); - oxTestModules::addFunction( 'oxReverseProxyHeader', 'sendHeader', '{}' ); $sTplPath = modConfig::getInstance()->getConfigParam( 'sShopDir' )."/application/views/"; $sTplPath .= modConfig::getInstance()->getConfigParam( 'sTheme' )."/tpl/page/checkout/basket.tpl"; @@ -386,7 +385,6 @@ class Unit_Views_oxShopControlTest extends OxidTestCase { oxTestModules::addFunction( 'oxUtils', 'isSearchEngine', '{ return false; }' ); oxTestModules::addFunction( 'oxUtils', 'setHeader', '{}' ); - oxTestModules::addFunction( 'oxReverseProxyHeader', 'sendHeader', '{}' ); modConfig::setRequestParameter('renderPartial', 'asd');
Reloading after saving category, as saving causes dependency event to fire and break the test.
OXID-eSales_oxideshop_ce
train
fa7cc42f0f1ef92f28d3bd0a9152c6623e7b0f59
diff --git a/web/undertow/src/main/java/org/seedstack/seed/undertow/internal/UndertowLauncher.java b/web/undertow/src/main/java/org/seedstack/seed/undertow/internal/UndertowLauncher.java index <HASH>..<HASH> 100644 --- a/web/undertow/src/main/java/org/seedstack/seed/undertow/internal/UndertowLauncher.java +++ b/web/undertow/src/main/java/org/seedstack/seed/undertow/internal/UndertowLauncher.java @@ -38,13 +38,11 @@ public class UndertowLauncher implements SeedLauncher { // Start the HTTP server start(serverConfig, undertowConfig); - LOGGER.info("Undertow Web server listening on {}:{}", serverConfig.getHost(), serverConfig.getPort()); } @Override public void shutdown() throws Exception { stop(); - LOGGER.info("Undertow Web server stopped"); undeploy(); } @@ -62,9 +60,6 @@ public class UndertowLauncher implements SeedLauncher { deploy(serverConfig); start(serverConfig, undertowConfig); - - LOGGER.info("Refresh complete, Undertow Web server listening on {}:{}", serverConfig.getHost(), - serverConfig.getPort()); } } @@ -98,11 +93,13 @@ public class UndertowLauncher implements SeedLauncher { undertowPlugin.getSslProvider() ); undertow.start(); + LOGGER.info("Undertow Web server listening on {}:{}", serverConfig.getHost(), serverConfig.getPort()); } private void stop() { if (undertow != null) { undertow.stop(); + LOGGER.info("Undertow Web server stopped"); undertow = null; } }
Update logging lines in undertow launcher
seedstack_seed
train
e3b1788aa3bf14d9c1192d4aa49dc0d2c60eb0d8
diff --git a/client/state/reader/posts/normalization-rules.js b/client/state/reader/posts/normalization-rules.js index <HASH>..<HASH> 100644 --- a/client/state/reader/posts/normalization-rules.js +++ b/client/state/reader/posts/normalization-rules.js @@ -135,11 +135,11 @@ const fastPostNormalizationRules = flow( [ removeStyles, removeElementsBySelector, makeImagesSafe(), - discoverFullBleedImages, makeEmbedsSafe, disableAutoPlayOnEmbeds, disableAutoPlayOnMedia, detectMedia, + discoverFullBleedImages, detectPolls, ] ), createBetterExcerpt,
Reader: move dicoverFullBleedImages to AFTER detectMedia (#<I>)
Automattic_wp-calypso
train
ac0979449d8a5acea1640d4fc3465fd62a9ca872
diff --git a/openpnm/models/physics/ad_dif_mig_conductance.py b/openpnm/models/physics/ad_dif_mig_conductance.py index <HASH>..<HASH> 100644 --- a/openpnm/models/physics/ad_dif_mig_conductance.py +++ b/openpnm/models/physics/ad_dif_mig_conductance.py @@ -62,7 +62,8 @@ def ad_dif_mig(target, throat_valence = throat_valence + "." + ion network = target.project.network - throats = network.throats(target.name) + domain = target._domain + throats = domain.throats(target.name) phase = target.project.find_phase(target) cn = network["throat.conns"][throats] T = phase[throat_temperature][throats]
Using domain.throats instead of network.throats
PMEAL_OpenPNM
train
7d1a419a30f3b931b2d730034e78de9d2bf57d72
diff --git a/opentargets_validator/cli.py b/opentargets_validator/cli.py index <HASH>..<HASH> 100644 --- a/opentargets_validator/cli.py +++ b/opentargets_validator/cli.py @@ -39,13 +39,13 @@ def main(): if not args.schema: logger.error('A --schema <schemafile> has to be specified.') return 1 - + if args.data_source_file == '-': validate(sys.stdin,args.schema, args.loglines) else: with URLZSource(args.data_source_file, args.loglines).open() as fh: - validate(fh,args.schema) - + validate(fh, args.schema, args.loglines) + return 0 diff --git a/opentargets_validator/validator.py b/opentargets_validator/validator.py index <HASH>..<HASH> 100644 --- a/opentargets_validator/validator.py +++ b/opentargets_validator/validator.py @@ -10,7 +10,7 @@ def validate(file_descriptor, schema_uri, loglines): l = LogAccum(logger,error_lines if error_lines < 1024 else 1024) line_counter = 1 parsed_line = None - + validator = generate_validator_from_schema(schema_uri) for line in file_descriptor: @@ -22,27 +22,27 @@ def validate(file_descriptor, schema_uri, loglines): t1 = time.time() validation_errors = [str(e) for e in validator.iter_errors(parsed_line)] t2 = time.time() - + if validation_errors: # here I have to log all fails to logger and elastic error_messages = ' '.join(validation_errors).replace('\n', ' ; ').replace('\r', '') - + error_messages_len = len(error_messages) - + # capping error message to 2048 error_messages = error_messages if error_messages_len <= 2048 \ else error_messages[:2048] + ' ; ...' - + l.log(logging.ERROR, 'failed validating line %i ' 'eval %s secs with these errors %s', line_counter, str(t2 - t1), error_messages) - + error_lines -= 1 if error_lines <= 0: l.flush(True) logger.warning('too many errors parsing the file, so exiting') return - + line_counter += 1 - - l.flush(True) \ No newline at end of file + + l.flush(True)
fix: validate argument missing if using with positioned arg file
opentargets_validator
train
d2d94b04cfd544c80b61377871763420e23a54d3
diff --git a/lib/venice/in_app_receipt.rb b/lib/venice/in_app_receipt.rb index <HASH>..<HASH> 100644 --- a/lib/venice/in_app_receipt.rb +++ b/lib/venice/in_app_receipt.rb @@ -55,7 +55,7 @@ module Venice @expires_at = Time.at(attributes['expires_date_ms'].to_i / 1000) if attributes['expires_date_ms'] # cancellation_date is in ms since the Epoch, Time.at expects seconds - @cancellation_date = Time.at(attributes['cancellation_date'].to_i / 1000) if attributes['cancellation_date'] + @cancellation_at = Time.at(attributes['cancellation_date'].to_i / 1000) if attributes['cancellation_date'] if attributes['original_transaction_id'] || attributes['original_purchase_date'] original_attributes = {
Change @cancellation_date to @cancellation_at (#<I>)
nomad_venice
train
6a0ef1c3ae2b08542871f576a2bbd1d893268570
diff --git a/packages/girder-ui/src/admin/components/add-user/index.js b/packages/girder-ui/src/admin/components/add-user/index.js index <HASH>..<HASH> 100644 --- a/packages/girder-ui/src/admin/components/add-user/index.js +++ b/packages/girder-ui/src/admin/components/add-user/index.js @@ -7,11 +7,10 @@ import PersonIcon from '@material-ui/icons/Person'; const styles = () => ({ root: { - margin:'50px 10px 0' + marginTop:'50px' }, paper: { - backgroundColor:'#37474F', - marginBottom:'5px' + backgroundColor:'#37474F' }, typography: { textAlign:'center', diff --git a/packages/girder-ui/src/admin/components/groups/index.js b/packages/girder-ui/src/admin/components/groups/index.js index <HASH>..<HASH> 100644 --- a/packages/girder-ui/src/admin/components/groups/index.js +++ b/packages/girder-ui/src/admin/components/groups/index.js @@ -3,23 +3,15 @@ import PropTypes from 'prop-types'; import moment from 'moment' import { - withStyles, Table, TableHead, TableBody, TableRow, TableCell, Link, Paper + Table, TableHead, TableBody, TableRow, TableCell, Link, Paper } from '@material-ui/core'; import DeleteIcon from '@material-ui/icons/Delete'; -const styles = () => ({ - root: { - margin:'20px', - maxWidth:'100%', - padding:'5px' - }, -}); - class Groups extends Component { render() { - const {listOfGroups, classes} = this.props; + const {listOfGroups} = this.props; return( - <Paper className={classes.root}> + <Paper> <Table> <TableHead> <TableRow> @@ -69,4 +61,4 @@ Groups.defaultProps = { listOfGroups: [] } -export default withStyles(styles)(Groups); +export default Groups; diff --git a/packages/girder-ui/src/admin/components/members/index.js b/packages/girder-ui/src/admin/components/members/index.js index <HASH>..<HASH> 100644 --- a/packages/girder-ui/src/admin/components/members/index.js +++ b/packages/girder-ui/src/admin/components/members/index.js @@ -10,15 +10,11 @@ import React, { Component } from 'react'; import moment from 'moment' const styles = () => ({ - root: { - margin:'10px' - }, header: { textAlign:'center' }, paper: { backgroundColor:'#37474F', - display:'flex', justifyContent:'space-between', marginBottom:'5px' }, @@ -37,7 +33,7 @@ class Members extends Component { render() { const {group, listOfMembers, search, classes} = this.props; return( - <div className={classes.root}> + <div> <Typography className={classes.header} variant='h4' gutterBottom> {group.name} </Typography> diff --git a/packages/girder-ui/src/admin/components/users/index.js b/packages/girder-ui/src/admin/components/users/index.js index <HASH>..<HASH> 100644 --- a/packages/girder-ui/src/admin/components/users/index.js +++ b/packages/girder-ui/src/admin/components/users/index.js @@ -8,10 +8,6 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; const styles = () => ({ - root: { - paddingTop:'5px', - margin:'10px' - }, typography: { textAlign: 'center' }, @@ -27,7 +23,7 @@ class Users extends Component { <Typography className={classes.typography} variant='subtitle1'> Showing search results for {query}: </Typography> - <Paper className={classes.root}> + <Paper> <Table> <TableHead> <TableRow>
Remove unused styling The PageHead and PageBody components take care of a lot of the needed layout styling. Remove redundant code.
OpenChemistry_oc-web-components
train
84ca4e25a3cd40dfdaa50743f7892fc28446dbc0
diff --git a/hazelcast/src/main/java/com/hazelcast/nio/tcp/TcpIpConnectionManager.java b/hazelcast/src/main/java/com/hazelcast/nio/tcp/TcpIpConnectionManager.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/nio/tcp/TcpIpConnectionManager.java +++ b/hazelcast/src/main/java/com/hazelcast/nio/tcp/TcpIpConnectionManager.java @@ -72,7 +72,7 @@ public class TcpIpConnectionManager implements ConnectionManager, PacketHandler // TODO Introducing this to allow disabling the spoofing checks on-demand // if there is a use-case that gets affected by the change. If there are no reports of misbehaviour we can remove than in // next release. - private static final boolean SPOOFING_CHECKS = parseBoolean(getProperty("hazelcast.nio.tcp.spoofing.checks", "true")); + private static final boolean SPOOFING_CHECKS = parseBoolean(getProperty("hazelcast.nio.tcp.spoofing.checks", "false")); final LoggingService loggingService;
Disable spoofing checks by default (#<I>)
hazelcast_hazelcast
train
46bf85895569413118ccc2a87237e72f4d52af84
diff --git a/src/system/modules/metamodelsattribute_tags/MetaModelAttributeTags.php b/src/system/modules/metamodelsattribute_tags/MetaModelAttributeTags.php index <HASH>..<HASH> 100644 --- a/src/system/modules/metamodelsattribute_tags/MetaModelAttributeTags.php +++ b/src/system/modules/metamodelsattribute_tags/MetaModelAttributeTags.php @@ -84,7 +84,7 @@ class MetaModelAttributeTags extends MetaModelAttributeComplex // TODO: add tree support here. $arrFieldDef=parent::getFieldDefinition($arrOverrides); $arrFieldDef['inputType'] = 'checkbox'; - $arrFieldDef['options'] = $this->getFilterOptions(NULL, true); + $arrFieldDef['options'] = $this->getFilterOptions(NULL, false); $arrFieldDef['eval']['includeBlankOption'] = true; $arrFieldDef['eval']['multiple'] = true; return $arrFieldDef;
Add bugfix. Change the "usedonly" from true to false to show all options in BE mode
MetaModels_attribute_tags
train
5a0a13aecc280f2beec151209a8486af19fb4b5f
diff --git a/src/Form/Field/Type/ObjectIdType.php b/src/Form/Field/Type/ObjectIdType.php index <HASH>..<HASH> 100644 --- a/src/Form/Field/Type/ObjectIdType.php +++ b/src/Form/Field/Type/ObjectIdType.php @@ -11,6 +11,7 @@ use Dms\Core\Form\IFieldProcessor; use Dms\Core\Model\IIdentifiableObjectSet; use Dms\Core\Model\Type\Builder\Type; use Dms\Core\Model\Type\IType as IPhpType; +use Dms\Core\Persistence\IRepository; /** * The object id type class. @@ -64,10 +65,16 @@ class ObjectIdType extends FieldType */ protected function buildProcessors() : array { + if ($this->objects instanceof IRepository) { + $inputType = Type::int()->nullable(); + } else { + $inputType = Type::string()->union(Type::int())->nullable(); + } + $processors = [ new EmptyStringToNullProcessor(Type::mixed()), new ObjectIdProcessor(Type::mixed()), - new ObjectIdValidator(Type::string()->union(Type::int())->nullable(), $this->objects), + new ObjectIdValidator($inputType, $this->objects), ]; if ($this->loadAsObjects) {
Update the object ids to only accept integers for repository data sources
dms-org_core
train
7eb16db8e39f402e4fdb1de01fd8e65dd9ea17b5
diff --git a/.rubocop.yml b/.rubocop.yml index <HASH>..<HASH> 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -2,8 +2,7 @@ Layout/IndentArray: Enabled: false Metrics/BlockLength: - Exclude: - - spec/**/*.rb + Enabled: false Metrics/LineLength: Max: 100 diff --git a/lib/increments/schedule.rb b/lib/increments/schedule.rb index <HASH>..<HASH> 100644 --- a/lib/increments/schedule.rb +++ b/lib/increments/schedule.rb @@ -45,14 +45,7 @@ module Increments end def winter_vacation_day?(date = Date.today) - case date.month - when 1 - first_three_days_or_adjoining_weekend?(date) - when 12 - last_four_days_or_after_last_saturday?(date) - else - false - end + WinterVacationSchedule.new(date).winter_vacation? end alias winter_vacation? winter_vacation_day? @@ -71,25 +64,85 @@ module Increments end end - private + WinterVacationSchedule = Struct.new(:date) do + def winter_vacation? + year_end_vacation.days.include?(date) || new_year_vacation.days.include?(date) + end - def first_three_days_or_adjoining_weekend?(date) - jan_3 = ExtendedDate.new(date.year, 1, 3) - return true if date <= jan_3 + private - first_sunday = ExtendedDate.new(date.year, 1, 1).find_next(&:sunday?) - return false unless date.between?(jan_3, first_sunday) + def year_end_vacation + @year_end_vacation ||= YearEndVacation.new(date.year) + end - jan_3.next_day.upto(first_sunday).all? { |d| weekend?(d) } - end + def new_year_vacation + @new_year_vacation ||= NewYearVacation.new(date.year) + end + + YearEndVacation = Struct.new(:year) do + def days + beginning_day..dec_31 + end + + def beginning_day + if coupled_new_year_vacation.days.count >= 5 + last_saturday + else + [dec_28, last_saturday].min + end + end + + def dec_28 + @dec_28 ||= Date.new(year, 12, 28) + end + + def dec_31 + @dec_31 ||= Date.new(year, 12, 31) + end + + def last_saturday + @last_saturday ||= dec_31.find_previous(&:saturday?) + end - def last_four_days_or_after_last_saturday?(date) - return true if date.day >= 28 + def coupled_new_year_vacation + @coupled_new_year_vacation ||= NewYearVacation.new(year + 1) + end + end + + NewYearVacation = Struct.new(:year) do + def days + jan_1..end_day + end - date >= ExtendedDate.new(date.year, 12, 31).find_previous(&:saturday?) + def end_day + return jan_3 if first_sunday <= jan_3 + + if first_weekend_almost_adjoins_jan_3? + first_sunday + else + jan_3 + end + end + + def first_weekend_almost_adjoins_jan_3? + jan_3.next_day.upto(first_sunday).all? { |d| d.friday? || d.saturday? || d.sunday? } + end + + def first_sunday + @first_sunday ||= jan_1.find_next(&:sunday?) + end + + def jan_1 + @jan_1 ||= Date.new(year, 1, 1) + end + + def jan_3 + @jan_3 ||= Date.new(year, 1, 3) + end + end end - class ExtendedDate < Date + class Date < Date INFINITY_FUTURE = Date.new(10_000, 1, 1) INFINITY_PAST = Date.new(0, 1, 1) diff --git a/spec/increments/schedule_spec.rb b/spec/increments/schedule_spec.rb index <HASH>..<HASH> 100644 --- a/spec/increments/schedule_spec.rb +++ b/spec/increments/schedule_spec.rb @@ -223,6 +223,28 @@ module Increments it { should be false } end end + + context 'on 2018-2019' do + context 'with December 28 2018' do + let(:date) { Date.new(2018, 12, 28) } + it { should be false } + end + + context 'with December 29 2018' do + let(:date) { Date.new(2018, 12, 29) } + it { should be true } + end + + context 'with January 6 2019' do + let(:date) { Date.new(2019, 1, 6) } + it { should be true } + end + + context 'with January 7 2019' do + let(:date) { Date.new(2019, 1, 7) } + it { should be false } + end + end end end end
Support <I>-<I> season in .winter_vacation?
increments_increments-schedule
train
60dc6b17ac3e8ea1755363853a0c51de03bc2326
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -42,7 +42,8 @@ "phpro/grumphp": "^0.11.6", "phpstan/phpstan": "^0.8", "phpunit/phpunit": "^5.7", - "sensiolabs/security-checker": "^4.1" + "sensiolabs/security-checker": "^4.1", + "sebastian/phpcpd": "^3.0" }, "bin": [ "bin/bunq-install" diff --git a/src/Security/KeyPair.php b/src/Security/KeyPair.php index <HASH>..<HASH> 100644 --- a/src/Security/KeyPair.php +++ b/src/Security/KeyPair.php @@ -21,16 +21,30 @@ class KeyPair const PRIVATE_KEY_LENGTH = 2048; const PRIVATE_KEY_ALGORITHM = "sha512"; - /** @var PrivateKey */ + /** + * @var PrivateKey + */ protected $privateKey; - /** @var PublicKey */ + /** + * @var PublicKey + */ protected $publicKey; /** + * @param PrivateKey $privateKey + * @param PublicKey $publicKey + */ + public function __construct(PrivateKey $privateKey, PublicKey $publicKey) + { + $this->privateKey = $privateKey; + $this->publicKey = $publicKey; + } + + /** * @return static */ - public static function generate() + public static function generate(): KeyPair { $opensslKeyPair = openssl_pkey_new([ self::FIELD_KEY_ALGORITHM => self::PRIVATE_KEY_ALGORITHM, @@ -46,28 +60,18 @@ class KeyPair } /** - * @param PrivateKey $privateKey - * @param PublicKey $publicKey + * @return PrivateKey */ - public function __construct(PrivateKey $privateKey, PublicKey $publicKey) + public function getPrivateKey(): PrivateKey { - $this->privateKey = $privateKey; - $this->publicKey = $publicKey; + return $this->privateKey; } /** * @return PublicKey */ - public function getPublicKey() + public function getPublicKey(): PublicKey { return $this->publicKey; } - - /** - * @return PrivateKey - */ - public function getPrivateKey() - { - return $this->privateKey; - } } diff --git a/src/Security/PrivateKey.php b/src/Security/PrivateKey.php index <HASH>..<HASH> 100644 --- a/src/Security/PrivateKey.php +++ b/src/Security/PrivateKey.php @@ -11,7 +11,7 @@ class PrivateKey protected $key; /** - * @param $key + * @param resource $key */ public function __construct($key) { @@ -23,7 +23,7 @@ class PrivateKey * * @return string */ - public function sign($dataToSign) + public function sign(string $dataToSign): string { openssl_sign($dataToSign, $signature, $this->getKey(), OPENSSL_ALGO_SHA256); @@ -31,21 +31,20 @@ class PrivateKey } /** - * @return string + * @return resource */ - public function export() + public function getKey() { - openssl_pkey_export($this->getKey(), $privateKeyString); - - return $privateKeyString; + return $this->key; } - /** - * @return resource + * @return string */ - public function getKey() + public function export(): string { - return $this->key; + openssl_pkey_export($this->getKey(), $privateKeyString); + + return $privateKeyString; } } diff --git a/src/Security/PublicKey.php b/src/Security/PublicKey.php index <HASH>..<HASH> 100644 --- a/src/Security/PublicKey.php +++ b/src/Security/PublicKey.php @@ -6,12 +6,12 @@ namespace bunq\Security; class PublicKey { /** - * @var string + * @var resource */ protected $key; /** - * @param $key + * @param resource $key */ public function __construct($key) { @@ -19,22 +19,22 @@ class PublicKey } /** - * @return string - */ - public function getKey() - { - return $this->key; - } - - /** * @param string $dataToEncrypt * * @return string */ - public function encrypt($dataToEncrypt) + public function encrypt(string $dataToEncrypt): string { openssl_public_encrypt($dataToEncrypt, $encrypted, $this->getKey()); return $encrypted; } + + /** + * @return resource + */ + public function getKey() + { + return $this->key; + } }
Add missing phpcd; fix types of Security [#<I>]
bunq_sdk_php
train
2844ce4f9dd0669c7e84234744519184d5da80e5
diff --git a/luaparser/__init__.py b/luaparser/__init__.py index <HASH>..<HASH> 100644 --- a/luaparser/__init__.py +++ b/luaparser/__init__.py @@ -1 +1 @@ -__version__ = '2.0.2' +__version__ = '2.1.2'
version: bump to <I>
boolangery_py-lua-parser
train
2f88b3c2b482dd15c2abe1c67a142ddfcb9d8501
diff --git a/acceptance/lib/puppet/acceptance/install_utils.rb b/acceptance/lib/puppet/acceptance/install_utils.rb index <HASH>..<HASH> 100644 --- a/acceptance/lib/puppet/acceptance/install_utils.rb +++ b/acceptance/lib/puppet/acceptance/install_utils.rb @@ -151,7 +151,7 @@ module Puppet platform_configs_dir ) - link = "http://%s/%s/%s/repos/%s/%s%s/products/%s/" % [ + link = "http://%s/%s/%s/repos/%s/%s%s/PC1/%s/" % [ tld, project, sha, @@ -162,6 +162,20 @@ module Puppet ] if not link_exists?(link) + logger.notify("Could not find PC1 repository at: #{link}") + link = "http://%s/%s/%s/repos/%s/%s%s/products/%s/" % [ + tld, + project, + sha, + variant, + fedora_prefix, + version, + arch + ] + end + + if not link_exists?(link) + logger.notify("Could not find repository at: #{link}") link = "http://%s/%s/%s/repos/%s/%s%s/devel/%s/" % [ tld, project, @@ -172,9 +186,12 @@ module Puppet arch ] end + if not link_exists?(link) raise "Unable to reach a repo directory at #{link}" end + + logger.notify("fetching repository from #{link}") repo_dir = fetch_remote_dir(link, platform_configs_dir) repo_loc = "/root/#{project}" @@ -194,6 +211,7 @@ module Puppet version = $2 arch = $3 + # If this isn't outdated yet it will be by end of week (4/3/2015) deb = fetch( "http://apt.puppetlabs.com/", "puppetlabs-release-%s.deb" % version, @@ -216,8 +234,13 @@ module Puppet scp_to host, list, repo_loc scp_to host, repo_dir, repo_loc + pc1_check = on(host, + "[[ -d /root/#{project}/#{version}/pool/PC1 ]]", + :acceptable_exit_codes => [0,1]) + + repo_name = pc1_check.exit_code == 0 ? 'PC1' : 'main' on host, "cp #{repo_loc}/*.list /etc/apt/sources.list.d" - on host, "find /etc/apt/sources.list.d/ -name \"*.list\" -exec sed -i \"s/deb\\s\\+http:\\/\\/#{tld}.*$/deb file:\\/\\/\\/root\\/#{project}\\/#{version} #{version} main/\" {} \\;" + on host, "find /etc/apt/sources.list.d/ -name \"*.list\" -exec sed -i \"s/deb\\s\\+http:\\/\\/#{tld}.*$/deb file:\\/\\/\\/root\\/#{project}\\/#{version} #{version} #{repo_name}/\" {} \\;" on host, "dpkg -i --force-all #{repo_loc}/*.deb" on host, "apt-get update" else
(maint) Ensure AIO pre-suite uses PC1 repositories Prior to this we were installing repositories for products/devel or main (for rpms and debs respectively). Now AIO packages will be in a repository called PC1. This adds checks to the repository set up steps so that PC1 will be tried first. Once packaging is fully switched over will need to remove references to older repositories.
puppetlabs_puppet
train
fb54bddae9d460e227bfff77724e066b4a0ca522
diff --git a/redis/typing.py b/redis/typing.py index <HASH>..<HASH> 100644 --- a/redis/typing.py +++ b/redis/typing.py @@ -16,7 +16,7 @@ EncodedT = Union[bytes, memoryview] DecodedT = Union[str, int, float] EncodableT = Union[EncodedT, DecodedT] AbsExpiryT = Union[int, datetime] -ExpiryT = Union[float, timedelta] +ExpiryT = Union[int, timedelta] ZScoreBoundT = Union[float, str] # str allows for the [ or ( prefix BitfieldOffsetT = Union[int, str] # str allows for #x syntax _StringLikeT = Union[bytes, str, memoryview]
Fix type hint annotations of expire time (#<I>) * fix typehint annotations of expire time. `ExpiryT` includes `float` type, but params of expiry-time (`ex`, `px`) for methods such as `set`, `expire`, `setnx`, etc. , should be `int`, not `float`. * add `IntExpiryT` annotation. * minor fix. * minor fix.
andymccurdy_redis-py
train
e5f96f67ab9c523bececaae528b6021df86223ef
diff --git a/lib/extensions/debugger/debugger.rb b/lib/extensions/debugger/debugger.rb index <HASH>..<HASH> 100644 --- a/lib/extensions/debugger/debugger.rb +++ b/lib/extensions/debugger/debugger.rb @@ -62,7 +62,14 @@ def get_variables(scope) vars = eval(prefix + cmd, $_binding) $_s.write("VSTART:#{vartype}\n") vars.each do |v| - $_s.write("V:#{vartype}:#{v}:#{eval(v,$_binding).inspect}\n") + if v !~ /^\$(=|KCODE)$/ + begin + result = eval(v,$_binding).inspect + rescue Exception => exc + result = "#{$!}".inspect + end + $_s.write("V:#{vartype}:#{v}:#{result}\n") + end end $_s.write("VEND:#{vartype}\n") rescue @@ -70,7 +77,7 @@ def get_variables(scope) end def log_command(cmd) - puts "[Debugger] Received command: #{cmd}" + # puts "[Debugger] Received command: #{cmd}" end def debug_handle_cmd(inline)
debugger extension: watch list improved, log cleaned
rhomobile_rhodes
train
dbe649c69f084d3e9500fd1e07869392b5e1749e
diff --git a/spec/integration/ssh_spec.rb b/spec/integration/ssh_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration/ssh_spec.rb +++ b/spec/integration/ssh_spec.rb @@ -39,25 +39,20 @@ describe Gas::Ssh do it 'should detect when an id_rsa is already in the .gas directory', :current => true do Gas::Ssh.corresponding_rsa_files_exist?(@uid).should be_true end - end describe "File System Changes..." do - before :all do - @gas_dir = File.expand_path('~/.gas') - @ssh_dir = File.expand_path('~/.ssh') - + # @gas_dir = File.expand_path('~/.gas') + # @ssh_dir = File.expand_path('~/.ssh') @nickname = "thisaccountmaybedeletedmysteriously" @name = "tim T" @email = "tim@timmy.com" - `rm #{@gas_dir}/#{@nickname}_id_rsa` - `rm #{@gas_dir}/#{@nickname}_id_rsa.pub` + #`rm #{@gas_dir}/#{@nickname}_id_rsa` + #`rm #{@gas_dir}/#{@nickname}_id_rsa.pub` Gas.delete(@nickname) - - # make sure that nickname isn't in use end
commented out some junk in a before filter that probably can be removed
walle_gas
train
3f17e433191497b5b2692bbad93ea0db52e416aa
diff --git a/devices/osram.js b/devices/osram.js index <HASH>..<HASH> 100644 --- a/devices/osram.js +++ b/devices/osram.js @@ -83,7 +83,7 @@ module.exports = [ model: 'AC03642', vendor: 'OSRAM', description: 'SMART+ CLASSIC A 60 TW', - extend: extend.ledvance.light_onoff_brightness_colortemp(), + extend: extend.ledvance.light_onoff_brightness_colortemp({colorTempRange: [153, 370]}), ota: ota.ledvance, }, {
Add color temp range for AC<I> (#<I>) * Update osram.js AC<I> doesn't suppport color_temp_startup and temperature-range is <I>-<I> mired. * Update osram.js
Koenkk_zigbee-shepherd-converters
train
c0d762748ec2186d5c51613c3af94b08ce52b6fe
diff --git a/Main.py b/Main.py index <HASH>..<HASH> 100755 --- a/Main.py +++ b/Main.py @@ -21,13 +21,16 @@ def usage(): """ Prints the usage of the todo.txt CLI """ exit(1) -def arguments(): +def arguments(p_start=2): """ Retrieves all values from the argument list starting from the given position. + + This is a parameter, because argv has a different structure when no + subcommand was given and it fallbacks to the default subcommand. """ try: - values = sys.argv[2:] # strip off subcommand at position 1 + values = sys.argv[p_start:] except IndexError: usage() @@ -69,16 +72,18 @@ class CLIApplication(object): 'pri': PriorityCommand, } - if subcommand in subcommand_map: - command = subcommand_map[subcommand](arguments(), self.todolist, - lambda o: sys.stdout.write(o + "\n"), - lambda e: sys.stderr.write(e + "\n"), - raw_input) + args = arguments() + if not subcommand in subcommand_map: + subcommand = Config.DEFAULT_ACTION + args = arguments(1) + + command = subcommand_map[subcommand](args, self.todolist, + lambda o: sys.stdout.write(o + "\n"), + lambda e: sys.stderr.write(e + "\n"), + raw_input) - if not command.execute(): - exit(1) - else: - usage() + if not command.execute(): + exit(1) if self.todolist.is_dirty(): todofile.write(str(self.todolist))
When the default subcommand is invoked, make sure that all arguments are passed to that subcommand. This is achieved by overriding the start position of where to take the arguments in argv.
bram85_topydo
train
d6d55233100c28e3524df9005bbd821653b345f1
diff --git a/src/core.js b/src/core.js index <HASH>..<HASH> 100644 --- a/src/core.js +++ b/src/core.js @@ -475,7 +475,7 @@ function QTip(target, options, id, attr) isAncestor = elem.parents(selector).filter(tooltip[0]).length > 0; if(elem[0] !== target[0] && elem[0] !== tooltip[0] && !isAncestor && - !target.has(elem[0]).length && !elem.attr('disabled') + !target.has(elem[0]).length && enabled ) { self.hide(event); }
Update src/core.js Prevent hiding qTip on unfocus (document click) when it is disabled
qTip2_qTip2
train
79e774e9642ea38c62b090353e1156959f1ff492
diff --git a/source/php/AcfFields/json/mod-contacts.json b/source/php/AcfFields/json/mod-contacts.json index <HASH>..<HASH> 100644 --- a/source/php/AcfFields/json/mod-contacts.json +++ b/source/php/AcfFields/json/mod-contacts.json @@ -188,11 +188,11 @@ "class": "", "id": "" }, - "min": 0, - "max": 0, + "collapsed": "", + "min": "", + "max": "", "layout": "table", "button_label": "L\u00e4gg till nummer", - "collapsed": "", "sub_fields": [ { "key": "field_5805e64a94d10", @@ -200,7 +200,7 @@ "name": "number", "type": "text", "instructions": "", - "required": 1, + "required": 0, "conditional_logic": 0, "wrapper": { "width": "", @@ -208,10 +208,10 @@ "id": "" }, "default_value": "", - "maxlength": "", "placeholder": "", "prepend": "", - "append": "" + "append": "", + "maxlength": "" } ] }, diff --git a/source/php/AcfFields/php/mod-contacts.php b/source/php/AcfFields/php/mod-contacts.php index <HASH>..<HASH> 100644 --- a/source/php/AcfFields/php/mod-contacts.php +++ b/source/php/AcfFields/php/mod-contacts.php @@ -191,11 +191,11 @@ 'class' => '', 'id' => '', ), - 'min' => 0, - 'max' => 0, + 'collapsed' => '', + 'min' => '', + 'max' => '', 'layout' => 'table', 'button_label' => 'Lägg till nummer', - 'collapsed' => '', 'sub_fields' => array( 0 => array( 'key' => 'field_5805e64a94d10', @@ -203,7 +203,7 @@ 'name' => 'number', 'type' => 'text', 'instructions' => '', - 'required' => 1, + 'required' => 0, 'conditional_logic' => 0, 'wrapper' => array( 'width' => '', @@ -211,10 +211,10 @@ 'id' => '', ), 'default_value' => '', - 'maxlength' => '', 'placeholder' => '', 'prepend' => '', 'append' => '', + 'maxlength' => '', ), ), ), diff --git a/source/php/Module/Contacts/Contacts.php b/source/php/Module/Contacts/Contacts.php index <HASH>..<HASH> 100644 --- a/source/php/Module/Contacts/Contacts.php +++ b/source/php/Module/Contacts/Contacts.php @@ -102,11 +102,6 @@ class Contacts extends \Modularity\Module $info['thumbnail'] = array($info['image'], 250, 250, false); } - //Block numbers that are to short - if (strlen($info['phone']) < 4) { - $info['phone'] = ""; - } - //Create full name $info['full_name'] = trim($info['first_name'] . ' ' . $info['last_name']);
Removes the requirement of a phone number
helsingborg-stad_Modularity
train
026c7401c3953c644ba8a58ec5bfa474a5ead774
diff --git a/docroot/sites/default/settings.php b/docroot/sites/default/settings.php index <HASH>..<HASH> 100644 --- a/docroot/sites/default/settings.php +++ b/docroot/sites/default/settings.php @@ -712,6 +712,37 @@ if (isset($_ENV['AH_SITE_ENVIRONMENT'])) { // if (file_exists(__DIR__ . '/settings.dev.php')) { // include __DIR__ . '/settings.dev.php'; // } + + $databases['legacy'] = [ + 'default' => [ + 'database' => 'ymcatwincdb78901', + 'username' => 's19044', + 'password' => 'YASRSkorw8gnC4d', + 'host' => '127.0.0.1', + ], + ]; + break; + + case 'stage': + $databases['legacy'] = [ + 'default' => [ + 'database' => 'E5g2tZkwSrjeUbv', + 'username' => 's19045', + 'password' => 'YASRSkorw8gnC4d', + 'host' => '127.0.0.1', + ], + ]; + break; + + case 'prod'; + $databases['legacy'] = [ + 'default' => [ + 'database' => 'ymcatwincdb78902', + 'username' => 's19043', + 'password' => 'eGEH5VCMimW7FC5', + 'host' => '127.0.0.1', + ], + ]; break; } }
Add settings for legacy db for Acquia
ymcatwincities_openy
train
3c7f41c913c2a934b78238ef373990b0eaf7ccf9
diff --git a/src/Auth/FootprintAwareTrait.php b/src/Auth/FootprintAwareTrait.php index <HASH>..<HASH> 100644 --- a/src/Auth/FootprintAwareTrait.php +++ b/src/Auth/FootprintAwareTrait.php @@ -141,8 +141,7 @@ trait FootprintAwareTrait */ protected function _getUserInstanceFromArray($user) { - $primaryKey = TableRegistry::get($this->_userModel)->primaryKey(); - $options = ['accessibleFields' => [$primaryKey => true]]; + $options = ['accessibleFields' => ['*' => true], 'validate' => false]; return $this->_circumventEventManager('newEntity', [$user, $options]); }
Minimize unnecessary validation/guarding
UseMuffin_Footprint
train
c0a8e9a1530b9c367d51599ca985e4fd4d8f20b3
diff --git a/cassandra_test.go b/cassandra_test.go index <HASH>..<HASH> 100644 --- a/cassandra_test.go +++ b/cassandra_test.go @@ -612,13 +612,6 @@ func injectInvalidPreparedStatement(t *testing.T, session *Session, table string TypeInfo: &TypeInfo{ Type: TypeVarchar, }, - }, ColumnInfo{ - Keyspace: "gocql_test", - Table: table, - Name: "bar", - TypeInfo: &TypeInfo{ - Type: TypeInt, - }, }}, } conn.prepMu.Unlock()
Removed extraneous query args that cause the test to fail now that the arg length is being checked
gocql_gocql
train
835cc3a696231a49fcd85b4e7f479a158d5a8b74
diff --git a/lib/beanstalk_client.js b/lib/beanstalk_client.js index <HASH>..<HASH> 100644 --- a/lib/beanstalk_client.js +++ b/lib/beanstalk_client.js @@ -44,8 +44,9 @@ BeanstalkJob.create = function(data) { // ##Internal command object -function BeanstalkCommand(obj) { +function BeanstalkCommand(obj, isRaw) { this._obj = obj; + this._isRaw = isRaw events.EventEmitter.call(this); }; util.inherits(BeanstalkCommand, events.EventEmitter); @@ -156,8 +157,10 @@ BeanstalkCommand.prototype.responseHandler = function(data, callback) { Debug.log( 'responseHandler waiting for more' ); this.multiBuffer = dataString; - // Store the buffer - this.rawBuffers.push(data); + if(this._isRaw) { + // Store the buffer because <data> is not completed yet + this.rawBuffers.push(data); + } this.multiErrorTimer = setTimeout(function () { self.emit('command_error', chunks); @@ -187,14 +190,20 @@ BeanstalkCommand.prototype.responseHandler = function(data, callback) { chunks.shift(); if(jobdata) { - // Accumulate last chunk, deep copy of this.rawBuffers (prototype), - // and concatenate all buffers - this.rawBuffers.push(data); - var rawBuffersCopy = this.rawBuffers.slice(); - var reserveOutput = Buffer.concat(rawBuffersCopy); - chunks.pop(); - chunks.push(this.extractDataReserveOutput(reserveOutput)); + + if(this._isRaw) { + // Append last buffer, full copy of the array (prototype), + // create the full buffer and extract <data> + this.rawBuffers.push(data); + var rawBuffersCopy = this.rawBuffers.slice(); + this.rawBuffers.length = 0; + var reserveOutput = Buffer.concat(rawBuffersCopy); + chunks.push(this._extractDataReserveOutput(reserveOutput)); + } else { + chunks.push(jobdata); + } + chunks = BeanstalkJob.create(chunks); } } @@ -210,7 +219,7 @@ BeanstalkCommand.prototype.responseHandler = function(data, callback) { * Extract <data> from the full response for reserve command looking for * the first "\r\n" aparition. */ -BeanstalkCommand.prototype.extractDataReserveOutput = function(buff) { +BeanstalkCommand.prototype._extractDataReserveOutput = function(buff) { var i; var length = buff.length; @@ -229,6 +238,7 @@ function BeanstalkClient() { this.address = '127.0.0.1'; this.port = 11300; + this.isRaw = false; this.conn; this.default_priority = 10; this.reserve_multichunk_timeout = 500; @@ -239,15 +249,17 @@ function BeanstalkClient() { util.inherits(BeanstalkClient, events.EventEmitter); // Singleton like method that returns an instance -BeanstalkClient.prototype.Instance = function(config) { +BeanstalkClient.prototype.Instance = function(config, isRaw) { if (config) { if (typeof config == 'string') { var c = config.split(':'); this.address = c[0] || this.address; this.port = c[1] || this.port; + this.isRaw = isRaw || this.isRaw; } else { this.address = config.address || this.address; this.port = config.port || this.port; + this.isRaw = config.isRaw || this.isRaw; } } @@ -258,7 +270,7 @@ BeanstalkClient.prototype.Instance = function(config) { BeanstalkClient.prototype.command = function(obj) { var _self = this; obj.reserve_multichunk_timeout = this.reserve_multichunk_timeout; - var cmd = new BeanstalkCommand(obj); + var cmd = new BeanstalkCommand(obj, this.isRaw); // pushes commands to the server var requestExec = function() { @@ -629,9 +641,9 @@ BeanstalkClient.prototype._createPutCommand = function(data, priority, delay, tt }; // ##Exposed to node -var Beanstalk = function(server) { +var Beanstalk = function(server, isRaw) { var c = new BeanstalkClient; - return c.Instance(server); + return c.Instance(server, isRaw); }; exports.Client = Beanstalk;
Added a new flag 'isRaw' to the constructor so, you can decide if your 'reserves' commands will return a String (isRaw=false) or a Bufffer (isRaw=true)
pascalopitz_nodestalker
train
9ae06199452606b4d54269dc67e3ea3db8459ce5
diff --git a/lib/phoney/formatter.rb b/lib/phoney/formatter.rb index <HASH>..<HASH> 100644 --- a/lib/phoney/formatter.rb +++ b/lib/phoney/formatter.rb @@ -92,7 +92,7 @@ module PhoneNumber return format(input, prefix.gsub(/[\\+0-9]/, '#'), fill: '') if input =~ regexp - if (input.start_with?('+') && input[1..-1] =~ regexp) + if (input.start_with?('+') && (stripped_prefix.start_with?(input[1..-1]) || input[1..-1] =~ regexp)) return format(input, '#'+prefix.gsub(/[\\+0-9]/, '#'), fill: '') end end diff --git a/test/formatter_test.rb b/test/formatter_test.rb index <HASH>..<HASH> 100644 --- a/test/formatter_test.rb +++ b/test/formatter_test.rb @@ -83,4 +83,9 @@ class FormatterTest < MiniTest::Unit::TestCase def test_format_number_with_double_international_prefix assert_equal "+011 49 40", PhoneNumber::Parser.parse("+0114940") end + + def test_international_prefix_with_plus_and_trunk_prefix_start + assert_equal "+0", international_call_prefix_for("+0", region: PhoneNumber::Region["de"]) + assert_equal "+00", international_call_prefix_for("+00", region: PhoneNumber::Region["de"]) + end end \ No newline at end of file diff --git a/test/regions/de_test.rb b/test/regions/de_test.rb index <HASH>..<HASH> 100644 --- a/test/regions/de_test.rb +++ b/test/regions/de_test.rb @@ -4,6 +4,11 @@ class DERegionTest < MiniTest::Unit::TestCase def setup PhoneNumber.region = :de end + + def test_plus_and_trunk_prefix_start + assert_equal "+0", PhoneNumber::Parser.parse("+0") + assert_equal "+00", PhoneNumber::Parser.parse("+00") + end def test_output_the_correct_format # with national prefix '0'
Only a few weird edge cases failing. The rest works well now.
haberbyte_phoney
train
964b7bba7f5878c79130479f75461c58dd0c4b3e
diff --git a/pandas/io/tests/json/test_pandas.py b/pandas/io/tests/json/test_pandas.py index <HASH>..<HASH> 100644 --- a/pandas/io/tests/json/test_pandas.py +++ b/pandas/io/tests/json/test_pandas.py @@ -1,4 +1,5 @@ # pylint: disable-msg=W0612,E1101 +import nose from pandas.compat import range, lrange, StringIO, OrderedDict import os @@ -967,6 +968,9 @@ DataFrame\\.index values are different \\(100\\.0 %\\) TypeError, '\[unicode\] is not implemented as a table column') return + # GH 13774 + raise nose.SkipTest("encoding not implemented in .to_json(), xref #13774") + values = [[b'E\xc9, 17', b'', b'a', b'b', b'c'], [b'E\xc9, 17', b'a', b'b', b'c'], [b'EE, 17', b'', b'a', b'b', b'c'],
TST: skip .to_json with encoding test as not implemented yet xref #<I> xref #<I>
pandas-dev_pandas
train
167188079fe09eb629ad803ce83cee957e016798
diff --git a/lib/haibu/drone/drone.js b/lib/haibu/drone/drone.js index <HASH>..<HASH> 100644 --- a/lib/haibu/drone/drone.js +++ b/lib/haibu/drone/drone.js @@ -151,6 +151,27 @@ Drone.prototype.clean = function (app, callback) { }); }; + +// +// ### function update (name, callback) +// #### @name {string} Name of the application to update (i.e. app.name). +// Stops an application, Cleans all source and deps, Starts the pplication +// +Drone.prototype.update = function (app, callback) { + + if (typeof this.apps[app.name] === 'undefined') { + return callback(new Error('Cannot update application that is not running.')); + } + + var self = this; + self.clean(app, function(err){ + self.start(app, function(err, result){ + callback(err, result); + }); + }); + +}; + // // ### function show (name) // #### @name {string} Name of the application to show (i.e. app.name) diff --git a/lib/haibu/drone/service.js b/lib/haibu/drone/service.js index <HASH>..<HASH> 100644 --- a/lib/haibu/drone/service.js +++ b/lib/haibu/drone/service.js @@ -131,7 +131,23 @@ exports.createRouter = function (drone) { response.send(200, {}, { clean: true }); }); }); + + // + // ### Update Drone + // `POST /drones/:id/update` cleans and starts + // the app with :id on this server. + // + this.post(/\/([\w|\-]+)\/update/).bind(function (response, id, data) { + drone.update(data, function (err, drones) { + if (err) { + return response.send(500, {}, { error: err }); + } + + response.send(200, {}, { update: true }); + }); + }); + }); - + return router; -}; +}; \ No newline at end of file diff --git a/test/drone/drone-api-test.js b/test/drone/drone-api-test.js index <HASH>..<HASH> 100644 --- a/test/drone/drone-api-test.js +++ b/test/drone/drone-api-test.js @@ -119,6 +119,29 @@ vows.describe('haibu/drone/api').addBatch( } }).addBatch({ "When using the drone server": { + "a request against /drones/:id/update": { + "when there are running drones": { + topic: function () { + var options = { + uri: 'http://localhost:9000/drones/test/update', + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(app) + }; + + request(options, this.callback); + }, + "should respond with 200": function (error, response, body) { + console.log(body); + assert.equal(response.statusCode, 200); + } + } + } + } +}).addBatch({ + "When using the drone server": { "a request against /drones": { "when there are running drones": { topic: function () {
[api]: Added new API method drone.update for stopping a running drone, updating its source, and starting it back up.
nodejitsu_haibu
train
1fbf8144f85accc24629dff5c624ff606b249f70
diff --git a/src/EntityHelper/EntityCustomFieldTransformer.php b/src/EntityHelper/EntityCustomFieldTransformer.php index <HASH>..<HASH> 100644 --- a/src/EntityHelper/EntityCustomFieldTransformer.php +++ b/src/EntityHelper/EntityCustomFieldTransformer.php @@ -11,6 +11,10 @@ use Doctrine\ORM\EntityManager; */ class EntityCustomFieldTransformer implements DataTransformerInterface { + private $em; + private $fieldType; + private $reverseAsSting; + public function __construct(EntityManager $em, $fieldType, $reverseAsString = false) { $this->em = $em; diff --git a/src/Utils/ConfigReader.php b/src/Utils/ConfigReader.php index <HASH>..<HASH> 100644 --- a/src/Utils/ConfigReader.php +++ b/src/Utils/ConfigReader.php @@ -7,6 +7,8 @@ namespace CubeTools\CubeCustomFieldsBundle\Utils; */ class ConfigReader { + private $config; + public function __construct($config) { $this->config = $config; diff --git a/src/Utils/CustomFieldRepoService.php b/src/Utils/CustomFieldRepoService.php index <HASH>..<HASH> 100644 --- a/src/Utils/CustomFieldRepoService.php +++ b/src/Utils/CustomFieldRepoService.php @@ -11,6 +11,9 @@ use Doctrine\ORM\EntityManager; */ class CustomFieldRepoService { + private $configReader; + private $em; + public function __construct(ConfigReader $configReader, EntityManager $em) { $this->configReader = $configReader;
[cleanup] save service values as private variables
EmchBerger_cube-custom-fields-bundle
train
9c2ae2d6ee984b82ab2db741fdccf800e20b4061
diff --git a/Lib/fontmake/font_project.py b/Lib/fontmake/font_project.py index <HASH>..<HASH> 100644 --- a/Lib/fontmake/font_project.py +++ b/Lib/fontmake/font_project.py @@ -154,7 +154,7 @@ class FontProject: otf_path = self._output_path(ufo, ext, is_instance, interpolatable) otf = otf_compiler(ufo, featureCompilerClass=fea_compiler, - mtiFeaFiles=(mti_paths and mti_paths.get(name))) + mtiFeaFiles=mti_paths.get(name) if mti_paths else None) otf.save(otf_path) if subset:
Fix GSUB/GPOS/GDEF compile I'm not sure how it was every working. If mti_paths is {}, then mtiFeaFiles=(mti_paths and mti_paths.get(name) will set mtiFeaFiles to {}, whereas ufo2ft expects None. Ie, we were getting no GSUB/GPOS/GDEF for any fonts that did NOT have mti sources.
googlefonts_fontmake
train
73c0b08d1c63fa282385114cb00d6519160f893b
diff --git a/djangoautoconf/auto_conf_admin_utils.py b/djangoautoconf/auto_conf_admin_utils.py index <HASH>..<HASH> 100644 --- a/djangoautoconf/auto_conf_admin_utils.py +++ b/djangoautoconf/auto_conf_admin_utils.py @@ -1,3 +1,4 @@ +import copy import inspect from django.conf import settings @@ -13,27 +14,16 @@ from django.contrib import admin #import xadmin as admin -def register_normal_admin(admin_class, class_inst): - # admin.site.register(class_inst) - try: - from normal_admin.admin import user_admin_site - if not (class_inst in user_admin_site): - user_admin_site.register(class_inst, admin_class) - except: - pass - #register(class_inst) - - def get_valid_admin_class(admin_class, class_inst): if admin_class is None: admin_class = type(class_inst.__name__ + "Admin", (SingleModelAdmin, ), {}) return admin_class -def register_admin(admin_class, class_inst): +def register_admin(admin_class, class_inst, admin_site=admin.site): try: - if not (class_inst in admin.site._registry): - admin.site.register(class_inst, admin_class) + if not (class_inst in admin_site._registry): + admin_site.register(class_inst, admin_class) except Exception, e: if True: # not (' is already registered' in e.message): print class_inst, admin_class @@ -41,18 +31,28 @@ def register_admin(admin_class, class_inst): traceback.print_exc() +def register_all_type_of_admin(admin_class, class_inst): + register_admin(admin_class, class_inst) + try: + from normal_admin.admin import user_admin_site + + register_admin(admin_class, class_inst, user_admin_site) + except ImportError: + pass + + def register_to_sys(class_inst, admin_class=None): admin_class = get_valid_admin_class(admin_class, class_inst) - register_admin(admin_class, class_inst) - register_normal_admin(admin_class, class_inst) + register_all_type_of_admin(admin_class, class_inst) def get_valid_admin_class_with_list(admin_list, class_inst): #print admin_list - admin_list.append(SingleModelAdmin) + copied_admin_list = copy.copy(admin_list) + copied_admin_list.append(SingleModelAdmin) #print ModelAdmin #print final_parents - admin_class = type(class_inst.__name__ + "Admin", tuple(admin_list), {}) + admin_class = type(class_inst.__name__ + "Admin", tuple(copied_admin_list), {}) return admin_class @@ -61,8 +61,7 @@ def register_to_sys_with_admin_list(class_inst, admin_list=None): admin_class = get_valid_admin_class_with_list([], class_inst) else: admin_class = get_valid_admin_class_with_list(admin_list, class_inst) - register_admin(admin_class, class_inst) - register_normal_admin(admin_class, class_inst) + register_all_type_of_admin(admin_class, class_inst) def register_all(class_list, admin_class_list=None):
Added normal admin. Fixed duplicated parent when customize admin site.
weijia_djangoautoconf
train
5360db86d94c6303362925627288fa1ad135c86f
diff --git a/scour/scour.py b/scour/scour.py index <HASH>..<HASH> 100644 --- a/scour/scour.py +++ b/scour/scour.py @@ -1471,7 +1471,7 @@ def _getStyle(node): def _setStyle(node, styleMap): u"""Sets the style attribute of a node to the dictionary ``styleMap``.""" - fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in list(styleMap.keys())]) + fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap]) if fixedStyle != '': node.setAttribute('style', fixedStyle) elif node.getAttribute('style'):
Fix the last instance of "list(dict.keys())"
scour-project_scour
train
248be82a78aa79a2cb9dc4b7017b76b76224bc31
diff --git a/spec/Crummy/Phlack/Common/HashSpec.php b/spec/Crummy/Phlack/Common/HashSpec.php index <HASH>..<HASH> 100644 --- a/spec/Crummy/Phlack/Common/HashSpec.php +++ b/spec/Crummy/Phlack/Common/HashSpec.php @@ -29,18 +29,8 @@ class HashSpec extends ObjectBehavior $this->__toString()->shouldReturn('{"text":"Hello!"}'); } - public function it_has_no_default_parameters() + public function it_has_no_defined_parameters() { - $this->getDefaults()->shouldBe([]); - } - - public function it_has_no_optional_parameters() - { - $this->getOptional()->shouldBe([]); - } - - public function it_has_no_required_parameters() - { - $this->getRequired()->shouldBe([]); + $this->jsonSerialize()->shouldBe([]); } } diff --git a/spec/Crummy/Phlack/WebHook/Reply/EmptyReplySpec.php b/spec/Crummy/Phlack/WebHook/Reply/EmptyReplySpec.php index <HASH>..<HASH> 100644 --- a/spec/Crummy/Phlack/WebHook/Reply/EmptyReplySpec.php +++ b/spec/Crummy/Phlack/WebHook/Reply/EmptyReplySpec.php @@ -14,7 +14,7 @@ class EmptyReplySpec extends ObjectBehavior public function its_default_is_empty_text() { - $this->getDefaults()->shouldReturn(['text' => '']); + $this->toArray()->shouldReturn(['text' => '']); } public function its_text_is_immutable() diff --git a/spec/Crummy/Phlack/WebHook/Reply/ReplySpec.php b/spec/Crummy/Phlack/WebHook/Reply/ReplySpec.php index <HASH>..<HASH> 100644 --- a/spec/Crummy/Phlack/WebHook/Reply/ReplySpec.php +++ b/spec/Crummy/Phlack/WebHook/Reply/ReplySpec.php @@ -8,7 +8,7 @@ class ReplySpec extends ObjectBehavior { public function let() { - $this->beConstructedWith(['text' => 'ok']); + $this->beConstructedWith([]); } public function it_is_initializable() @@ -19,22 +19,25 @@ class ReplySpec extends ObjectBehavior public function it_defaults_to_empty_text() { - $this->getDefaults()->shouldReturn(['text' => '']); + $this->toArray()->shouldReturn(['text' => '']); } public function it_stores_text_in_the_array() { + $this->offsetSet('text', 'ok'); $this->toArray()->shouldReturn(['text' => 'ok']); } public function it_only_serializes_text() { + $this->offsetSet('text', 'bar'); $this->offsetSet('channel', 'foo'); - $this->jsonSerialize()->shouldReturn(['text' => 'ok']); + $this->jsonSerialize()->shouldReturn(['text' => 'bar']); } public function it_only_echoes_text() { + $this->offsetSet('text', 'ok'); $this->offsetSet('iconEmoji', 'ghost'); $this->__toString()->shouldReturn('{"text":"ok"}'); } diff --git a/src/Crummy/Phlack/Common/Hash.php b/src/Crummy/Phlack/Common/Hash.php index <HASH>..<HASH> 100644 --- a/src/Crummy/Phlack/Common/Hash.php +++ b/src/Crummy/Phlack/Common/Hash.php @@ -32,48 +32,6 @@ class Hash extends GuzzleCollection implements Encodable } /** - * Returns an array of keys and the default values for this Hash. - * - * @see \Guzzle\Common\Collection::setDefaults() - * - * @return array - * - * @deprecated Will be removed in 0.6.0 - */ - public function getDefaults() - { - return $this->defaults; - } - - /** - * Returns an array of required keys for this Hash. - * - * @see \Guzzle\Common\Collection::setRequired() - * - * @return array - * - * @deprecated Will be removed in 0.6.0 - */ - public function getRequired() - { - return $this->required; - } - - /** - * Returns an array of optional keys for this Hash. - * - * @see \Guzzle\Common\Collection::setOptional() - * - * @return array - * - * @deprecated Will be removed in 0.6.0 - */ - public function getOptional() - { - return $this->optional; - } - - /** * {@inheritdoc} */ public function __toString()
refactor(Hash): Remove deprecated methods from Hash
mcrumm_phlack
train
482ef3c44e5211807ce2a45b06d839d15a887473
diff --git a/src/eventDispatchers/shared/customCallbackHandler.js b/src/eventDispatchers/shared/customCallbackHandler.js index <HASH>..<HASH> 100644 --- a/src/eventDispatchers/shared/customCallbackHandler.js +++ b/src/eventDispatchers/shared/customCallbackHandler.js @@ -1,4 +1,4 @@ -import { getters, state } from './../../store/index.js'; +import { state } from './../../store/index.js'; import getActiveToolsForElement from './../../store/getActiveToolsForElement.js'; export default function (handlerType, customFunction, evt) { @@ -7,16 +7,14 @@ export default function (handlerType, customFunction, evt) { } // TODO: We sometimes see a null detail for TOUCH_PRESS - let tools = - handlerType === 'Touch' ? getters.touchTools() : getters.mouseTools(); const element = evt.detail.element; + let tools = state.tools.filter((tool) => + tool.supportedInteractionTypes.includes(handlerType) + ); - tools = getActiveToolsForElement(element, tools); - - if (handlerType === 'Touch') { - tools = tools.filter((tool) => tool.options.isTouchActive); - } - + // Tool is active, and specific callback is active + tools = getActiveToolsForElement(element, tools, handlerType); + // Tool has expected callback custom function tools = tools.filter((tool) => typeof tool[customFunction] === 'function'); if (tools.length === 0) { diff --git a/src/store/getActiveToolsForElement.js b/src/store/getActiveToolsForElement.js index <HASH>..<HASH> 100644 --- a/src/store/getActiveToolsForElement.js +++ b/src/store/getActiveToolsForElement.js @@ -1,5 +1,8 @@ -export default function (element, tools) { +export default function (element, tools, handlerType) { return tools.filter( - (tool) => tool.element === element && tool.mode === 'active' + (tool) => + tool.element === element && + tool.mode === 'active' && + (handlerType === undefined || tool.options[`is${handlerType}Active`]) ); }
Update customCallbackHandler to work with more than two handler types
cornerstonejs_cornerstoneTools
train
2cf795464d1da7fbc6d77ba92c9813080c24d93c
diff --git a/pax-logging-api/src/main/java/org/apache/log4j/Category.java b/pax-logging-api/src/main/java/org/apache/log4j/Category.java index <HASH>..<HASH> 100644 --- a/pax-logging-api/src/main/java/org/apache/log4j/Category.java +++ b/pax-logging-api/src/main/java/org/apache/log4j/Category.java @@ -642,7 +642,7 @@ public abstract class Category implements AppenderAttachable, PaxLoggingManagerA if (level == LogLevel.ERROR) { return Level.ERROR; } - return null; + return Level.OFF; } /** diff --git a/pax-logging-api/src/main/java/org/apache/logging/log4j/status/StatusLogger.java b/pax-logging-api/src/main/java/org/apache/logging/log4j/status/StatusLogger.java index <HASH>..<HASH> 100644 --- a/pax-logging-api/src/main/java/org/apache/logging/log4j/status/StatusLogger.java +++ b/pax-logging-api/src/main/java/org/apache/logging/log4j/status/StatusLogger.java @@ -43,6 +43,7 @@ import org.apache.logging.log4j.util.Strings; import org.ops4j.pax.logging.PaxLogger; import org.ops4j.pax.logging.spi.support.FallbackLogFactory; import org.osgi.framework.FrameworkUtil; +import org.osgi.service.log.LogLevel; /** * Records events that occur in the logging system. By default, only error messages are logged to {@link System#err}. @@ -238,7 +239,11 @@ public final class StatusLogger extends AbstractLogger { @Override public Level getLevel() { - switch (logger.getLogLevel()) { + LogLevel logLevel = logger.getLogLevel(); + if (logLevel == null) { + return Level.OFF; + } + switch (logLevel) { case AUDIT: return Level.ALL; case INFO: diff --git a/pax-logging-api/src/main/java/org/ops4j/pax/logging/log4jv2/Log4jv2Logger.java b/pax-logging-api/src/main/java/org/ops4j/pax/logging/log4jv2/Log4jv2Logger.java index <HASH>..<HASH> 100644 --- a/pax-logging-api/src/main/java/org/ops4j/pax/logging/log4jv2/Log4jv2Logger.java +++ b/pax-logging-api/src/main/java/org/ops4j/pax/logging/log4jv2/Log4jv2Logger.java @@ -29,6 +29,7 @@ import org.ops4j.pax.logging.PaxLoggingManagerAwareLogger; import org.ops4j.pax.logging.PaxMarker; import org.ops4j.pax.logging.spi.support.FallbackLogFactory; import org.osgi.framework.FrameworkUtil; +import org.osgi.service.log.LogLevel; /** * This is the default logger that is used when no suitable logging implementation is available. @@ -193,7 +194,11 @@ public class Log4jv2Logger extends AbstractLogger implements PaxLoggingManagerAw @Override public Level getLevel() { - switch (m_delegate.getLogLevel()) { + LogLevel logLevel = m_delegate.getLogLevel(); + if (logLevel == null) { + return Level.OFF; + } + switch (logLevel) { case TRACE: return Level.TRACE; case DEBUG:
[#<I>] Fix NPE when logging level is set to OFF (fixes #<I>)
ops4j_org.ops4j.pax.logging
train
b42a3843b6ebe86548392e6116e78aeda2c0a12a
diff --git a/legacy/Manager.php b/legacy/Manager.php index <HASH>..<HASH> 100644 --- a/legacy/Manager.php +++ b/legacy/Manager.php @@ -82,7 +82,7 @@ class Manager */ public function filePath($cacheId) { - $cacheId = DIRECTORY_SEPARATOR . trim($cacheId, [DIRECTORY_SEPARATOR]); + $cacheId = DIRECTORY_SEPARATOR . trim($cacheId, DIRECTORY_SEPARATOR); return $this->cachePath() . $cacheId . '.php'; }
fix get path (cherry picked from commit bda2b<I>ffa<I>f4a8a<I>a<I>d0b<I>e<I>)
bytic_cache
train
92aa8f122e1115fd26c7f0276c6e9c9fb217d448
diff --git a/knights/helpers.py b/knights/helpers.py index <HASH>..<HASH> 100644 --- a/knights/helpers.py +++ b/knights/helpers.py @@ -1,6 +1,7 @@ ''' Default helper functions ''' +from contextlib import contextmanager from functools import wraps from .library import Library @@ -23,6 +24,16 @@ def stringfilter(func): return _dec + +@register.helper +@contextmanager +def forwrapper(context, **kwargs): + ''' + Helper for the for tag + ''' + ctx = dict(context, **kwargs) + yield ctx + # add # addslashes diff --git a/knights/tags.py b/knights/tags.py index <HASH>..<HASH> 100644 --- a/knights/tags.py +++ b/knights/tags.py @@ -51,13 +51,49 @@ def do_for(parser, token): {% for a, b, c in iterable %} {% endfor %} + + We create the structure: + + for a, b, c in iterable: + with helpers['forwrapper'](context, a=a, b=b, c=c): + ... ''' code = ast.parse('for %s: pass' % token, mode='exec') loop = code.body[0] loop.iter = wrap_name_in_context(loop.iter) - loop.body = list(parser.parse_node(['endfor'])) + body = list(parser.parse_node(['endfor'])) + + if isinstance(loop.target, ast.Tuple): + targets = [elt.id for elt in loop.target.elts] + else: + targets = [loop.target.id] # Need to inject the loop values back into the context + inner = ast.With( + items=[ + ast.withitem( + context_expr=ast.Call( + func=ast.Subscript( + value=ast.Name(id='helpers', ctx=ast.Load()), + slice=ast.Index(value=ast.Str(s='forwrapper')), + ctx=ast.Load() + ), + args=[ + ast.Name(id='context', ctx=ast.Load()), + ], + keywords=[ + ast.keyword(arg=elt, value=ast.Name(id=elt, ctx=ast.Load())) + for elt in targets + ], + starargs=None, kwargs=None + ), + optional_vars=ast.Name(id='context', ctx=ast.Store()) + ), + ], + body=body, + ) + + loop.body = [inner] return loop
Add forwrapper helper to help for tag
funkybob_knights-templater
train
61bf236a2cbe2eda6888563a2bd8baa5ce70b5e5
diff --git a/specs/Task.spec.php b/specs/Task.spec.php index <HASH>..<HASH> 100644 --- a/specs/Task.spec.php +++ b/specs/Task.spec.php @@ -46,6 +46,12 @@ describe("Task", function () { expect( $this->task->resource("@dummy", false) )->to->equal(42); }); + describe("name()", function() { + it("returns its name", function(){ + expect($this->task->name())->to->equal("demo"); + }); + }); + describe("__toString()", function() { it("is its name initially", function() { expect("$this->task")->to->equal("demo"); diff --git a/src/Task.php b/src/Task.php index <HASH>..<HASH> 100644 --- a/src/Task.php +++ b/src/Task.php @@ -19,6 +19,7 @@ class Task { $this->schedule(); } + function name() { return $this->name; } // ===== Task Declaration API ===== //
Add name() method to Tasks and Resources
dirtsimple_imposer
train
08400b05f5f3e20c24c9222a9cb9216d1a76aea5
diff --git a/PyFunceble/__init__.py b/PyFunceble/__init__.py index <HASH>..<HASH> 100644 --- a/PyFunceble/__init__.py +++ b/PyFunceble/__init__.py @@ -75,7 +75,7 @@ from PyFunceble.production import Production from PyFunceble.publicsuffix import PublicSuffix CURRENT_DIRECTORY = getcwd() + directory_separator -VERSION = "0.84.0.dev-beta" +VERSION = "0.84.1.dev-beta" CONFIGURATION_FILENAME = ".PyFunceble.yaml" diff --git a/PyFunceble/config.py b/PyFunceble/config.py index <HASH>..<HASH> 100644 --- a/PyFunceble/config.py +++ b/PyFunceble/config.py @@ -80,7 +80,7 @@ class Load(object): # pylint: disable=too-few-public-methods def __init__(self, path_to_config): self.path_to_config = path_to_config - if path_to_config.endswith(directory_separator): + if not path_to_config.endswith(directory_separator): self.path_to_config += directory_separator self.path_to_config += PyFunceble.CONFIGURATION_FILENAME diff --git a/version.yaml b/version.yaml index <HASH>..<HASH> 100644 --- a/version.yaml +++ b/version.yaml @@ -1,4 +1,4 @@ -current_version: 0.84.0.dev-beta +current_version: 0.84.1.dev-beta deprecated: [0.0.0, 0.0.1, 0.65.0, 0.67.1, 0.68.0, 0.69.3, 0.69.5, 0.70.4, 0.71.2, 0.72.7, 0.73.1, 0.74.5, 0.75.1, 0.76.2, 0.77.0, 0.78.0, 0.79.1, 0.80.9, 0.81.8, 0.82.4, 0.83.2]
Fix issue regarding the way we check if a trailing directory separator is present or not
funilrys_PyFunceble
train
8a486a3769293fa26a77902d0a6853053fd8ad32
diff --git a/src/MigrationTrait.php b/src/MigrationTrait.php index <HASH>..<HASH> 100644 --- a/src/MigrationTrait.php +++ b/src/MigrationTrait.php @@ -5,17 +5,18 @@ use Cake\Core\Configure; use Cake\Utility\Inflector; use CsvMigrations\CsvMigrationsUtils; use CsvMigrations\CsvTrait; +use CsvMigrations\FieldHandlers\CsvField; trait MigrationTrait { use CsvTrait; /** - * Pattern for associated fields + * Associated fields identifier * * @var string */ - protected $_patternAssoc = 'related:'; + protected $_assocIdentifier = 'related'; /** * Field parameters @@ -141,13 +142,14 @@ trait MigrationTrait foreach ($csvData as $module => $fields) { foreach ($fields as $row) { - $assocModule = $this->_getAssociatedModuleName($row['type']); + $csvField = new CsvField($row); /* Skip if not associated module name was found */ - if ('' === trim($assocModule)) { + if ($this->_assocIdentifier !== $csvField->getType()) { continue; } + $assocModule = $csvField->getLimit(); /* If current model alias matches csv module, then assume belongsTo association. @@ -196,21 +198,4 @@ trait MigrationTrait return $result; } - - /** - * Method that extracts module name from field type definition. - * - * @param string $name field type - * @return string - */ - protected function _getAssociatedModuleName($name) - { - $result = ''; - if (false !== $pos = strpos($name, $this->_patternAssoc)) { - $result = str_replace($this->_patternAssoc, '', $name); - $result = Inflector::camelize($result); - } - - return $result; - } }
identify associated fields and get associated module using CsvField object (task #<I>)
QoboLtd_cakephp-csv-migrations
train
9cb0a45cbf5c1b2964cb7c095b9f87d94eb59c26
diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectBuildersExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectBuildersExecutor.java index <HASH>..<HASH> 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectBuildersExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectBuildersExecutor.java @@ -22,6 +22,7 @@ package org.sonar.scanner.scan; import org.sonar.api.batch.bootstrap.ProjectBuilder; import org.sonar.api.batch.bootstrap.ProjectReactor; import org.sonar.api.batch.bootstrap.internal.ProjectBuilderContext; +import org.sonar.api.utils.MessageException; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; @@ -46,9 +47,14 @@ public class ProjectBuildersExecutor { ProjectBuilderContext context = new ProjectBuilderContext(reactor); for (ProjectBuilder projectBuilder : projectBuilders) { - projectBuilder.build(context); + try { + projectBuilder.build(context); + } catch (Exception e) { + throw MessageException.of("Failed to execute project builder: " + projectBuilder, e); + } } profiler.stopInfo(); } + } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumTest.java index <HASH>..<HASH> 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumTest.java @@ -25,12 +25,20 @@ import java.io.IOException; import java.util.Date; import java.util.List; import org.apache.commons.io.FileUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; +import org.sonar.api.batch.bootstrap.ProjectBuilder; import org.sonar.api.utils.MessageException; import org.sonar.scanner.mediumtest.BatchMediumTester; import org.sonar.scanner.mediumtest.TaskResult; @@ -49,8 +57,10 @@ public class ProjectBuilderMediumTest { @Rule public ExpectedException exception = ExpectedException.none(); + private ProjectBuilder projectBuilder = mock(ProjectBuilder.class); + public BatchMediumTester tester = BatchMediumTester.builder() - .registerPlugin("xoo", new XooPlugin()) + .registerPlugin("xoo", new XooPluginWithBuilder(projectBuilder)) .addRules(new XooRulesDefinition()) .addDefaultQProfile("xoo", "Sonar Way") .setPreviousAnalysisDate(new Date()) @@ -62,12 +72,64 @@ public class ProjectBuilderMediumTest { tester.start(); } + private class XooPluginWithBuilder extends XooPlugin { + private ProjectBuilder builder; + + XooPluginWithBuilder(ProjectBuilder builder) { + this.builder = builder; + } + + @Override + public void define(Context context) { + super.define(context); + context.addExtension(builder); + } + } + @After public void stop() { tester.stop(); } @Test + public void testProjectReactorValidation() throws IOException { + File baseDir = prepareProject(); + + doThrow(new IllegalStateException("My error message")).when(projectBuilder).build(any(ProjectBuilder.Context.class)); + exception.expectMessage("Failed to execute project builder"); + exception.expect(MessageException.class); + exception.expectCause(new BaseMatcher<Throwable>() { + + @Override + public boolean matches(Object item) { + if (!(item instanceof IllegalStateException)) { + return false; + } + IllegalStateException e = (IllegalStateException) item; + return "My error message".equals(e.getMessage()); + } + + @Override + public void describeTo(Description description) { + } + }); + + tester.newTask() + .properties(ImmutableMap.<String, String>builder() + .put("sonar.task", "scan") + .put("sonar.projectBaseDir", baseDir.getAbsolutePath()) + .put("sonar.projectKey", "com.foo.project") + .put("sonar.projectName", "Foo Project") + .put("sonar.projectVersion", "1.0-SNAPSHOT") + .put("sonar.projectDescription", "Description of Foo Project") + .put("sonar.sources", ".") + .put("sonar.xoo.enableProjectBuilder", "true") + .build()) + .start(); + + } + + @Test public void testProjectBuilder() throws IOException { File baseDir = prepareProject();
SONAR-<I> Improve error log when there is a failure in a ProjectBuilder
SonarSource_sonarqube
train
4aa63584e8a0248935dcf153e735d9ee2dc3bd4e
diff --git a/salt/config.py b/salt/config.py index <HASH>..<HASH> 100644 --- a/salt/config.py +++ b/salt/config.py @@ -1823,7 +1823,7 @@ def get_id(opts, minion_id=False): if name.startswith(codecs.BOM): # Remove BOM if exists name = name.replace(codecs.BOM, '', 1) if name: - log.info('Using cached minion ID from {0}: {1}' + log.debug('Using cached minion ID from {0}: {1}' .format(id_cache, name)) return name, False except (IOError, OSError):
Make this a debug line, we see it a lot and don't really care :)
saltstack_salt
train
059714d54737f613874ed60d578cf87f34201e44
diff --git a/src/shellingham/posix.py b/src/shellingham/posix.py index <HASH>..<HASH> 100644 --- a/src/shellingham/posix.py +++ b/src/shellingham/posix.py @@ -1,5 +1,6 @@ import collections import os +import platform import shlex import subprocess import sys @@ -30,11 +31,36 @@ def _get_process_mapping(): return processes +def _linux_get_process_mapping(): + """Try to look up the process tree via linux's /proc""" + STAT_PPID = 3 + STAT_TTY = 6 + with open('/proc/%s/stat' % os.getpid()) as f: + self_tty = f.read().split()[STAT_TTY] + pids = [pid for pid in os.listdir('/proc') if pid.isdigit()] + processes = {} + for pid in pids: + try: + with open('/proc/%s/stat' % pid) as fstat, open('/proc/%s/cmdline' % pid) as fcmdline: + stat = fstat.read().split() + cmd = fcmdline.read()[:-1] + ppid = stat[STAT_PPID] + tty = stat[STAT_TTY] + if tty == self_tty: + processes[pid] = Process( + args=tuple(shlex.split(cmd)), pid=pid, ppid=ppid, + ) + except IOError: + # process has disappeared - just ignore it + pass + return processes + + def get_shell(pid=None, max_depth=6): """Get the shell that the supplied pid or os.getpid() is running in. """ pid = str(pid or os.getpid()) - mapping = _get_process_mapping() + mapping = _linux_get_process_mapping() if platform.system() == 'Linux' else _get_process_mapping() login_shell = os.environ.get('SHELL', '') for _ in range(max_depth): try:
use /proc instead of ps on linux ps is not always available in minimum linux install, like in docker containers. This change avoid to the need to install the procps package.
sarugaku_shellingham
train
0159800364eada4cdb241c38182fca3ab6ce1bd9
diff --git a/Classes/Domain/Repository/CategoryRepository.php b/Classes/Domain/Repository/CategoryRepository.php index <HASH>..<HASH> 100644 --- a/Classes/Domain/Repository/CategoryRepository.php +++ b/Classes/Domain/Repository/CategoryRepository.php @@ -2,33 +2,16 @@ namespace Clickstorm\GoMapsExt\Domain\Repository; -/*************************************************************** - * Copyright notice - * - * (c) 2012 Marc Hirdes <Marc_Hirdes@gmx.de>, clickstorm GmbH - * - * All rights reserved - * - * This script is part of the TYPO3 project. The TYPO3 project is - * free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * The GNU General Public License can be found at - * http://www.gnu.org/copyleft/gpl.html. - * - * This script is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * This copyright notice MUST APPEAR in all copies of the script! - ***************************************************************/ +use TYPO3\CMS\Core\Utility\GeneralUtility; +use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings; +use TYPO3\CMS\Extbase\Persistence\Repository; -/** - * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later - */ -class CategoryRepository extends \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository +class CategoryRepository extends Repository { + public function initializeObject() + { + $querySettings = GeneralUtility::makeInstance(Typo3QuerySettings::class); + $querySettings->setRespectStoragePage(false); + $this->setDefaultQuerySettings($querySettings); + } } diff --git a/Classes/Form/Element/GomapsextMapElement.php b/Classes/Form/Element/GomapsextMapElement.php index <HASH>..<HASH> 100644 --- a/Classes/Form/Element/GomapsextMapElement.php +++ b/Classes/Form/Element/GomapsextMapElement.php @@ -30,7 +30,6 @@ namespace Clickstorm\GoMapsExt\Form\Element; use TYPO3\CMS\Backend\Form\Element\AbstractFormElement; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface; -use TYPO3\CMS\Extbase\Object\ObjectManager; use TYPO3\CMS\Extbase\Utility\LocalizationUtility; /** @@ -308,8 +307,7 @@ EOT; */ private static function getSettings(): array { - return GeneralUtility::makeInstance(ObjectManager::class) - ->get(ConfigurationManagerInterface::class) + return GeneralUtility::makeInstance(ConfigurationManagerInterface::class) ->getConfiguration( ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT )['plugin.']['tx_gomapsext.']['settings.'] ?? [];
[BUGFIX] extension scanner warnings
mhirdes_go_maps_ext
train
9c91e279338f4d8bf09e1f7f5904d34cd525b102
diff --git a/cmd/web.go b/cmd/web.go index <HASH>..<HASH> 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -368,6 +368,7 @@ func runWeb(ctx *cli.Context) { m.Combo("").Get(org.Settings). Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost) m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), org.SettingsAvatar) + m.Post("/avatar/delete", org.SettingsDeleteAvatar) m.Group("/hooks", func() { m.Get("", org.Webhooks) diff --git a/models/user.go b/models/user.go index <HASH>..<HASH> 100644 --- a/models/user.go +++ b/models/user.go @@ -346,6 +346,19 @@ func (u *User) UploadAvatar(data []byte) error { return sess.Commit() } +// DeleteAvatar deletes the user's custom avatar. +func (u *User) DeleteAvatar() error { + log.Info("Deleting user avatar: %s", u.CustomAvatarPath()) + os.Remove(u.CustomAvatarPath()) + + u.UseCustomAvatar = false + if err := UpdateUser(u); err != nil { + return fmt.Errorf("updateUser: %v", err) + } + + return nil +} + // IsAdminOfRepo returns true if user has admin or higher access of repository. func (u *User) IsAdminOfRepo(repo *Repository) bool { has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN) diff --git a/routers/org/setting.go b/routers/org/setting.go index <HASH>..<HASH> 100644 --- a/routers/org/setting.go +++ b/routers/org/setting.go @@ -96,6 +96,14 @@ func SettingsAvatar(ctx *middleware.Context, form auth.UploadAvatarForm) { ctx.Redirect(ctx.Org.OrgLink + "/settings") } +func SettingsDeleteAvatar(ctx *middleware.Context) { + if err := ctx.Org.Organization.DeleteAvatar(); err != nil { + ctx.Flash.Error(err.Error()) + } + + ctx.Redirect(ctx.Org.OrgLink + "/settings") +} + func SettingsDelete(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("org.settings") ctx.Data["PageIsSettingsDelete"] = true diff --git a/routers/user/setting.go b/routers/user/setting.go index <HASH>..<HASH> 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io/ioutil" - "os" "strings" "github.com/Unknwon/com" @@ -156,12 +155,10 @@ func SettingsAvatar(ctx *middleware.Context, form auth.UploadAvatarForm) { } func SettingsDeleteAvatar(ctx *middleware.Context) { - os.Remove(ctx.User.CustomAvatarPath()) - - ctx.User.UseCustomAvatar = false - if err := models.UpdateUser(ctx.User); err != nil { - ctx.Flash.Error(fmt.Sprintf("UpdateUser: %v", err)) + if err := ctx.User.DeleteAvatar(); err != nil { + ctx.Flash.Error(err.Error()) } + ctx.Redirect(setting.AppSubUrl + "/user/settings") } diff --git a/templates/org/settings/options.tmpl b/templates/org/settings/options.tmpl index <HASH>..<HASH> 100644 --- a/templates/org/settings/options.tmpl +++ b/templates/org/settings/options.tmpl @@ -59,6 +59,7 @@ <div class="field"> <button class="ui green button">{{$.i18n.Tr "settings.update_avatar"}}</button> + <a class="ui red button delete-post" data-request-url="{{.Link}}/avatar/delete" data-done-url="{{.Link}}">{{$.i18n.Tr "settings.delete_current_avatar"}}</a> </div> </form> </div>
Added: Ability to delete org avatar.
gogs_gogs
train
289ce63a3e8c5f9efe7c47411a24757f15ba8c4d
diff --git a/test/standards/standards.py b/test/standards/standards.py index <HASH>..<HASH> 100644 --- a/test/standards/standards.py +++ b/test/standards/standards.py @@ -12,21 +12,22 @@ test_task_ansiblelint_success = Standard(dict( check = lintcheck('TEST0002'), name = "Test task lint success", version = "0.2", - types = "playbook,tasks" + types = ["playbook", "tasks", "handlers"] )) test_task_ansiblelint_failure = Standard(dict( check = lintcheck('TEST0001'), name = "Test task lint failure", version = "0.4", - types = "playbook,tasks" + types = ["playbook", "tasks", "handlers"] )) test_failure = Standard(dict( check = check_fail, name = "Test general failure", version = "0.5", - types = "playbook,tasks,vars" + types=["playbook", "task", "handler", "rolevars", + "hostvars", "groupvars", "meta"] )) test_success = Standard(dict(
Update standards to use new types declaration types should be an array, not a comma separated string
willthames_ansible-review
train
fd942284fe190615d098af0b63e1698ef0969df1
diff --git a/api.go b/api.go index <HASH>..<HASH> 100644 --- a/api.go +++ b/api.go @@ -543,9 +543,9 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt // For errors verify if its retryable otherwise fail quickly. errResponse := ToErrorResponse(httpRespToErrorResponse(res, metadata.bucketName, metadata.objectName)) - // Bucket region if set in error response, we can retry the - // request with the new region. - if errResponse.Region != "" { + // Bucket region if set in error response and the error code dictates invalid region, + // we can retry the request with the new region. + if errResponse.Code == "InvalidRegion" && errResponse.Region != "" { c.bucketLocCache.Set(metadata.bucketName, errResponse.Region) continue // Retry. }
api: Check for Code 'InvalidRegion' for retrying with server Region. (#<I>)
minio_minio-go
train
7f4f62b2e1b19584b3bb9b7999af6f2d84e7ae43
diff --git a/lib/bud.rb b/lib/bud.rb index <HASH>..<HASH> 100644 --- a/lib/bud.rb +++ b/lib/bud.rb @@ -94,6 +94,7 @@ module Bud @budtime = 0 @inbound = [] @declarations = [] + @done_bootstrap = false @server = nil # Setup options (named arguments), along with default values @@ -168,10 +169,9 @@ module Bud bootstrap # Make sure that new_delta tuples from bootstrap rules are transitioned into - # storage before first tick. + # storage. tables.each{|name,coll| coll.install_deltas} - # Note that any tuples installed into a channel won't immediately be - # flushed; we need to wait for EM startup to do that + @done_bootstrap = true end def do_rewrite @@ -350,18 +350,12 @@ module Bud do_start_server - # Flush any tuples installed into channels during bootstrap block - # XXX: doing this here is a kludge; we should do all of bootstrap - # in one place - do_flush - # Initialize periodics @periodics.each do |p| @timers << set_periodic_timer(p.pername, p.ident, p.period) end - # Compute a fixpoint. We do this so that transitive consequences of any - # bootstrap facts are computed. + # Compute a fixpoint; this will also invoke any bootstrap blocks. tick @rtracer.sleep if options[:rtrace] @@ -386,7 +380,7 @@ module Bud end def tick - do_bootstrap if @budtime == 0 + do_bootstrap unless @done_bootstrap @tables.each_value do |t| t.tick end @@ -418,7 +412,7 @@ module Bud table :t_cycle, [:predicate, :via, :neg, :temporal] end - # Invoke all the user-defined state blocks and init builtin state. + # Invoke all the user-defined state blocks and initialize builtin state. def init_state builtin_state @state_methods.each do |s|
Code cleanup for bootstrap. flush() during start_bud() is no longer necessary.
bloom-lang_bud
train
9fa96a5b67bd2f03b1940d649a618b4453cc9761
diff --git a/delphi/program_analysis/ProgramAnalysisGraph.py b/delphi/program_analysis/ProgramAnalysisGraph.py index <HASH>..<HASH> 100644 --- a/delphi/program_analysis/ProgramAnalysisGraph.py +++ b/delphi/program_analysis/ProgramAnalysisGraph.py @@ -147,3 +147,6 @@ class ProgramAnalysisGraph(nx.DiGraph): for n in self.nodes(data=True): n[1]["visited"] = False + + def call(self, inputs): + pass diff --git a/delphi/program_analysis/interpreter.py b/delphi/program_analysis/interpreter.py index <HASH>..<HASH> 100644 --- a/delphi/program_analysis/interpreter.py +++ b/delphi/program_analysis/interpreter.py @@ -4,10 +4,31 @@ from typing import Dict import json import delphi.program_analysis.scopes as scp +import delphi.program_analysis.ProgramAnalysisGraph as pag +from delphi.visualization import visualize +import delphi.program_analysis.autoTranslate.lambdas as lambdas + +from IPython.display import display, Image + + +def printScopeTree(scope): + for node in scope.nodes: + if isinstance(node, scp.ActionNode): + print(node.lambda_fn) + for child in scope.child_scopes: + printScopeTree(child) + if __name__ == "__main__": dbn_json_file = "autoTranslate/pgm.json" scope = scp.Scope.from_json(normpath(dbn_json_file)) + # printScopeTree(scope) + A = scope.to_agraph() - A.write("nested_graph.dot") - A.draw("nested_graph.png", prog="dot") + pgraph = pag.ProgramAnalysisGraph.from_agraph(A, lambdas) + petpt_graph = "petpt-pa-graph" + pgraph.initialize() + visualize(pgraph, save_to_dot=petpt_graph, show_values=True) + + # B = AGraph("{}.dot".format(petpt_graph)) + # B.draw("{}.png".format(petpt_graph), prog="dot") diff --git a/delphi/program_analysis/scopes.py b/delphi/program_analysis/scopes.py index <HASH>..<HASH> 100644 --- a/delphi/program_analysis/scopes.py +++ b/delphi/program_analysis/scopes.py @@ -58,7 +58,9 @@ class Scope(metaclass=ABCMeta): scope.remove_non_scope_children(scope_names) # Build the nested tree of scopes using recursion - root = scopes[data["start"]] + non_lambdas = [f["name"] for f in data["functions"] if "__" not in f["name"]] + root_func_name = non_lambdas[0] # There should only ever be one, otherwise we need multiple roots + root = scopes[root_func_name] root.build_scope_tree(scopes) root.setup_from_json() return root diff --git a/delphi/visualization.py b/delphi/visualization.py index <HASH>..<HASH> 100644 --- a/delphi/visualization.py +++ b/delphi/visualization.py @@ -37,7 +37,7 @@ def _(G: AnalysisGraph, *args, **kwargs): @visualize.register(ProgramAnalysisGraph) -def _(G: ProgramAnalysisGraph, **kwargs): +def _(G: ProgramAnalysisGraph, save_to_dot="", **kwargs): """ Exports AnalysisGraph to pygraphviz AGraph Args: @@ -74,6 +74,10 @@ def _(G: ProgramAnalysisGraph, **kwargs): # Drawing indicator variables + if save_to_dot != "": + A.draw("{}.png".format(save_to_dot), format="png", prog=kwargs.get("layout", "dot")) + # A.write("{}.dot".format(save_to_dot)) + return Image( A.draw(format="png", prog=kwargs.get("layout", "dot")), retina=True )
Attempting to get a PETPT ProgramAnalysisGraph working
ml4ai_delphi
train
c8c24eb77c2a64992c6fb65c78d214a554905bff
diff --git a/spring-social-core/src/main/java/org/springframework/social/connect/ConnectionKey.java b/spring-social-core/src/main/java/org/springframework/social/connect/ConnectionKey.java index <HASH>..<HASH> 100644 --- a/spring-social-core/src/main/java/org/springframework/social/connect/ConnectionKey.java +++ b/spring-social-core/src/main/java/org/springframework/social/connect/ConnectionKey.java @@ -65,7 +65,7 @@ public final class ConnectionKey { } ConnectionKey other = (ConnectionKey) o; boolean sameProvider = providerId.equals(other.providerId); - return providerUserId != null ? sameProvider && providerUserId.equals(providerUserId) : sameProvider; + return providerUserId != null ? sameProvider && providerUserId.equals(other.providerUserId) : sameProvider; } public int hashCode() { diff --git a/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Operations.java b/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Operations.java index <HASH>..<HASH> 100644 --- a/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Operations.java +++ b/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Operations.java @@ -47,6 +47,8 @@ public interface OAuth2Operations { * Exchange the authorization code for an access grant. * @param authorizationCode the authorization code returned by the provider upon user authorization * @param redirectUri the authorization callback url; this value must match the redirectUri registered with the provider + * @param additionalParameters any additional parameters to be sent when exchanging the authorization code for an access grant. Should not be encoded. + * @return the access grant. */ AccessGrant exchangeForAccess(String authorizationCode, String redirectUri, MultiValueMap<String, String> additionalParameters); @@ -54,6 +56,8 @@ public interface OAuth2Operations { * Refreshes a previous access grant. * @param refreshToken the refresh token from the previous access grant. * @param scope optional scope to narrow to when refreshing access; if null, the existing scope is preserved. + * @param additionalParameters any additional parameters to be sent when refreshing a previous access grant. Should not be encoded. + * @return the access grant. */ AccessGrant refreshAccess(String refreshToken, String scope, MultiValueMap<String, String> additionalParameters); diff --git a/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Template.java b/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Template.java index <HASH>..<HASH> 100644 --- a/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Template.java +++ b/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Template.java @@ -66,7 +66,7 @@ public class OAuth2Template implements OAuth2Operations { String clientInfo = "?client_id=" + formEncode(clientId); this.authorizeUrl = authorizeUrl + clientInfo; if (authenticateUrl != null) { - this.authenticateUrl = authenticateUrl + "?client_id=" + formEncode(clientId); + this.authenticateUrl = authenticateUrl + clientInfo; } else { this.authenticateUrl = null; }
Polishing while porting to .NET
spring-projects_spring-social
train
64dc9cd7ef3db1ba77d4cd465f26434190e75956
diff --git a/packages/simplebar/src/simplebar.js b/packages/simplebar/src/simplebar.js index <HASH>..<HASH> 100755 --- a/packages/simplebar/src/simplebar.js +++ b/packages/simplebar/src/simplebar.js @@ -439,10 +439,8 @@ export default class SimpleBar { this.axis.y.isOverflowing = this.elStyles.overflowY === 'hidden' ? false : this.axis.y.isOverflowing; - this.axis.x.forceVisible = - this.elStyles.overflowX === 'scroll' || this.options.forceVisible; - this.axis.y.forceVisible = - this.elStyles.overflowY === 'scroll' || this.options.forceVisible; + this.axis.x.forceVisible = this.options.forceVisible === "x" || this.options.forceVisible === true; + this.axis.y.forceVisible = this.options.forceVisible === "y" || this.options.forceVisible === true; this.axis.x.scrollbar.size = this.getScrollbarSize('x'); this.axis.y.scrollbar.size = this.getScrollbarSize('y');
chore: remove check on overflow: scroll as it shouldn't be done
Grsmto_simplebar
train
a0d5cbd2f1fe4961fd2bd4c4a43f950430ac2806
diff --git a/servlet/src/main/java/io/undertow/servlet/handlers/ServletInitialHandler.java b/servlet/src/main/java/io/undertow/servlet/handlers/ServletInitialHandler.java index <HASH>..<HASH> 100644 --- a/servlet/src/main/java/io/undertow/servlet/handlers/ServletInitialHandler.java +++ b/servlet/src/main/java/io/undertow/servlet/handlers/ServletInitialHandler.java @@ -116,9 +116,12 @@ public class ServletInitialHandler implements HttpHandler, ServletDispatcher { listeners.requestInitialized(request); next.handleRequest(exchange); - if (!exchange.isResponseStarted() && exchange.getResponseCode() >= 400 && !exchange.isDispatched()) { - String location = servletContext.getDeployment().getErrorPages().getErrorLocation(exchange.getResponseCode()); + int responseCode = exchange.getResponseCode(); + if (!exchange.isResponseStarted() && responseCode >= 400 && !exchange.isDispatched()) { + String location = servletContext.getDeployment().getErrorPages().getErrorLocation(responseCode); if (location != null) { + response.reset(); //reset the response + exchange.setResponseCode(responseCode); //the reset call cleared the response code RequestDispatcherImpl dispatcher = new RequestDispatcherImpl(location, servletContext); dispatcher.error(request, response, servletChain.getManagedServlet().getServletInfo().getName()); } @@ -130,6 +133,7 @@ public class ServletInitialHandler implements HttpHandler, ServletDispatcher { servletRequestContext.getOriginalRequest().getAsyncContextInternal().handleError(t); } else { if (!exchange.isResponseStarted()) { + response.reset(); //reset the response exchange.setResponseCode(500); exchange.getResponseHeaders().clear(); String location = servletContext.getDeployment().getErrorPages().getErrorLocation(t); diff --git a/servlet/src/main/java/io/undertow/servlet/spec/HttpServletResponseImpl.java b/servlet/src/main/java/io/undertow/servlet/spec/HttpServletResponseImpl.java index <HASH>..<HASH> 100644 --- a/servlet/src/main/java/io/undertow/servlet/spec/HttpServletResponseImpl.java +++ b/servlet/src/main/java/io/undertow/servlet/spec/HttpServletResponseImpl.java @@ -112,7 +112,6 @@ public final class HttpServletResponseImpl implements HttpServletResponse { if (exchange.isResponseStarted()) { throw UndertowServletMessages.MESSAGES.responseAlreadyCommited(); } - resetBuffer(); writer = null; responseState = ResponseState.NONE; exchange.setResponseCode(sc); diff --git a/servlet/src/main/java/io/undertow/servlet/spec/RequestDispatcherImpl.java b/servlet/src/main/java/io/undertow/servlet/spec/RequestDispatcherImpl.java index <HASH>..<HASH> 100644 --- a/servlet/src/main/java/io/undertow/servlet/spec/RequestDispatcherImpl.java +++ b/servlet/src/main/java/io/undertow/servlet/spec/RequestDispatcherImpl.java @@ -307,7 +307,6 @@ public class RequestDispatcherImpl implements RequestDispatcher { } } } - response.resetBuffer(); final ServletRequest oldRequest = servletRequestContext.getServletRequest(); final ServletResponse oldResponse = servletRequestContext.getServletResponse();
WFLY-<I> reset the response before sending an error page
undertow-io_undertow
train
67e7f42714491fdacaacc3b26f9830a2e8c0f71b
diff --git a/src/gr/spinellis/umlgraph/doclet/View.java b/src/gr/spinellis/umlgraph/doclet/View.java index <HASH>..<HASH> 100644 --- a/src/gr/spinellis/umlgraph/doclet/View.java +++ b/src/gr/spinellis/umlgraph/doclet/View.java @@ -61,12 +61,23 @@ class View implements OptionProvider { globalOptions = new ArrayList<String[]>(); for (int i = 0; i < tags.length; i++) { if (tags[i].name().equals("@match")) { + // store the current pattern and its options if (currPattern != null) { String[][] options = patternOptions .toArray(new String[patternOptions.size()][]); optionOverrides.put(Pattern.compile(currPattern), options); } - currPattern = tags[i].text(); + // start gathering data for the new patters + String[] strings = StringUtil.tokenize(tags[i].text()); + if(strings.length < 2) { + System.err.println("Skipping uncomplete @match tag, type missing. "); + currPattern = null; + } else if(!strings[0].equals("class")) { + System.err.println("Skipping @match tag, unknown match type (only 'class' is supported for the moment). "); + currPattern = null; + } else { + currPattern = strings[1]; + } patternOptions.clear(); } else if (tags[i].name().equals("@opt")) { String[] opts = StringUtil.tokenize(tags[i].text()); diff --git a/src/org/umlgraph/doclet/View.java b/src/org/umlgraph/doclet/View.java index <HASH>..<HASH> 100644 --- a/src/org/umlgraph/doclet/View.java +++ b/src/org/umlgraph/doclet/View.java @@ -61,12 +61,23 @@ class View implements OptionProvider { globalOptions = new ArrayList<String[]>(); for (int i = 0; i < tags.length; i++) { if (tags[i].name().equals("@match")) { + // store the current pattern and its options if (currPattern != null) { String[][] options = patternOptions .toArray(new String[patternOptions.size()][]); optionOverrides.put(Pattern.compile(currPattern), options); } - currPattern = tags[i].text(); + // start gathering data for the new patters + String[] strings = StringUtil.tokenize(tags[i].text()); + if(strings.length < 2) { + System.err.println("Skipping uncomplete @match tag, type missing. "); + currPattern = null; + } else if(!strings[0].equals("class")) { + System.err.println("Skipping @match tag, unknown match type (only 'class' is supported for the moment). "); + currPattern = null; + } else { + currPattern = strings[1]; + } patternOptions.clear(); } else if (tags[i].name().equals("@opt")) { String[] opts = StringUtil.tokenize(tags[i].text());
"@match class" changes and some feedback on why we skip incorrect @match specifications
dspinellis_UMLGraph
train
8196d2d3b7989a451c99ca5a0bdf701489b462ed
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ setup( name='Flask-RESTeasy', author='Clinton James', author_email='clinton.james@anuit.com', - url='https://www.github.com/jidn/flask-restful/', + url='https://www.github.com/jidn/flask-resteasy/', download_url='https://github.com/jidn/flask-resteasy/tarball/'+__version__, description='Create easy REST APIs with Flask', license='Apache License 2.0',
Fix so the URL is now pointing at the correct GitHub project.
jidn_flask-resteasy
train
caf35816855b62f012d22f6ba73b9bf3de138b0a
diff --git a/src/WithoutOverlapping.php b/src/WithoutOverlapping.php index <HASH>..<HASH> 100644 --- a/src/WithoutOverlapping.php +++ b/src/WithoutOverlapping.php @@ -7,6 +7,23 @@ use Symfony\Component\Console\Output\OutputInterface; trait WithoutOverlapping { + public function getMutexStrategy() + { + return (isset($this->mutexStrategy) ? $this->mutexStrategy : 'file'); + } + + public function setMutexStrategy($strategy) + { + $this->mutexStrategy = $strategy; + } + + public function getMutexName() + { + $name = $this->getName(); + $arguments = json_encode($this->argument()); + return "icmutex-{$name}-" . md5($arguments); + } + protected function execute(InputInterface $input, OutputInterface $output) { $mutex = new Mutex($this); @@ -20,14 +37,4 @@ trait WithoutOverlapping return $code; } - - public function getMutexStrategy() - { - return (isset($this->mutexStrategy) ? $this->mutexStrategy : 'file'); - } - - public function setMutexStrategy($strategy) - { - $this->mutexStrategy = $strategy; - } }
ICM: Formatted & getMutexName() method added.
dmitry-ivanov_laravel-console-mutex
train
5697744bda0633b08520a52a60bc83453d942792
diff --git a/tests/src/test/java/alluxio/master/file/ConcurrentFileSystemMasterTest.java b/tests/src/test/java/alluxio/master/file/ConcurrentFileSystemMasterTest.java index <HASH>..<HASH> 100644 --- a/tests/src/test/java/alluxio/master/file/ConcurrentFileSystemMasterTest.java +++ b/tests/src/test/java/alluxio/master/file/ConcurrentFileSystemMasterTest.java @@ -61,8 +61,11 @@ import java.util.regex.Pattern; */ public class ConcurrentFileSystemMasterTest { private static final String TEST_USER = "test"; - private static final long SLEEP_MS = Constants.SECOND_MS; private static final int CONCURRENCY_FACTOR = 50; + /** Duration to sleep during the rename call to show the benefits of concurrency */ + private static final long SLEEP_MS = Constants.SECOND_MS; + /** Timeout for the concurrent test after which we will mark the test as failed */ + private static final long LIMIT_MS = SLEEP_MS * CONCURRENCY_FACTOR / 10; /** * Options to mark a created file as persisted. Note that this does not actually persist the * file but flag the file to be treated as persisted, which will invoke ufs operations. @@ -404,8 +407,8 @@ public class ConcurrentFileSystemMasterTest { t.join(); } long durationMs = CommonUtils.getCurrentMs() - startMs; - Assert.assertTrue("Execution duration " + durationMs + " took longer than expected " - + (SLEEP_MS * 2), durationMs < SLEEP_MS * 2); + Assert.assertTrue("Execution duration " + durationMs + " took longer than expected " + LIMIT_MS, + durationMs < LIMIT_MS); return errors.size(); }
Make the concurrency test timeout based on the concurrency factor.
Alluxio_alluxio
train
7160c0a899220d8d7706a889c94a8eec7c442131
diff --git a/nolearn/lasagne/visualize.py b/nolearn/lasagne/visualize.py index <HASH>..<HASH> 100644 --- a/nolearn/lasagne/visualize.py +++ b/nolearn/lasagne/visualize.py @@ -152,20 +152,18 @@ def occlusion_heatmap(net, x, target, square_length=7): heat_array = np.zeros((s0, s1)) pad = square_length // 2 + 1 - x_occluded = np.zeros((s0, s1, col, s0, s1), dtype=img.dtype) + x_occluded = np.zeros((s1, col, s0, s1), dtype=img.dtype) + probs = np.zeros((s0, s1, num_classes)) # generate occluded images for i in range(s0): + # batch s1 occluded images for faster prediction for j in range(s1): x_pad = np.pad(img, ((0, 0), (pad, pad), (pad, pad)), 'constant') x_pad[:, i:i + square_length, j:j + square_length] = 0. - x_occluded[i, j] = x_pad[:, pad:-pad, pad:-pad] - - # make batch predictions for each occluded image - probs = np.zeros((s0, s1, num_classes)) - for i in range(s0): - y_proba = net.predict_proba(np.squeeze(x_occluded[i:i + 1], 0)) - probs[i:i + 1] = y_proba.reshape(1, s1, num_classes) + x_occluded[j] = x_pad[:, pad:-pad, pad:-pad] + y_proba = net.predict_proba(x_occluded) + probs[i] = y_proba.reshape(s1, num_classes) # from predicted probabilities, pick only those of target class for i in range(s0):
plot_occlusion how requires less memory.
dnouri_nolearn
train
b39d5ffb3881abd61194820481ee0ed8f21adc54
diff --git a/src/main/java/com/couchbase/lite/LiveQuery.java b/src/main/java/com/couchbase/lite/LiveQuery.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/couchbase/lite/LiveQuery.java +++ b/src/main/java/com/couchbase/lite/LiveQuery.java @@ -19,7 +19,7 @@ public final class LiveQuery extends Query implements Database.ChangeListener { private QueryEnumerator rows; private List<ChangeListener> observers = new ArrayList<ChangeListener>(); private Throwable lastError; - private AtomicBoolean runningState; // true == running, false == stopped + private final AtomicBoolean runningState; // true == running, false == stopped /** * If a query is running and the user calls stop() on this query, the future @@ -39,20 +39,8 @@ public final class LiveQuery extends Query implements Database.ChangeListener { */ @InterfaceAudience.Private /* package */ LiveQuery(Query query) { - super(query.getDatabase(), query.getView()); + super(query.getDatabase(), query); runningState = new AtomicBoolean(false); - setLimit(query.getLimit()); - setSkip(query.getSkip()); - setStartKey(query.getStartKey()); - setEndKey(query.getEndKey()); - setDescending(query.isDescending()); - setPrefetch(query.shouldPrefetch()); - setKeys(query.getKeys()); - setGroupLevel(query.getGroupLevel()); - setMapOnly(query.isMapOnly()); - setStartKeyDocId(query.getStartKeyDocId()); - setEndKeyDocId(query.getEndKeyDocId()); - setIndexUpdateMode(query.getIndexUpdateMode()); } /**
Fix toLiveQuery() ignoring some setted properties. It did not copy prefetch, all docs mode, inclusiveEnd and postFilter.
couchbase_couchbase-lite-java-core
train
aacca0c7e1473543912fd97f152a11ffe4e2e458
diff --git a/aws/resource_aws_vpc_dhcp_options_test.go b/aws/resource_aws_vpc_dhcp_options_test.go index <HASH>..<HASH> 100644 --- a/aws/resource_aws_vpc_dhcp_options_test.go +++ b/aws/resource_aws_vpc_dhcp_options_test.go @@ -90,6 +90,7 @@ func TestAccAWSDHCPOptions_basic(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, + ErrorCheck: testAccErrorCheck(t, ec2.EndpointsID), Providers: testAccProviders, CheckDestroy: testAccCheckDHCPOptionsDestroy, Steps: []resource.TestStep{ @@ -124,6 +125,7 @@ func TestAccAWSDHCPOptions_deleteOptions(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, + ErrorCheck: testAccErrorCheck(t, ec2.EndpointsID), Providers: testAccProviders, CheckDestroy: testAccCheckDHCPOptionsDestroy, Steps: []resource.TestStep{ @@ -146,6 +148,7 @@ func TestAccAWSDHCPOptions_tags(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, + ErrorCheck: testAccErrorCheck(t, ec2.EndpointsID), Providers: testAccProviders, CheckDestroy: testAccCheckDHCPOptionsDestroy, Steps: []resource.TestStep{ @@ -190,6 +193,7 @@ func TestAccAWSDHCPOptions_disappears(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, + ErrorCheck: testAccErrorCheck(t, ec2.EndpointsID), Providers: testAccProviders, CheckDestroy: testAccCheckDHCPOptionsDestroy, Steps: []resource.TestStep{
tests/r/vpc_dhcp_options: Add ErrorCheck
terraform-providers_terraform-provider-aws
train
15096313036f48d346c3f84981718f9176485727
diff --git a/src/main/java/net/jodah/failsafe/TimeoutExecutor.java b/src/main/java/net/jodah/failsafe/TimeoutExecutor.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/jodah/failsafe/TimeoutExecutor.java +++ b/src/main/java/net/jodah/failsafe/TimeoutExecutor.java @@ -110,10 +110,10 @@ class TimeoutExecutor extends PolicyExecutor<Timeout> { // Schedule timeout if not an async execution if (!execution.isAsyncExecution()) { - try { - // Guard against race with future.complete or future.cancel - synchronized (future) { - if (!future.isDone()) { + // Guard against race with future.complete or future.cancel + synchronized (future) { + if (!future.isDone()) { + try { // Schedule timeout check timeoutFuture.set((Future) scheduler.schedule(() -> { if (executionResult.compareAndSet(null, ExecutionResult.failure(new TimeoutExceededException(policy))) @@ -128,12 +128,12 @@ class TimeoutExecutor extends PolicyExecutor<Timeout> { return null; }, policy.getTimeout().toNanos(), TimeUnit.NANOSECONDS)); future.injectTimeout(timeoutFuture.get()); + } catch (Throwable t) { + // Hard scheduling failure + promise.completeExceptionally(t); + return promise; } } - } catch (Throwable t) { - // Hard scheduling failure - promise.completeExceptionally(t); - return promise; } }
Narrow the scheduler try/catch block in Timeout
jhalterman_failsafe
train
0a16cf21021bc85cccd743da84897d3abcbabfbe
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ServerRunCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ServerRunCommand.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/ServerRunCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/ServerRunCommand.php @@ -101,6 +101,14 @@ EOF ->locateResource(sprintf('@FrameworkBundle/Resources/config/router_%s.php', $env)) ; + if (!file_exists($router)) { + $output->writeln(sprintf('<error>The given router script "%s" does not exist</error>', $router)); + + return 1; + } + + $router = realpath($router); + $output->writeln(sprintf("Server running on <info>http://%s</info>\n", $input->getArgument('address'))); $builder = new ProcessBuilder(array(PHP_BINARY, '-S', $input->getArgument('address'), $router));
improve handling router script paths The `server:run` command switches the working directory before starting the built-in web server. Therefore, the path to a custom router script had to be specified based on the document root path and not based on the user's working directory.
symfony_symfony
train
c9b79faf97f8520544712c4fab81e3679d4c0cd6
diff --git a/test/com/esotericsoftware/kryo/SerializationCompatTestData.java b/test/com/esotericsoftware/kryo/SerializationCompatTestData.java index <HASH>..<HASH> 100644 --- a/test/com/esotericsoftware/kryo/SerializationCompatTestData.java +++ b/test/com/esotericsoftware/kryo/SerializationCompatTestData.java @@ -218,7 +218,7 @@ public class SerializationCompatTestData { _integerArray = new Integer[] {13}; _date = new Date(42); - _calendar = Calendar.getInstance(); + _calendar = Calendar.getInstance(Locale.ENGLISH); _calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); _calendar.set(2009, Calendar.JANUARY, 25, 10, 29, 0); _calendar.set(Calendar.MILLISECOND, 0);
Fix test when building with JDK<I> (Locale providers changed in JDK<I> <URL>)
EsotericSoftware_kryo
train
e44a40f34d7f1ae6441b2eb263c06a87fdcfa855
diff --git a/lib/layout/position.js b/lib/layout/position.js index <HASH>..<HASH> 100644 --- a/lib/layout/position.js +++ b/lib/layout/position.js @@ -37,9 +37,7 @@ module.exports = function() { return self; function run(g) { - g = g.filterNodes(nodesFromList(g.nodes().filter(function(u) { - return !g.children(u).length; - }))); + g = g.filterNodes(util.filterNonSubgraphs(g)); var layering = []; g.eachNode(function(u, node) { diff --git a/lib/layout/rank.js b/lib/layout/rank.js index <HASH>..<HASH> 100644 --- a/lib/layout/rank.js +++ b/lib/layout/rank.js @@ -7,6 +7,8 @@ var util = require("../util"), module.exports = function(g, debugLevel) { var timer = util.createTimer(debugLevel >= 1); timer.wrap("Rank phase", function() { + g = g.filterNodes(util.filterNonSubgraphs(g)); + initRank(g); components(g).forEach(function(cmpt) { diff --git a/lib/util.js b/lib/util.js index <HASH>..<HASH> 100644 --- a/lib/util.js +++ b/lib/util.js @@ -89,3 +89,13 @@ exports.ordering = function(g) { }); return ordering; }; + +/* + * A filter that can be used with `filterNodes` to get a graph that only + * includes nodes that do not contain others nodes. + */ +exports.filterNonSubgraphs = function(g) { + return function(u) { + return g.children(u).length === 0; + }; +}; diff --git a/test/unit/layout/rank-test.js b/test/unit/layout/rank-test.js index <HASH>..<HASH> 100644 --- a/test/unit/layout/rank-test.js +++ b/test/unit/layout/rank-test.js @@ -40,5 +40,14 @@ describe("layout/rank", function() { assert.equal(g.node("A").rank, 0); assert.equal(g.node("B").rank, 2); }); + + it("does not assign a rank to a subgraph node", function() { + var g = dot.parse("digraph { subgraph sg1 { A } }"); + + rank(g); + + assert.equal(g.node("A").rank, 0); + assert.notProperty(g.node("sg1"), "rank"); + }); });
Don't add rank to composite nodes
dagrejs_dagre
train