hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
afd7f08db8c66c9208dcc086d883c829727a0c8c
diff --git a/lib/tay/cli/generate.rb b/lib/tay/cli/generate.rb index <HASH>..<HASH> 100644 --- a/lib/tay/cli/generate.rb +++ b/lib/tay/cli/generate.rb @@ -33,6 +33,18 @@ module Tay # Render a template in the context of self and return its contents # Thor does not provide a way to do this. def render_template(path, locals = {}) + path = path.to_s + + # Try to use a haml file path if available + if path[/\.html$/] && using_haml? + begin + if find_in_source_paths(path + '.haml') + path = path + '.haml' + end + rescue Exception + end + end + tayfile_template = Tilt::ERBTemplate.new(find_in_source_paths(path), { :trim => '-' }) @@ -60,6 +72,17 @@ module Tay end ## + # Create a file, tacking on .haml if we're using it + def create_file(path, content, *args) + path = path.to_s + if path[/\.html$/] && using_haml? + path = path + '.haml' + end + + super + end + + ## # Get path to src/assets def asset_dir src_dir.join('assets') diff --git a/lib/tay/cli/generators/browser_action.rb b/lib/tay/cli/generators/browser_action.rb index <HASH>..<HASH> 100644 --- a/lib/tay/cli/generators/browser_action.rb +++ b/lib/tay/cli/generators/browser_action.rb @@ -13,8 +13,7 @@ module Tay copy_file('browser_action/action.js', javascript_dir.join(fs_name+ '.js')) copy_file('browser_action/action.css', stylesheet_dir.join(fs_name+ '.css')) - html_ext = using_haml? ? '.html.haml' : '.html' - create_file(html_dir.join(fs_name + html_ext), render_template('browser_action/action' + html_ext, :fs_name => fs_name)) + create_file(html_dir.join(fs_name + '.html'), render_template('browser_action/action.html', :fs_name => fs_name)) inject_tayfile_content(render_template('browser_action/tayfile', :fs_name => fs_name)) end
Abstract away haml detection in generators
rixth_tay
train
fd6e56fc87821acc4a84e0144e298597edea3848
diff --git a/test/testsuite/runtime/util/BasePeerTest.php b/test/testsuite/runtime/util/BasePeerTest.php index <HASH>..<HASH> 100644 --- a/test/testsuite/runtime/util/BasePeerTest.php +++ b/test/testsuite/runtime/util/BasePeerTest.php @@ -65,6 +65,8 @@ class BasePeerTest extends BookstoreTestBase { */ public function testBigIntIgnoreCaseOrderBy() { + BookstorePeer::doDeleteAll(); + // Some sample data $b = new Bookstore(); $b->setStoreName("SortTest1")->setPopulationServed(2000)->save(); @@ -95,7 +97,6 @@ class BasePeerTest extends BookstoreTestBase { */ public function testMixedJoinOrder() { - $this->markTestIncomplete(); $c = new Criteria(BookPeer::DATABASE_NAME); $c->addSelectColumn(BookPeer::ID); $c->addSelectColumn(BookPeer::TITLE); @@ -107,6 +108,6 @@ class BasePeerTest extends BookstoreTestBase { $sql = BasePeer::createSelectSql($c, $params); $expectedSql = "SELECT book.ID, book.TITLE FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.ID), author WHERE book.AUTHOR_ID=author.ID"; - // print $sql . "\n"; + $this->assertEquals($expectedSql, $sql); } }
[<I>] changed error to failure in BasePeerTest
propelorm_Propel
train
db1d4b9e52d7496a9049424906b6980305926980
diff --git a/imgaug/augmenters/color.py b/imgaug/augmenters/color.py index <HASH>..<HASH> 100644 --- a/imgaug/augmenters/color.py +++ b/imgaug/augmenters/color.py @@ -94,6 +94,37 @@ _CSPACE_OPENCV_CONV_VARS = { if hasattr(cv2, "COLOR_Lab2BGR") else cv2.COLOR_LAB2BGR) } +# TODO test these pairs +_CHANGE_COLORSPACE_INPLACE = { + # RGB + (CSPACE_RGB, CSPACE_BGR): True, + (CSPACE_RGB, CSPACE_GRAY): False, + (CSPACE_RGB, CSPACE_CIE): True, + (CSPACE_RGB, CSPACE_YCrCb): True, + (CSPACE_RGB, CSPACE_HSV): True, + (CSPACE_RGB, CSPACE_HLS): True, + (CSPACE_RGB, CSPACE_Lab): False, + (CSPACE_RGB, CSPACE_Luv): True, + # BGR + (CSPACE_BGR, CSPACE_RGB): True, + (CSPACE_BGR, CSPACE_GRAY): False, + (CSPACE_BGR, CSPACE_CIE): True, + (CSPACE_BGR, CSPACE_YCrCb): True, + (CSPACE_BGR, CSPACE_HSV): True, + (CSPACE_BGR, CSPACE_HLS): True, + (CSPACE_BGR, CSPACE_Lab): False, + (CSPACE_BGR, CSPACE_Luv): True, + # HSV + (CSPACE_HSV, CSPACE_RGB): True, + (CSPACE_HSV, CSPACE_BGR): True, + # HLS + (CSPACE_HLS, CSPACE_RGB): True, + (CSPACE_HLS, CSPACE_BGR): True, + # Lab + (CSPACE_Lab, CSPACE_RGB): False, + (CSPACE_Lab, CSPACE_BGR): False +} + # TODO add direct tests # TODO allow grayscale input images that have three channels @@ -159,6 +190,16 @@ def change_colorspace_(image, to_colorspace, from_colorspace=CSPACE_RGB): # the docs, but at least for conversion to grayscale that # results in errors, ie uint8 is expected + def _get_dst(image, from_to_cspace): + if _CHANGE_COLORSPACE_INPLACE[from_to_cspace]: + # inplace mode for cv2's cvtColor seems to have issues with + # images that are views (e.g. image[..., 0:3]) and returns a + # cv2.UMat instance instead of an array. So we check here first + # if the array looks like it is non-contiguous or a view. + if image.flags["C_CONTIGUOUS"] and image.flags["OWNDATA"]: + return image + return None + iadt.gate_dtypes( image, allowed=["uint8"], @@ -204,12 +245,17 @@ def change_colorspace_(image, to_colorspace, from_colorspace=CSPACE_RGB): image_aug = image if from_to_direct in _CSPACE_OPENCV_CONV_VARS: from2to_var = _CSPACE_OPENCV_CONV_VARS[from_to_direct] - image_aug = cv2.cvtColor(image, from2to_var, dst=image_aug) + dst = _get_dst(image_aug, from_to_direct) + image_aug = cv2.cvtColor(image_aug, from2to_var, dst=dst) else: from2rgb_var = _CSPACE_OPENCV_CONV_VARS[from_to_indirect[0]] rgb2to_var = _CSPACE_OPENCV_CONV_VARS[from_to_indirect[1]] - image_aug = cv2.cvtColor(image_aug, from2rgb_var, dst=image_aug) - image_aug = cv2.cvtColor(image_aug, rgb2to_var, dst=image_aug) + + dst1 = _get_dst(image_aug, from_to_indirect[0]) + dst2 = _get_dst(image_aug, from_to_indirect[1]) + + image_aug = cv2.cvtColor(image_aug, from2rgb_var, dst=dst1) + image_aug = cv2.cvtColor(image_aug, rgb2to_var, dst=dst2) # TODO dont convert to uint8 if image_aug.dtype.kind == "f":
Fix cspace conv failing for some cspaces/arrays
aleju_imgaug
train
008d10376cd9577d7ca8432560ed1f24800240b4
diff --git a/lib/reader.js b/lib/reader.js index <HASH>..<HASH> 100644 --- a/lib/reader.js +++ b/lib/reader.js @@ -127,7 +127,11 @@ ModuleReader.prototype = { }); }); - return promise; + return promise.fail(function(err) { + // Provide additional context for uncaught build errors. + util.log.err("Error while reading module " + id + ":"); + throw err; + }); }, function(source) { var deps = getRequiredIDs(id, source);
Provide additional context for uncaught build errors.
facebookarchive_commoner
train
827557a1356523e13c2c41a6ea8ff85e2288242a
diff --git a/libre/apps/scheduler/literals.py b/libre/apps/scheduler/literals.py index <HASH>..<HASH> 100644 --- a/libre/apps/scheduler/literals.py +++ b/libre/apps/scheduler/literals.py @@ -1 +1 @@ -SHUTDOWN_COMMANDS = ['syncdb', 'migrate', 'schemamigration', 'datamigration', 'collectstatic', 'shell', 'shell_plus'] +SHUTDOWN_COMMANDS = ['syncdb', 'migrate', 'schemamigration', 'datamigration', 'collectstatic', 'shell', 'shell_plus', 'test']
Shutdown scheduler during tests too
commonwealth-of-puerto-rico_libre
train
d4e0b753cf8b1b81d16569bf5445abe4bcabda36
diff --git a/log4go.go b/log4go.go index <HASH>..<HASH> 100644 --- a/log4go.go +++ b/log4go.go @@ -295,6 +295,61 @@ func (log Logger) Log(lvl level, source, message string) { } } +// Send a formatted log message internally +func (log Logger) intLogNamef(logname string, lvl level, format string, args ...interface{}) { + l, ok := log[logname] + if !ok { + return + } + + // Determine caller func + pc, _, lineno, ok := runtime.Caller(2) + src := "" + if ok { + src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno) + } + + msg := format + if len(args) > 0 { + msg = fmt.Sprintf(format, args...) + } + // Make the log record + rec := &LogRecord{ + Level: lvl, + Created: time.Now(), + Source: src, + Message: msg, + } + // Dispatch the logs + l.LogWrite(rec) +} + +// Send a closure log message internally +func (log Logger) intLogNamec(logname string, lvl level, closure func() string) { + l, ok := log[logname] + if !ok { + return + } + + // Determine caller func + pc, _, lineno, ok := runtime.Caller(2) + src := "" + if ok { + src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno) + } + + // Make the log record + rec := &LogRecord{ + Level: lvl, + Created: time.Now(), + Source: src, + Message: closure(), + } + + // Dispatch the logs + l.LogWrite(rec) +} + // Logf logs a formatted log message at the given log level, using the caller as // its source. func (log Logger) Logf(lvl level, format string, args ...interface{}) { @@ -460,54 +515,6 @@ func (log Logger) Error(arg0 interface{}, args ...interface{}) error { return errors.New(msg) } -// Error logs a message at the error log level and returns the formatted error, -// See Warn for an explanation of the performance and Debug for an explanation -// of the parameters. -func (log Logger) ErrorLog(logname string, arg0 interface{}, args ...interface{}) error { - const ( - lvl = ERROR - ) - var msg string - switch first := arg0.(type) { - case string: - // Use the string as a format string - msg = fmt.Sprintf(first, args...) - case func() string: - // Log the closure (no other arguments used) - return errors.New("unsupport ErrorLog closure!") - default: - // Build a format string so that it will be similar to Sprint - msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) - } - - l, ok := log[logname] - if !ok { - return errors.New("no log filter") - } - // Determine caller func - pc, _, lineno, ok := runtime.Caller(2) - src := "" - if ok { - src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno) - } - - if len(args) > 0 { - msg = fmt.Sprintf(msg, args...) - } - - // Make the log record - rec := &LogRecord{ - Level: lvl, - Created: time.Now(), - Source: src, - Message: msg, - } - - //log record - l.LogWrite(rec) - return nil -} - // Critical logs a message at the critical log level and returns the formatted error, // See Warn for an explanation of the performance and Debug for an explanation // of the parameters. diff --git a/wrapper.go b/wrapper.go index <HASH>..<HASH> 100644 --- a/wrapper.go +++ b/wrapper.go @@ -4,8 +4,8 @@ package log4go import ( "errors" - "os" "fmt" + "os" "strings" ) @@ -252,6 +252,31 @@ func Error(arg0 interface{}, args ...interface{}) error { return nil } +// Utility for error log messages (returns an error for easy function returns) (see Debug() for parameter explanation) +// These functions will execute a closure exactly once, to build the error message for the return +// Wrapper for (*Logger).Error +func ErrorLog(logname string, arg0 interface{}, args ...interface{}) error { + const ( + lvl = ERROR + ) + switch first := arg0.(type) { + case string: + // Use the string as a format string + Global.intLogNamef(logname, lvl, first, args...) + return errors.New(fmt.Sprintf(first, args...)) + case func() string: + // Log the closure (no other arguments used) + str := first() + Global.intLogNamef(logname, lvl, "%s", str) + return errors.New(str) + default: + // Build a format string so that it will be similar to Sprint + Global.intLogNamef(logname, lvl, fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...) + return errors.New(fmt.Sprint(first) + fmt.Sprintf(strings.Repeat(" %v", len(args)), args...)) + } + return nil +} + // Utility for critical log messages (returns an error for easy function returns) (see Debug() for parameter explanation) // These functions will execute a closure exactly once, to build the error message for the return // Wrapper for (*Logger).Critical
modified: log4go.go modified: wrapper.go
blackbeans_log4go
train
3042b2a622815bdd91b14516ae6ba96288337daa
diff --git a/app/models/devise_token_auth/concerns/user.rb b/app/models/devise_token_auth/concerns/user.rb index <HASH>..<HASH> 100644 --- a/app/models/devise_token_auth/concerns/user.rb +++ b/app/models/devise_token_auth/concerns/user.rb @@ -11,7 +11,7 @@ module DeviseTokenAuth::Concerns::User self.devise_modules.delete(:omniauthable) end - serialize :tokens, HashWithIndifferentAccess + serialize :tokens, JSON validates_presence_of :email, if: Proc.new { |u| u.provider == 'email' } validates_presence_of :uid, if: Proc.new { |u| u.provider != 'email' } @@ -102,32 +102,39 @@ module DeviseTokenAuth::Concerns::User def token_is_current?(token, client_id) + # ghetto HashWithIndifferentAccess + expiry = self.tokens[client_id]['expiry'] || self.tokens[client_id][:expiry] + token_hash = self.tokens[client_id]['token'] || self.tokens[client_id][:token] + return true if ( # ensure that expiry and token are set - self.tokens[client_id]['expiry'] and - self.tokens[client_id]['token'] and + expiry and token and # ensure that the token has not yet expired - DateTime.strptime(self.tokens[client_id]['expiry'].to_s, '%s') > Time.now and + DateTime.strptime(expiry.to_s, '%s') > Time.now and # ensure that the token is valid - BCrypt::Password.new(self.tokens[client_id]['token']) == token + BCrypt::Password.new(token_hash) == token ) end # allow batch requests to use the previous token def token_can_be_reused?(token, client_id) + # ghetto HashWithIndifferentAccess + updated_at = self.tokens[client_id]['updated_at'] || self.tokens[client_id][:updated_at] + last_token = self.tokens[client_id]['last_token'] || self.tokens[client_id][:last_token] + + return true if ( # ensure that the last token and its creation time exist - self.tokens[client_id]['updated_at'] and - self.tokens[client_id]['last_token'] and + updated_at and last_token and # ensure that previous token falls within the batch buffer throttle time of the last request - self.tokens[client_id]['updated_at'] > Time.now - DeviseTokenAuth.batch_request_buffer_throttle and + updated_at > Time.now - DeviseTokenAuth.batch_request_buffer_throttle and # ensure that the token is valid - BCrypt::Password.new(self.tokens[client_id]['last_token']) == token + BCrypt::Password.new(last_token) == token ) end diff --git a/test/models/user_test.rb b/test/models/user_test.rb index <HASH>..<HASH> 100644 --- a/test/models/user_test.rb +++ b/test/models/user_test.rb @@ -79,11 +79,11 @@ class UserTest < ActiveSupport::TestCase end test 'expired token was removed' do - refute @resource.tokens[@old_auth_headers['client']] + refute @resource.tokens[@old_auth_headers[:client]] end test 'current token was not removed' do - assert @resource.tokens[@new_auth_headers['client']] + assert @resource.tokens[@new_auth_headers["client"]] end end end
fix testing issue with symbol / string token hash access
lynndylanhurley_devise_token_auth
train
dd571459719473a00c143eb37b7661207c5ff9ef
diff --git a/sh.py b/sh.py index <HASH>..<HASH> 100644 --- a/sh.py +++ b/sh.py @@ -1639,31 +1639,33 @@ class OProc(object): session_pipe_read, session_pipe_write = os.pipe() exc_pipe_read, exc_pipe_write = os.pipe() + # this pipe is for synchronzing with the child that the parent has + # closed its in/out/err fds. this is a bug on OSX (but not linux), + # where we can lose output sometimes, due to a race, if we do + # os.close(self._stdout_write_fd) in the parent after the child starts + # writing. + if IS_OSX: + close_pipe_read, close_pipe_write = os.pipe() + # session id, group id, process id self.sid = None self.pgid = None self.pid = os.fork() - # child if self.pid == 0: # pragma: no cover + if IS_OSX: + os.read(close_pipe_read, 1) + os.close(close_pipe_read) + os.close(close_pipe_write) + try: # ignoring SIGHUP lets us persist even after the parent process # exits. only ignore if we're backgrounded if ca["bg"] is True: signal.signal(signal.SIGHUP, signal.SIG_IGN) - # this piece of ugliness is due to a bug where we can lose output - # if we do os.close(self._stdout_write_fd) in the parent after - # the child starts writing. - # see http://bugs.python.org/issue15898 - # - # TODO is this still necessary or was it a bug in sh's process - # model? - if IS_OSX: - time.sleep(0.01) - # put our forked process in a new session? this will relinquish # any control of our inherited CTTY and also make our parent # process init @@ -1765,6 +1767,17 @@ class OProc(object): if gc_enabled: gc.enable() + os.close(self._stdin_write_fd) + os.close(self._stdout_write_fd) + os.close(self._stderr_write_fd) + + # tell our child process that we've closed our write_fds, so it is + # ok to proceed towards exec. see the comment where this pipe is + # opened, for why this is necessary + if IS_OSX: + os.close(close_pipe_read) + os.write(close_pipe_write, str(1).encode(DEFAULT_ENCODING)) + os.close(close_pipe_write) os.close(exc_pipe_write) fork_exc = os.read(exc_pipe_read, 1024**2) @@ -1775,7 +1788,6 @@ class OProc(object): os.close(session_pipe_write) self.sid = int(os.read(session_pipe_read, 1024)) - os.close(session_pipe_read) self.pgid = os.getpgid(self.pid) @@ -1815,9 +1827,6 @@ class OProc(object): self.log = parent_log.get_child("process", repr(self)) - os.close(self._stdin_write_fd) - os.close(self._stdout_write_fd) - os.close(self._stderr_write_fd) self.log.debug("started process")
more robust fix of osx dropped output bug
amoffat_sh
train
8266ba8c8e19e4d59effc2529cac028e80beb6cb
diff --git a/src/Symfony/Component/Mime/Header/AbstractHeader.php b/src/Symfony/Component/Mime/Header/AbstractHeader.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Mime/Header/AbstractHeader.php +++ b/src/Symfony/Component/Mime/Header/AbstractHeader.php @@ -109,6 +109,11 @@ abstract class AbstractHeader implements HeaderInterface } $phraseStr = $this->encodeWords($header, $string, $usedLength); } + } elseif (str_contains($phraseStr, '(')) { + foreach (['\\', '"'] as $char) { + $phraseStr = str_replace($char, '\\'.$char, $phraseStr); + } + $phraseStr = '"'.$phraseStr.'"'; } return $phraseStr; diff --git a/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php b/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php +++ b/src/Symfony/Component/Mime/Tests/Header/MailboxListHeaderTest.php @@ -50,6 +50,12 @@ class MailboxListHeaderTest extends TestCase $this->assertEquals(['"Chris Corbyn, \\\\escaped\\\\" <chris@swiftmailer.org>'], $header->getAddressStrings()); } + public function testParenthesesInNameAreQuoted() + { + $header = new MailboxListHeader('From', [new Address('j.doe@example.com', 'J Doe (ACME)')]); + $this->assertEquals(['"J Doe (ACME)" <j.doe@example.com>'], $header->getAddressStrings()); + } + public function testUtf8CharsInDomainAreIdnEncoded() { $header = new MailboxListHeader('From', [new Address('chris@swïftmailer.org', 'Chris Corbyn')]);
quote address names if they contain parentheses
symfony_symfony
train
444e7e8af4ecbb48f7779aa7f90ca1937df9ecfc
diff --git a/src/main/java/org/jenkinsci/plugins/ghprb/Ghprb.java b/src/main/java/org/jenkinsci/plugins/ghprb/Ghprb.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/jenkinsci/plugins/ghprb/Ghprb.java +++ b/src/main/java/org/jenkinsci/plugins/ghprb/Ghprb.java @@ -391,9 +391,7 @@ public class Ghprb { specifications.add(new SchemeSpecification(serverUri.getScheme())); specifications.add(new PathSpecification(serverUri.getPath(), null, false)); - - - Domain domain = new Domain(serverAPIUrl, "Auto generated credentials domain", specifications); + Domain domain = new Domain(serverUri.getHost(), "Auto generated credentials domain", specifications); CredentialsStore provider = new SystemCredentialsProvider.StoreImpl(); provider.addDomain(domain, credentials); return credentials.getId();
Change to just use the host name for the default domain
jenkinsci_ghprb-plugin
train
1cbcfdde4e666ee93218f918e96cf8c590fbe517
diff --git a/lib/chef/provider/user/windows.rb b/lib/chef/provider/user/windows.rb index <HASH>..<HASH> 100644 --- a/lib/chef/provider/user/windows.rb +++ b/lib/chef/provider/user/windows.rb @@ -36,7 +36,7 @@ class Chef def load_current_resource if new_resource.gid - Chef::Log.warn("The 'gid' attribute is not implemented by the Windows platform. Please use the 'group' resource to assign a user to a group.") + Chef::Log.warn("The 'gid' (or 'group') property is not implemented on the Windows platform. Please use the `members` property of the 'group' resource to assign a user to a group.") end @current_resource = Chef::Resource::User.new(new_resource.name)
change worning msg for windows create user resource
chef_chef
train
79e5fd6b74abface96e3df2feeb17b713cfab6e0
diff --git a/cmd/helm/search.go b/cmd/helm/search.go index <HASH>..<HASH> 100644 --- a/cmd/helm/search.go +++ b/cmd/helm/search.go @@ -21,6 +21,7 @@ import ( "io" "strings" + "github.com/gosuri/uitable" "github.com/spf13/cobra" "k8s.io/helm/cmd/helm/helmpath" @@ -71,6 +72,7 @@ func (s *searchCmd) run(args []string) error { if len(args) == 0 { s.showAllCharts(index) + return nil } q := strings.Join(args, " ") @@ -80,17 +82,34 @@ func (s *searchCmd) run(args []string) error { } search.SortScore(res) - for _, r := range res { - fmt.Fprintln(s.out, r.Name) - } + fmt.Fprintln(s.out, s.formatSearchResults(res)) return nil } func (s *searchCmd) showAllCharts(i *search.Index) { - for name := range i.Entries() { - fmt.Fprintln(s.out, name) + e := i.Entries() + res := make([]*search.Result, len(e)) + j := 0 + for name, ch := range e { + res[j] = &search.Result{ + Name: name, + Chart: ch, + } + j++ + } + search.SortScore(res) + fmt.Fprintln(s.out, s.formatSearchResults(res)) +} + +func (s *searchCmd) formatSearchResults(res []*search.Result) string { + table := uitable.New() + table.MaxColWidth = 50 + table.AddRow("NAME", "VERSION", "DESCRIPTION") + for _, r := range res { + table.AddRow(r.Name, r.Chart.Version, r.Chart.Description) } + return table.String() } func (s *searchCmd) buildIndex() (*search.Index, error) { diff --git a/cmd/helm/search/search.go b/cmd/helm/search/search.go index <HASH>..<HASH> 100644 --- a/cmd/helm/search/search.go +++ b/cmd/helm/search/search.go @@ -39,6 +39,7 @@ import ( type Result struct { Name string Score int + Chart *repo.ChartVersion } // Index is a searchable index of chart information. @@ -117,7 +118,7 @@ func (i *Index) SearchLiteral(term string, threshold int) []*Result { for k, v := range i.lines { res := strings.Index(v, term) if score := i.calcScore(res, v); res != -1 && score < threshold { - buf = append(buf, &Result{Name: k, Score: score}) + buf = append(buf, &Result{Name: k, Score: score, Chart: i.charts[k]}) } } return buf @@ -136,7 +137,7 @@ func (i *Index) SearchRegexp(re string, threshold int) ([]*Result, error) { continue } if score := i.calcScore(ind[0], v); ind[0] >= 0 && score < threshold { - buf = append(buf, &Result{Name: k, Score: score}) + buf = append(buf, &Result{Name: k, Score: score, Chart: i.charts[k]}) } } return buf, nil diff --git a/cmd/helm/search_test.go b/cmd/helm/search_test.go index <HASH>..<HASH> 100644 --- a/cmd/helm/search_test.go +++ b/cmd/helm/search_test.go @@ -34,23 +34,23 @@ func TestSearchCmd(t *testing.T) { { name: "search for 'maria', expect one match", args: []string{"maria"}, - expect: "testing/mariadb", + expect: "NAME \tVERSION\tDESCRIPTION \ntesting/mariadb\t0.3.0 \tChart for MariaDB", }, { name: "search for 'alpine', expect two matches", args: []string{"alpine"}, - expect: "testing/alpine", + expect: "NAME \tVERSION\tDESCRIPTION \ntesting/alpine\t0.1.0 \tDeploy a basic Alpine Linux pod", }, { name: "search for 'syzygy', expect no matches", args: []string{"syzygy"}, - expect: "", + expect: "NAME\tVERSION\tDESCRIPTION", }, { name: "search for 'alp[a-z]+', expect two matches", args: []string{"alp[a-z]+"}, flags: []string{"--regexp"}, - expect: "testing/alpine", + expect: "NAME \tVERSION\tDESCRIPTION \ntesting/alpine\t0.1.0 \tDeploy a basic Alpine Linux pod", regexp: true, }, {
fix(helm): fix 'helm search' to use UITable Closes #<I>
helm_helm
train
a6319d1c8ba9b9c12f7ce7116538152878225af0
diff --git a/tests/test_make_request.py b/tests/test_make_request.py index <HASH>..<HASH> 100644 --- a/tests/test_make_request.py +++ b/tests/test_make_request.py @@ -9,6 +9,7 @@ from mock import patch, Mock, ANY from twilio import TwilioRestException from twilio.rest.resources.base import make_request, make_twilio_request from twilio.rest.resources.connection import Connection +from twilio.rest.resources.connection import PROXY_TYPE_SOCKS5 get_headers = { "User-Agent": "twilio-python/%s" % (twilio.__version__), @@ -99,11 +100,16 @@ def test_proxy_info(http_mock, resp_mock): http = Mock() http.request.return_value = (Mock(), Mock()) http_mock.return_value = http - Connection.set_proxy_info('http://example.com/proxy', '8080') + Connection.set_proxy_info( + 'example.com', + 8080, + proxy_type=PROXY_TYPE_SOCKS5, + ) make_request("GET", "http://httpbin.org/get") http_mock.assert_called_with(timeout=None, ca_certs=ANY, proxy_info=ANY) http.request.assert_called_with("http://httpbin.org/get", "GET", body=None, headers=None) proxy_info = http_mock.call_args[1]['proxy_info'] - assert_equal(proxy_info.proxy_host, 'http://example.com/proxy') - assert_equal(proxy_info.proxy_port, '8080') + assert_equal(proxy_info.proxy_host, 'example.com') + assert_equal(proxy_info.proxy_port, 8080) + assert_equal(proxy_info.proxy_type, PROXY_TYPE_SOCKS5) diff --git a/twilio/rest/resources/connection.py b/twilio/rest/resources/connection.py index <HASH>..<HASH> 100644 --- a/twilio/rest/resources/connection.py +++ b/twilio/rest/resources/connection.py @@ -1,5 +1,9 @@ from twilio.rest.resources.imports import httplib2 from twilio.rest.resources.imports import socks +from twilio.rest.resources.imports import PROXY_TYPE_HTTP +from twilio.rest.resources.imports import PROXY_TYPE_HTTP_NO_TUNNEL +from twilio.rest.resources.imports import PROXY_TYPE_SOCKS4 +from twilio.rest.resources.imports import PROXY_TYPE_SOCKS5 class Connection(object): @@ -10,9 +14,22 @@ class Connection(object): return cls._proxy_info @classmethod - def set_proxy_info(cls, proxy_url, proxy_port): + def set_proxy_info(cls, proxy_host, proxy_port, + proxy_type=PROXY_TYPE_HTTP, proxy_rdns=None, + proxy_user=None, proxy_pass=None): cls._proxy_info = httplib2.ProxyInfo( - socks.PROXY_TYPE_HTTP, - proxy_url, + proxy_type, + proxy_host, proxy_port, + proxy_rdns=proxy_rdns, + proxy_user=proxy_user, + proxy_pass=proxy_pass, ) + + +_hush_pyflakes = [ + socks, + PROXY_TYPE_HTTP_NO_TUNNEL, + PROXY_TYPE_SOCKS4, + PROXY_TYPE_SOCKS5 +] diff --git a/twilio/rest/resources/imports.py b/twilio/rest/resources/imports.py index <HASH>..<HASH> 100644 --- a/twilio/rest/resources/imports.py +++ b/twilio/rest/resources/imports.py @@ -19,5 +19,13 @@ import httplib2 # socks try: from httplib2 import socks + from httplib2.socks import PROXY_TYPE_HTTP + from httplib2.socks import PROXY_TYPE_HTTP_NO_TUNNEL + from httplib2.socks import PROXY_TYPE_SOCKS4 + from httplib2.socks import PROXY_TYPE_SOCKS5 except ImportError: import socks + from socks import PROXY_TYPE_HTTP + from socks import PROXY_TYPE_HTTP_NO_TUNNEL + from socks import PROXY_TYPE_SOCKS4 + from socks import PROXY_TYPE_SOCKS5
Support all proxy types and the other args for good measure
twilio_twilio-python
train
9b2ef002ea5dfe4299dfdf51989098dd7fa94798
diff --git a/dvc/repo/__init__.py b/dvc/repo/__init__.py index <HASH>..<HASH> 100644 --- a/dvc/repo/__init__.py +++ b/dvc/repo/__init__.py @@ -24,6 +24,7 @@ def locked(f): @wraps(f) def wrapper(repo, *args, **kwargs): with repo.lock, repo.state: + repo._reset() ret = f(repo, *args, **kwargs) # Our graph cache is no longer valid after we release the repo.lock repo._reset() diff --git a/dvc/repo/add.py b/dvc/repo/add.py index <HASH>..<HASH> 100644 --- a/dvc/repo/add.py +++ b/dvc/repo/add.py @@ -126,6 +126,7 @@ def _create_stages(repo, targets, fname, pbar=None): stage = Stage.create( repo, outs=[out], accompany_outs=True, fname=fname ) + repo._reset() if not stage: if pbar is not None: diff --git a/tests/func/test_add.py b/tests/func/test_add.py index <HASH>..<HASH> 100644 --- a/tests/func/test_add.py +++ b/tests/func/test_add.py @@ -655,3 +655,10 @@ def test_add_from_data_dir(tmp_dir, scm, dvc): "tracked output: 'dir'.\n" "To include '{out}' in 'dir', run 'dvc commit dir.dvc'" ).format(out=os.path.join("dir", "file2")) + + +def test_not_raises_on_re_add(tmp_dir, dvc): + tmp_dir.dvc_gen("file", "file content") + + tmp_dir.gen({"file2": "file2 content", "file": "modified file"}) + dvc.add(["file2", "file"]) diff --git a/tests/unit/repo/test_repo.py b/tests/unit/repo/test_repo.py index <HASH>..<HASH> 100644 --- a/tests/unit/repo/test_repo.py +++ b/tests/unit/repo/test_repo.py @@ -2,6 +2,8 @@ import os import pytest +from dvc.repo import locked + def test_is_dvc_internal(dvc): assert dvc.is_dvc_internal(os.path.join("path", "to", ".dvc", "file")) @@ -49,3 +51,18 @@ def test_used_cache(tmp_dir, dvc, path): used_cache._items == expected._items and used_cache.external == expected.external ) + + +def test_locked(mocker): + repo = mocker.MagicMock() + repo.method = locked(repo.method) + + args = {} + kwargs = {} + repo.method(repo, args, kwargs) + + assert repo.method_calls == [ + mocker.call._reset(), + mocker.call.method(repo, args, kwargs), + mocker.call._reset(), + ]
Stage: create: reset repo after new stage creation (#<I>)
iterative_dvc
train
92b6b6babb0b7f718faff32e63294a157be35b97
diff --git a/src/Generator.php b/src/Generator.php index <HASH>..<HASH> 100644 --- a/src/Generator.php +++ b/src/Generator.php @@ -44,6 +44,10 @@ class Generator foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { $noExt = $this->removeExtension($fileinfo->getFilename()); + // Ignore non *.php files (ex.: .gitignore, vim swap files etc.) + if (pathinfo($fileinfo->getFileName())['extension'] !== 'php') { + continue; + } $tmp = include($path . '/' . $fileinfo->getFilename()); $data[$noExt] = $this->adjustArray($tmp);
Ignore non php files in resources/lang folders, for example .gitignore and vim swap files are causing errors on generate
martinlindhe_laravel-vue-i18n-generator
train
eb3d52fc51673323bef2332de2181ee66fc46bac
diff --git a/hazelcast/src/main/java/com/hazelcast/util/OperatingSystemMXBeanSupport.java b/hazelcast/src/main/java/com/hazelcast/util/OperatingSystemMXBeanSupport.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/util/OperatingSystemMXBeanSupport.java +++ b/hazelcast/src/main/java/com/hazelcast/util/OperatingSystemMXBeanSupport.java @@ -19,7 +19,6 @@ package com.hazelcast.util; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import static com.hazelcast.util.EmptyStatement.ignore; @@ -38,7 +37,7 @@ public final class OperatingSystemMXBeanSupport { * Reads a long attribute from OperatingSystemMXBean. * * @param attributeName name of the attribute - * @param defaultValue default value if the attribute value is null + * @param defaultValue default value if the attribute value is null * @return value of the attribute */ public static long readLongAttribute(String attributeName, long defaultValue) { @@ -46,10 +45,7 @@ public final class OperatingSystemMXBeanSupport { String methodName = "get" + attributeName; OperatingSystemMXBean systemMXBean = OPERATING_SYSTEM_MX_BEAN; Method method = systemMXBean.getClass().getMethod(methodName); - // the method is public in Java 9 - if (!Modifier.isPublic(method.getModifiers())) { - method.setAccessible(true); - } + method.setAccessible(true); Object value = method.invoke(systemMXBean); if (value == null) {
Fixes issue with OperatingSystemMBeanSupport throwing IllegalAccessException There is some funky issue whereby the method says that it public even though it isn't. The issue seems to be related to the combination with native. The issue is resolved by always calling setAccessible(true) no matter if it already is accessible or not.
hazelcast_hazelcast
train
75ac2bc5db28186d90b585f2322b9f4e4ed9d571
diff --git a/lib/rest-ftp-daemon/config.rb b/lib/rest-ftp-daemon/config.rb index <HASH>..<HASH> 100644 --- a/lib/rest-ftp-daemon/config.rb +++ b/lib/rest-ftp-daemon/config.rb @@ -1,4 +1,9 @@ -require 'settingslogic' +# Try to load Settingslogic +begin + require "settingslogic" +rescue LoadError + raise "config.rb warning: Settingslogic is needed to provide configuration values to the Gemspec file" +end # Terrific assertions #raise "config.rb: APP_ROOT is not defined" unless defined? APP_ROOT @@ -6,6 +11,7 @@ APP_NAME = "rest-ftp-daemon" APP_CONF = "/etc/#{APP_NAME}.yml" APP_DEV = ARGV.include?("development") ? true : false +# Configuration class class Settings < Settingslogic # Read configuration source (File.exists? APP_CONF) ? APP_CONF : Hash.new
protected config.rb for situations where SettingsLogic gem was not available to load Gemspec
bmedici_rest-ftp-daemon
train
7c5ad817e8a74e7c2dc879c4b873f403ef3ed005
diff --git a/eZ/Publish/Core/Repository/Repository.php b/eZ/Publish/Core/Repository/Repository.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/Repository/Repository.php +++ b/eZ/Publish/Core/Repository/Repository.php @@ -175,7 +175,8 @@ class Repository implements RepositoryInterface, LegacyKernelAware 'trash' => array(), 'io' => array(), 'objectState' => array(), - 'legacy' => array() + 'legacy' => array(), + 'fieldType' => array(), ); if ( $user !== null ) @@ -493,7 +494,7 @@ class Repository implements RepositoryInterface, LegacyKernelAware if ( $this->fieldTypeService !== null ) return $this->fieldTypeService; - $this->fieldTypeService = new FieldTypeService( $this, $this->persistenceHandler, $this->serviceSettings['contentType']['field_type'] ); + $this->fieldTypeService = new FieldTypeService( $this, $this->persistenceHandler, $this->serviceSettings['fieldType'] ); return $this->fieldTypeService; }
Use top level field type service configuration setting
ezsystems_ezpublish-kernel
train
0aa57efcedbe003640916e6b286d50fb08e42a20
diff --git a/dwave_micro_client.py b/dwave_micro_client.py index <HASH>..<HASH> 100644 --- a/dwave_micro_client.py +++ b/dwave_micro_client.py @@ -175,7 +175,7 @@ class Connection: self.session.headers.update({'X-Auth-Token': self.token}) self.session.proxies = proxies if permissive_ssl: - self.session.verfy = False + self.session.verify = False # Build the problem submission queue, start its workers self._submission_queue = queue.Queue()
Fix bug where permissive_ssl was not correctly applied
dwavesystems_dwave-cloud-client
train
dc39cd22c9cd80c471f888a259db16c2e6a918b6
diff --git a/server/src/main/java/com/paypal/selion/utils/process/UnixProcessHandler.java b/server/src/main/java/com/paypal/selion/utils/process/UnixProcessHandler.java index <HASH>..<HASH> 100644 --- a/server/src/main/java/com/paypal/selion/utils/process/UnixProcessHandler.java +++ b/server/src/main/java/com/paypal/selion/utils/process/UnixProcessHandler.java @@ -1,5 +1,5 @@ /*-------------------------------------------------------------------------------------------------------------------*\ -| Copyright (C) 2014-2015 PayPal | +| Copyright (C) 2014-2016 PayPal | | | | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance | | with the License. | @@ -41,10 +41,11 @@ public class UnixProcessHandler extends AbstractProcessHandler implements Proces LOGGER.entering(); int ourProcessPID = getCurrentProcessID(); - // Find all processes that are our direct children using our PID as the parent pid to pgrep. + // Find all processes that are our direct children using our PID with pgrep. + // Including any orphaned ones as candidates for cleanup (we will kill all candidate children). // The pgrep command is basically getting all child processes and we are interested only in // process name and PID with "<#>" as a delimiter. - String cmd = String.format("pgrep -P %s -l | awk '{ print $2\"%s\"$1 }'", + String cmd = String.format("pgrep -P 1,2,%s -l | awk '{ print $2\"%s\"$1 }'", Integer.toString(ourProcessPID), DELIMITER); try { @@ -59,6 +60,8 @@ public class UnixProcessHandler extends AbstractProcessHandler implements Proces @Override public void killProcess(List<ProcessInfo> processes) throws ProcessHandlerException { + // Kill all the child processes then actually kill candidates. Still may not be ideal. + super.killProcess(new String[] { "pkill", "-9", "-P" }, processes); super.killProcess(new String[] { "kill", "-9" }, processes); } diff --git a/server/src/test/java/com/paypal/selion/node/servlets/ProcessShutdownHandlerTest.java b/server/src/test/java/com/paypal/selion/node/servlets/ProcessShutdownHandlerTest.java index <HASH>..<HASH> 100644 --- a/server/src/test/java/com/paypal/selion/node/servlets/ProcessShutdownHandlerTest.java +++ b/server/src/test/java/com/paypal/selion/node/servlets/ProcessShutdownHandlerTest.java @@ -1,5 +1,5 @@ /*-------------------------------------------------------------------------------------------------------------------*\ -| Copyright (C) 2015 PayPal | +| Copyright (C) 2015-2016 PayPal | | | | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance | | with the License. | @@ -38,7 +38,7 @@ public class ProcessShutdownHandlerTest extends PowerMockTestCase { mockStatic(ConfigParser.class); when(ConfigParser.parse()).thenReturn(configParser); - if (System.getProperty("os.name").startsWith("Windows")) { + if (SystemUtils.IS_OS_WINDOWS) { when(configParser.getString("customProcessHandler")).thenReturn( "com.paypal.selion.utils.process.WindowsProcessHandler"); } else {
fix UnixProcessHandler Fix the process termination on Unix to kill all browser/driver decendents during process cleanup. We now also search for orphaned processes we've started (ppid = 1 or 2). KillProcesses now kills any child processes first beforing terminating each candidate process.
paypal_SeLion
train
8b465bc1ea6e80d9c97ebde8501391be99b6cbec
diff --git a/lang/fr/forum.php b/lang/fr/forum.php index <HASH>..<HASH> 100644 --- a/lang/fr/forum.php +++ b/lang/fr/forum.php @@ -134,7 +134,7 @@ $string['reply'] = 'R $string['replyforum'] = 'R�pondre au forum'; $string['rsssubscriberssdiscussions'] = 'Affichage du canal RSS des discussions du forum � $a �'; $string['rsssubscriberssposts'] = 'Affichage du canal RSS des messages du forum � $a �'; -$string['searchforumintro'] = 'Veuillez saisir les termes � rechercher dans l\'un ou plusieurs des champs c-dessous&nbsp;:'; +$string['searchforumintro'] = 'Veuillez saisir les termes � rechercher dans l\'un ou plusieurs des champs ci-dessous&nbsp;:'; $string['search'] = 'Rechercher'; $string['searchforums'] = 'Recherche (forums)'; $string['searchfullwords'] = 'Mots entiers'; @@ -143,9 +143,10 @@ $string['searchphrase'] = 'Phrase exacte dans le corps du message'; $string['searchsubject'] = 'Terme dans le sujet du message'; $string['searchuser'] = 'Nom de l\'auteur'; $string['searchuserid'] = 'Identifiant (Moodle ID) de l\'auteur'; -$string['searchwords'] = 'Termes apparaissant n\'importe o� dans le messge'; +$string['searchwords'] = 'Termes apparaissant n\'importe o� dans le message'; $string['searcholderposts'] = 'Rechercher les anciens messages...'; $string['searchresults'] = 'R�sultats de la recherche'; +$string['seeallposts'] = 'Afficher tous les messages �crits par cet utilisateur'; $string['sendinratings'] = 'Envoyer mes derni�res �valuations'; $string['showsubscribers'] = 'Afficher/modifier les abonn�s � ce forum'; $string['singleforum'] = 'Une seule discussion simple';
Added a link from the user page to a search for all posts.
moodle_moodle
train
b6402624d2501e76cd09803f390c328667a421c6
diff --git a/lib/plugins/platform/platform.js b/lib/plugins/platform/platform.js index <HASH>..<HASH> 100644 --- a/lib/plugins/platform/platform.js +++ b/lib/plugins/platform/platform.js @@ -366,6 +366,9 @@ class Platform { } } subscription.event = event.stream; + if (typeof event.stream === 'object') { + subscription.event.arn = JSON.stringify(event.stream.arn); + } } else if (Object.keys(event)[0] === 's3') { subscription = this.getS3Subscription(event.s3, fn); } else if (Object.keys(event)[0] === 'schedule') {
fix bug when using dynamo events with platform
serverless_serverless
train
e01c7dfc9fe78a5e5611130fde2524a1cd4573ff
diff --git a/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/solver/solution/initializer/ExaminationStartingSolutionInitializer.java b/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/solver/solution/initializer/ExaminationStartingSolutionInitializer.java index <HASH>..<HASH> 100644 --- a/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/solver/solution/initializer/ExaminationStartingSolutionInitializer.java +++ b/drools-planner-examples/src/main/java/org/drools/planner/examples/examination/solver/solution/initializer/ExaminationStartingSolutionInitializer.java @@ -289,7 +289,7 @@ public class ExaminationStartingSolutionInitializer implements CustomSolverPhase return examList; } - private class ExamInitializationWeight implements Comparable<ExamInitializationWeight> { + private static class ExamInitializationWeight implements Comparable<ExamInitializationWeight> { private Exam exam; private int totalStudentSize;
findbugs be a _static_ inner class?
kiegroup_optaplanner
train
abc3ab39b2742177de1b7e16466878388b82c2e1
diff --git a/tests/PostmarkAdminClientDomainTest.php b/tests/PostmarkAdminClientDomainTest.php index <HASH>..<HASH> 100644 --- a/tests/PostmarkAdminClientDomainTest.php +++ b/tests/PostmarkAdminClientDomainTest.php @@ -70,7 +70,7 @@ class PostmarkAdminClientDomainTest extends PostmarkClientBaseTest { $tk = parent::$testKeys; $client = new PostmarkAdminClient($tk->WRITE_ACCOUNT_TOKEN, $tk->TEST_TIMEOUT); - $domainName = $tk->WRITE_TEST_DOMAIN_NAME; + $domainName = $tk->WRITE_TEST_DOMAIN_NAME; $name = 'test-php-delete-' . $domainName; $domain = $client->createDomain($name); @@ -82,19 +82,20 @@ class PostmarkAdminClientDomainTest extends PostmarkClientBaseTest { foreach ($domains as $key => $value) { $this->assertNotSame($domain->name, $value->name); } - } function testClientCanVerifySPFForDomain() { $tk = parent::$testKeys; $client = new PostmarkAdminClient($tk->WRITE_ACCOUNT_TOKEN, $tk->TEST_TIMEOUT); - $domainName = $tk->WRITE_TEST_DOMAIN_NAME; + $domainName = $tk->WRITE_TEST_DOMAIN_NAME; $name = 'test-php-spf-' . $domainName; $domain = $client->createDomain($name); - $client->verifyDomainSPF($domain->id); + $result = $client->verifyDomainSPF($domain->id); + + $this->assertTrue($result->SPFVerified); } } diff --git a/tests/PostmarkAdminClientSenderSignatureTest.php b/tests/PostmarkAdminClientSenderSignatureTest.php index <HASH>..<HASH> 100644 --- a/tests/PostmarkAdminClientSenderSignatureTest.php +++ b/tests/PostmarkAdminClientSenderSignatureTest.php @@ -104,7 +104,9 @@ class PostmarkAdminClientSenderSignatureTest extends PostmarkClientBaseTest { $name = 'test-php-reverify-' . date('U'); $sig = $client->createSenderSignature($sender, $name); - $client->resendSenderSignatureConfirmation($sig->id); + $result = $client->resendSenderSignatureConfirmation($sig->id); + + $this->assertEquals(0, $result->ErrorCode); } function testClientCanVerifySPFForSignature() { @@ -117,7 +119,9 @@ class PostmarkAdminClientSenderSignatureTest extends PostmarkClientBaseTest { $sender = str_replace('[TOKEN]', 'test-php-spf-' . date('U'), $i); $sig = $client->createSenderSignature($sender, $name); - $client->verifySenderSignatureSPF($sig->id); + $result = $client->verifySenderSignatureSPF($sig->id); + + $this->assertTrue($result->SPFVerified); } }
Fix risky unit tests (having no assertions)
wildbit_postmark-php
train
fe02e68ad6bf7320557137e616fa8773ce4632d2
diff --git a/librosa/__init__.py b/librosa/__init__.py index <HASH>..<HASH> 100644 --- a/librosa/__init__.py +++ b/librosa/__init__.py @@ -1,9 +1,9 @@ #!/usr/bin/env python -"""Top-level module for librosa.""" +"""Top-level module for librosa""" # And all the librosa sub-modules from . import core, beat, decompose, display, feature, filters, onset, output, segment from librosa.core import * -__version__ = '0.2.0dev' +__version__ = '0.2.0'
gearing up for <I>
librosa_librosa
train
6efb5cdf8ed7e9105b521f889f2554edda01cc09
diff --git a/src/carousel/Carousel.js b/src/carousel/Carousel.js index <HASH>..<HASH> 100644 --- a/src/carousel/Carousel.js +++ b/src/carousel/Carousel.js @@ -5,9 +5,11 @@ import shallowCompare from 'react-addons-shallow-compare'; import { defaultScrollInterpolator, stackScrollInterpolator, + tinderScrollInterpolator, defaultAnimatedStyles, shiftAnimatedStyles, - stackAnimatedStyles + stackAnimatedStyles, + tinderAnimatedStyles } from '../utils/animations'; const IS_IOS = Platform.OS === 'ios'; @@ -50,12 +52,13 @@ export default class Carousel extends Component { inactiveSlideOpacity: PropTypes.number, inactiveSlideScale: PropTypes.number, inactiveSlideShift: PropTypes.number, - layout: PropTypes.oneOf(['default', 'stack']), + layout: PropTypes.oneOf(['default', 'stack', 'tinder']), + layoutCardOffset: PropTypes.number, lockScrollWhileSnapping: PropTypes.bool, loop: PropTypes.bool, loopClonesPerSide: PropTypes.number, scrollInterpolator: PropTypes.func, - slideInterpolatedStyle: PropTypes.object, + slideInterpolatedStyle: PropTypes.func, slideStyle: Animated.View.propTypes.style, shouldOptimizeUpdates: PropTypes.bool, swipeThreshold: PropTypes.number, @@ -278,7 +281,7 @@ export default class Carousel extends Component { _needsScrollView () { const { useScrollView } = this.props; - return useScrollView || !AnimatedFlatList; + return useScrollView || !AnimatedFlatList || this._shouldUseStackLayout() || this._shouldUseTinderLayout(); } _needsRTLAdaptations () { @@ -300,10 +303,11 @@ export default class Carousel extends Component { const { inactiveSlideOpacity, inactiveSlideScale, scrollInterpolator, slideInterpolatedStyle } = props; return inactiveSlideOpacity < 1 || inactiveSlideScale < 1 || - scrollInterpolator || - slideInterpolatedStyle || + !!scrollInterpolator || + !!slideInterpolatedStyle || this._shouldUseShiftLayout() || - this._shouldUseStackLayout(); + this._shouldUseStackLayout() || + this._shouldUseTinderLayout(); } _shouldUseCustomAnimation () { @@ -320,6 +324,10 @@ export default class Carousel extends Component { return this.props.layout === 'stack'; } + _shouldUseTinderLayout () { + return this.props.layout === 'tinder'; + } + _getCustomData (props = this.props) { const { data, loopClonesPerSide } = props; const dataLength = data.length; @@ -540,6 +548,8 @@ export default class Carousel extends Component { interpolator = scrollInterpolator(_index, props); } else if (this._shouldUseStackLayout()) { interpolator = stackScrollInterpolator(_index, props); + } else if (this._shouldUseTinderLayout()) { + interpolator = tinderScrollInterpolator(_index, props); } if (!interpolator || !interpolator.inputRange || !interpolator.outputRange) { @@ -1052,12 +1062,14 @@ export default class Carousel extends Component { } _getSlideInterpolatedStyle (index, animatedValue) { - const { slideInterpolatedStyle } = this.props; + const { layoutCardOffset, slideInterpolatedStyle } = this.props; if (slideInterpolatedStyle) { - return slideInterpolatedStyle(index, animatedValue, this.props); + return slideInterpolatedStyle(index, animatedValue, this.props, this._activeItem); + } else if (this._shouldUseTinderLayout()) { + return tinderAnimatedStyles(index, animatedValue, this.props, layoutCardOffset); } else if (this._shouldUseStackLayout()) { - return stackAnimatedStyles(index, animatedValue, this.props); + return stackAnimatedStyles(index, animatedValue, this.props, layoutCardOffset); } else if (this._shouldUseShiftLayout()) { return shiftAnimatedStyles(index, animatedValue, this.props); } else {
feat(Carousel): add the 'tinder' layout to the built-in ones and add the ability to customize it with prop `layoutCardOffset`
archriss_react-native-snap-carousel
train
17974b0998780d96d159a8d1bdcbbe251a5eac53
diff --git a/src/CrudCommand.php b/src/CrudCommand.php index <HASH>..<HASH> 100644 --- a/src/CrudCommand.php +++ b/src/CrudCommand.php @@ -100,7 +100,7 @@ class CrudCommand extends Command { return [ ['fields', null, InputOption::VALUE_OPTIONAL, 'Fields of form & model.', null], - ['makeroutes', null, InputOption::VALUE_OPTIONAL, 'Add the new routes to your routes.php file? yes/no', 'yes'], + ['makeroutes', '-m', InputOption::VALUE_OPTIONAL, 'Add the new routes to your routes.php file? yes/no', 'yes'], ]; }
Added shortcut to makeroutes command option
appzcoder_crud-generator
train
66bcf8c4836691e3b4d2c57798ce5bef6e7fbc4f
diff --git a/web/concrete/src/Multilingual/Page/Section/Processor/MultilingualProcessorTarget.php b/web/concrete/src/Multilingual/Page/Section/Processor/MultilingualProcessorTarget.php index <HASH>..<HASH> 100644 --- a/web/concrete/src/Multilingual/Page/Section/Processor/MultilingualProcessorTarget.php +++ b/web/concrete/src/Multilingual/Page/Section/Processor/MultilingualProcessorTarget.php @@ -4,6 +4,7 @@ namespace Concrete\Core\Multilingual\Page\Section\Processor; use Concrete\Core\Foundation\Processor\TargetInterface; use Concrete\Core\Multilingual\Page\Section\Section; +use Concrete\Core\Page\Stack\StackList; defined('C5_EXECUTE') or die("Access Denied."); @@ -30,6 +31,14 @@ class MultilingualProcessorTarget implements TargetInterface 'cID' => $this->section->getCollectionID()), $this->section->getCollectionParentID(), 0, false ); + + // Add in all the stack pages found for the current locale. + $list = new StackList(); + $list->filterByLanguageSection($this->getSection()); + $results = $list->get(); + foreach($results as $result) { + $pages[] = array('cID' => $result->getCollectionID()); + } return $pages; } diff --git a/web/concrete/src/Page/Stack/StackList.php b/web/concrete/src/Page/Stack/StackList.php index <HASH>..<HASH> 100644 --- a/web/concrete/src/Page/Stack/StackList.php +++ b/web/concrete/src/Page/Stack/StackList.php @@ -42,11 +42,16 @@ class StackList extends PageList } if (is_object($ms)) { - $this->filter('stMultilingualSection', $ms->getCollectionID()); + $this->filterByLanguageSection($ms); } } + public function filterByLanguageSection(Section $ms) + { + $this->filter('stMultilingualSection', $ms->getCollectionID()); + } + public static function export(\SimpleXMLElement $x) {
Rescanning multilingual tree for links now rescans stacks/global areas in that multilingual area as well Former-commit-id: <I>b0bd<I>d8dac<I>e<I>e<I>f<I>d<I>b Former-commit-id: 3e<I>e<I>b<I>ba<I>f<I>a1c2a3bd7ca<I>
concrete5_concrete5
train
89bf2fcc55ffea57e7541faacd1606c18b65a5b9
diff --git a/packages/create-react-app/createReactApp.js b/packages/create-react-app/createReactApp.js index <HASH>..<HASH> 100755 --- a/packages/create-react-app/createReactApp.js +++ b/packages/create-react-app/createReactApp.js @@ -619,6 +619,12 @@ function isSafeToCreateProjectIn(root, name) { '.hg', '.hgignore', '.hgcheck', + '.npmignore', + 'mkdocs.yml', + 'docs', + '.travis.yml', + '.gitlab-ci.yml', + '.gitattributes', ]; console.log();
Adding some more non-conflicting files to validFiles (#<I>)
facebook_create-react-app
train
61164eb1a56c120bf70567a3a121e7322bfaf4cf
diff --git a/src/Prototype/src/NodeVisitors/AddProperty.php b/src/Prototype/src/NodeVisitors/AddProperty.php index <HASH>..<HASH> 100644 --- a/src/Prototype/src/NodeVisitors/AddProperty.php +++ b/src/Prototype/src/NodeVisitors/AddProperty.php @@ -85,7 +85,7 @@ final class AddProperty extends NodeVisitorAbstract $b = new Property($dependency->property); $b->makePrivate(); - if ($this->useTypedProperties) { + if ($this->useTypedProperty()) { $b->setType($this->getPropertyType($dependency)); } @@ -96,6 +96,11 @@ final class AddProperty extends NodeVisitorAbstract return $b->getNode(); } + private function useTypedProperty(): bool + { + return $this->useTypedProperties && method_exists(Property::class, 'setType'); + } + private function renderDoc(): bool { return !($this->useTypedProperties && $this->noPhpDoc);
fix php parser legacy version support
spiral_framework
train
43f41863fa55a4708815552cbcd76e8bdad36983
diff --git a/src/ocrmypdf/helpers.py b/src/ocrmypdf/helpers.py index <HASH>..<HASH> 100644 --- a/src/ocrmypdf/helpers.py +++ b/src/ocrmypdf/helpers.py @@ -190,8 +190,10 @@ def check_pdf(input_file: Path) -> bool: log.warning(msg) sio = StringIO() - linearize = None + linearize_msgs = '' try: + # If linearization is missing entirely, we do not complain. We do + # complain if linearization is present but incorrect. pdf.check_linearization(sio) except RuntimeError: pass @@ -202,11 +204,11 @@ def check_pdf(input_file: Path) -> bool: ): pass else: - linearize = sio.getvalue() - if linearize: - log.warning(linearize) + linearize_msgs = sio.getvalue() + if linearize_msgs: + log.warning(linearize_msgs) - if not messages and not linearize: + if not messages and not linearize_msgs: return True return False finally:
check_pdf: document how we handle linearization
jbarlow83_OCRmyPDF
train
e990ac4889dfe4ce2f08d2d6a3c89e89be38c53e
diff --git a/lib/http_objects/version.rb b/lib/http_objects/version.rb index <HASH>..<HASH> 100644 --- a/lib/http_objects/version.rb +++ b/lib/http_objects/version.rb @@ -1,3 +1,3 @@ module HttpObjects - VERSION = "0.0.4" + VERSION = "0.0.5pre" end
Bumping to version <I>pre
rogerleite_http_objects
train
5b456610f3a0a7904ce66e0b03a56d2c98b4d886
diff --git a/scripts/make-sne-catalog.py b/scripts/make-sne-catalog.py index <HASH>..<HASH> 100755 --- a/scripts/make-sne-catalog.py +++ b/scripts/make-sne-catalog.py @@ -653,7 +653,7 @@ if args.writecatalog and not args.eventlist: sourcecount = len(ct['source'].split(',')) if sourcecount > maxsources: maxsources = sourcecount - cleanedtype = ct['type'].strip('?* ') + cleanedtype = ct['value'].strip('?* ') if not cleanedtype: cleanedtype = 'Unknown' if cleanedtype in ctypedict:
edited make catalog script to account for new quanta structures
astrocatalogs_astrocats
train
e840a040e249d64b6ba2069750cee6add75c0698
diff --git a/src/poetry/utils/_compat.py b/src/poetry/utils/_compat.py index <HASH>..<HASH> 100644 --- a/src/poetry/utils/_compat.py +++ b/src/poetry/utils/_compat.py @@ -5,8 +5,10 @@ import sys from contextlib import suppress -if sys.version_info < (3, 8): - # compatibility for python <3.8 +# TODO: use try/except ImportError when +# https://github.com/python/mypy/issues/1393 is fixed +if sys.version_info < (3, 10): + # compatibility for python <3.10 import importlib_metadata as metadata else: from importlib import metadata
fix: use importlib_metadata on python <<I> We updated our version of importlib_metadata, so we might as well take advantage of it to have full compatibility with the features introduced in Python <I>.
sdispater_poetry
train
62bda176be3f08d62fc9f411fd9d7eaa8496434e
diff --git a/src/certificate.js b/src/certificate.js index <HASH>..<HASH> 100644 --- a/src/certificate.js +++ b/src/certificate.js @@ -373,7 +373,7 @@ export default class Certificate { * @private */ _isFailing () { - return this._stepsStatuses.length > 0 && this._stepsStatuses.indexOf(VERIFICATION_STATUSES.FAILURE) > -1; + return this._stepsStatuses.some(step => step.status === VERIFICATION_STATUSES.FAILURE); } /** diff --git a/test/application/certificate/certificate.test.js b/test/application/certificate/certificate.test.js index <HASH>..<HASH> 100644 --- a/test/application/certificate/certificate.test.js +++ b/test/application/certificate/certificate.test.js @@ -1,40 +1,63 @@ import FIXTURES from '../../fixtures'; import { Certificate } from '../../../src'; +import { VERIFICATION_STATUSES } from '../../../src/constants'; -describe('Certificate entity test suite', () => { - describe('constructor method', () => { - describe('given is is not called with a JSON object', () => { +describe('Certificate entity test suite', function () { + describe('constructor method', function () { + describe('given is is not called with a JSON object', function () { let certificate; - beforeEach(() => { + beforeEach(function () { certificate = new Certificate(JSON.stringify(FIXTURES.MainnetV2Valid)); }); - afterEach(() => { + afterEach(function () { certificate = null; }); - it('should coerce certificateJson to an object', () => { + it('should coerce certificateJson to an object', function () { expect(certificate.certificateJson).toEqual(FIXTURES.MainnetV2Valid); }); }); - describe('given it is called with invalid certificate data', () => { - it('should return an error', () => { - expect(() => { + describe('given it is called with invalid certificate data', function () { + it('should return an error', function () { + expect(function () { /* eslint no-new: "off" */ new Certificate('invalid-certificate-data'); }).toThrowError('This is not a valid certificate'); }); }); - describe('given it is called with no certificate data', () => { - it('should throw an error', () => { - expect(() => { + describe('given it is called with no certificate data', function () { + it('should throw an error', function () { + expect(function () { /* eslint no-new: "off" */ new Certificate(); }).toThrowError('This is not a valid certificate'); }); }); }); + + describe('isFailing method', function () { + describe('when all checks are successful', function () { + it('should return false', function () { + const certificate = new Certificate(FIXTURES.MainnetV2Valid); + certificate._stepsStatuses.push({step: 'testStep 1', status: VERIFICATION_STATUSES.SUCCESS, action: 'Test Step 1'}); + certificate._stepsStatuses.push({step: 'testStep 2', status: VERIFICATION_STATUSES.SUCCESS, action: 'Test Step 2'}); + + expect(certificate._isFailing()).toBe(false); + }); + }); + + describe('when one check is failing', function () { + it('should return true', function () { + const certificate = new Certificate(FIXTURES.MainnetV2Valid); + certificate._stepsStatuses.push({step: 'testStep 1', status: VERIFICATION_STATUSES.SUCCESS, action: 'Test Step 1'}); + certificate._stepsStatuses.push({step: 'testStep 2', status: VERIFICATION_STATUSES.FAILURE, action: 'Test Step 2'}); + + expect(certificate._isFailing()).toBe(true); + }); + }); + }); });
fix(Certificate): ensure isFailing method returns the truth
blockchain-certificates_cert-verifier-js
train
2177ada5891f78ccc7b8c3c46d16616df51301f3
diff --git a/core/src/test/java/de/javakaffee/web/msm/MemcachedBackupSessionManagerTest.java b/core/src/test/java/de/javakaffee/web/msm/MemcachedBackupSessionManagerTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/de/javakaffee/web/msm/MemcachedBackupSessionManagerTest.java +++ b/core/src/test/java/de/javakaffee/web/msm/MemcachedBackupSessionManagerTest.java @@ -64,6 +64,7 @@ public class MemcachedBackupSessionManagerTest { _manager = new MemcachedBackupSessionManager(); _manager.setMemcachedNodes( "n1:127.0.0.1:11211" ); + _manager.setSessionBackupAsync( false ); _manager.setSticky( true ); final StandardContext container = new StandardContext(); @@ -142,6 +143,9 @@ public class MemcachedBackupSessionManagerTest { _manager.backupSession( session.getIdInternal(), false, null ).get(); verify( _memcachedMock, times( 1 ) ).set( eq( session.getId() ), anyInt(), any() ); + // we need at least 1 milli between last backup and next access (due to check in BackupSessionService) + Thread.sleep(1L); + /* simulate the second request, with session access */ session.access(); @@ -151,6 +155,9 @@ public class MemcachedBackupSessionManagerTest { _manager.backupSession( session.getIdInternal(), false, null ).get(); verify( _memcachedMock, times( 2 ) ).set( eq( session.getId() ), anyInt(), any() ); + // we need at least 1 milli between last backup and next access (due to check in BackupSessionService) + Thread.sleep(1L); + /* simulate the third request, without session access */ _manager.backupSession( session.getIdInternal(), false, null ).get(); @@ -211,11 +218,17 @@ public class MemcachedBackupSessionManagerTest { _manager.backupSession( session.getIdInternal(), false, null ).get(); verify( transcoderServiceMock, times( 1 ) ).serializeAttributes( eq( session ), eq( session.getAttributesInternal() ) ); + // we need at least 1 milli between last backup and next access (due to check in BackupSessionService) + Thread.sleep(1L); + session.access(); session.getAttribute( "foo" ); _manager.backupSession( session.getIdInternal(), false, null ).get(); verify( transcoderServiceMock, times( 2 ) ).serializeAttributes( eq( session ), eq( session.getAttributesInternal() ) ); + // we need at least 1 milli between last backup and next access (due to check in BackupSessionService) + Thread.sleep(1L); + _manager.backupSession( session.getIdInternal(), false, null ).get(); verify( transcoderServiceMock, times( 2 ) ).serializeAttributes( eq( session ), eq( session.getAttributesInternal() ) ); diff --git a/core/src/test/java/de/javakaffee/web/msm/integration/TestUtils.java b/core/src/test/java/de/javakaffee/web/msm/integration/TestUtils.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/de/javakaffee/web/msm/integration/TestUtils.java +++ b/core/src/test/java/de/javakaffee/web/msm/integration/TestUtils.java @@ -26,6 +26,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.InetSocketAddress; import java.net.MalformedURLException; +import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; @@ -407,9 +408,11 @@ public class TestUtils { engine.setRealm( realm ); final URL root = new URL( TestUtils.class.getResource( "/" ), "../resources" ); + // use file to get correct separator char, replace %20 introduced by URL for spaces + final String cleanedRoot = new File( root.getFile().replaceAll("%20", " ") ).toString(); final String fileSeparator = File.separator.equals( "\\" ) ? "\\\\" : File.separator; - final String docBase = root.getFile() + File.separator + TestUtils.class.getPackage().getName().replaceAll( "\\.", fileSeparator ); + final String docBase = cleanedRoot + File.separator + TestUtils.class.getPackage().getName().replaceAll( "\\.", fileSeparator ); final Host host = catalina.createHost( DEFAULT_HOST, docBase ); engine.addChild( host ); new File( docBase ).mkdirs();
Make tests running better on windows: The docBase setup in TestUtils was wrong on windows, and timing/concurrency/system clock seems to behave different on windows (slight changes in MemcachedBackupSessionManagerTest). Still open: concurrency issues / different behaviour of memcached client in MemcachedFailoverIntegrationTest.
magro_memcached-session-manager
train
7b62af88610b49290e5b92aeea0d4976a8ede686
diff --git a/test/TemplateWriterTest.js b/test/TemplateWriterTest.js index <HASH>..<HASH> 100644 --- a/test/TemplateWriterTest.js +++ b/test/TemplateWriterTest.js @@ -425,6 +425,8 @@ test("Glob Watcher Files with Passthroughs", (t) => { }); test("Pagination and TemplateContent", async (t) => { + rimraf.sync("./test/stubs/pagination-templatecontent/_site/"); + let eleventyConfig = new TemplateConfig(); let tw = new TemplateWriter( "./test/stubs/pagination-templatecontent", @@ -698,6 +700,8 @@ test.skip("JavaScript with alias", async (t) => { }); test("Passthrough file output", async (t) => { + rimraf.sync("./test/stubs/template-passthrough/_site/"); + let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.passthroughCopies = { "./test/stubs/template-passthrough/static": true,
Make the tests a bit more resilient when creating files.
11ty_eleventy
train
9a33aa7c33f053049f1fe9d86feb9b77d050edfd
diff --git a/CyrillicToTranslit.js b/CyrillicToTranslit.js index <HASH>..<HASH> 100644 --- a/CyrillicToTranslit.js +++ b/CyrillicToTranslit.js @@ -76,6 +76,7 @@ module.exports = function cyrillicToTranslit(config) { let newStr = ""; for (let i = 0; i < input.length; i++) { + const isUpperCaseOrWhatever = input[i] === input[i].toUpperCase(); let strLowerCase = input[i].toLowerCase(); if (strLowerCase === " " && spaceReplacement) { newStr += spaceReplacement; @@ -85,10 +86,10 @@ module.exports = function cyrillicToTranslit(config) { ? "gh" : (i === 0 ? _firstLetterAssociations : _associations)[strLowerCase]; if ("undefined" === typeof newLetter) { - newStr += strLowerCase; + newStr += isUpperCaseOrWhatever ? strLowerCase.toUpperCase() : strLowerCase; } else { - newStr += newLetter; + newStr += isUpperCaseOrWhatever ? newLetter.toUpperCase() : newLetter; } } return newStr;
Preserve string case after translit
greybax_cyrillic-to-translit-js
train
675f879c1ec6cf1c77cbf96d8b7b2cd51e1cbaad
diff --git a/gitlab/v4/objects.py b/gitlab/v4/objects.py index <HASH>..<HASH> 100644 --- a/gitlab/v4/objects.py +++ b/gitlab/v4/objects.py @@ -909,7 +909,7 @@ class Group(SaveMixin, ObjectDeleteMixin, RESTObject): GitlabAuthenticationError: If authentication is not correct GitlabTransferProjectError: If the project could not be transfered """ - path = '/groups/%d/projects/%d' % (self.id, to_project_id) + path = '/groups/%s/projects/%s' % (self.id, to_project_id) self.manager.gitlab.http_post(path, **kwargs) @cli.register_custom_action('Group', ('scope', 'search')) @@ -930,7 +930,7 @@ class Group(SaveMixin, ObjectDeleteMixin, RESTObject): GitlabList: A list of dicts describing the resources found. """ data = {'scope': scope, 'search': search} - path = '/groups/%d/search' % self.get_id() + path = '/groups/%s/search' % self.get_id() return self.manager.gitlab.http_list(path, query_data=data, **kwargs) @cli.register_custom_action('Group', ('cn', 'group_access', 'provider')) @@ -949,7 +949,7 @@ class Group(SaveMixin, ObjectDeleteMixin, RESTObject): GitlabAuthenticationError: If authentication is not correct GitlabCreateError: If the server cannot perform the request """ - path = '/groups/%d/ldap_group_links' % self.get_id() + path = '/groups/%s/ldap_group_links' % self.get_id() data = {'cn': cn, 'group_access': group_access, 'provider': provider} self.manager.gitlab.http_post(path, post_data=data, **kwargs) @@ -967,7 +967,7 @@ class Group(SaveMixin, ObjectDeleteMixin, RESTObject): GitlabAuthenticationError: If authentication is not correct GitlabDeleteError: If the server cannot perform the request """ - path = '/groups/%d/ldap_group_links' % self.get_id() + path = '/groups/%s/ldap_group_links' % self.get_id() if provider is not None: path += '/%s' % provider path += '/%s' % cn @@ -985,7 +985,7 @@ class Group(SaveMixin, ObjectDeleteMixin, RESTObject): GitlabAuthenticationError: If authentication is not correct GitlabCreateError: If the server cannot perform the request """ - path = '/groups/%d/ldap_sync' % self.get_id() + path = '/groups/%s/ldap_sync' % self.get_id() self.manager.gitlab.http_post(path, **kwargs) @@ -3216,7 +3216,7 @@ class ProjectExport(RefreshMixin, RESTObject): Returns: str: The blob content if streamed is False, None otherwise """ - path = '/projects/%d/export/download' % self.project_id + path = '/projects/%s/export/download' % self.project_id result = self.manager.gitlab.http_get(path, streamed=streamed, raw=True, **kwargs) return utils.response_content(result, streamed, action, chunk_size) @@ -3717,7 +3717,7 @@ class Project(SaveMixin, ObjectDeleteMixin, RESTObject): Returns: str: The uncompressed tar archive of the repository """ - path = '/projects/%d/snapshot' % self.get_id() + path = '/projects/%s/snapshot' % self.get_id() result = self.manager.gitlab.http_get(path, streamed=streamed, raw=True, **kwargs) return utils.response_content(result, streamed, action, chunk_size) @@ -3740,7 +3740,7 @@ class Project(SaveMixin, ObjectDeleteMixin, RESTObject): GitlabList: A list of dicts describing the resources found. """ data = {'scope': scope, 'search': search} - path = '/projects/%d/search' % self.get_id() + path = '/projects/%s/search' % self.get_id() return self.manager.gitlab.http_list(path, query_data=data, **kwargs) @cli.register_custom_action('Project') @@ -3755,7 +3755,7 @@ class Project(SaveMixin, ObjectDeleteMixin, RESTObject): GitlabAuthenticationError: If authentication is not correct GitlabCreateError: If the server failed to perform the request """ - path = '/projects/%d/mirror/pull' % self.get_id() + path = '/projects/%s/mirror/pull' % self.get_id() self.manager.gitlab.http_post(path, **kwargs) @cli.register_custom_action('Project', ('to_namespace', )) @@ -3772,7 +3772,7 @@ class Project(SaveMixin, ObjectDeleteMixin, RESTObject): GitlabAuthenticationError: If authentication is not correct GitlabTransferProjectError: If the project could not be transfered """ - path = '/projects/%d/transfer' % (self.id,) + path = '/projects/%s/transfer' % (self.id,) self.manager.gitlab.http_put(path, post_data={"namespace": to_namespace}, **kwargs)
Fix for #<I>: %d replaced by %s
python-gitlab_python-gitlab
train
238b1867d95c68629740dc699713f081204887e2
diff --git a/classes/PodsInit.php b/classes/PodsInit.php index <HASH>..<HASH> 100644 --- a/classes/PodsInit.php +++ b/classes/PodsInit.php @@ -256,10 +256,6 @@ class PodsInit { wp_register_script( 'pods-select2', PODS_URL . 'ui/js/select2/select2.min.js', array( 'jquery' ), '3.3.1' ); wp_register_script( 'pods-handlebars', PODS_URL . 'ui/js/handlebars.js', array(), '1.0.0.beta.6' ); - - wp_register_style( 'responsive-modal', PODS_URL . 'ui/js/responsive/modal.css', array(), '4.1.1' ); - wp_register_script( 'responsive-core', PODS_URL . 'ui/js/responsive/responsive.core.js', array(), '4.1.1', true ); - wp_register_script( 'responsive-modal', PODS_URL . 'ui/js/responsive/responsive.modal.js', array( 'responsive-core' ), '4.1.1', true ); } /** diff --git a/ui/fields-mv/pick.php b/ui/fields-mv/pick.php index <HASH>..<HASH> 100644 --- a/ui/fields-mv/pick.php +++ b/ui/fields-mv/pick.php @@ -9,9 +9,6 @@ wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-sortable' ); -wp_enqueue_style( 'responsive-modal' ); -wp_enqueue_script( 'responsive-modal' ); - wp_enqueue_script( 'backbone' ); wp_enqueue_script( 'marionette', PODS_URL . 'ui/js/marionette/backbone.marionette.js', array( 'backbone' ), '2.4.4', true );
Responsive modal stuff is bye-bye
pods-framework_pods
train
40fa59b067f5740213bfcefec2956c9946f26a91
diff --git a/src/PlaygroundCore/Controller/FormgenController.php b/src/PlaygroundCore/Controller/FormgenController.php index <HASH>..<HASH> 100755 --- a/src/PlaygroundCore/Controller/FormgenController.php +++ b/src/PlaygroundCore/Controller/FormgenController.php @@ -40,6 +40,22 @@ class FormgenController extends AbstractActionController 'websites' => $websites, )); } + public function editAction() + { + if ($this->getRequest()->isPost()) { + $data = $this->getRequest()->getPost()->toArray(); + $formGenService = $this->getFormgenService(); + $formGenService->update($data); + } + $formId = $this->getEvent()->getRouteMatch()->getParam('formId'); + $formgen = $formGenService = $this->getFormgenService()->getFormgenMapper()->findById($formId); + + $websites = $this->getWebsiteService()->getWebsiteMapper()->findAll(); + return new ViewModel(array( + 'websites' => $websites, + 'form' => $formgen, + )); + } public function activateAction() {
can edit a form, ccc-<I>
gregorybesson_PlaygroundCore
train
fe27139f6c06847e6439f54ec05bdecf83f4da65
diff --git a/core/server/master/src/main/java/alluxio/master/file/DefaultFileSystemMaster.java b/core/server/master/src/main/java/alluxio/master/file/DefaultFileSystemMaster.java index <HASH>..<HASH> 100644 --- a/core/server/master/src/main/java/alluxio/master/file/DefaultFileSystemMaster.java +++ b/core/server/master/src/main/java/alluxio/master/file/DefaultFileSystemMaster.java @@ -1498,8 +1498,15 @@ public class DefaultFileSystemMaster extends CoreMaster LockedInodePath inodePath = mInodeTree.lockFullInodePath(path, LockPattern.WRITE_INODE); FileSystemMasterAuditContext auditContext = createAuditContext("completeFile", path, null, inodePath.getInodeOrNull())) { + Mode.Bits permissionNeed = Mode.Bits.WRITE; + if (skipFileWritePermissionCheck(inodePath)) { + // A file may be created with read-only permission, to enable writing to it + // for the owner the permission needed is decreased here. + // Please check Alluxio/alluxio/issues/15808 for details. + permissionNeed = Mode.Bits.NONE; + } try { - mPermissionChecker.checkPermission(Mode.Bits.WRITE, inodePath); + mPermissionChecker.checkPermission(permissionNeed, inodePath); } catch (AccessControlException e) { auditContext.setAllowed(false); throw e; @@ -1771,8 +1778,15 @@ public class DefaultFileSystemMaster extends CoreMaster LockedInodePath inodePath = mInodeTree.lockFullInodePath(path, LockPattern.WRITE_INODE); FileSystemMasterAuditContext auditContext = createAuditContext("getNewBlockIdForFile", path, null, inodePath.getInodeOrNull())) { + Mode.Bits permissionNeed = Mode.Bits.WRITE; + if (skipFileWritePermissionCheck(inodePath)) { + // A file may be created with read-only permission, to enable writing to it + // for the owner the permission needed is decreased here. + // Please check Alluxio/alluxio/issues/15808 for details. + permissionNeed = Mode.Bits.NONE; + } try { - mPermissionChecker.checkPermission(Mode.Bits.WRITE, inodePath); + mPermissionChecker.checkPermission(permissionNeed, inodePath); } catch (AccessControlException e) { auditContext.setAllowed(false); throw e; @@ -1787,6 +1801,24 @@ public class DefaultFileSystemMaster extends CoreMaster } } + /** + * In order to allow writing to read-only files when creating, + * we need to skip write permission check for files sometimes. + */ + private boolean skipFileWritePermissionCheck(LockedInodePath inodePath) + throws FileDoesNotExistException { + if (!inodePath.getInode().isFile() || inodePath.getInodeFile().isCompleted()) { + return false; + } + String user; + try { + user = AuthenticatedClientUser.getClientUser(Configuration.global()); + } catch (AccessControlException e) { + return false; + } + return user.equals(inodePath.getInodeFile().getOwner()); + } + @Override public Map<String, MountPointInfo> getMountPointInfoSummary() { return getMountPointInfoSummary(true); diff --git a/core/server/master/src/test/java/alluxio/master/file/FileSystemMasterTest.java b/core/server/master/src/test/java/alluxio/master/file/FileSystemMasterTest.java index <HASH>..<HASH> 100644 --- a/core/server/master/src/test/java/alluxio/master/file/FileSystemMasterTest.java +++ b/core/server/master/src/test/java/alluxio/master/file/FileSystemMasterTest.java @@ -3146,8 +3146,37 @@ public final class FileSystemMasterTest { } } + @Test + public void writeToReadOnlyFileWhileCreating() throws Exception { + mFileSystemMaster.createDirectory(NESTED_URI, CreateDirectoryContext + .mergeFrom(CreateDirectoryPOptions.newBuilder().setRecursive(true))); + Set<String> newEntries = Sets.newHashSet("user::r--", "group::r--", "other::r--"); + // The owner of the root path will be treated as a privileged user, + // so we need another user to do validation. + String user = "test_user1"; + CreateFileContext context = CreateFileContext + .mergeFrom(mNestedFileContext.getOptions()) + .setOwner(user) + .setAcl(newEntries.stream().map(AclEntry::fromCliString).collect(Collectors.toList())); + try (Closeable r = new AuthenticatedUserRule(user, Configuration.global()) + .toResource()) { + createFileWithSingleBlock(NESTED_FILE_URI, context); + try { + mFileSystemMaster.getNewBlockIdForFile(NESTED_FILE_URI); + Assert.fail("getNewBlockIdForFile after completed should fail!"); + } catch (AccessControlException e) { + // ignored + } + } + } + private long createFileWithSingleBlock(AlluxioURI uri) throws Exception { - mFileSystemMaster.createFile(uri, mNestedFileContext); + return createFileWithSingleBlock(uri, mNestedFileContext); + } + + private long createFileWithSingleBlock(AlluxioURI uri, CreateFileContext createFileContext) + throws Exception { + mFileSystemMaster.createFile(uri, createFileContext); long blockId = mFileSystemMaster.getNewBlockIdForFile(uri); mBlockMaster.commitBlock(mWorkerId1, Constants.KB, Constants.MEDIUM_MEM, Constants.MEDIUM_MEM, blockId, Constants.KB);
Allow writing to read-only file when creating ### What changes are proposed in this pull request? Allow writing to read-only file when creating ### Why are the changes needed? Fix <URL>
Alluxio_alluxio
train
f7c2a3c11d2600ee0ea7b29a7322da00e130fd1c
diff --git a/runtime/src/tests/work-item/work-item-list/page-objects/work-item-list.page.js b/runtime/src/tests/work-item/work-item-list/page-objects/work-item-list.page.js index <HASH>..<HASH> 100644 --- a/runtime/src/tests/work-item/work-item-list/page-objects/work-item-list.page.js +++ b/runtime/src/tests/work-item/work-item-list/page-objects/work-item-list.page.js @@ -282,7 +282,7 @@ class WorkItemListPage { } clickWorkItem(workItemElement) { - workItemElement.element(by.css(".f8-wi__list-description")).element(by.css("p")).click() + workItemElement.$$(".f8-wi__list-description").first().element(by.css("p")).click() return new WorkItemDetailPage(); }
fix(tests): Fix smoketest warnings (#<I>)
fabric8-ui_fabric8-planner
train
1e958ab32a9b5662e2313e36d52bf34c023de00b
diff --git a/plugins/assets/src/main/java/org/kantega/reststop/assets/AssetFilter.java b/plugins/assets/src/main/java/org/kantega/reststop/assets/AssetFilter.java index <HASH>..<HASH> 100644 --- a/plugins/assets/src/main/java/org/kantega/reststop/assets/AssetFilter.java +++ b/plugins/assets/src/main/java/org/kantega/reststop/assets/AssetFilter.java @@ -11,6 +11,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; +import java.net.URLConnection; import java.util.Collection; /** @@ -60,21 +61,50 @@ public class AssetFilter implements Filter { } if(resource != null) { + String mimeType = req.getServletContext().getMimeType(path.substring(path.lastIndexOf("/") + 1)); if(mimeType != null) { resp.setContentType(mimeType); } - try (InputStream in = resource.openStream()) { - copy(in, servletResponse.getOutputStream()); + URLConnection urlConnection = resource.openConnection(); + + if(isUnmodified(urlConnection, req, resp)) { + return; + } else { + + long contentLength = urlConnection.getContentLengthLong(); + + if (contentLength != -1) { + resp.setContentLengthLong(contentLength); + } + + try (InputStream in = urlConnection.getInputStream()) { + copy(in, servletResponse.getOutputStream()); + } + return; } - return; } } filterChain.doFilter(servletRequest, servletResponse); } + private boolean isUnmodified(URLConnection urlConnection, HttpServletRequest req, HttpServletResponse resp) throws IOException { + long lastModified = urlConnection.getLastModified(); + if(lastModified != 0) { + resp.addDateHeader("Last-Modified", lastModified); + long ifModifiedSince = req.getDateHeader("If-Modified-Since"); + if(ifModifiedSince != -1 && lastModified <= ifModifiedSince) { + resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); + return true; + } + + } + return false; + } + + private boolean isDirectoryResource(URL resource, ClassLoader loader, String path) { try {
AssetFilter now sets Content-Length, and supports Last-Modified/If-Modified-Since
kantega_reststop
train
330dfc4bad74ed24b3a0e9d7f7c355e6bd05213a
diff --git a/libsubmit/channels/ssh/ssh.py b/libsubmit/channels/ssh/ssh.py index <HASH>..<HASH> 100644 --- a/libsubmit/channels/ssh/ssh.py +++ b/libsubmit/channels/ssh/ssh.py @@ -1,6 +1,7 @@ import os import logging import paramiko +import getpass from libsubmit.channels.channel_base import Channel from libsubmit.channels.errors import * @@ -17,10 +18,20 @@ class SshChannel (): ''' - def __init__ (self, hostname, username=None, password=None, **kwargs): + def __init__ (self, hostname, username=None, password=None, + channel_script_dir=None, **kwargs): ''' Initialize a persistent connection to the remote system. We should know at this point whether ssh connectivity is possible + Args: + - hostname (String) : Hostname + + KWargs: + - username (string) : Username on remote system + - password (string) : Password for remote system + - channel_script_dir (string) : Full path to a script dir where + generated scripts could be sent to. + Raises: ''' @@ -32,6 +43,12 @@ class SshChannel (): self.ssh_client = paramiko.SSHClient() self.ssh_client.load_system_host_keys() self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + if channel_script_dir: + self.channel_script_dir = channel_script_dir + else: + self.channel_script_dir = "/tmp/{0}/scripts/".format(getpass.getuser()) + try : self.ssh_client.connect(hostname, username=username, @@ -41,11 +58,21 @@ class SshChannel (): self.sftp_client = paramiko.SFTPClient.from_transport(t) except paramiko.BadHostKeyException as e: - raise BadHostKeyException(e) + raise BadHostKeyException(e, self.hostname) except paramiko.AuthenticationException as e: - raise AuthException(e) - #self.sftp_client = paramiko.SFTPClient.from_transport(self.transport) + raise AuthException(e, self.hostname) + + except paramiko.SSHException as e: + raise SSHException(e, self.hostname) + + except Exception as e: + raise SSHException(e, self.hostname) + + + @property + def script_dir(self): + return self.channel_script_dir def execute_wait(self, cmd, walltime=2, envs={}):
Adding support for channel.script_dir property, and fixed paramiko exception handling
Parsl_libsubmit
train
ba6dce5577920f4916336a45fafb9b7d434d7ca6
diff --git a/bugwarrior/services/activecollab3.py b/bugwarrior/services/activecollab3.py index <HASH>..<HASH> 100644 --- a/bugwarrior/services/activecollab3.py +++ b/bugwarrior/services/activecollab3.py @@ -46,7 +46,7 @@ class Client(object): # string in project slug format: "client-example-project" project_name = project_name.lower() project_name = re.sub('[\s+]', '-', project_name) - project_name = re.sub('[:]', '', project_name) + project_name = re.sub('[:,"/"]', '', project_name) return project_name # Return a priority of L, M, or H based on AC's priority index of -2 to 2
Remove slashes from project slug
ralphbean_bugwarrior
train
2ced131decf766200e8571e1820d282646481202
diff --git a/test/namespacer_test.rb b/test/namespacer_test.rb index <HASH>..<HASH> 100644 --- a/test/namespacer_test.rb +++ b/test/namespacer_test.rb @@ -1,3 +1,5 @@ +require 'boson' +require 'boson/namespacer' require File.join(File.dirname(__FILE__), 'test_helper') describe "Loader" do diff --git a/test/pipes_test.rb b/test/pipes_test.rb index <HASH>..<HASH> 100644 --- a/test/pipes_test.rb +++ b/test/pipes_test.rb @@ -1,3 +1,4 @@ +require 'boson/pipes' require File.join(File.dirname(__FILE__), 'test_helper') describe "Pipes" do @@ -62,4 +63,4 @@ describe "Pipes" do capture_stderr { Pipes.sort_pipe(@objects, :blah)}.should =~ /failed.*'blah'/ end end -end \ No newline at end of file +end diff --git a/test/repo_index_test.rb b/test/repo_index_test.rb index <HASH>..<HASH> 100644 --- a/test/repo_index_test.rb +++ b/test/repo_index_test.rb @@ -1,3 +1,6 @@ +require 'boson' +require 'boson/repo_index' +require 'boson/save' require File.join(File.dirname(__FILE__), 'test_helper') describe "RepoIndex" do diff --git a/test/repo_test.rb b/test/repo_test.rb index <HASH>..<HASH> 100644 --- a/test/repo_test.rb +++ b/test/repo_test.rb @@ -1,3 +1,4 @@ +require 'boson/repo' require File.join(File.dirname(__FILE__), 'test_helper') describe "config" do @@ -20,4 +21,4 @@ describe "config" do @repo.config[:libraries].class.should == Hash end after_all { FileUtils.rm_r File.dirname(__FILE__)+'/config', :force=>true } -end \ No newline at end of file +end diff --git a/test/runner_options_test.rb b/test/runner_options_test.rb index <HASH>..<HASH> 100644 --- a/test/runner_options_test.rb +++ b/test/runner_options_test.rb @@ -1,7 +1,16 @@ +require 'boson' +require 'boson/bin_runner' +require 'test/test_helper' + describe "BinRunner" do describe "at commandline" do + def aborts_with(regex) + BinRunner.expects(:abort).with {|e| e[regex] } + yield + end + def start(*args) - Hirb.stubs(:enable) + # Hirb.stubs(:enable) BinRunner.start(args) end
fix tests except for runner_options
cldwalker_boson-more
train
d6ad55aaf6a2f3c9fdeb9b54dc35d36a7304cceb
diff --git a/beautysh/__init__.py b/beautysh/__init__.py index <HASH>..<HASH> 100644 --- a/beautysh/__init__.py +++ b/beautysh/__init__.py @@ -1,4 +1,4 @@ """__init__: Holds version info.""" from .beautysh import Beautify -__version__ = '6.0.0' +__version__ = '6.0.1'
beautysh: bump to <I>
lovesegfault_beautysh
train
d47266aa46357dbf875287a0d65fe3a7f9a5636f
diff --git a/api-endpoints-v2/versions.go b/api-endpoints-v2/versions.go index <HASH>..<HASH> 100644 --- a/api-endpoints-v2/versions.go +++ b/api-endpoints-v2/versions.go @@ -76,24 +76,31 @@ type ModifyVersionOptions struct { } func ModifyVersion(options *ModifyVersionOptions) (*Endpoint, error) { - ep, err := GetVersion(&GetVersionOptions{ - options.EndpointId, - options.Version, - }) - - if err != nil { - return nil, err - } + req, err := client.NewJSONRequest( + Config, + "PUT", + fmt.Sprintf( + "/api-definitions/v2/endpoints/%s/versions/%s", + options.EndpointId, + options.Version, + ), + options, + ) - if IsActive(ep, "production") || IsActive(ep, "staging") { + return call(req, err) +} - } +type CloneVersionOptions struct { + EndpointId string + Version string +} +func CloneVersion(options *CloneVersionOptions) (*Endpoint, error) { req, err := client.NewJSONRequest( Config, - "PUT", + "POST", fmt.Sprintf( - "/api-definitions/v2/endpoints/%s/versions/%s", + "/api-definitions/v2/endpoints/%s/versions/%s/cloneVersion", options.EndpointId, options.Version, ),
Add modify and clone version
akamai_AkamaiOPEN-edgegrid-golang
train
749ff6e3aeb3f06faa9862446f6a23bd104747de
diff --git a/library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java b/library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java +++ b/library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java @@ -44,6 +44,7 @@ class CompactCalendarController { private Date currentDate = new Date(); private Locale locale = Locale.getDefault(); private Calendar currentCalender = Calendar.getInstance(locale); + private Calendar todayCalender = Calendar.getInstance(locale); private Calendar calendarWithFirstDayOfMonth = Calendar.getInstance(locale); private Calendar eventsCalendar = Calendar.getInstance(locale); private Direction currentDirection = Direction.NONE; @@ -105,6 +106,9 @@ class CompactCalendarController { textHeight = rect.height() * 3; textWidth = rect.width() * 2; + todayCalender.setTime(currentDate); + setToMidnight(todayCalender); + currentCalender.setTime(currentDate); setCalenderToFirstDayOfMonth(calendarWithFirstDayOfMonth, currentDate, 0); @@ -394,7 +398,10 @@ class CompactCalendarController { void drawEvents(Canvas canvas, Calendar currentMonthToDrawCalender, int offset){ List<CalendarDayEvent> uniqCalendarDayEvents = events.get(getKeyForCalendarEvent(currentMonthToDrawCalender)); - boolean shouldDrawCurrentDayCircle = currentMonthToDrawCalender.get(Calendar.MONTH) == currentCalender.get(Calendar.MONTH); + + boolean shouldDrawCurrentDayCircle = currentMonthToDrawCalender.get(Calendar.MONTH) == todayCalender.get(Calendar.MONTH); + int todayDayOfMonth = todayCalender.get(Calendar.DAY_OF_MONTH); + if(uniqCalendarDayEvents != null){ for(int i = 0; i < uniqCalendarDayEvents.size() ; i++){ CalendarDayEvent event = uniqCalendarDayEvents.get(i); @@ -410,7 +417,7 @@ class CompactCalendarController { float yPosition = weekNumberForMonth * heightPerDay + paddingHeight; int dayOfMonth = eventsCalendar.get(Calendar.DAY_OF_MONTH); - boolean isSameDayAsCurrentDay = (currentCalender.get(Calendar.DAY_OF_MONTH) == dayOfMonth && shouldDrawCurrentDayCircle); + boolean isSameDayAsCurrentDay = (todayDayOfMonth == dayOfMonth && shouldDrawCurrentDayCircle); if(!isSameDayAsCurrentDay && dayOfMonth != 1){ if(showSmallIndicator){ //draw small indicators below the day in the calendar @@ -433,7 +440,8 @@ class CompactCalendarController { //offset by one because of 0 index based calculations firstDayOfMonth = firstDayOfMonth - 1; - boolean shouldDrawCurrentDayCircle = currentMonthToDrawCalender.get(Calendar.MONTH) == currentCalender.get(Calendar.MONTH); + boolean isSameMonth = currentMonthToDrawCalender.get(Calendar.MONTH) == todayCalender.get(Calendar.MONTH); + int todayDayOfMonth = todayCalender.get(Calendar.DAY_OF_MONTH); for(int dayColumn = 0, dayRow = 0; dayColumn <= 6; dayRow++){ if(dayRow == 7){ @@ -456,12 +464,12 @@ class CompactCalendarController { }else{ int day = ((dayRow - 1) * 7 + dayColumn + 1) - firstDayOfMonth; float yPosition = dayRow * heightPerDay + paddingHeight; - if(shouldDrawCurrentDayCircle && currentCalender.get(Calendar.DAY_OF_MONTH) == day){ + if(isSameMonth && todayDayOfMonth == day){ // TODO calculate position of circle in a more reliable way drawCircle(canvas, xPosition, yPosition, currentDayBackgroundColor); } if(day <= currentMonthToDrawCalender.getActualMaximum(Calendar.DAY_OF_MONTH) && day > 0){ - if(day == 1){ + if(currentCalender.get(Calendar.DAY_OF_MONTH) == day){ drawCircle(canvas, xPosition, yPosition, firstDayBackgroundColor); } canvas.drawText(String.valueOf(day), xPosition, yPosition, dayPaint);
Added sepereate calendar to track today
SundeepK_CompactCalendarView
train
75f40b8bea2081e0cb35056bb4223f9c5389d278
diff --git a/cobald/controller/linear.py b/cobald/controller/linear.py index <HASH>..<HASH> 100644 --- a/cobald/controller/linear.py +++ b/cobald/controller/linear.py @@ -30,7 +30,7 @@ class LinearController(Controller): assert low_utilisation <= high_allocation self.low_utilisation = low_utilisation self.high_allocation = high_allocation - runner.register_coroutine(self.run) + runner.register_payload(self.run) async def run(self): while True: diff --git a/cobald/decorator/buffer.py b/cobald/decorator/buffer.py index <HASH>..<HASH> 100644 --- a/cobald/decorator/buffer.py +++ b/cobald/decorator/buffer.py @@ -1,4 +1,4 @@ -import asyncio +import trio from cobald.interfaces import Pool, PoolDecorator @@ -21,11 +21,10 @@ class Buffer(PoolDecorator): super().__init__(target=target) self.window = window self.demand = target.demand - runner.register_subroutine(self.run) + runner.register_payload(self.run) - @asyncio.coroutine - def run(self): + async def run(self): while True: if self.demand != self.target.demand: self.target.demand = self.demand - yield from asyncio.sleep(self.window) + await trio.sleep(self.window)
adjusted runnables to work with current runners
MatterMiners_cobald
train
5038e0bf5fc213d646727766f34ab78918e24e6a
diff --git a/src/Crypt/Crypt.php b/src/Crypt/Crypt.php index <HASH>..<HASH> 100755 --- a/src/Crypt/Crypt.php +++ b/src/Crypt/Crypt.php @@ -2,7 +2,7 @@ namespace ConductorCore\Crypt; -use ConductorCore\Exception\RuntimeException; +use ConductorCore\Exception; use Defuse\Crypto\Crypto; use Defuse\Crypto\Key; @@ -14,6 +14,8 @@ use Defuse\Crypto\Key; */ class Crypt { + const ENCRYPTION_TYPE_DEFUSE_PHP_ENCRYPTION = 'defuse/php-encryption'; + /** * @return string */ @@ -31,7 +33,7 @@ class Crypt public function encrypt(string $message, string $key): string { $key = Key::loadFromAsciiSafeString($key); - return Crypto::encrypt($message, $key); + return 'ENC[' . self::ENCRYPTION_TYPE_DEFUSE_PHP_ENCRYPTION . ',' . Crypto::encrypt($message, $key) . ']'; } /** @@ -42,8 +44,28 @@ class Crypt */ public function decrypt(string $ciphertext, string $key): string { - $key = Key::loadFromAsciiSafeString($key); - return Crypto::decrypt($ciphertext, $key); + preg_match_all('%^ENC\[([^,]+),(.*)\]$%', $ciphertext, $matches); + if (3 != count($matches)) { + throw new Exception\RuntimeException('$ciphertext must be in the format ENC[$encryptionType,$ciphertext].'); + } + + $encryptionType = $matches[1][0]; + $ciphertext = $matches[2][0]; + + switch ($encryptionType) { + case self::ENCRYPTION_TYPE_DEFUSE_PHP_ENCRYPTION: + $key = Key::loadFromAsciiSafeString($key); + return Crypto::decrypt($ciphertext, $key); + + default: + throw new Exception\RuntimeException(sprintf( + 'Unsupported encryption type "%s". Supported encryption types: "%s".', + $encryptionType, + implode('", "', [self::ENCRYPTION_TYPE_DEFUSE_PHP_ENCRYPTION]) + )); + } + + } /** @@ -68,13 +90,12 @@ class Crypt } unset($value); } else { - if (!is_null($cryptKey) && preg_match('/^ENC\[defuse\/php-encryption,.*\]/', $data)) { - $data = preg_replace('/^ENC\[defuse\/php-encryption,(.*)\]/', '$1', $data); + if (!is_null($cryptKey) && preg_match('/^ENC\[[^,]+,.*\]/', $data)) { try { $data = $crypt->decrypt($data, $cryptKey); } catch (\Exception $e) { $message = "Error decrypting configuration key \"$dataKey\"."; - throw new RuntimeException($message, 0, $e); + throw new Exception\RuntimeException($message, 0, $e); } } }
Updated Crypt commands to use ciphertext with ENC[, ] and added support for ability to use other encryption types
conductorphp_conductor-core
train
930606c867fcb0c35905118b12d944e434bd6198
diff --git a/hazelcast-spring/src/main/java/com/hazelcast/spring/cache/SpringHazelcastCachingProvider.java b/hazelcast-spring/src/main/java/com/hazelcast/spring/cache/SpringHazelcastCachingProvider.java index <HASH>..<HASH> 100644 --- a/hazelcast-spring/src/main/java/com/hazelcast/spring/cache/SpringHazelcastCachingProvider.java +++ b/hazelcast-spring/src/main/java/com/hazelcast/spring/cache/SpringHazelcastCachingProvider.java @@ -54,9 +54,6 @@ public final class SpringHazelcastCachingProvider { ExceptionUtil.rethrow(e); } } - if (props.getProperty(HazelcastCachingProvider.HAZELCAST_INSTANCE_NAME) == null) { - props.setProperty(HazelcastCachingProvider.HAZELCAST_INSTANCE_NAME, instance.getName()); - } if (instance instanceof HazelcastClientProxy) { return HazelcastClientCachingProvider.createCachingProvider(instance).getCacheManager(uri, null, props); } else {
fix unneccessary instance-name set in properties
hazelcast_hazelcast
train
676acd3d841cb9eea30aa4704fa5cc0748b19128
diff --git a/src/frontend/org/voltdb/plannodes/ReceivePlanNode.java b/src/frontend/org/voltdb/plannodes/ReceivePlanNode.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/plannodes/ReceivePlanNode.java +++ b/src/frontend/org/voltdb/plannodes/ReceivePlanNode.java @@ -58,6 +58,6 @@ public class ReceivePlanNode extends AbstractPlanNode { @Override protected String explainPlanForNode(String indent) { - return "NODE RECIEVE"; + return "RECIEVE FROM ALL PARTITIONS"; } } diff --git a/src/frontend/org/voltdb/plannodes/SendPlanNode.java b/src/frontend/org/voltdb/plannodes/SendPlanNode.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/plannodes/SendPlanNode.java +++ b/src/frontend/org/voltdb/plannodes/SendPlanNode.java @@ -61,6 +61,11 @@ public class SendPlanNode extends AbstractPlanNode { @Override protected String explainPlanForNode(String indent) { - return "NODE SEND"; + if (m_parents.size() == 0) + return "RETURN RESULTS TO STORED PROCEDURE"; + else + return "SEND PARTITION RESULTS TO COORDINATOR"; + + } }
Improvements to the explain plan text for send and receive nodes, including differentiating between nodes that send to java and nodes that send data around in MP txns.
VoltDB_voltdb
train
005c7c938e8ddc3203d3e4b2f93575bfef02b6f0
diff --git a/lib/tilelive/mbtiles.js b/lib/tilelive/mbtiles.js index <HASH>..<HASH> 100644 --- a/lib/tilelive/mbtiles.js +++ b/lib/tilelive/mbtiles.js @@ -1,4 +1,4 @@ -var sqlite = require('sqlite').sqlite3_bindings; +var sqlite = require('sqlite'); var Step = require('step'); var crypto = require('crypto'); @@ -174,13 +174,23 @@ MBTiles.prototype.insertTile = function(tile, callback) { + 'VALUES (?, ?, ?, ?);', function(err, statement) { if (statement) { - statement.bind(1, tile.tile_id); - statement.bind(2, tile.zoom_level); - statement.bind(3, tile.tile_column); - statement.bind(4, tile.tile_row); - statement.step(function(err) { - callback(err); - }); + Step( + function() { + statement.bind(1, tile.tile_id, this); + }, + function() { + statement.bind(2, tile.zoom_level, this); + }, + function() { + statement.bind(3, tile.tile_column, this); + }, + function() { + statement.bind(4, tile.tile_row, this); + }, + function() { + statement.step(callback); + } + ); } else { callback(err); @@ -204,11 +214,17 @@ MBTiles.prototype.insertImage = function(image, callback) { + 'VALUES (?, ?);', function(err, statement) { if (statement) { - statement.bind(1, image.tile_id); - statement.bind(2, image.tile_data); - statement.step(function(err) { - callback(err); - }); + Step( + function() { + statement.bind(1, image.tile_id, this); + }, + function() { + statement.bind(2, image.tile_data, this); + }, + function() { + statement.step(callback); + } + ); } else { callback(err); @@ -229,9 +245,17 @@ MBTiles.prototype.metadata = function(metadata, callback) { that.db.prepare( 'INSERT INTO metadata (name, value) VALUES (?, ?);', function(err, statement) { - statement.bind(1, key); - statement.bind(2, value); - statement.step(callback); + Step( + function() { + statement.bind(1, key, this); + }, + function() { + statement.bind(2, value, this); + }, + function() { + statement.step(callback); + } + ); } ); }; @@ -268,10 +292,20 @@ MBTiles.prototype.tile = function(x, y, z, callback) { + 'tile_row = ?;', function(err, statement) { if (statement) { - statement.bind(1, z); - statement.bind(2, x); - statement.bind(3, y); - statement.step(next); + Step( + function() { + statement.bind(1, z, this); + }, + function() { + statement.bind(2, x, this); + }, + function() { + statement.bind(3, y, this); + }, + function() { + statement.step(next); + } + ); } else { next(err); @@ -280,12 +314,12 @@ MBTiles.prototype.tile = function(x, y, z, callback) { ); }, function(err, row) { - that.db.close(); if (!err && row && row.tile_data) { callback(err, row.tile_data); } else { callback(err); } + that.db.close(function() {}); } ); };
Take two on switch to orlandov/node-sqlite.
mapbox_tilelive
train
f3eb704c41382fb4b395ccd4398cdca86ea7c4f7
diff --git a/src/REST/__init__.py b/src/REST/__init__.py index <HASH>..<HASH> 100644 --- a/src/REST/__init__.py +++ b/src/REST/__init__.py @@ -67,7 +67,8 @@ class REST(Keywords): instances=[]): self.request = { 'method': None, - 'scheme': "http", + 'url': "", + 'scheme': "", 'netloc': "", 'path': "", 'query': {}, @@ -88,7 +89,7 @@ class REST(Keywords): if url.endswith('/'): url = url[:-1] if not url.startswith(("http://", "https://")): - url = self.request['scheme'] + "://" + url + url = "http://" + url url_parts = urlparse(url) self.request['scheme'] = url_parts.scheme self.request['netloc'] = url_parts.netloc diff --git a/src/REST/keywords.py b/src/REST/keywords.py index <HASH>..<HASH> 100644 --- a/src/REST/keywords.py +++ b/src/REST/keywords.py @@ -386,12 +386,13 @@ class Keywords(object): if not endpoint.startswith('/'): endpoint = "/" + endpoint endpoint = urljoin(base_url, self.request['path']) + endpoint - url_parts = urlparse(endpoint) + request['url'] = endpoint + url_parts = urlparse(request['url']) request['scheme'] = url_parts.scheme request['netloc'] = url_parts.netloc request['path'] = url_parts.path try: - response = client(request['method'], endpoint, + response = client(request['method'], request['url'], params=request['query'], json=request['body'], headers=request['headers'],
Add request field `url`, always having the full URL
asyrjasalo_RESTinstance
train
867e1311970a7cbf9c70725d56e8827dda3dddb0
diff --git a/lib/api-client/resources/authorization.js b/lib/api-client/resources/authorization.js index <HASH>..<HASH> 100644 --- a/lib/api-client/resources/authorization.js +++ b/lib/api-client/resources/authorization.js @@ -110,5 +110,20 @@ Authorization.save = function(authorization, done) { }; + +/** + * Delete an authorization + * + * @param {uuid} id of the authorization to delete + * @param {Function} done + */ +Authorization.delete = function(id, done) { + return this.http.del(this.path +'/'+ id, { + done: done + }); +}; + + + module.exports = Authorization;
feat(API services): add authorization.delete method Related to: CAM-<I>
camunda_camunda-bpm-sdk-js
train
3f7859992d19148397b095bf7276f8e4b196831b
diff --git a/vsgen/__main__.py b/vsgen/__main__.py index <HASH>..<HASH> 100644 --- a/vsgen/__main__.py +++ b/vsgen/__main__.py @@ -31,7 +31,7 @@ def main(argv=None): pylogger = VSGLogger() # Construct a command line parser and parse the command line - args = VSGSuite.make_parser(description='Executes the VSG package as an application.').parse_args(argv[1:]) + args = VSGSuite.make_parser(description='Executes the vsgen package as an application.').parse_args(argv[1:]) for s in VSGSuite.from_args(**vars(args)): s.write(False) return 0
Corrected package name in argparse construction.
dbarsam_python-vsgen
train
6ea74ae2f7c01fd5f22a842f423f07127e7c4cb5
diff --git a/openquake/hazardlib/contexts.py b/openquake/hazardlib/contexts.py index <HASH>..<HASH> 100644 --- a/openquake/hazardlib/contexts.py +++ b/openquake/hazardlib/contexts.py @@ -52,7 +52,8 @@ class Timer(object): OQ_TIMER=timer.csv oq run job.ini """ - fields = ['source_id', 'nrups', 'nsites', 'weight', 'dt', 'task_no'] + fields = ['source_id', 'code', 'nrups', 'nsites', 'weight', 'dt', + 'task_no'] def __init__(self, fname): self.fname = fname @@ -60,8 +61,8 @@ class Timer(object): def save(self, src, dt, task_no): # save the source info if self.fname: - row = [src.source_id, src.num_ruptures, src.nsites, src.weight, - dt, task_no] + row = [src.source_id, src.code.decode('ascii'), + src.num_ruptures, src.nsites, src.weight, dt, task_no] open(self.fname, 'a').write(','.join(map(str, row)) + '\n') def read_df(self):
Improved the Timer [skip CI]
gem_oq-engine
train
110fedd86bdeaace908774a34d41ea69138937e2
diff --git a/lib/nis/client.rb b/lib/nis/client.rb index <HASH>..<HASH> 100644 --- a/lib/nis/client.rb +++ b/lib/nis/client.rb @@ -14,6 +14,14 @@ class Nis::Client timeout: 5 }.freeze + LOCAL_ONLY_PATHES = [ + '/local/account/transfers/incoming', + '/local/account/transfers/outgoing', + '/local/account/transfers/all', + '/node/boot', + '/transaction/prepare-announce' + ] + attr_reader :options # @param [hash] options HTTP Client connection information @@ -31,6 +39,9 @@ class Nis::Client # @param [Hash] params API Parameters # @return [Hash] Hash converted API Response def request(method, path, params = {}) + if connection.remote? && local_only?(path) + raise Nis::Error, "The request (#{method} #{path}) is only permitted to local NIS." + end if params.is_a?(Hash) && !params.empty? params.reject! { |_, value| value.nil? } end @@ -53,6 +64,10 @@ class Nis::Client private + def local_only?(path) + LOCAL_ONLY_PATHES.include?(path) + end + def connection @connection ||= Faraday.new(url: @options[:url]) do |f| f.options[:timeout] = @options[:timeout] @@ -61,7 +76,7 @@ class Nis::Client # logger.filter(/(privateKey=)(\w+)/,'\1[FILTERED]') # end f.adapter Faraday.default_adapter - end + end.tap { |c| c.extend(Local) } end def parse_body(body) @@ -103,4 +118,14 @@ class Nis::Client options end + + module Local + def local? + host == '127.0.0.1' || host == 'localhost' + end + + def remote? + !local? + end + end end
prevent local only request before fire request.
44uk_nis-ruby
train
aacbb93bb22a9496d0629ff1aa89d228e90ca9d1
diff --git a/hazelcast/src/main/java/com/hazelcast/map/impl/proxy/MapProxyImpl.java b/hazelcast/src/main/java/com/hazelcast/map/impl/proxy/MapProxyImpl.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/map/impl/proxy/MapProxyImpl.java +++ b/hazelcast/src/main/java/com/hazelcast/map/impl/proxy/MapProxyImpl.java @@ -83,6 +83,7 @@ import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import static com.hazelcast.config.InMemoryFormat.NATIVE; import static com.hazelcast.map.impl.MapService.SERVICE_NAME; import static com.hazelcast.map.impl.querycache.subscriber.QueryCacheRequests.newQueryCacheRequest; import static com.hazelcast.util.Preconditions.checkNotInstanceOf; @@ -845,6 +846,8 @@ public class MapProxyImpl<K, V> extends MapProxySupport implements IMap<K, V>, I @Override public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier, Aggregation<K, SuppliedValue, Result> aggregation) { + checkTrue(NATIVE != mapConfig.getInMemoryFormat(), "NATIVE storage format is not supported for MapReduce"); + HazelcastInstance hazelcastInstance = getNodeEngine().getHazelcastInstance(); JobTracker jobTracker = hazelcastInstance.getJobTracker("hz::aggregation-map-" + getName()); return aggregate(supplier, aggregation, jobTracker); @@ -854,6 +857,8 @@ public class MapProxyImpl<K, V> extends MapProxySupport implements IMap<K, V>, I public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier, Aggregation<K, SuppliedValue, Result> aggregation, JobTracker jobTracker) { + checkTrue(NATIVE != mapConfig.getInMemoryFormat(), "NATIVE storage format is not supported for MapReduce"); + try { isNotNull(jobTracker, "jobTracker"); KeyValueSource<K, V> keyValueSource = KeyValueSource.fromMap(this);
Map.aggregate not available when in-memory format is NATIVE
hazelcast_hazelcast
train
a933fd03f149dfc46951de47125c6449adef45f2
diff --git a/src/main/java/org/mapdb/DataInput2.java b/src/main/java/org/mapdb/DataInput2.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mapdb/DataInput2.java +++ b/src/main/java/org/mapdb/DataInput2.java @@ -27,8 +27,8 @@ import java.nio.ByteBuffer; */ public final class DataInput2 implements DataInput { - ByteBuffer buf; - int pos; + public ByteBuffer buf; + public int pos; public DataInput2(final ByteBuffer buf, final int pos) { this.buf = buf; diff --git a/src/main/java/org/mapdb/DataOutput2.java b/src/main/java/org/mapdb/DataOutput2.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mapdb/DataOutput2.java +++ b/src/main/java/org/mapdb/DataOutput2.java @@ -29,14 +29,19 @@ import java.util.Arrays; */ public final class DataOutput2 implements DataOutput { - byte[] buf; - int pos; + public byte[] buf; + public int pos; - DataOutput2(){ + public DataOutput2(){ pos = 0; buf = new byte[16]; //TODO take hint from serializer for initial size } + public DataOutput2(byte[] buf){ + pos=0; + this.buf = buf; + } + byte[] copyBytes(){ return Arrays.copyOf(buf, pos); }
Make some stuff in DataInput2/DataOutput2 public
jankotek_mapdb
train
3de2acd3e3b149825b2cd209fa2bb6933393e19b
diff --git a/bin/cmd.js b/bin/cmd.js index <HASH>..<HASH> 100755 --- a/bin/cmd.js +++ b/bin/cmd.js @@ -36,10 +36,13 @@ function Cli (opts) { }) if (argv.format) { - var typeFormatter = typeof opts.formatter - - if (typeFormatter !== 'object' || typeof opts.formatter.transform !== 'function') { - console.error('Invalid formatter API') + if (typeof opts.formatter === 'string') { + console.error(opts.cmd + ': ' + opts.formatter) + process.exit(1) + } + if (typeof opts.formatter !== 'object' || + typeof opts.formatter.transform !== 'function') { + console.error(opts.cmd + ': Invalid formatter API') process.exit(0) } }
if `formatter` opt is string, print it So packages like `standard` that offer formatters, can unbundle them.
standard_standard-engine
train
5875eda12a09a1e3abbc22a2530f2c4759488493
diff --git a/src/CoandaCMS/Coanda/Pages/Repositories/Eloquent/Queries/SubPageQuery.php b/src/CoandaCMS/Coanda/Pages/Repositories/Eloquent/Queries/SubPageQuery.php index <HASH>..<HASH> 100644 --- a/src/CoandaCMS/Coanda/Pages/Repositories/Eloquent/Queries/SubPageQuery.php +++ b/src/CoandaCMS/Coanda/Pages/Repositories/Eloquent/Queries/SubPageQuery.php @@ -319,12 +319,15 @@ class SubPageQuery { if ($this->parent_page_id != 0) { - $parent = $this->repository->findById($this->parent_page_id); - - if ($parent) + try { + $parent = $this->repository->findById($this->parent_page_id); $order = $parent->sub_page_order; } + catch (\CoandaCMS\Coanda\Pages\Exceptions\PageNotFound $exception) + { + // Default to manual above... + } } $query = $this->handleOrder($order, $query);
Added a try catch block to see if the page exists.
CoandaCMS_coanda-core
train
ef1ac3b14ccfa59947ff939e8470b2c0829fca3c
diff --git a/lib/waterline/core/validations.js b/lib/waterline/core/validations.js index <HASH>..<HASH> 100644 --- a/lib/waterline/core/validations.js +++ b/lib/waterline/core/validations.js @@ -71,7 +71,7 @@ Validator.prototype.initialize = function(attrs, types) { // If property is reserved don't do anything with it if(['defaultsTo', 'primaryKey', 'autoIncrement', 'unique', 'index', 'collection', 'dominant', 'columnName', 'foreignKey', 'references', 'on', 'groupKey', 'model', 'via', 'size', - 'example', 'validationMessage', 'validations'].indexOf(prop) > -1) return; + 'example', 'validationMessage', 'validations', 'populateSettings'].indexOf(prop) > -1) return; // use the Anchor `in` method for enums if(prop === 'enum') {
Added SailsJs "populateSettings" property to the non-validatable fields
balderdashy_waterline
train
286c6d6a8529b3b6d2c6732d9f0e804081335740
diff --git a/http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/NettyCarbonMessage.java b/http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/NettyCarbonMessage.java index <HASH>..<HASH> 100644 --- a/http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/NettyCarbonMessage.java +++ b/http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/NettyCarbonMessage.java @@ -44,10 +44,10 @@ public class NettyCarbonMessage extends CarbonMessage { private BlockingQueue<ByteBuffer> outContentQueue = new LinkedBlockingQueue<>(); public void addHttpContent(HttpContent httpContent) { + httpContentQueue.add(httpContent); if (httpContent instanceof LastHttpContent) { setEndOfMsgAdded(true); } - httpContentQueue.add(httpContent); } public HttpContent getHttpContent() { diff --git a/http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/common/Constants.java b/http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/common/Constants.java index <HASH>..<HASH> 100644 --- a/http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/common/Constants.java +++ b/http/netty/components/org.wso2.carbon.transport.http.netty/src/main/java/org/wso2/carbon/transport/http/netty/common/Constants.java @@ -71,7 +71,7 @@ public final class Constants { public static final String CLIENT_SUPPORT_CIPHERS = "client.ssl.ciphers"; public static final String CLIENT_SUPPORT_HTTPS_PROTOCOLS = "client.ssl.http.protocols"; public static final String CLIENT_ENABLE_SESSION_CREATION = "client.eanble.session.creation"; - + // Server Bootstrap related public static final String SERVER_BOOTSTRAP_TCP_NO_DELY = "server.bootstrap.nodelay";
Fixing Bug incorrect state in CMSG
wso2_transport-http
train
45228fc570384e84f04d100d0412259810e0fbd2
diff --git a/ninio-snmp/src/main/java/com/davfx/ninio/snmp/SnmpClient.java b/ninio-snmp/src/main/java/com/davfx/ninio/snmp/SnmpClient.java index <HASH>..<HASH> 100644 --- a/ninio-snmp/src/main/java/com/davfx/ninio/snmp/SnmpClient.java +++ b/ninio-snmp/src/main/java/com/davfx/ninio/snmp/SnmpClient.java @@ -110,10 +110,10 @@ public final class SnmpClient implements AutoCloseable, Closeable { public static final int IGNORE_ID = 0; - private static final int MAX_ID = Integer.MAX_VALUE / 2; - private static final int INITIAL_VARIABILITY = 100000; + private static final int MAX_ID = 2_000_000_000; + private static final int INITIAL_VARIABILITY = 100_000; - private static int NEXT = IGNORE_ID; + private static int NEXT = MAX_ID; private static final Object LOCK = new Object(); @@ -629,6 +629,9 @@ public final class SnmpClient implements AutoCloseable, Closeable { for (Result r : results) { LOGGER.trace("Received in bulk: {}", r); } + if (!results.iterator().hasNext()) { + LOGGER.error("No result in GETBULK response: {}", requestOid); + } for (Result r : results) { if (r.getValue() == null) { continue; diff --git a/ninio-snmp/src/main/java/com/davfx/ninio/snmp/v3/SnmpClient.java b/ninio-snmp/src/main/java/com/davfx/ninio/snmp/v3/SnmpClient.java index <HASH>..<HASH> 100644 --- a/ninio-snmp/src/main/java/com/davfx/ninio/snmp/v3/SnmpClient.java +++ b/ninio-snmp/src/main/java/com/davfx/ninio/snmp/v3/SnmpClient.java @@ -290,10 +290,10 @@ public final class SnmpClient implements AutoCloseable, Closeable { public static final int IGNORE_ID = 0; - private static final int MAX_ID = Integer.MAX_VALUE / 2; - private static final int INITIAL_VARIABILITY = 100000; + private static final int MAX_ID = 2_000_000_000; + private static final int INITIAL_VARIABILITY = 100_000; - private static int NEXT = IGNORE_ID; + private static int NEXT = MAX_ID; private static final Object LOCK = new Object(); diff --git a/pom.xml b/pom.xml index <HASH>..<HASH> 100644 --- a/pom.xml +++ b/pom.xml @@ -4,6 +4,8 @@ <groupId>com.davfx.ninio</groupId> <artifactId>ninio</artifactId> <version>2.2.5-SNAPSHOT</version> + <!-- mvn versions:set -DgenerateBackupPoms=false --> + <packaging>pom</packaging> <name>${project.groupId}:${project.artifactId}</name>
Fix SNMP for the first request
davidfauthoux_ninio
train
0583f27720e8aaab53014c56539c02f8d68fbbb9
diff --git a/confpy/core/option.py b/confpy/core/option.py index <HASH>..<HASH> 100644 --- a/confpy/core/option.py +++ b/confpy/core/option.py @@ -8,12 +8,7 @@ from __future__ import unicode_literals class Option(object): - """Base class for all validated options. - - Attributes: - default (optional): The default value for the options. - required (bool): Whether or not the option is required. - """ + """Base class for all validated options.""" def __init__(self, description=None, default=None, required=False): """Initialize the option with some basic metadata. @@ -30,6 +25,11 @@ class Option(object): self._required = bool(required) @property + def description(self): + """Get the human description of the options.""" + return self.__doc__ + + @property def default(self): """Get the default value of the property.""" return self._default @@ -39,6 +39,26 @@ class Option(object): """Get whether or not the value is required.""" return self._required + @property + def value(self): + """Get the current value of the option. + + If the value is unset the default value will be used instead. + """ + return self._value if self._value is not None else self._default + + @value.setter + def value(self, val): + """Set the value of the option. + Args: + val: The value to set the option to. + + Raises: + TypeError: If the value is not a string or appropriate native type. + ValueError: If the value is a string but cannot be coerced. + """ + self._value = self.coerce(val) + def coerce(self, value): """Convert a string to the appropriate Python value. @@ -58,32 +78,9 @@ class Option(object): return value def __get__(self, obj=None, objtype=None): - """Get the current value of the option. - - Returns: - object: The current value of the option. - - If the value is unset, a default option is defined, and the - option is not required then the default value will be returned. - - Raises: - AttributeError: If the value is unset and required. - """ - if self.required and self._value is None: - - raise AttributeError("Attempted to access an unset option.") - - if not self.required and self._value is None: - - return self.default - - return self._value + """Proxy the request to the 'value' property.""" + return self.value def __set__(self, obj, value): - """Set the current value of the option. - - Raises: - TypeError: If the value is not a string or appropriate native type. - ValueError: If the value is a string but cannot be coerced. - """ - self._value = self.coerce(value) + """Proxy the request to the 'value' property.""" + self.value = value diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ with open('LICENSE', 'r') as licensefile: setup( name='confpy', - version='0.2.0', + version='0.3.0', url='https://github.com/kevinconway/confpy', description='Config file parsing and option management.', author="Kevin Conway",
Add expanded Option API The new properties and methods allow for an alternative way of interaction with the option in addition to the descriptor interface.
kevinconway_confpy
train
7344c59aa6f64678f6e93e3b774553b1a9493189
diff --git a/tests/test_bibo.py b/tests/test_bibo.py index <HASH>..<HASH> 100644 --- a/tests/test_bibo.py +++ b/tests/test_bibo.py @@ -56,6 +56,13 @@ def test_list_with_search_by_field(runner, database): assert 'The Lord of the Rings' in result.output +def test_list_with_no_arguments_to_get_everything(runner, database, data): + args = ['--database', database, 'list'] + result = runner.invoke(bibo.cli, args) + for entry in data: + assert entry['key'] in result.output + + def test_open(runner, database): with mock.patch('bibo.internals.open_file') as open_file_mock: args = ['--database', database, 'open', 'tolkien1937']
Test listing everything (no search terms)
Nagasaki45_bibo
train
23a87ef8e16403e849b53b7e090f94e1a499f7dd
diff --git a/src/Input/Input.js b/src/Input/Input.js index <HASH>..<HASH> 100644 --- a/src/Input/Input.js +++ b/src/Input/Input.js @@ -227,7 +227,6 @@ class Input extends React.Component { constructor(props, context) { super(props, context); - this.isControlled = props.value != null; if (this.isControlled) { this.checkDirty(props); } @@ -281,8 +280,8 @@ class Input extends React.Component { } } - // Holds the input reference - input = null; + isControlled = this.props.value != null; + input = null; // Holds the input reference handleFocus = event => { // Fix an bug with IE11 where the focus/blur events are triggered diff --git a/src/Select/SelectInput.js b/src/Select/SelectInput.js index <HASH>..<HASH> 100644 --- a/src/Select/SelectInput.js +++ b/src/Select/SelectInput.js @@ -16,7 +16,7 @@ class SelectInput extends React.Component { }; componentDidMount() { - if (this.isControlled && this.props.open) { + if (this.isOpenControlled && this.props.open) { // Focus the display node so the focus is restored on this element once // the menu is closed. this.displayNode.focus(); @@ -32,9 +32,10 @@ class SelectInput extends React.Component { ignoreNextBlur = false; displayNode = null; displayWidth = null; - isControlled = this.props.open !== undefined; + isOpenControlled = this.props.open !== undefined; + isControlled = this.props.value != null; - update = this.isControlled + update = this.isOpenControlled ? ({ event, open }) => { if (open) { this.props.onOpen(event); @@ -174,7 +175,7 @@ class SelectInput extends React.Component { value, ...other } = this.props; - const open = this.isControlled && this.displayNode ? openProp : this.state.open; + const open = this.isOpenControlled && this.displayNode ? openProp : this.state.open; if (native) { warning( @@ -218,7 +219,7 @@ class SelectInput extends React.Component { ); } - if (value === undefined) { + if (!this.isControlled) { throw new Error( 'Material-UI: the `value` property is required ' + 'when using the `Select` component with `native=false` (default).',
[Select] Throw when the non native select is not controlled (#<I>)
mui-org_material-ui
train
53f1fae27f351da8a31bffa3e83d7d7d462449eb
diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,3 +1,4 @@ +require 'support/coverage' require 'minitest' require 'byebug' require 'byebug/interfaces/test_interface'
Restore test coverage tracking Somehow this got lost recently.
deivid-rodriguez_byebug
train
a7b5a1ec44100c7649de77214189a1eeeb243fe5
diff --git a/lib/deliver/app.rb b/lib/deliver/app.rb index <HASH>..<HASH> 100644 --- a/lib/deliver/app.rb +++ b/lib/deliver/app.rb @@ -28,10 +28,14 @@ module Deliver # INVALID_BINARY = "Invalid Binary" end - # @param apple_id The Apple ID of the app you want to modify or update. This ID has usually 9 digits - # @param app_identifier If you don't pass this, it will automatically be fetched from the Apple API - # which means it takes longer. If you **can** pass the app_identifier (e.g. com.facebook.Facebook) do it - def initialize(apple_id: nil, app_identifier: nil) + # @param options + # @param apple_id The Apple ID of the app you want to modify or update. This ID has usually 9 digits + # @param app_identifier If you don't pass this, it will automatically be fetched from the Apple API + # which means it takes longer. If you **can** pass the app_identifier (e.g. com.facebook.Facebook) do it + def initialize(options = {}) + apple_id = options.fetch(:apple_id, nil) + app_identifier = options.fetch(:app_identifier, nil) + self.apple_id = (apple_id || '').to_s.gsub('id', '').to_i self.app_identifier = app_identifier
Fixed deliver not working on ruby < <I>
fastlane_fastlane
train
aa5e3dd26da751b50c8e4cc4969d483d2ce9c270
diff --git a/spec/helper/spec_helper.rb b/spec/helper/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/helper/spec_helper.rb +++ b/spec/helper/spec_helper.rb @@ -270,6 +270,7 @@ module SpecHelpers end RSpec.configure do |c| + c.treat_symbols_as_metadata_keys_with_true_values = true c.include SpecHelpers c.before(:each) do diff --git a/spec/unit_test/instance_utils_spec.rb b/spec/unit_test/instance_utils_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit_test/instance_utils_spec.rb +++ b/spec/unit_test/instance_utils_spec.rb @@ -1,7 +1,7 @@ # Copyright (c) 2009-2012 VMware, Inc. require "helper/spec_helper" -describe "Service instance utilities test" do +describe "Service instance utilities test", :requires_warden do describe '.warden_connect' do it 'uses the warden_socket_path to connect to Warden' do path = '/tmp/warden.sock' diff --git a/spec/unit_test/warden_service_spec.rb b/spec/unit_test/warden_service_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit_test/warden_service_spec.rb +++ b/spec/unit_test/warden_service_spec.rb @@ -1,7 +1,7 @@ # Copyright (c) 2009-2012 VMware, Inc. require "helper/spec_helper" -describe "Warden Service test" do +describe "Warden Service test", :requires_warden do before :all do DataMapper.initialize_lock_file('/tmp/test_lock_file') FileUtils.mkdir_p(DEF_OPTIONS[:base_dir])
Tag tests that require warden to allow for green local run To run without warden dependent tests: rspec spec --tag ~requires_warden
cloudfoundry-attic_vcap-services-base
train
bb99e62f86e23137405de415d0af4360735a637c
diff --git a/geomdl/BSpline.py b/geomdl/BSpline.py index <HASH>..<HASH> 100644 --- a/geomdl/BSpline.py +++ b/geomdl/BSpline.py @@ -805,11 +805,12 @@ class Surface(object): def ctrlpts(self): """ Control points. - The v index varies first. That is, a row of v control points for the first u value is found first. - Then, the row of v control points for the next u value. + .. note:: + + The v index varies first. That is, a row of v control points for the first u value is found first. + Then, the row of v control points for the next u value. :getter: Gets the control points - :setter: Sets the control points :type: list """ ret_list = [] @@ -817,31 +818,75 @@ class Surface(object): ret_list.append(tuple(pt)) return tuple(ret_list) - @ctrlpts.setter - def ctrlpts(self, value): + @property + def ctrlpts2d(self): + """ Control points. + + 2D control points in *[u][v]* format. + + :getter: Gets the control points + :type: list + """ + return self._control_points2D + + @property + def ctrlpts_size_u(self): + """ Gets the size of the control points array in U-direction. + + :return: number of control points in U-direction + :rtype: int + """ + return self._control_points_size_u + + @property + def ctrlpts_size_v(self): + """ Gets the size of the control points array in V-direction. + + :return: number of control points in V-direction + :rtype: int + """ + return self._control_points_size_v + + def set_ctrlpts(self, ctrlpts, size_u, size_v): + """ Sets 1D control points. + + This function expects a list coordinates which is also a list. For instance, if you are working in 3D space, then + your coordinates will be a list of 3 elements representing *(x, y, z)* coordinates. + + This function also generates 2D control points in *[u][v]* format which can be accessed via + :py:attr:`~ctrlpts2d` property. + + .. note:: + + The v index varies first. That is, a row of v control points for the first u value is found first. + Then, the row of v control points for the next u value. + + :param ctrlpts: input control points as a list of coordinates + :type ctrlpts: list + :param size_u: size of the control points grid in U-direction + :param size_u: int + :param size_v: size of the control points grid in V-direction + :param size_v: int + :return: None + """ # Clean up the surface and control points lists, if necessary self._reset_surface() self._reset_ctrlpts() - # First check v-direction - if len(value) < self._degree_v + 1: + if self._degree_u == 0 or self._degree_v == 0: + raise ValueError("First, set the degrees!") + if size_u < self._degree_u + 1: + raise ValueError("Number of control points in u-direction should be at least degree + 1.") + if size_v < self._degree_v + 1: raise ValueError("Number of control points in v-direction should be at least degree + 1.") - # Then, check U direction - u_cnt = 0 - for u_coords in value: - if len(u_coords) < self._degree_u + 1: - raise ValueError("Number of control points in u-direction should be at least degree + 1.") - u_cnt += 1 - for coord in u_coords: - # Save the control points as a list of 3D coordinates - if len(coord) < 0 or len(coord) > self._dimension: - raise ValueError("Please input 3D coordinates") - # Convert to list of floats - coord_float = [float(c) for c in coord] - self._control_points.append(coord_float) + + # Set the new control points + self._control_points = copy.deepcopy(ctrlpts) + # Set u and v sizes - self._control_points_size_u = u_cnt - self._control_points_size_v = len(value) + self._control_points_size_u = size_u + self._control_points_size_v = size_v + # Generate a 2D list of control points for i in range(0, self._control_points_size_u): ctrlpts_v = [] @@ -850,17 +895,6 @@ class Surface(object): self._control_points2D.append(ctrlpts_v) @property - def ctrlpts2d(self): - """ Control points. - - 2D control points in [u][v] format. - - :getter: Gets the control points - :type: list - """ - return self._control_points2D - - @property def knotvector_u(self): """ Knot vector for U direction.
Update control points getters and setter
orbingol_NURBS-Python
train
96a7322100cf6253ed0e23258a0213774055d97b
diff --git a/fishbase/__init__.py b/fishbase/__init__.py index <HASH>..<HASH> 100644 --- a/fishbase/__init__.py +++ b/fishbase/__init__.py @@ -27,4 +27,4 @@ from .fish_system import * from .fish_project import * from .fish_random import * -__version__ = '1.3' # type: str +__version__ = '1.4' # type: str
<I>, <I> release
chinapnr_fishbase
train
9465f516f606bf0819b6d687c47013b5d91c64c6
diff --git a/src/Ademes/Core/Http/Client.php b/src/Ademes/Core/Http/Client.php index <HASH>..<HASH> 100644 --- a/src/Ademes/Core/Http/Client.php +++ b/src/Ademes/Core/Http/Client.php @@ -15,6 +15,22 @@ class Client { $this->client = new \GuzzleHttp\Client(['base_url'=>$base_url]); } + public function get($uri, array $option=null) { + return $this->client->get($url, $option); + } + + public function post($uri, array $option=null) { + return $this->client->get($url, $option); + } + + public function put($uri, array $option=null) { + return $this->client->get($url, $option); + } + + public function delete($uri, array $option=null) { + return $this->client->get($url, $option); + } + public function postFile($field_name, $content) { return new PostFile($field_name, $content);
added new methods in Http/Client
lhj1982_ademes-core
train
7f04cf742ddcf61f898434e8176a0989930c5c4d
diff --git a/lxd/networks.go b/lxd/networks.go index <HASH>..<HASH> 100644 --- a/lxd/networks.go +++ b/lxd/networks.go @@ -157,7 +157,7 @@ func networkGet(d *Daemon, r *http.Request) Response { return SmartError(err) } - etag := []interface{}{n.Name, n.Description, n.Managed, n.Type, n.Config} + etag := []interface{}{n.Name, n.Managed, n.Type, n.Description, n.Config} return SyncResponseETag(true, &n, etag) }
network: Fix ETag regression The "description" branch modified the etag source but used a different order in different places, causing validation failure.
lxc_lxd
train
dc7c8459ed684abc5c83512a589173322da8d97e
diff --git a/lib/chef/provider/git.rb b/lib/chef/provider/git.rb index <HASH>..<HASH> 100644 --- a/lib/chef/provider/git.rb +++ b/lib/chef/provider/git.rb @@ -283,6 +283,7 @@ class Chef env['GIT_SSH'] = @new_resource.ssh_wrapper if @new_resource.ssh_wrapper run_opts[:log_tag] = @new_resource.to_s run_opts[:timeout] = @new_resource.timeout if @new_resource.timeout + @new_resource.environment.delete('HOME') if @new_resource.environment run_opts[:environment] = @new_resource.environment ? env.merge(@new_resource.environment) : env run_opts diff --git a/lib/chef/resource/scm.rb b/lib/chef/resource/scm.rb index <HASH>..<HASH> 100644 --- a/lib/chef/resource/scm.rb +++ b/lib/chef/resource/scm.rb @@ -40,7 +40,7 @@ class Chef @allowed_actions.push(:checkout, :export, :sync, :diff, :log) @action = [:sync] @checkout_branch = "deploy" - @environment = {} + @environment = nil end def destination(arg=nil) diff --git a/spec/unit/resource/scm_spec.rb b/spec/unit/resource/scm_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/resource/scm_spec.rb +++ b/spec/unit/resource/scm_spec.rb @@ -147,6 +147,10 @@ describe Chef::Resource::Scm do @resource.ssh_wrapper.should be_nil end + it "defaults to nil for the environment" do + @resource.environment.should be_nil + end + describe "when it has a timeout attribute" do let(:ten_seconds) { 10 } before { @resource.timeout(ten_seconds) } @@ -179,4 +183,11 @@ describe Chef::Resource::Scm do end end + describe "when it has a environment attribute" do + let(:test_environment) { {'CHEF_ENV' => '/tmp' } } + before { @resource.environment(test_environment) } + it "stores this environment" do + @resource.environment.should == test_environment + end + end end
set nil by default, add two specs
chef_chef
train
7af0ad0781a92bb5c6b126cc169f661be323eacb
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/models/api/utils.rb b/sonar-server/src/main/webapp/WEB-INF/app/models/api/utils.rb index <HASH>..<HASH> 100644 --- a/sonar-server/src/main/webapp/WEB-INF/app/models/api/utils.rb +++ b/sonar-server/src/main/webapp/WEB-INF/app/models/api/utils.rb @@ -60,10 +60,9 @@ class Api::Utils # For history reference: # - http://jira.codehaus.org/browse/SONAR-2282 first modified the behaviour to keep the trailing lines # - then http://jira.codehaus.org/browse/SONAR-3003 reverted this modification to remove potential last empty line + # - then http://jira.codehaus.org/browse/SONAR-3896 reactivate this modification to display last empty line def self.split_newlines(input) - result = input.split(/\r?\n|\r/, -1) - result.pop if result.last=='' - result + input.split(/\r?\n|\r/, -1) end def self.convert_string_to_unix_newlines(input)
SONAR-<I> The last empty line of source file is not displayed in the source code viewer
SonarSource_sonarqube
train
d61989033ff1c3fafa8e23faf43a56c02c1cfb91
diff --git a/calendar/lib.php b/calendar/lib.php index <HASH>..<HASH> 100644 --- a/calendar/lib.php +++ b/calendar/lib.php @@ -104,9 +104,15 @@ function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_y list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display $display->maxdays = calendar_days_in_month($m, $y); - // We 'll keep these values as GMT here, and offset them when the time comes to query the db - $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT - $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT + if (get_user_timezone_offset() < 99) { + // We 'll keep these values as GMT here, and offset them when the time comes to query the db + $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT + $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT + } else { + // no timezone info specified + $display->tstart = mktime(0, 0, 0, $m, 1, $y); + $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y); + } $startwday = dayofweek(1, $m, $y);
Bug #<I> - The calendar does not show the month's first day's event; merged from MOODLE_<I>_STABLE
moodle_moodle
train
71d26732e1dc9d7e41a10b3bea4d3a991341ccfc
diff --git a/lib/connection.js b/lib/connection.js index <HASH>..<HASH> 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -88,7 +88,7 @@ function escapeCQL(val) { return val.toString('hex'); } - if(typeof val === 'boolean' || typeof val === 'number'){ + if(typeof val === 'number'){ return val.toString(); } @@ -97,7 +97,7 @@ function escapeCQL(val) { return sanitized.join(','); } - if (typeof val === 'object') { + if (typeof val === 'object' || typeof val === 'boolean') { val = (typeof val.toISOString === 'function') ? val.toISOString() : val.toString(); }
Boolean values need to be enclused in single quotes.
lyveminds_scamandrios
train
d7a55994d5c76f2cce74bcec47b574aa7d849af3
diff --git a/product/selectors/product.js b/product/selectors/product.js index <HASH>..<HASH> 100644 --- a/product/selectors/product.js +++ b/product/selectors/product.js @@ -236,7 +236,7 @@ export const getProductImages = createSelector( export const getProductRating = createSelector( getCurrentProduct, (product) => { - if (!product || product.rating) { + if (!product || !product.rating) { return {}; }
CON-<I>: Users can write new reviews - fix rating not showing up
shopgate_pwa
train
6b95febc8e373d983851672271c1d5526be8542e
diff --git a/app/models/manager_refresh/dto_collection.rb b/app/models/manager_refresh/dto_collection.rb index <HASH>..<HASH> 100644 --- a/app/models/manager_refresh/dto_collection.rb +++ b/app/models/manager_refresh/dto_collection.rb @@ -3,9 +3,10 @@ module ManagerRefresh attr_accessor :saved, :data, :data_index, :dependency_attributes, :manager_ref, :attributes, :association, :parent - attr_reader :model_class, :attributes_blacklist + attr_reader :model_class, :attributes_blacklist, :custom_save_block - def initialize(model_class, manager_ref: nil, attributes: nil, association: nil, parent: nil, strategy: nil) + def initialize(model_class, manager_ref: nil, attributes: nil, association: nil, parent: nil, strategy: nil, + custom_save_block: nil) @model_class = model_class @manager_ref = manager_ref || [:ems_ref] @attributes = attributes || [] @@ -18,6 +19,7 @@ module ManagerRefresh @strategy = process_strategy(strategy) @attributes_blacklist = Set.new @attributes_whitelist = Set.new + @custom_save_block = custom_save_block end def process_strategy(strategy_name) diff --git a/app/models/manager_refresh/save_collection/helper.rb b/app/models/manager_refresh/save_collection/helper.rb index <HASH>..<HASH> 100644 --- a/app/models/manager_refresh/save_collection/helper.rb +++ b/app/models/manager_refresh/save_collection/helper.rb @@ -3,11 +3,15 @@ module ManagerRefresh::SaveCollection def save_dto_inventory(ems, dto_collection) _log.info("Synchronizing #{ems.name} collection #{dto_collection.size} of size #{dto_collection} to database") - save_dto_inventory_multi_batch(dto_collection.parent.send(dto_collection.association), - dto_collection, - :use_association, - dto_collection.manager_ref) - + if dto_collection.custom_save_block.present? + dto_collection.custom_save_block.call(ems, dto_collection) + else + _log.info("Synchronizing #{ems.name} collection #{dto_collection.size} using a custom save block") + save_dto_inventory_multi_batch(dto_collection.parent.send(dto_collection.association), + dto_collection, + :use_association, + dto_collection.manager_ref) + end _log.info("Synchronized #{ems.name} collection #{dto_collection}") dto_collection.saved = true end
Allow custom saving block Allow custom saving block, for cases where we do special saving logic, like orchestration_templates. In many cases though, the special logic is not needed, so we should do refactoring of the code. (transferred from ManageIQ/manageiq@<I>b<I>d<I>cc6bc<I>e<I>fdca3f5fc<I>fcf<I>)
ManageIQ_inventory_refresh
train
7239a2013caafd039a9c993490fc96d1fb5d54be
diff --git a/Clipper/joplin-webclipper/content_scripts/index.js b/Clipper/joplin-webclipper/content_scripts/index.js index <HASH>..<HASH> 100644 --- a/Clipper/joplin-webclipper/content_scripts/index.js +++ b/Clipper/joplin-webclipper/content_scripts/index.js @@ -103,7 +103,7 @@ // Cleans up element by removing all its invisible children (which we don't want to render as Markdown) // And hard-code the image dimensions so that the information can be used by the clipper server to // display them at the right sizes in the notes. - function cleanUpElement(element, imageSizes, imageIndexes) { + function cleanUpElement(convertToMarkup, element, imageSizes, imageIndexes) { const childNodes = element.childNodes; const hiddenNodes = []; @@ -132,19 +132,19 @@ if (!(src in imageIndexes)) imageIndexes[src] = 0; const imageSize = imageSizes[src][imageIndexes[src]]; imageIndexes[src]++; - if (imageSize) { + if (imageSize && convertToMarkup === 'markdown') { node.width = imageSize.width; node.height = imageSize.height; } } - cleanUpElement(node, imageSizes, imageIndexes); + cleanUpElement(convertToMarkup, node, imageSizes, imageIndexes); } } for (const hiddenNode of hiddenNodes) { if (!hiddenNode.parentNode) continue; - hiddenNode.parentNode.remove(hiddenNode); + hiddenNode.parentNode.removeChild(hiddenNode); } } @@ -260,6 +260,8 @@ async function prepareCommandResponse(command) { console.info('Got command: ' + command.name); + const convertToMarkup = command.preProcessFor ? command.preProcessFor : 'markdown'; + const clippedContentResponse = (title, html, imageSizes, anchorNames, stylesheets) => { return { name: 'clippedContent', @@ -272,7 +274,7 @@ image_sizes: imageSizes, anchor_names: anchorNames, source_command: Object.assign({}, command), - convert_to: command.preProcessFor ? command.preProcessFor : 'markdown', + convert_to: convertToMarkup, stylesheets: stylesheets, }; } @@ -306,9 +308,9 @@ const cleanDocument = document.body.cloneNode(true); const imageSizes = getImageSizes(document, true); const imageIndexes = {}; - cleanUpElement(cleanDocument, imageSizes, imageIndexes); + cleanUpElement(convertToMarkup, cleanDocument, imageSizes, imageIndexes); - const stylesheets = command.preProcessFor === 'html' ? getStyleSheets(document) : null; + const stylesheets = convertToMarkup === 'html' ? getStyleSheets(document) : null; return clippedContentResponse(pageTitle(), cleanDocument.innerHTML, imageSizes, getAnchorNames(document), stylesheets); } else if (command.name === "selectedHtml") { @@ -320,7 +322,7 @@ container.appendChild(range.cloneContents()); const imageSizes = getImageSizes(document, true); const imageIndexes = {}; - cleanUpElement(container, imageSizes, imageIndexes); + cleanUpElement(convertToMarkup, container, imageSizes, imageIndexes); return clippedContentResponse(pageTitle(), container.innerHTML, getImageSizes(document), getAnchorNames(document)); } else if (command.name === 'screenshot') { diff --git a/ElectronClient/app/gui/NoteText.jsx b/ElectronClient/app/gui/NoteText.jsx index <HASH>..<HASH> 100644 --- a/ElectronClient/app/gui/NoteText.jsx +++ b/ElectronClient/app/gui/NoteText.jsx @@ -1643,6 +1643,7 @@ class NoteTextComponent extends React.Component { const style = this.props.style; const note = this.state.note; const body = note && note.body ? note.body : ''; + const markupLanguage = note ? note.markup_language : Note.MARKUP_LANGUAGE_MARKDOWN; const theme = themeStyle(this.props.theme); const visiblePanes = this.props.visiblePanes || ['editor', 'viewer']; const isTodo = note && !!note.is_todo; @@ -1813,7 +1814,7 @@ class NoteTextComponent extends React.Component { const toolbarItems = this.createToolbarItems(note); - const toolbar = <Toolbar + const toolbar = markupLanguage !== Note.MARKUP_LANGUAGE_MARKDOWN ? null : <Toolbar style={toolbarStyle} items={toolbarItems} /> diff --git a/ReactNativeClient/lib/renderers/utils.js b/ReactNativeClient/lib/renderers/utils.js index <HASH>..<HASH> 100644 --- a/ReactNativeClient/lib/renderers/utils.js +++ b/ReactNativeClient/lib/renderers/utils.js @@ -92,6 +92,8 @@ utils.resourceStatus = function(resourceInfo) { } utils.imageReplacement = function(src, resources, resourceBaseUrl) { + if (!Resource.isResourceUrl(src)) return null; + const resourceId = Resource.urlToId(src); const result = resources[resourceId]; const resource = result ? result.item : null; diff --git a/ReactNativeClient/lib/services/rest/Api.js b/ReactNativeClient/lib/services/rest/Api.js index <HASH>..<HASH> 100644 --- a/ReactNativeClient/lib/services/rest/Api.js +++ b/ReactNativeClient/lib/services/rest/Api.js @@ -585,7 +585,7 @@ class Api { }); } - const concurrency = 3 + const concurrency = 10; const pool = new PromisePool(promiseProducer, concurrency) await pool.start()
Clipper: Improved clipping of images in HTML mode
laurent22_joplin
train
f61d0760e90f514c659f25450613d745a7a6e7e1
diff --git a/app/models/effective/order.rb b/app/models/effective/order.rb index <HASH>..<HASH> 100644 --- a/app/models/effective/order.rb +++ b/app/models/effective/order.rb @@ -77,17 +77,15 @@ module Effective end retval = cart_items.map do |item| - self.order_items.build( + order_items.build( :title => item.title, :quantity => item.quantity, :price => item.price, :tax_exempt => item.tax_exempt, :tax_rate => item.tax_rate, :quickbooks_item_name => item.quickbooks_item_name, - :purchasable_id => item.purchasable_id, - :purchasable_type => item.purchasable_type, :seller_id => (item.purchasable.try(:seller).try(:id) rescue nil) - ) + ).tap { |order_item| order_item.purchasable = item.purchasable } end retval.size == 1 ? retval.first : retval
Allow non-persisted purchasables to work with order.add_to_order
code-and-effect_effective_orders
train
f9719ba85a2ce5ce4ac0228c43fd6c46ec68dfb9
diff --git a/code/model/OrderStep.php b/code/model/OrderStep.php index <HASH>..<HASH> 100644 --- a/code/model/OrderStep.php +++ b/code/model/OrderStep.php @@ -58,6 +58,18 @@ class OrderStep extends DataObject { "ShowAsCompletedOrderNice" => "Varchar" ); + + public static $searchable_fields = array( + 'Name' => array( + 'title' => 'Name', + 'filter' => 'PartialMatchFilter' + ), + 'Code' => array( + 'title' => 'Code', + 'filter' => 'PartialMatchFilter' + ) + ); + function CustomerCanEditNice() {if($this->CustomerCanEdit) {return _t("OrderStep.YES", "Yes");}return _t("OrderStep.NO", "No");} function CustomerCanPayNice() {if($this->CustomerCanPay) {return _t("OrderStep.YES", "Yes");}return _t("OrderStep.NO", "No");} function CustomerCanCancelNice() {if($this->CustomerCanCancel) {return _t("OrderStep.YES", "Yes");}return _t("OrderStep.NO", "No");}
changed Searchable fields for OrderStep
silvershop_silvershop-core
train
cb47c8aba9e3871de85d91f8c1df3cb1a9904880
diff --git a/eZ/Publish/API/Repository/Values/Content/URLAlias.php b/eZ/Publish/API/Repository/Values/Content/URLAlias.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/API/Repository/Values/Content/URLAlias.php +++ b/eZ/Publish/API/Repository/Values/Content/URLAlias.php @@ -21,6 +21,7 @@ use eZ\Publish\API\Repository\Values\ValueObject; * @property-read string[] languageCodes the languages for which this alias is valid * @property-read boolean $alwaysAvailable Fallback indicator for other languages * @property-read boolean $isHistory Indicates that this alias was autogenerated for an in the meanwhile archived version of the content + * @property-read boolean $forward Indicates if the url should be redirected */ class URLAlias extends ValueObject @@ -79,5 +80,12 @@ class URLAlias extends ValueObject * @var boolean */ protected $isHistory; + + /** + * Indicates if the url should be redirected + * + * @var boolean + */ + protected $forward; } \ No newline at end of file diff --git a/eZ/Publish/SPI/Persistence/Content/UrlAlias.php b/eZ/Publish/SPI/Persistence/Content/UrlAlias.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/SPI/Persistence/Content/UrlAlias.php +++ b/eZ/Publish/SPI/Persistence/Content/UrlAlias.php @@ -73,5 +73,10 @@ class UrlAlias extends ValueObject */ public $isHistory; - + /** + * Indicates if the url should be redirected + * + * @var boolean + */ + public $forward; }
small corrections - added forward property to value
ezsystems_ezpublish-kernel
train
548fe9965f5e71d52f720cd5eac962e70aa46459
diff --git a/lib/extinction.py b/lib/extinction.py index <HASH>..<HASH> 100644 --- a/lib/extinction.py +++ b/lib/extinction.py @@ -106,17 +106,6 @@ _smc = _computeSMC(_waveset) _xgal = _computeXgal(_waveset) -class Ebmvx(spectrum.SpectralElement): - def __init__(self, extval, redlaw): - ''' Extinction mimics as a spectral element. - ''' - law = factory(redlaw, extval) - - self._wavetable = 10000.0 / law._wavetable - self._throughputtable = law.transparencytable - self.name=redlaw - self.waveunits=units.Units('angstrom') - class _ExtinctionLaw(object): @@ -124,33 +113,42 @@ class _ExtinctionLaw(object): return 10.0 ** (-0.4 * extval * curve) -class Gal1(_ExtinctionLaw): +class Gal1(_ExtinctionLaw): + citation = 'Seaton 1979 (MNRAS 187:75)' + name = 'gal1' def __init__(self, extval): - self.name = 'Seaton' + global _seaton self._wavetable = _waveset.copy() self.transparencytable = self._computeTransparency(extval, _seaton) -class Gal2(_ExtinctionLaw): +class Gal2(_ExtinctionLaw): + citation = 'Savage & Mathis 1979 (ARA&A 17:73)' + name = 'gal2' def __init__(self, extval): - self.name = 'Savage & Mathis' - - -class Gal3(_ExtinctionLaw): - def __init__(self, extval): - self.name = 'Cardelli, Clayton & Mathis' + raise NotImplementedError("Sorry, %s is not yet implemented"%self.name) + +class Gal3(_ExtinctionLaw): + citation='Cardelli, Clayton & Mathis 1989 (ApJ 345:245)' + name='gal3' + + def __init__(self, extval): + raise NotImplementedError("Sorry, %s is not yet implemented"%self.name) -class Smc(_ExtinctionLaw): +class Smc(_ExtinctionLaw): + citation='Prevot et al.1984 (A&A 132:389)' + name='SMC' def __init__(self, extval): - self.name = 'SMC' global _smc self._wavetable = _waveset.copy() self.transparencytable = self._computeTransparency(extval, _smc) -class Lmc(_ExtinctionLaw): +class Lmc(_ExtinctionLaw): + citation='Howarth 1983 (MNRAS 203:301)' + name='LMC' def __init__(self, extval): self.name = 'LMC' global _lmc @@ -158,9 +156,10 @@ class Lmc(_ExtinctionLaw): self.transparencytable = self._computeTransparency(extval, _lmc) -class Xgal(_ExtinctionLaw): - def __init__(self, extval): - self.name = 'Extragalactic' +class Xgal(_ExtinctionLaw): + citation = 'Calzetti, Kinney and Storchi-Bergmann, 1994 (ApJ 429:582)' + name='XGAL' + def __init__(self, extval): global _xgal self._wavetable = _waveset.copy() self.transparencytable = self._computeTransparency(extval, _xgal) @@ -176,3 +175,19 @@ reddeningClasses = {'gal1': Gal1, def factory(redlaw, *args, **kwargs): return apply(reddeningClasses[string.lower(redlaw)], args, kwargs) +class Ebmvx(spectrum.SpectralElement): + def __init__(self, extval, redlaw): + ''' Extinction mimics as a spectral element. + ''' + law = factory(redlaw, extval) + self._wavetable = 10000.0 / law._wavetable + self._throughputtable = law.transparencytable + self.name=law.name + self.citation=law.citation + self.waveunits=units.Units('angstrom') + + def options(): + print "Supported reddening laws:" + for k in reddeningClasses.keys(): + print "%s: %s"%(k,reddeningClasses[k].citation) + options=staticmethod(options)
Extinction.py: added .citation attribute to Ebmvx objects, which closes #<I>. Added static class method Ebmvx.options() that prints the supported reddening laws & their citations. Modified stubbed-out Gal2 and Gal3 classes to raise NotImplementedError. git-svn-id: <URL>
spacetelescope_pysynphot
train
dce3931f20822850d40851c2a87fddda3984fa70
diff --git a/modules/system/models/MailPartial.php b/modules/system/models/MailPartial.php index <HASH>..<HASH> 100644 --- a/modules/system/models/MailPartial.php +++ b/modules/system/models/MailPartial.php @@ -72,14 +72,24 @@ class MailPartial extends Model */ public static function createPartials() { - $dbPartials = self::lists('code', 'code'); - - $definitions = MailManager::instance()->listRegisteredPartials(); - foreach ($definitions as $code => $path) { - if (array_key_exists($code, $dbPartials)) { + $partials = MailManager::instance()->listRegisteredPartials(); + $dbPartials = self::lists('is_custom', 'code'); + $newPartials = array_diff_key($partials, $dbPartials); + + /* + * Clean up non-customized partials + */ + foreach ($dbPartials as $code => $isCustom) { + if ($isCustom) { continue; } + if (!array_key_exists($code, $partials)) { + self::whereCode($code)->delete(); + } + } + + foreach ($newPartials as $code => $path) { $partial = new static; $partial->code = $code; $partial->is_custom = 0;
Clean up uncustomised partials if they are no longer provided. An exception was being thrown in some instances if a partial had been added to the DB that was provided by a plugin that no longer exists, or had been disabled. This will remove any partials provided by non-existent plugins, only if they haven't been subsequently customised by the developer. Fixes <URL>
octobercms_october
train
bc6ec46620be2805792da6fdfe5f541f9134ca7f
diff --git a/plugins/CoreHome/angularjs/notification/notification.directive.js b/plugins/CoreHome/angularjs/notification/notification.directive.js index <HASH>..<HASH> 100644 --- a/plugins/CoreHome/angularjs/notification/notification.directive.js +++ b/plugins/CoreHome/angularjs/notification/notification.directive.js @@ -87,8 +87,9 @@ function closeExistingNotificationHavingSameIdIfNeeded(id, notificationElement) { // TODO: instead of doing a global query for notification, there should be a notification-container // directive that manages notifications. + var notificationStillExists = !!notificationElement.parents('body').length; var existingNode = angular.element('[notification-id=' + id + ']').not(notificationElement); - if (existingNode && existingNode.length) { + if (notificationStillExists && existingNode && existingNode.length) { existingNode.remove(); } }
Ensure at least one notification with the same id remains (#<I>)
matomo-org_matomo
train
5e2b9410a7db019e4ad1056ec0a3d507374e5e4b
diff --git a/tests/test_replay.py b/tests/test_replay.py index <HASH>..<HASH> 100644 --- a/tests/test_replay.py +++ b/tests/test_replay.py @@ -92,10 +92,16 @@ def test_run_json_dump( ) spy_json_dump = mocker.spy('json.dump') + mock_get_user_config = mocker.patch( + 'cookiecutter.config.get_user_config', + return_value=replay_dir + ) + replay.dump(template_name, context) spy_ensure.assert_called_once_with(replay_dir) assert spy_json_dump.called == 1 + assert mock_get_user_config.called == 1 replay_dir = os.path.expanduser('~/.cookiecutter_replay/') replay_file = os.path.join(replay_dir, template_name)
Make sure that get_user_config is called in replay.dump
audreyr_cookiecutter
train
db89c0ec337a540da67b76b104676bd1efedd91b
diff --git a/experiments/lm/char_irnn_lm.py b/experiments/lm/char_irnn_lm.py index <HASH>..<HASH> 100644 --- a/experiments/lm/char_irnn_lm.py +++ b/experiments/lm/char_irnn_lm.py @@ -15,14 +15,15 @@ logging.basicConfig(level=logging.INFO) model_path = "/tmp/rnn_lm_params12.gz" resource_dir = os.path.abspath(os.path.dirname(__file__)) + os.sep + "resources" -train_vocab_path = os.path.join(resource_dir, "ptb.train.txt") +vocab_path = os.path.join(resource_dir, "ptb.train.txt") train_path = os.path.join(resource_dir, "ptb.train.txt") valid_path = os.path.join(resource_dir, "ptb.valid.txt") vocab = Vocab(char_based=True) -vocab.load(train_vocab_path, fixed_size=1000) +vocab.load(vocab_path, fixed_size=1000) model = NeuralLM(input_dim=vocab.size, input_tensor=3) model.stack_layers( + IRNN(hidden_size=100, output_size=vocab.size, output_type="all_hidden"), IRNN(hidden_size=100, output_size=vocab.size, output_type="all_output")) @@ -39,7 +40,7 @@ if __name__ == '__main__': print "".join(map(vocab.word, targets)) raise SystemExit - lmdata = LMDataset(vocab, train_path, valid_path, history_len=-1, char_based=True, max_tokens=300) + lmdata = LMDataset(vocab, train_path, valid_path, history_len=30, char_based=True, max_tokens=300) batch = SequentialMiniBatches(lmdata, batch_size=20) trainer = SGDTrainer(model)
Char-based LM with history <I>
zomux_deepy
train
7f982a8daa985694a01d2b615619d468d2c582e4
diff --git a/dependency/bson/bson_test.go b/dependency/bson/bson_test.go index <HASH>..<HASH> 100644 --- a/dependency/bson/bson_test.go +++ b/dependency/bson/bson_test.go @@ -10,7 +10,7 @@ import ( "testing" "time" - "github.com/youtube/vitess/go/bytes2" + "github.com/xwb1989/sqlparser/dependency/bytes2" ) type alltypes struct { diff --git a/dependency/bson/custom_test.go b/dependency/bson/custom_test.go index <HASH>..<HASH> 100644 --- a/dependency/bson/custom_test.go +++ b/dependency/bson/custom_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "github.com/youtube/vitess/go/bytes2" + "github.com/xwb1989/sqlparser/dependency/bytes2" ) const ( diff --git a/dependency/bson/marshal_test.go b/dependency/bson/marshal_test.go index <HASH>..<HASH> 100644 --- a/dependency/bson/marshal_test.go +++ b/dependency/bson/marshal_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/youtube/vitess/go/bytes2" + "github.com/xwb1989/sqlparser/dependency/bytes2" ) type String1 string
Refer to dependencies folder for all packages copied from github.com/youtube/vitess/go references so that tests will run.
xwb1989_sqlparser
train
f5c8ae0fcdb531b22acf38ea9bfa27e5f916caea
diff --git a/lib/adhearsion/call.rb b/lib/adhearsion/call.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/call.rb +++ b/lib/adhearsion/call.rb @@ -310,7 +310,7 @@ module Adhearsion # @param [Hash, Optional] options further options to be joined with # def join(target, options = {}) - logger.info "Joining to #{target.inspect}" + logger.info "Joining to #{target}" command = Punchblock::Command::Join.new options.merge(join_options_with_target(target)) write_and_await_response command end @@ -323,7 +323,7 @@ module Adhearsion # @option target [String] mixer_name The mixer to unjoin from # def unjoin(target) - logger.info "Unjoining from #{target.inspect}" + logger.info "Unjoining from #{target}" command = Punchblock::Command::Unjoin.new join_options_with_target(target) write_and_await_response command end
[BUGFIX] Revert potentially breaking change to logging
adhearsion_adhearsion
train
3caa4ad1baba3019c06733e1a80d78d9a57137bb
diff --git a/p2p/protocol_test.go b/p2p/protocol_test.go index <HASH>..<HASH> 100644 --- a/p2p/protocol_test.go +++ b/p2p/protocol_test.go @@ -4,6 +4,7 @@ import ( "fmt" "net" "reflect" + "sync" "testing" "github.com/ethereum/go-ethereum/crypto" @@ -36,50 +37,71 @@ func newTestPeer() (peer *Peer) { } func TestBaseProtocolPeers(t *testing.T) { - cannedPeerList := []*peerAddr{ + peerList := []*peerAddr{ {IP: net.ParseIP("1.2.3.4"), Port: 2222, Pubkey: []byte{}}, {IP: net.ParseIP("5.6.7.8"), Port: 3333, Pubkey: []byte{}}, } - var ownAddr *peerAddr = &peerAddr{IP: net.ParseIP("1.3.5.7"), Port: 1111, Pubkey: []byte{}} + listenAddr := &peerAddr{IP: net.ParseIP("1.3.5.7"), Port: 1111, Pubkey: []byte{}} rw1, rw2 := MsgPipe() + defer rw1.Close() + wg := new(sync.WaitGroup) + // run matcher, close pipe when addresses have arrived - addrChan := make(chan *peerAddr, len(cannedPeerList)) + numPeers := len(peerList) + 1 + addrChan := make(chan *peerAddr) + wg.Add(1) go func() { - for _, want := range cannedPeerList { - got := <-addrChan - t.Logf("got peer: %+v", got) + i := 0 + for got := range addrChan { + var want *peerAddr + switch { + case i < len(peerList): + want = peerList[i] + case i == len(peerList): + want = listenAddr // listenAddr should be the last thing sent + } + t.Logf("got peer %d/%d: %v", i+1, numPeers, got) if !reflect.DeepEqual(want, got) { - t.Errorf("mismatch: got %#v, want %#v", got, want) + t.Errorf("mismatch: got %+v, want %+v", got, want) + } + i++ + if i == numPeers { + break } } - close(addrChan) - var own []*peerAddr - var got *peerAddr - for got = range addrChan { - own = append(own, got) - } - if len(own) != 1 || !reflect.DeepEqual(ownAddr, own[0]) { - t.Errorf("mismatch: peers own address is incorrectly or not given, got %v, want %#v", ownAddr) + if i != numPeers { + t.Errorf("wrong number of peers received: got %d, want %d", i, numPeers) } - rw2.Close() + rw1.Close() + wg.Done() }() - // run first peer + + // run first peer (in background) peer1 := newTestPeer() - peer1.ourListenAddr = ownAddr + peer1.ourListenAddr = listenAddr peer1.otherPeers = func() []*Peer { - pl := make([]*Peer, len(cannedPeerList)) - for i, addr := range cannedPeerList { + pl := make([]*Peer, len(peerList)) + for i, addr := range peerList { pl[i] = &Peer{listenAddr: addr} } return pl } - go runBaseProtocol(peer1, rw1) + wg.Add(1) + go func() { + runBaseProtocol(peer1, rw1) + wg.Done() + }() + // run second peer peer2 := newTestPeer() peer2.newPeerAddr = addrChan // feed peer suggestions into matcher if err := runBaseProtocol(peer2, rw2); err != ErrPipeClosed { t.Errorf("peer2 terminated with unexpected error: %v", err) } + + // terminate matcher + close(addrChan) + wg.Wait() } func TestBaseProtocolDisconnect(t *testing.T) {
p2p: improve test for peers message The test now checks that the number of of addresses is correct and terminates cleanly.
ethereum_go-ethereum
train
7088bea224ce144405c65e3781c9ab505dba48c9
diff --git a/src/main/java/org/agmip/dome/Calculate.java b/src/main/java/org/agmip/dome/Calculate.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/agmip/dome/Calculate.java +++ b/src/main/java/org/agmip/dome/Calculate.java @@ -262,7 +262,7 @@ public class Calculate extends Command { continue; } - for (int i=0; i < pointerSize; i++) { + for (int i=0, j=0; i < pointerSize; i++) { String liveEvent = ""; Object objEvent = pointer.get(i).get("event"); if (objEvent != null) { @@ -270,12 +270,13 @@ public class Calculate extends Command { } if (liveEvent.equals(eventType)) { log.debug("Level 1 passed, i: {} ss: {}", i, sourceSize); - if ( i < sourceSize ) { + if ( j < sourceSize ) { log.debug("Level 2 passed"); if (replace || (!replace && !varHasValue(pointer.get(i), targetVariable, isEvent))) { // Replace if only I have something for you. log.debug("Level 3, writing [{}] now", var); - pointer.get(i).put(var, values.get(i)); + pointer.get(i).put(var, values.get(j)); + j++; } } }
Fix the issue that the calculated result for event variable might not be set back to data set correctly.
agmip_dome
train
4ce18dfeaa33749bf0568ee57cde0b311ddbc74a
diff --git a/werkzeug/security.py b/werkzeug/security.py index <HASH>..<HASH> 100644 --- a/werkzeug/security.py +++ b/werkzeug/security.py @@ -253,7 +253,7 @@ def safe_join(directory, *pathnames): cannot be done, this function returns ``None``. :param directory: the base directory. - :param filename: the untrusted filename relative to that directory. + :param pathnames: the untrusted pathnames relative to that directory. """ parts = [directory] for filename in pathnames:
Typo fix for a `safe_join` docstring Just fix a minor inconsistency for function params and docstring names. The original commit comes from: - <URL>
pallets_werkzeug
train
84f121e0fec8e1f73ec47d9894eb9946b900be22
diff --git a/src/HttpMasterWorker.js b/src/HttpMasterWorker.js index <HASH>..<HASH> 100644 --- a/src/HttpMasterWorker.js +++ b/src/HttpMasterWorker.js @@ -6,7 +6,8 @@ var crypto = require('crypto'), regexpQuote = require('./DispatchTable').regexpQuote, tls = require('tls'), DI = require('./di'), - path = require('path'); + path = require('path'), + extend = require('extend'); var nodeVersion = Number(process.version.match(/^v(\d+\.\d+)/)[1]); @@ -202,39 +203,72 @@ function createHandlers(portNumber, portConfig) { }; } -function handleConfigEntryAfterLoadingKeys(host, portNumber, config, callback) { + +function serverForPortConfig(host, portNumber, portConfig) { var self = this; + var server; - var handlers = createHandlers.call(this, portNumber, config); + self.cachedServers = self.cachedServers || {}; + var key = (host? host + ':' + portNumber : portNumber); - var handler = require('./requestHandler')(handlers.request, handlers.error); - var server; - try { - if (config.ssl) { - var baseModule = config.ssl.spdy ? require('spdy') : require('https'); + var sslCachedConfig = extend({}, portConfig.ssl); + delete sslCachedConfig.SNI; - patchSslConfig.call(self, config.ssl); + var cached = self.cachedServers[key]; + if(cached) { + server = self.cachedServers[key].server; + server.removeAllListeners(); + if(JSON.stringify(sslCachedConfig) === cached.sslConfig) { + return server; + } + } - server = baseModule.createServer(config.ssl, handler); + if (portConfig.ssl) { + var baseModule = portConfig.ssl.spdy ? require('spdy') : require('https'); - if (!config.ssl.skipWorkerSessionResumption) { - server.on('resumeSession', self.tlsSessionStore.get.bind(self.tlsSessionStore)); - server.on('newSession', self.tlsSessionStore.set.bind(self.tlsSessionStore)); + patchSslConfig.call(self, portConfig.ssl); - if (self.token) { - if (server._setServerData) { - server._setServerData({ - ticketKeys: self.token - }); - } else { - self.logNotice('SSL/TLS ticket session resumption may not work due to missing method _setServerData, you might be using an old version of Node'); - } + server = baseModule.createServer(portConfig.ssl); + + if (!portConfig.ssl.skipWorkerSessionResumption) { + server.on('resumeSession', self.tlsSessionStore.get.bind(self.tlsSessionStore)); + server.on('newSession', self.tlsSessionStore.set.bind(self.tlsSessionStore)); + + if (self.token) { + if (server._setServerData) { + server._setServerData({ + ticketKeys: self.token + }); + } else { + self.logNotice('SSL/TLS ticket session resumption may not work due to missing method _setServerData, you might be using an old version of Node'); } } - } else { - server = http.createServer(handler); } + } else { + server = http.createServer(); + } + + + self.cachedServers[key] = { + server: server, + sslConfig: JSON.stringify(sslCachedConfig) + } + return server; +} + +function handleConfigEntryAfterLoadingKeys(host, portNumber, config, callback) { + var self = this; + + var handlers = createHandlers.call(this, portNumber, config); + + var handler = require('./requestHandler')(handlers.request, handlers.error); + + var server; + try { + server = serverForPortConfig.call(this, host, portNumber, config); + server.removeAllListeners('request'); + server.on('request', handler); } catch (err) { return callback(err, null); } @@ -253,6 +287,8 @@ function handleConfigEntryAfterLoadingKeys(host, portNumber, config, callback) { server.once('listening', listeningHandler); server.once('error', errorHandler); + + server.removeAllListeners('upgrade'); server.on('upgrade', function(req, socket, head) { req.upgrade = { socket: socket,
Cache http servers for better reloading of SSL.
virtkick_http-master
train
9e23e8453014a65198b8aae5c5b151f6ed048609
diff --git a/src/rudiments/reamed/click.py b/src/rudiments/reamed/click.py index <HASH>..<HASH> 100644 --- a/src/rudiments/reamed/click.py +++ b/src/rudiments/reamed/click.py @@ -88,6 +88,10 @@ class Configuration(object): '/etc/{appname}.d/', '{appcfg}.conf', ] + DEFAULT_CONFIG_OPTS = dict( + encoding='utf-8', + default_encoding='utf-8', + ) @classmethod def from_context(cls, ctx, config_paths=None, project=None): @@ -107,7 +111,7 @@ class Configuration(object): If the environment variable ``<prefix>_CONFIG`` is set, its value will be appended to the default locations. """ - self.values = configobj.ConfigObj({}, encoding='utf-8', default_encoding='utf-8') + self.values = configobj.ConfigObj({}, **self.DEFAULT_CONFIG_OPTS) self.project = project self.name = name self.config_paths = [] @@ -159,10 +163,10 @@ class Configuration(object): def load(self): """Load configuration from the defined locations.""" if not self.loaded: - self.values = configobj.ConfigObj({}, encoding='utf-8', default_encoding='utf-8') + self.values = configobj.ConfigObj({}, **self.DEFAULT_CONFIG_OPTS) for path in self.locations(): try: - part = configobj.ConfigObj(infile=path, encoding='utf-8', default_encoding='utf-8') + part = configobj.ConfigObj(infile=path, **self.DEFAULT_CONFIG_OPTS) except configobj.ConfigObjError as cause: raise LoggedFailure("Error in file '{path}': {cause}".format(path=pretty_path(path), cause=cause)) self.values.merge(part)
pass the same config opts to every ConfigObj()
jhermann_rudiments
train
547285f151b4b42851f8e300303e779e699cf855
diff --git a/src/View/Helper/AlaxosFormHelper.php b/src/View/Helper/AlaxosFormHelper.php index <HASH>..<HASH> 100644 --- a/src/View/Helper/AlaxosFormHelper.php +++ b/src/View/Helper/AlaxosFormHelper.php @@ -321,4 +321,12 @@ class AlaxosFormHelper extends FormHelper return $this->AlaxosHtml->script(Router::url(['prefix' => false, 'plugin' => 'Alaxos', 'controller' => 'Javascripts', 'action' => 'antispam', '_ext' => 'js', '?' => ['fid' => $form_dom_id, 'token' => $token]], true), ['block' => true]); } + + /*******************************/ + + public function domId($value) + { + return $this->_domId($value); + } + } \ No newline at end of file
Added public domId() method to AlaxosFormHelper
alaxos_cakephp3-libs
train