hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
cd988e7e934812f463c08c2dc7dc7b3abb68b288
|
diff --git a/recipes/rails.rb b/recipes/rails.rb
index <HASH>..<HASH> 100644
--- a/recipes/rails.rb
+++ b/recipes/rails.rb
@@ -169,6 +169,7 @@ deploy_revision app['id'] do
user app['owner']
group app['group']
deploy_to app['deploy_to']
+ environment({'RAILS_ENV' => node.app_environment})
action app['force'][node.app_environment] ? :force_deploy : :deploy
ssh_wrapper "#{app['deploy_to']}/deploy-ssh-wrapper" if app['deploy_key']
if app['migrate'][node.app_environment] && node[:apps][app['id']][node.app_environment][:run_migrations]
@@ -193,7 +194,7 @@ deploy_revision app['id'] do
end
elsif node.app_environment && app['databases'].has_key?(node.app_environment)
- execute "rake gems:install RAILS_ENV=#{app['migrate'][node.app_environment]}" do
+ execute "rake gems:install" do
ignore_failure true
end
end
|
set RAILS_ENV so it's applicable to all commands, including db:migrate
|
poise_application
|
train
|
ae588f6ceaac5ecfd7e02aa1c026c7d9179c0522
|
diff --git a/lib/ruby-asterisk/request.rb b/lib/ruby-asterisk/request.rb
index <HASH>..<HASH> 100644
--- a/lib/ruby-asterisk/request.rb
+++ b/lib/ruby-asterisk/request.rb
@@ -21,7 +21,11 @@ module RubyAsterisk
protected
def generate_action_id
- Random.rand(999).to_s
+ if RUBY_VERSION.start_with?("1.9")
+ Random.rand(999).to_s
+ else
+ rand(999).to_s
+ end
end
end
|
Added support to ruby <I>
|
emilianodellacasa_ruby-asterisk
|
train
|
ecb9ab348fbaa111f8053c4079dfab3af3f72414
|
diff --git a/default.go b/default.go
index <HASH>..<HASH> 100644
--- a/default.go
+++ b/default.go
@@ -240,11 +240,14 @@ func (b *Base64) UnmarshalText(data []byte) error { // validation is performed l
func (b *Base64) Scan(raw interface{}) error {
switch v := raw.(type) {
case []byte:
- if err := b.UnmarshalText(v); err != nil {
+ dbuf := make([]byte, base64.StdEncoding.DecodedLen(len(v)))
+ n, err := base64.StdEncoding.Decode(dbuf, v)
+ if err != nil {
return err
}
+ *b = dbuf[:n]
case string:
- vv, err := base64.URLEncoding.DecodeString(v)
+ vv, err := base64.StdEncoding.DecodeString(v)
if err != nil {
return err
}
@@ -262,7 +265,7 @@ func (b Base64) Value() (driver.Value, error) {
}
func (b Base64) String() string {
- return base64.URLEncoding.EncodeToString([]byte(b))
+ return base64.StdEncoding.EncodeToString([]byte(b))
}
// MarshalJSON returns the Base64 as JSON
@@ -276,7 +279,7 @@ func (b *Base64) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &b64str); err != nil {
return err
}
- vb, err := base64.URLEncoding.DecodeString(b64str)
+ vb, err := base64.StdEncoding.DecodeString(b64str)
if err != nil {
return err
}
@@ -297,7 +300,7 @@ func (b *Base64) UnmarshalBSON(data []byte) error {
}
if bd, ok := m["data"].(string); ok {
- vb, err := base64.URLEncoding.DecodeString(bd)
+ vb, err := base64.StdEncoding.DecodeString(bd)
if err != nil {
return err
}
|
revert back to stdencodign for base<I>
|
go-openapi_strfmt
|
train
|
1e95924a01f224354c7cd56a0e1a6e8727bf02a1
|
diff --git a/aeron-cluster/src/main/java/io/aeron/cluster/service/ClusteredServiceContainer.java b/aeron-cluster/src/main/java/io/aeron/cluster/service/ClusteredServiceContainer.java
index <HASH>..<HASH> 100644
--- a/aeron-cluster/src/main/java/io/aeron/cluster/service/ClusteredServiceContainer.java
+++ b/aeron-cluster/src/main/java/io/aeron/cluster/service/ClusteredServiceContainer.java
@@ -571,9 +571,9 @@ public final class ClusteredServiceContainer implements AutoCloseable
throw new ConcurrentConcludeException();
}
- if (serviceId < 0)
+ if (serviceId < 0 || serviceId > 127)
{
- throw new ConfigurationException("service id cannot be negative: " + serviceId);
+ throw new ConfigurationException("service id outside allowed range (0-127): " + serviceId);
}
if (null == threadFactory)
diff --git a/aeron-cluster/src/test/java/io/aeron/cluster/StubClusteredService.java b/aeron-cluster/src/test/java/io/aeron/cluster/StubClusteredService.java
index <HASH>..<HASH> 100644
--- a/aeron-cluster/src/test/java/io/aeron/cluster/StubClusteredService.java
+++ b/aeron-cluster/src/test/java/io/aeron/cluster/StubClusteredService.java
@@ -72,6 +72,6 @@ class StubClusteredService implements ClusteredService
protected long serviceCorrelationId(final int correlationId)
{
- return ((long)cluster.context().serviceId()) << 32 | correlationId;
+ return ((long)cluster.context().serviceId()) << 56 | correlationId;
}
}
|
[Java] Limit cluster service id range.
|
real-logic_aeron
|
train
|
fd2542da8b9bc3f68832b5cda98372e4e19b1a4b
|
diff --git a/pygccxml/parser/source_reader.py b/pygccxml/parser/source_reader.py
index <HASH>..<HASH> 100644
--- a/pygccxml/parser/source_reader.py
+++ b/pygccxml/parser/source_reader.py
@@ -141,13 +141,8 @@ class source_reader_t:
# so that we can parse them with pygccxml
cmd.append('--castxml-gccxml')
- # Add all additional defined symbols
- symbols = self.__config.define_symbols
- cmd.append(''.join(
- [' -D"%s"' % defined_symbol for defined_symbol in symbols]))
- un_symbols = self.__config.undefine_symbols
- cmd.append(''.join(
- [' -U"%s"' % undefined_symbol for undefined_symbol in un_symbols]))
+ # Add symbols
+ cmd = self.__add_symbols(cmd)
# The destination file
cmd.append('-o %s' % xmlfile)
@@ -162,6 +157,25 @@ class source_reader_t:
self.logger.info('castxml cmd: %s' % cmd_line)
return cmd_line
+ def __add_symbols(self, cmd):
+
+ """
+ Add all additional defined and undefined symbols.
+
+ """
+
+ if len(self.__config.define_symbols) != 0:
+ symbols = self.__config.define_symbols
+ cmd.append(''.join(
+ [' -D"%s"' % defined_symbol for defined_symbol in symbols]))
+ if len(self.__config.undefine_symbols) != 0:
+ un_symbols = self.__config.undefine_symbols
+ cmd.append(
+ ''.join([' -U"%s"' % undefined_symbol for
+ undefined_symbol in un_symbols]))
+
+ return cmd
+
def __create_command_line_gccxml(self, file, xmlfile):
assert isinstance(self.__config, config.gccxml_configuration_t)
# returns
@@ -178,13 +192,10 @@ class source_reader_t:
# second all additional includes directories
dirs = self.__search_directories
cmd.append(''.join([' -I"%s"' % search_dir for search_dir in dirs]))
- # third all additional defined symbols
- symbols = self.__config.define_symbols
- cmd.append(''.join(
- [' -D"%s"' % defined_symbol for defined_symbol in symbols]))
- un_symbols = self.__config.undefine_symbols
- cmd.append(''.join(
- [' -U"%s"' % undefined_symbol for undefined_symbol in un_symbols]))
+
+ # Add symbols
+ cmd = self.__add_symbols(cmd)
+
# fourth source file
cmd.append('"%s"' % file)
# five destination file
|
Add symbols to command line only if symbols have been defined.
|
gccxml_pygccxml
|
train
|
953d3c8cdcc10b71cb18d52de6efff323da94030
|
diff --git a/aikif/lib/cls_file.py b/aikif/lib/cls_file.py
index <HASH>..<HASH> 100644
--- a/aikif/lib/cls_file.py
+++ b/aikif/lib/cls_file.py
@@ -1,4 +1,9 @@
+#!/usr/bin/python3
+# coding: utf-8
# cls_file.py
+# Other modules that inherit from this class:
+# toolbox.xml_tools.XmlFile (in progress)
+# toolbox.image_tools.ImageFile (TODO)
import os
import sys
|
py3 header and noting which other class inherits from this
|
acutesoftware_AIKIF
|
train
|
a3994a39dac06a935767cd62b0348340dee06656
|
diff --git a/assets/app/scripts/directives/nav.js b/assets/app/scripts/directives/nav.js
index <HASH>..<HASH> 100644
--- a/assets/app/scripts/directives/nav.js
+++ b/assets/app/scripts/directives/nav.js
@@ -21,13 +21,16 @@ angular.module('openshiftConsole')
};
})
.directive('projectHeader', function($timeout, $location, $filter, DataService, projectOverviewURLFilter) {
+
+ // cache these to eliminate flicker
+ var projects = {};
+ var sortedProjects = [];
+
return {
restrict: 'EA',
templateUrl: 'views/directives/header/project-header.html',
link: function($scope, $elem) {
var select = $elem.find('.selectpicker');
- var projects = {};
- var sortedProjects = [];
var options = [];
var updateOptions = function() {
diff --git a/pkg/assets/bindata.go b/pkg/assets/bindata.go
index <HASH>..<HASH> 100644
--- a/pkg/assets/bindata.go
+++ b/pkg/assets/bindata.go
@@ -5732,23 +5732,24 @@ replace:!0,
templateUrl:"views/_sidebar-main-nav-item.html"
};
}).directive("projectHeader", [ "$timeout", "$location", "$filter", "DataService", "projectOverviewURLFilter", function(a, b, c, d, e) {
+var f = {}, g = [];
return {
restrict:"EA",
templateUrl:"views/directives/header/project-header.html",
-link:function(a, f) {
-var g = f.find(".selectpicker"), h = {}, i = [], j = [], k = function() {
+link:function(a, h) {
+var i = h.find(".selectpicker"), j = [], k = function() {
var b = a.project || {}, d = a.projectName, e = b.metadata && b.metadata.name;
(d || e) && (d || (d = b.metadata.name), e || (b = {
metadata:{
name:d
}
-}), h[d] || (h[d] = b), i = c("orderByDisplayName")(h), j = _.map(i, function(a) {
-return $("<option>").attr("value", a.metadata.name).attr("selected", a.metadata.name === d).text(c("uniqueDisplayName")(a, i));
-}), g.empty(), g.append(j), g.append($('<option data-divider="true"></option>')), g.append($('<option value="">View all projects</option>')), g.selectpicker("refresh"));
+}), f[d] || (f[d] = b), g = c("orderByDisplayName")(f), j = _.map(g, function(a) {
+return $("<option>").attr("value", a.metadata.name).attr("selected", a.metadata.name === d).text(c("uniqueDisplayName")(a, g));
+}), i.empty(), i.append(j), i.append($('<option data-divider="true"></option>')), i.append($('<option value="">View all projects</option>')), i.selectpicker("refresh"));
};
d.list("projects", a, function(a) {
-h = a.by("metadata.name"), k();
-}), k(), g.selectpicker({
+f = a.by("metadata.name"), k();
+}), k(), i.selectpicker({
iconBase:"fa",
tickIcon:"fa-check"
}).change(function() {
|
Cache projects outside of projectHeader link fn
|
openshift_origin
|
train
|
66ba5278b86e5e58bc532172492b820c84a3ffe6
|
diff --git a/app/view/js/bolt-extend.js b/app/view/js/bolt-extend.js
index <HASH>..<HASH> 100644
--- a/app/view/js/bolt-extend.js
+++ b/app/view/js/bolt-extend.js
@@ -309,13 +309,15 @@ var BoltExtender = Object.extend(Object, {
},
packageReadme: function(e) {
- var controller = this;
- $('#readmeModal').modal({ 'remote': jQuery(e.target).data("readme") });
+ jQuery.get( jQuery(e.target).data("readme") )
+ .done(function(data) {
+ bootbox.dialog({
+ message: data
+ });
+ });
- alert("Show README for: " + jQuery(e.target).data("readme") );
e.preventDefault();
-
},
uninstall: function(e) {
|
Show readme for extensions. Fixes #<I>
|
bolt_bolt
|
train
|
2e32b5a338dcbdd5b10ecd486836b3923eda9c4c
|
diff --git a/state/backups.go b/state/backups.go
index <HASH>..<HASH> 100644
--- a/state/backups.go
+++ b/state/backups.go
@@ -399,8 +399,8 @@ func (s *backupMetadataStorage) New() filestorage.Metadata {
return metadata.NewMetadata(*origin, "", nil)
}
-func (s *backupMetadataStorage) SetStored(meta filestorage.Metadata) error {
- err := setBackupStored(s.state, meta.ID())
+func (s *backupMetadataStorage) SetStored(id string) error {
+ err := setBackupStored(s.state, id)
if err != nil {
return errors.Trace(err)
}
|
Fix the signature of SetStored.
|
juju_juju
|
train
|
4acec33562e4e1230092eee7d76c2b8061ffc914
|
diff --git a/src/Core/Config/Middleware/ExtensionMiddleware.php b/src/Core/Config/Middleware/ExtensionMiddleware.php
index <HASH>..<HASH> 100644
--- a/src/Core/Config/Middleware/ExtensionMiddleware.php
+++ b/src/Core/Config/Middleware/ExtensionMiddleware.php
@@ -39,7 +39,7 @@ class ExtensionMiddleware implements Middleware
}
foreach ($this->getExtraConfig($class, $config, $excludeMiddleware) as $extra) {
- $config = Priority::mergeArray($extra, $config);
+ $config = Priority::mergeArray($config, $extra);
}
return $config;
}
diff --git a/tests/php/ORM/DataObjectTest.php b/tests/php/ORM/DataObjectTest.php
index <HASH>..<HASH> 100644
--- a/tests/php/ORM/DataObjectTest.php
+++ b/tests/php/ORM/DataObjectTest.php
@@ -1062,72 +1062,88 @@ class DataObjectTest extends SapphireTest
// Test logical fields (including composite)
$teamSpecifications = $schema->fieldSpecs(DataObjectTest\Team::class);
- $this->assertEquals(
- array(
- 'ID',
- 'ClassName',
- 'LastEdited',
- 'Created',
- 'Title',
- 'DatabaseField',
- 'ExtendedDatabaseField',
- 'CaptainID',
- 'FounderID',
- 'HasOneRelationshipID',
- 'ExtendedHasOneRelationshipID'
- ),
- array_keys($teamSpecifications),
+ $expected = array(
+ 'ID',
+ 'ClassName',
+ 'LastEdited',
+ 'Created',
+ 'Title',
+ 'DatabaseField',
+ 'ExtendedDatabaseField',
+ 'CaptainID',
+ 'FounderID',
+ 'HasOneRelationshipID',
+ 'ExtendedHasOneRelationshipID'
+ );
+ $actual = array_keys($teamSpecifications);
+ sort($expected);
+ sort($actual);
+ $this->assertEquals(
+ $expected,
+ $actual,
'fieldSpecifications() contains all fields defined on instance: base, extended and foreign keys'
);
$teamFields = $schema->databaseFields(DataObjectTest\Team::class, false);
- $this->assertEquals(
- array(
- 'ID',
- 'ClassName',
- 'LastEdited',
- 'Created',
- 'Title',
- 'DatabaseField',
- 'ExtendedDatabaseField',
- 'CaptainID',
- 'FounderID',
- 'HasOneRelationshipID',
- 'ExtendedHasOneRelationshipID'
- ),
- array_keys($teamFields),
+ $expected = array(
+ 'ID',
+ 'ClassName',
+ 'LastEdited',
+ 'Created',
+ 'Title',
+ 'DatabaseField',
+ 'ExtendedDatabaseField',
+ 'CaptainID',
+ 'FounderID',
+ 'HasOneRelationshipID',
+ 'ExtendedHasOneRelationshipID'
+ );
+ $actual = array_keys($teamFields);
+ sort($expected);
+ sort($actual);
+ $this->assertEquals(
+ $expected,
+ $actual,
'databaseFields() contains only fields defined on instance, including base, extended and foreign keys'
);
$subteamSpecifications = $schema->fieldSpecs(DataObjectTest\SubTeam::class);
- $this->assertEquals(
- array(
- 'ID',
- 'ClassName',
- 'LastEdited',
- 'Created',
- 'Title',
- 'DatabaseField',
- 'ExtendedDatabaseField',
- 'CaptainID',
- 'FounderID',
- 'HasOneRelationshipID',
- 'ExtendedHasOneRelationshipID',
- 'SubclassDatabaseField',
- 'ParentTeamID',
- ),
- array_keys($subteamSpecifications),
+ $expected = array(
+ 'ID',
+ 'ClassName',
+ 'LastEdited',
+ 'Created',
+ 'Title',
+ 'DatabaseField',
+ 'ExtendedDatabaseField',
+ 'CaptainID',
+ 'FounderID',
+ 'HasOneRelationshipID',
+ 'ExtendedHasOneRelationshipID',
+ 'SubclassDatabaseField',
+ 'ParentTeamID',
+ );
+ $actual = array_keys($subteamSpecifications);
+ sort($expected);
+ sort($actual);
+ $this->assertEquals(
+ $expected,
+ $actual,
'fieldSpecifications() on subclass contains all fields, including base, extended and foreign keys'
);
$subteamFields = $schema->databaseFields(DataObjectTest\SubTeam::class, false);
+ $expected = array(
+ 'ID',
+ 'SubclassDatabaseField',
+ 'ParentTeamID',
+ );
+ $actual = array_keys($subteamFields);
+ sort($expected);
+ sort($actual);
$this->assertEquals(
- array(
- 'ID',
- 'SubclassDatabaseField',
- 'ParentTeamID',
- ),
- array_keys($subteamFields),
+ $expected,
+ $actual,
'databaseFields() on subclass contains only fields defined on instance'
);
}
|
FIX Fixed bug in config merging priorities so that config values set by extensions are now least important instead of most important
|
silverstripe_silverstripe-framework
|
train
|
bdcd5f94b2efdf661f201917d63476c245aa7c09
|
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -127,7 +127,7 @@ module AbstractController
def process(action, *args)
@_action_name = action.to_s
- unless action_name = method_for_action(@_action_name)
+ unless action_name = _find_action_name(@_action_name)
raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
end
@@ -160,7 +160,7 @@ module AbstractController
# ==== Returns
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
def available_action?(action_name)
- method_for_action(action_name).present?
+ _find_action_name(action_name).present?
end
private
@@ -204,6 +204,23 @@ module AbstractController
end
# Takes an action name and returns the name of the method that will
+ # handle the action.
+ #
+ # It checks if the action name is valid and returns false otherwise.
+ #
+ # See method_for_action for more information.
+ #
+ # ==== Parameters
+ # * <tt>action_name</tt> - An action name to find a method name for
+ #
+ # ==== Returns
+ # * <tt>string</tt> - The name of the method that handles the action
+ # * false - No valid method name could be found. Raise ActionNotFound.
+ def _find_action_name(action_name)
+ _valid_action_name?(action_name) && method_for_action(action_name)
+ end
+
+ # Takes an action name and returns the name of the method that will
# handle the action. In normal cases, this method returns the same
# name as it receives. By default, if #method_for_action receives
# a name that is not an action, it will look for an #action_missing
@@ -225,7 +242,7 @@ module AbstractController
#
# ==== Returns
# * <tt>string</tt> - The name of the method that handles the action
- # * <tt>nil</tt> - No method name could be found. Raise ActionNotFound.
+ # * <tt>nil</tt> - No method name could be found.
def method_for_action(action_name)
if action_method?(action_name)
action_name
@@ -233,5 +250,10 @@ module AbstractController
"_handle_action_missing"
end
end
+
+ # Checks if the action name is valid and returns false otherwise.
+ def _valid_action_name?(action_name)
+ action_name.to_s !~ Regexp.new(File::SEPARATOR)
+ end
end
end
diff --git a/actionpack/test/controller/new_base/render_implicit_action_test.rb b/actionpack/test/controller/new_base/render_implicit_action_test.rb
index <HASH>..<HASH> 100644
--- a/actionpack/test/controller/new_base/render_implicit_action_test.rb
+++ b/actionpack/test/controller/new_base/render_implicit_action_test.rb
@@ -6,7 +6,7 @@ module RenderImplicitAction
"render_implicit_action/simple/hello_world.html.erb" => "Hello world!",
"render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!",
"render_implicit_action/simple/not_implemented.html.erb" => "Not Implemented"
- )]
+ ), ActionView::FileSystemResolver.new(File.expand_path('../../../controller', __FILE__))]
def hello_world() end
end
@@ -33,10 +33,25 @@ module RenderImplicitAction
assert_status 200
end
+ test "render does not traverse the file system" do
+ assert_raises(AbstractController::ActionNotFound) do
+ action_name = %w(.. .. fixtures shared).join(File::SEPARATOR)
+ SimpleController.action(action_name).call(Rack::MockRequest.env_for("/"))
+ end
+ end
+
test "available_action? returns true for implicit actions" do
assert SimpleController.new.available_action?(:hello_world)
assert SimpleController.new.available_action?(:"hyphen-ated")
assert SimpleController.new.available_action?(:not_implemented)
end
+
+ test "available_action? does not allow File::SEPARATOR on the name" do
+ action_name = %w(evil .. .. path).join(File::SEPARATOR)
+ assert_equal false, SimpleController.new.available_action?(action_name.to_sym)
+
+ action_name = %w(evil path).join(File::SEPARATOR)
+ assert_equal false, SimpleController.new.available_action?(action_name.to_sym)
+ end
end
end
|
Only accept actions without File::SEPARATOR in the name.
This will avoid directory traversal in implicit render.
Fixes: CVE-<I>-<I>
Conflicts:
actionpack/lib/abstract_controller/base.rb
|
rails_rails
|
train
|
dc6e5603ed353c050358eb717102088d672cfdc9
|
diff --git a/wunderline-add.js b/wunderline-add.js
index <HASH>..<HASH> 100755
--- a/wunderline-add.js
+++ b/wunderline-add.js
@@ -139,6 +139,7 @@ function main() {
});
},
function(task, cb) {
+ app.note = app.note.replace(/\\n/g, "\n");
if (app.note) {
api.post(
{ url: "/notes", body: { task_id: task.id, content: app.note } },
|
Add multilined note with \n (#<I>)
Fix #<I>
|
wayneashleyberry_wunderline
|
train
|
eee81bb4da26ca553451cb7513e4a261a3f55560
|
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb
index <HASH>..<HASH> 100644
--- a/lib/barby/barcode/code_128.rb
+++ b/lib/barby/barcode/code_128.rb
@@ -238,7 +238,8 @@ module Barby
#there are no more extras, the barcode ends with that object.
#Most barcodes probably don't change charsets and don't have extras.
def extra
- @extra ||= nil
+ return @extra if defined?(@extra)
+ @extra = nil
end
#Set the extra for this barcode. The argument is a string starting with the
diff --git a/lib/barby/barcode/code_25.rb b/lib/barby/barcode/code_25.rb
index <HASH>..<HASH> 100644
--- a/lib/barby/barcode/code_25.rb
+++ b/lib/barby/barcode/code_25.rb
@@ -32,7 +32,7 @@ module Barby
attr_writer :narrow_width, :wide_width, :space_width
attr_reader :data
-
+
def initialize(data)
self.data = data
@narrow_width, @wide_width, @space_width = nil
|
Use defined? to avoid reassignment to nil
|
toretore_barby
|
train
|
95d5c24bfc154046c5fb4e4e41d170a42350e2d9
|
diff --git a/lib/liquid/standardfilters.rb b/lib/liquid/standardfilters.rb
index <HASH>..<HASH> 100644
--- a/lib/liquid/standardfilters.rb
+++ b/lib/liquid/standardfilters.rb
@@ -65,9 +65,10 @@ module Liquid
return if input.nil?
input_str = input.to_s
length = Utils.to_integer(length)
- l = length - truncate_string.length
+ truncate_string_str = truncate_string.to_s
+ l = length - truncate_string_str.length
l = 0 if l < 0
- input_str.length > length ? input_str[0...l] + truncate_string : input_str
+ input_str.length > length ? input_str[0...l] + truncate_string_str : input_str
end
def truncatewords(input, words = 15, truncate_string = "...".freeze)
diff --git a/test/integration/standard_filter_test.rb b/test/integration/standard_filter_test.rb
index <HASH>..<HASH> 100644
--- a/test/integration/standard_filter_test.rb
+++ b/test/integration/standard_filter_test.rb
@@ -115,6 +115,7 @@ class StandardFiltersTest < Minitest::Test
assert_equal '...', @filters.truncate('1234567890', 0)
assert_equal '1234567890', @filters.truncate('1234567890')
assert_equal "测试...", @filters.truncate("测试测试测试测试", 5)
+ assert_equal '12341', @filters.truncate("1234567890", 5, 1)
end
def test_split
|
Standard filter truncate: truncate_string string coercion
The argument `truncate_string` is now coerced into a string to avoid
`NoMethodError`s. This is mostly for added resiliency. It is doubtful
that someone would actually intent to use a number as truncate string,
but accidentally supplying one is entirely possible.
|
Shopify_liquid
|
train
|
71324c55b56ecd47eafa6f0dc1b7b531ca1ad465
|
diff --git a/platform/bb/RubyVM/src/com/rho/net/NetRequest.java b/platform/bb/RubyVM/src/com/rho/net/NetRequest.java
index <HASH>..<HASH> 100644
--- a/platform/bb/RubyVM/src/com/rho/net/NetRequest.java
+++ b/platform/bb/RubyVM/src/com/rho/net/NetRequest.java
@@ -157,6 +157,11 @@ public class NetRequest
try{
m_mxNet.Lock();
closeConnection();
+
+ LOG.INFO("GC start.");
+ System.gc();
+ LOG.INFO("GC stop.");
+
m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, m_bIgnoreSuffixOnSim);
LOG.INFO("connection done");
|
bb: one more possible fix for network error
|
rhomobile_rhodes
|
train
|
e7c28661d50f1d97f957a39a87069ca37246239a
|
diff --git a/wffweb/src/main/java/com/webfirmframework/wffweb/util/URIUtil.java b/wffweb/src/main/java/com/webfirmframework/wffweb/util/URIUtil.java
index <HASH>..<HASH> 100644
--- a/wffweb/src/main/java/com/webfirmframework/wffweb/util/URIUtil.java
+++ b/wffweb/src/main/java/com/webfirmframework/wffweb/util/URIUtil.java
@@ -86,7 +86,42 @@ public final class URIUtil {
* @since 12.0.0-beta.2
*/
public static boolean patternMatches(final String pattern, final String uri) {
- return parseValues(pattern, uri).size() > 0;
+ if (pattern.equals(uri)) {
+ return true;
+ }
+ final String[] patternParts = StringUtil.split(pattern, '/');
+ final String[] urlParts = StringUtil.split(uri, '/');
+
+ if (patternParts.length != urlParts.length) {
+ return false;
+ }
+
+ final Map<String, String> variableNameValue = new HashMap<>(Math.min(urlParts.length, 16));
+
+ for (int i = 0; i < patternParts.length; i++) {
+ final String patternPart = patternParts[i];
+ final String uriValue = urlParts[i];
+
+ if (patternPart.length() > 1 && patternPart.indexOf('{') == 0
+ && patternPart.indexOf('}') == patternPart.length() - 1) {
+
+ final String variableName = patternPart.substring(1, patternPart.length() - 1);
+
+ final String uriValueDecoded = URLDecoder.decode(uriValue, StandardCharsets.UTF_8);
+ final String previous = variableNameValue.put(variableName, uriValueDecoded);
+
+ if (previous != null) {
+ throw new InvalidValueException("duplicate variable name found in the uri pattern");
+ }
+
+ } else {
+ if (!patternPart.equals(uriValue)) {
+ return false;
+ }
+ }
+ }
+
+ return true;
}
/**
@@ -98,6 +133,10 @@ public final class URIUtil {
*/
public static boolean patternMatchesBase(final String pattern, final String uri) {
+ if (pattern.equals(uri)) {
+ return true;
+ }
+
final String[] patternParts = StringUtil.split(pattern, '/');
final String[] urlParts = StringUtil.split(uri, '/');
diff --git a/wffweb/src/test/java/com/webfirmframework/wffweb/util/URIUtilTest.java b/wffweb/src/test/java/com/webfirmframework/wffweb/util/URIUtilTest.java
index <HASH>..<HASH> 100644
--- a/wffweb/src/test/java/com/webfirmframework/wffweb/util/URIUtilTest.java
+++ b/wffweb/src/test/java/com/webfirmframework/wffweb/util/URIUtilTest.java
@@ -78,4 +78,18 @@ public class URIUtilTest {
assertFalse(URIUtil.patternMatchesBase("/some/uri/user/{userId}/item/{itemId}", "some/uri/user/123/item/456"));
}
+
+ @Test
+ public void testPatternMatches() {
+ assertTrue(URIUtil.patternMatches("/some/uri/user/{userId}", "/some/uri/user/123"));
+ assertTrue(URIUtil.patternMatches("/some/uri/user/{userId}/item/{itemId}", "/some/uri/user/123/item/456"));
+ assertTrue(URIUtil.patternMatches("some/uri/user/{userId}/item/{itemId}", "some/uri/user/123/item/456"));
+ assertTrue(URIUtil.patternMatches("/some/uri/user", "/some/uri/user"));
+
+ assertFalse(URIUtil.patternMatches("/some/uri/user/{userId}/item/{itemId}", "/some/uri/user/123"));
+ assertFalse(URIUtil.patternMatches("/some/uri/user/{userId}/item/{itemId}", "/some/uri/user/123/item2/456"));
+ assertFalse(URIUtil.patternMatches("some/uri/user/{userId}/item/{itemId}", "/some/uri/user/123/item/456"));
+ assertFalse(URIUtil.patternMatches("/some/uri/user/{userId}/item/{itemId}", "some/uri/user/123/item/456"));
+
+ }
}
|
Improvements in URIUtil methods and update test cases as well
|
webfirmframework_wff
|
train
|
e9e7b11855f1890fd0858bf44be731eea150e915
|
diff --git a/test/exe_test.rb b/test/exe_test.rb
index <HASH>..<HASH> 100644
--- a/test/exe_test.rb
+++ b/test/exe_test.rb
@@ -1,5 +1,5 @@
require "minitest_helper"
-require "english"
+require "English"
class ExeTest < Minitest::Test
def test_chandler_is_executable_and_exits_with_success
|
English must be capitalized on case-sensitive FS
|
mattbrictson_chandler
|
train
|
b451a22124a7bb9574d6bc1b12dfdda65c1df1fb
|
diff --git a/addon/components/mobiledoc-editor/component.js b/addon/components/mobiledoc-editor/component.js
index <HASH>..<HASH> 100644
--- a/addon/components/mobiledoc-editor/component.js
+++ b/addon/components/mobiledoc-editor/component.js
@@ -56,6 +56,7 @@ export default Component.extend({
placeholder: this.get('placeholder'),
spellcheck: this.get('spellcheck'),
autofocus: this.get('autofocus'),
+ cardOptions: this.get('cardOptions'),
cards: this.get('cards') || [],
atoms: this.get('atoms') || []
}, options);
@@ -159,7 +160,7 @@ export default Component.extend({
// Create a new editor.
let editorOptions = this.get('editorOptions');
editorOptions.mobiledoc = mobiledoc;
- editorOptions.cardOptions = {
+ let componentHooks = {
[ADD_CARD_HOOK]: ({env, options, payload}, isEditing=false) => {
let cardId = Ember.uuid();
let cardName = env.name;
@@ -178,6 +179,7 @@ export default Component.extend({
cardName,
payload,
env,
+ options,
editor,
postModel: env.postModel
});
@@ -202,6 +204,7 @@ export default Component.extend({
payload,
value,
callbacks: env,
+ options,
editor,
postModel: env.postModel
});
@@ -217,6 +220,7 @@ export default Component.extend({
this.get('componentAtoms').removeObject(atom);
}
};
+ editorOptions.cardOptions = assign(componentHooks, editorOptions.cardOptions);
editor = new Editor(editorOptions);
editor.willRender(() => {
// The editor's render/rerender will happen after this `editor.willRender`,
diff --git a/addon/components/mobiledoc-editor/template.hbs b/addon/components/mobiledoc-editor/template.hbs
index <HASH>..<HASH> 100644
--- a/addon/components/mobiledoc-editor/template.hbs
+++ b/addon/components/mobiledoc-editor/template.hbs
@@ -33,6 +33,7 @@
payload=card.payload
data=card.payload
env=card.env
+ options=card.options
editCard=(action card.env.edit)
saveCard=(action card.env.save)
cancelCard=(action card.env.cancel)
@@ -48,6 +49,7 @@
atomName=atom.atomName
payload=atom.payload
value=atom.value
+ options=atom.options
saveAtom=(action atom.callbacks.save)
}}
{{/ember-wormhole}}
diff --git a/tests/integration/components/mobiledoc-editor/component-test.js b/tests/integration/components/mobiledoc-editor/component-test.js
index <HASH>..<HASH> 100644
--- a/tests/integration/components/mobiledoc-editor/component-test.js
+++ b/tests/integration/components/mobiledoc-editor/component-test.js
@@ -16,9 +16,9 @@ import wait from 'ember-test-helpers/wait';
let { Component } = Ember;
-const COMPONENT_CARD_EXPECTED_PROPS = ['env', 'editCard', 'saveCard', 'cancelCard', 'removeCard', 'postModel'];
+const COMPONENT_CARD_EXPECTED_PROPS = ['env', 'editCard', 'saveCard', 'cancelCard', 'removeCard', 'postModel', 'options'];
-const COMPONENT_ATOM_EXPECTED_PROPS = ['saveAtom'];
+const COMPONENT_ATOM_EXPECTED_PROPS = ['saveAtom', 'options'];
moduleForComponent('mobiledoc-editor', 'Integration | Component | mobiledoc editor', {
integration: true,
@@ -579,6 +579,48 @@ test(`sets ${COMPONENT_CARD_EXPECTED_PROPS.join(',')} properties on card compone
`);
});
+test(`passes options through to card components`, function(assert) {
+
+ let cardOptions = {
+ foo: 'bar'
+ };
+ let Component = Ember.Component.extend({
+ didInsertElement() {
+ assert.equal(this.get('options.foo'), 'bar', `options property has been passed`);
+ }
+ });
+ let card = this.registerCardComponent('demo-card', hbs`<div id='demo-card'></div>`, Component);
+ this.set('cards', [card]);
+ this.set('mobiledoc', mobiledocWithCard('demo-card'));
+ this.set('cardOptions', cardOptions);
+
+ this.render(hbs`
+ {{#mobiledoc-editor mobiledoc=mobiledoc cards=cards cardOptions=cardOptions as |editor|}}
+ {{/mobiledoc-editor}}
+ `);
+});
+
+test(`passes options through to atom components`, function(assert) {
+
+ let cardOptions = {
+ foo: 'bar'
+ };
+ let Component = Ember.Component.extend({
+ didInsertElement() {
+ assert.equal(this.get('options.foo'), 'bar', `options property has been passed`);
+ }
+ });
+ let atom = this.registerAtomComponent('demo-atom', hbs`I AM AN ATOM`, Component);
+ this.set('atoms', [atom]);
+ this.set('mobiledoc', mobiledocWithAtom('demo-atom'));
+ this.set('cardOptions', cardOptions);
+
+ this.render(hbs`
+ {{#mobiledoc-editor mobiledoc=mobiledoc atoms=atoms cardOptions=cardOptions as |editor|}}
+ {{/mobiledoc-editor}}
+ `);
+});
+
test('component card `env` property exposes `isInEditor`', function(assert) {
assert.expect(1);
|
Pass card options to card/atom components
|
bustle_ember-mobiledoc-editor
|
train
|
4d5974929145223195ce54369b06bea8e3c9e95f
|
diff --git a/app/jobs/indexer.rb b/app/jobs/indexer.rb
index <HASH>..<HASH> 100644
--- a/app/jobs/indexer.rb
+++ b/app/jobs/indexer.rb
@@ -23,7 +23,7 @@ class Indexer
# do all processing _before_ we upload anything to S3, so we lower the chances of orphaned files
RubygemFs.instance.store(gem_path, gem_contents)
- RubygemFs.instance.store(spec_path,spec_contents)
+ RubygemFs.instance.store(spec_path, spec_contents)
Fastly.purge(path: gem_path)
Fastly.purge(path: spec_path)
diff --git a/test/integration/push_test.rb b/test/integration/push_test.rb
index <HASH>..<HASH> 100644
--- a/test/integration/push_test.rb
+++ b/test/integration/push_test.rb
@@ -94,7 +94,7 @@ class PushTest < ActionDispatch::IntegrationTest
test "push errors don't save files" do
build_gem "sandworm", "1.0.0" do |spec|
- spec.instance_variable_set :@authors, 'string'
+ spec.instance_variable_set :@authors, "string"
end
assert_nil Rubygem.find_by(name: "sandworm")
push_gem "sandworm-1.0.0.gem"
|
Fix lint failures that made it to master
|
rubygems_rubygems.org
|
train
|
05253055807aa9fd663f87611b88b0282284f8d6
|
diff --git a/hawtio-web/src/main/java/io/hawt/web/LoginServlet.java b/hawtio-web/src/main/java/io/hawt/web/LoginServlet.java
index <HASH>..<HASH> 100644
--- a/hawtio-web/src/main/java/io/hawt/web/LoginServlet.java
+++ b/hawtio-web/src/main/java/io/hawt/web/LoginServlet.java
@@ -68,7 +68,7 @@ public class LoginServlet extends HttpServlet {
for (Principal principal : principals) {
if (principal.getClass().getSimpleName().equals("UserPrincipal")) {
username = principal.getName();
- LOG.info("Authorizing user " + username);
+ LOG.debug("Authorizing user " + username);
}
}
}
|
use debug log level to turn down the noise
|
hawtio_hawtio
|
train
|
a4c5cfe11dbb7a478dc43cc892f09ffd3372171a
|
diff --git a/web/concrete/controllers/single_page/dashboard/system/registration/open.php b/web/concrete/controllers/single_page/dashboard/system/registration/open.php
index <HASH>..<HASH> 100644
--- a/web/concrete/controllers/single_page/dashboard/system/registration/open.php
+++ b/web/concrete/controllers/single_page/dashboard/system/registration/open.php
@@ -59,7 +59,7 @@ class Open extends DashboardPageController
}
Config::save('REGISTRATION_TYPE', $this->post('registration_type'));
- $this->redirect('/dashboard/system/registration/public', 1);
+ $this->redirect('/dashboard/system/registration/open', 1);
}
}
diff --git a/web/concrete/single_pages/dashboard/system/registration/open.php b/web/concrete/single_pages/dashboard/system/registration/open.php
index <HASH>..<HASH> 100644
--- a/web/concrete/single_pages/dashboard/system/registration/open.php
+++ b/web/concrete/single_pages/dashboard/system/registration/open.php
@@ -9,7 +9,7 @@
$h = Loader::helper('concrete/ui');
?>
<form class="form-stacked" method="post" id="registration-type-form"
- action="<?php echo $view->url('/dashboard/system/registration/public', 'update_registration_type') ?>">
+ action="<?php echo $view->action('update_registration_type') ?>">
<div class="row">
|
Update registration/open to point at itself
Former-commit-id: cc<I>c1af<I>b1c2f4bd2bdeed6f<I>cbb<I>bd1f2
|
concrete5_concrete5
|
train
|
832b31ebd98a4a085bca928b87ad8780c5cc083b
|
diff --git a/framework/core/src/Api/Controller/UpdateDiscussionController.php b/framework/core/src/Api/Controller/UpdateDiscussionController.php
index <HASH>..<HASH> 100644
--- a/framework/core/src/Api/Controller/UpdateDiscussionController.php
+++ b/framework/core/src/Api/Controller/UpdateDiscussionController.php
@@ -13,6 +13,7 @@ namespace Flarum\Api\Controller;
use Flarum\Core\Command\EditDiscussion;
use Flarum\Core\Command\ReadDiscussion;
use Illuminate\Contracts\Bus\Dispatcher;
+use Illuminate\Database\Eloquent\Collection;
use Psr\Http\Message\ServerRequestInterface;
use Tobscure\JsonApi\Document;
@@ -60,14 +61,13 @@ class UpdateDiscussionController extends AbstractResourceController
}
if ($posts = $discussion->getModifiedPosts()) {
+ $posts = (new Collection($posts))->load('discussion', 'user');
$discussionPosts = $discussion->postsVisibleTo($actor)->orderBy('time')->lists('id')->all();
foreach ($discussionPosts as &$id) {
foreach ($posts as $post) {
if ($id == $post->id) {
$id = $post;
- $post->discussion = $post->discussion_id;
- $post->user = $post->user_id;
}
}
}
|
Fix error when renaming discussion
Discussion/user info is needed when serialising posts (checking permissions, etc.) so we can't just use the ID.
|
flarum_core
|
train
|
532ccc69a643725850dde0d21994f52247718b39
|
diff --git a/docs/guide/js/docs.js b/docs/guide/js/docs.js
index <HASH>..<HASH> 100644
--- a/docs/guide/js/docs.js
+++ b/docs/guide/js/docs.js
@@ -13,14 +13,12 @@
$('.guide-example').each(function() {
var btn = '' +
- '<div>' +
'<hr class="divider-lg"/>' +
'<div class="btn-toolbar">' +
'<button class="btn btn-ghost btn-sm" data-toggle="code">' +
- 'View Code<i class="icon icon-code"></i>' +
+ 'View Code <i class="icon icon-code"></i>' +
'</button>' +
- '</div>' +
- '</div>';
+ '</div>';
$(this).append($(btn));
});
diff --git a/gulp/tasks/less.js b/gulp/tasks/less.js
index <HASH>..<HASH> 100644
--- a/gulp/tasks/less.js
+++ b/gulp/tasks/less.js
@@ -9,6 +9,7 @@ var browserSync = require('browser-sync');
var reload = browserSync.reload;
var using = require('gulp-using');
var gulpif = require('gulp-if');
+var bless = require('gulp-bless');
var replace = require('gulp-replace');
var config = require('../config');
@@ -26,12 +27,15 @@ gulp.task('less:dev', function() {
}))
.pipe(less())
.pipe(replace(config.regex.select[0], config.regex.select[1]))
- .pipe(sourcemaps.init({loadMaps: true}))
+ // .pipe(sourcemaps.init({loadMaps: true}))
.pipe(prefixer({
browsers: config.less.browsers
}))
.pipe(insert.prepend(banner() + '\n'))
- .pipe(sourcemaps.write(config.less.destMaps))
+ // .pipe(sourcemaps.write(config.less.destMaps))
+ .pipe(bless({
+ imports: true
+ }))
.pipe(gulp.dest(config.less.dest))
.pipe(filter('**/*.css')) // Filtering stream to only css files
.pipe(gulpif(config.args.verbose, using({prefix:'Task [less:dev] using'})))
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"glob": "^5.0.13",
"gulp": "^3.9.0",
"gulp-autoprefixer": "^2.3.1",
+ "gulp-bless": "^3.0.1",
"gulp-bump": "^0.3.1",
"gulp-concat": "^2.6.0",
"gulp-filter": "^3.0.0",
|
add bless plugin to fix IE selector count issue
|
Availity_availity-uikit
|
train
|
18122ba6278c4b7285e8ebf50547ed27eaaaabd2
|
diff --git a/integration-tests@latest/karma.conf.js b/integration-tests@latest/karma.conf.js
index <HASH>..<HASH> 100644
--- a/integration-tests@latest/karma.conf.js
+++ b/integration-tests@latest/karma.conf.js
@@ -21,14 +21,17 @@ module.exports = function(config) {
karmaTypescriptConfig: {
tsconfig: "./tsconfig.json",
- excludedFiles: /\.(d|spec|test)\.ts/,
compilerOptions: {
sourceMap: true
},
+ excludedFiles: /\.(d|spec|test)\.ts/,
reports:
{
"html": "coverage",
"text-summary": ""
+ },
+ transformPath: function(filepath) {
+ return filepath.replace(/\.(ts|tsx)$/, ".js");
}
},
diff --git a/lib/preprocessor.js b/lib/preprocessor.js
index <HASH>..<HASH> 100644
--- a/lib/preprocessor.js
+++ b/lib/preprocessor.js
@@ -5,12 +5,10 @@ function Preprocessor(compiler, nodeModulesLoader, sharedProcessedFiles) {
log,
config,
- excludedFiles = /\.(spec|test)\.ts/;
-
- function transformPath(filepath) {
-
- return filepath.replace(/\.(ts|tsx)$/, ".js");
- }
+ excludedFiles = /\.(spec|test)\.ts/,
+ transformPath = function(filepath) {
+ return filepath.replace(/\.(ts|tsx)$/, ".js");
+ };
function hasPreprocessor(name) {
@@ -128,6 +126,7 @@ function Preprocessor(compiler, nodeModulesLoader, sharedProcessedFiles) {
);
excludedFiles = (config.karmaTypescriptConfig && config.karmaTypescriptConfig.excludedFiles) || excludedFiles;
+ transformPath = (config.karmaTypescriptConfig && config.karmaTypescriptConfig.transformPath) || transformPath;
return function(originalSource, file, done) {
|
Exposed transformPath in karma config
|
monounity_karma-typescript
|
train
|
ec2008012c787ea641054f53038b5c81f6e0e770
|
diff --git a/src/Picqer/Financials/Exact/Account.php b/src/Picqer/Financials/Exact/Account.php
index <HASH>..<HASH> 100644
--- a/src/Picqer/Financials/Exact/Account.php
+++ b/src/Picqer/Financials/Exact/Account.php
@@ -6,27 +6,124 @@ class Account extends Model {
use Persistance\Storable;
protected $fillable = [
+ 'ID',
+ 'Accountant',
+ 'AccountManager',
+ 'AccountManagerFullName',
+ 'AccountManagerHID',
+ 'ActivitySector',
+ 'ActivitySubSector',
'AddressLine1',
'AddressLine2',
+ 'AddressLine3',
+ 'BankAccounts',
+ 'Blocked',
+ 'BusinessType',
+ 'CanDropShip',
'ChamberOfCommerce',
'City',
+ 'Classification1',
+ 'Classification2',
+ 'Classification3',
+ 'Classification4',
+ 'Classification5',
+ 'Classification6',
+ 'Classification7',
+ 'Classification8',
'Code',
+ 'CodeAtSupplier',
+ 'CompanySize',
+ 'ConsolidationScenario',
+ 'ControlledDate',
'Country',
+ 'CountryName',
+ 'Created',
+ 'Creator',
+ 'CreatorFullName',
+ 'CreditLinePurchase',
+ 'CreditLineSales',
+ 'DiscountPurchase',
+ 'DiscountSales',
'Division',
'Email',
- 'ID',
+ 'EndDate',
+ 'Fax',
+ 'GLAccountPurchase',
+ 'GLAccountSales',
+ 'GLAP',
+ 'GLAR',
+ 'IntraStatArea',
+ 'IntraStatDeliveryTerm',
+ 'IntraStatSystem',
+ 'IntraStatTransactionA',
+ 'IntraStatTransactionB',
+ 'IntraStatTransportMethod',
+ 'InvoiceAccount',
+ 'InvoiceAccountCode',
+ 'InvoiceAccountName',
+ 'InvoiceAttachmentType',
+ 'InvoicingMethod',
+ 'IsAccountant',
+ 'IsAgency',
+ 'IsCompetitor',
+ 'IsMailing',
+ 'IsPilot',
+ 'IsReseller',
+ 'IsSales',
+ 'IsSupplier',
'Language',
+ 'LanguageDescription',
+ 'Latitude',
+ 'LeadSource',
+ 'Logo',
+ 'LogoFileName',
+ 'LogoThumbnailUrl',
+ 'LogoUrl',
+ 'Longitude',
+ 'MainContact',
+ 'Modified',
+ 'Modifier',
+ 'ModifierFullName',
'Name',
+ 'PaymentConditionPurchase',
+ 'PaymentConditionPurchaseDescription',
+ 'PaymentConditionSales',
+ 'PaymentConditionSalesDescription',
'Phone',
+ 'PhoneExtension',
'Postcode',
- 'Website',
- 'Status',
- 'SearchCode',
- 'MainContact',
- 'Remarks',
+ 'PriceList',
+ 'PurchaseCurrency',
+ 'PurchaseCurrencyDescription',
+ 'PurchaseLeadDays',
'PurchaseVATCode',
+ 'PurchaseVATCodeDescription',
+ 'RecepientOfCommissions',
+ 'Remarks',
+ 'Reseller',
+ 'ResellerCode',
+ 'ResellerName',
+ 'SalesCurrency',
+ 'SalesCurrencyDescription',
+ 'SalesTaxSchedule',
+ 'SalesTaxScheduleCode',
+ 'SalesTaxScheduleDescription',
+ 'SalesVATCode',
+ 'SalesVATCodeDescription',
+ 'SearchCode',
+ 'SecurityLevel',
+ 'SeparateInvPerProject',
+ 'SeparateInvPerSubscription',
+ 'ShippingLeadDays',
+ 'ShippingMethod',
+ 'StartDate',
+ 'State',
+ 'StateName',
+ 'Status',
+ 'Type',
+ 'VATLiability',
'VATNumber',
- 'IsSales'
+ 'Website'
];
protected $url = 'crm/Accounts';
|
Update Account.php
Added all the properties except obsolete ones
|
picqer_exact-php-client
|
train
|
a87fa040374ef828713f66a22ddfef6a9175b9a8
|
diff --git a/prestans/exception.py b/prestans/exception.py
index <HASH>..<HASH> 100644
--- a/prestans/exception.py
+++ b/prestans/exception.py
@@ -162,7 +162,7 @@ class ValidationError(Base):
super(ValidationError, self).__init__(prestans.http.STATUS.BAD_REQUEST, message)
self._attribute_name = attribute_name
- self._value = value
+ self._value = str(value)
self.append_validation_trace(blueprint)
|
converted validation error value to string so it can be properly serialized for complex types like date, datetime and time
|
anomaly_prestans
|
train
|
76d3c527ae664e62d2de596a7944ed353dd69385
|
diff --git a/server/storage/mvcc/hash.go b/server/storage/mvcc/hash.go
index <HASH>..<HASH> 100644
--- a/server/storage/mvcc/hash.go
+++ b/server/storage/mvcc/hash.go
@@ -33,7 +33,7 @@ func unsafeHashByRev(tx backend.ReadTx, lower, upper int64, keep map[revision]st
type kvHasher struct {
hash hash.Hash32
- lower, upper revision
+ lower, upper int64
keep map[revision]struct{}
}
@@ -42,20 +42,22 @@ func newKVHasher(lower, upper int64, keep map[revision]struct{}) kvHasher {
h.Write(schema.Key.Name())
return kvHasher{
hash: h,
- lower: revision{main: lower + 1},
- upper: revision{main: upper + 1},
+ lower: lower,
+ upper: upper,
keep: keep,
}
}
func (h *kvHasher) WriteKeyValue(k, v []byte) {
kr := bytesToRev(k)
- if !h.upper.GreaterThan(kr) {
+ upper := revision{main: h.upper + 1}
+ if !upper.GreaterThan(kr) {
return
}
+ lower := revision{main: h.lower + 1}
// skip revisions that are scheduled for deletion
// due to compacting; don't skip if there isn't one.
- if h.lower.GreaterThan(kr) && len(h.keep) > 0 {
+ if lower.GreaterThan(kr) && len(h.keep) > 0 {
if _, ok := h.keep[kr]; !ok {
return
}
|
server: Store real rv range in hasher
|
etcd-io_etcd
|
train
|
83e4e08ba99ff45ed7c3bdd179a423a761bbe1af
|
diff --git a/salt/engines/libvirt_events.py b/salt/engines/libvirt_events.py
index <HASH>..<HASH> 100644
--- a/salt/engines/libvirt_events.py
+++ b/salt/engines/libvirt_events.py
@@ -63,17 +63,11 @@ A polkit rule like the following one will allow `salt` user to connect to libvir
.. versionadded:: 2019.2.0
"""
-
import logging
+import urllib.parse
-# Import salt libs
import salt.utils.event
-# pylint: disable=no-name-in-module,import-error
-from salt.ext.six.moves.urllib.parse import urlparse
-
-# pylint: enable=no-name-in-module,import-error
-
log = logging.getLogger(__name__)
@@ -217,7 +211,7 @@ def _salt_send_event(opaque, conn, data):
# Prepare the connection URI to fit in the tag
# qemu+ssh://user@host:1234/system -> qemu+ssh/user@host:1234/system
- uri = urlparse(conn.getURI())
+ uri = urllib.parse.urlparse(conn.getURI())
uri_tag = [uri.scheme]
if uri.netloc:
uri_tag.append(uri.netloc)
|
Drop Py2 and six on salt/engines/libvirt_events.py
|
saltstack_salt
|
train
|
ec115ec1c88da568178cf8613f8ee77a85b0583c
|
diff --git a/src/Str.php b/src/Str.php
index <HASH>..<HASH> 100644
--- a/src/Str.php
+++ b/src/Str.php
@@ -683,6 +683,8 @@ final class Str implements \Countable {
/**
* Returns whether this string matches the other string
*
+ * This operation is case-sensitive
+ *
* @param string $other the other string to compare with
* @return bool whether the two strings are equal
*/
|
Clarify existing behavior of 'equals' regarding case
|
delight-im_PHP-Str
|
train
|
7cee2509c07e5514dc7647fcf8a4f066feaaa6df
|
diff --git a/eth/downloader/statesync.go b/eth/downloader/statesync.go
index <HASH>..<HASH> 100644
--- a/eth/downloader/statesync.go
+++ b/eth/downloader/statesync.go
@@ -197,12 +197,7 @@ func (d *Downloader) runStateSync(s *stateSync) *stateSync {
}
// Start a timer to notify the sync loop if the peer stalled.
req.timer = time.AfterFunc(req.timeout, func() {
- select {
- case timeout <- req:
- case <-s.done:
- // Prevent leaking of timer goroutines in the unlikely case where a
- // timer is fired just before exiting runStateSync.
- }
+ timeout <- req
})
active[req.peer.id] = req
}
@@ -214,7 +209,6 @@ func (d *Downloader) runStateSync(s *stateSync) *stateSync {
// are marked as idle and de facto _are_ idle.
func (d *Downloader) spindownStateSync(active map[string]*stateReq, finished []*stateReq, timeout chan *stateReq, peerDrop chan *peerConnection) {
log.Trace("State sync spinning down", "active", len(active), "finished", len(finished))
-
for len(active) > 0 {
var (
req *stateReq
|
eth/downloader: allow all timers to exit
|
ethereum_go-ethereum
|
train
|
d4d29e7ffb23b35e482f26216dfe7ffe06f1ac95
|
diff --git a/test_acid.py b/test_acid.py
index <HASH>..<HASH> 100755
--- a/test_acid.py
+++ b/test_acid.py
@@ -52,12 +52,15 @@ def diff(before, after):
after))
-def run(filename, verbose=False):
+def run(filename, verbose=False, options=None):
"""Run autoflake on file at filename.
Return True on success.
"""
+ if not options:
+ options = []
+
import test_autoflake
with test_autoflake.temporary_directory() as temp_directory:
temp_filename = os.path.join(temp_directory,
@@ -65,7 +68,8 @@ def run(filename, verbose=False):
import shutil
shutil.copyfile(filename, temp_filename)
- if 0 != subprocess.call([AUTOFLAKE_BIN, '--in-place', temp_filename]):
+ if 0 != subprocess.call([AUTOFLAKE_BIN, '--in-place', temp_filename] +
+ options):
sys.stderr.write('autoflake crashed on ' + filename + '\n')
return False
@@ -125,6 +129,9 @@ def process_args():
default=-1,
type=float)
+ parser.add_argument('--imports',
+ help='pass to the autoflake "--imports" option')
+
parser.add_argument('-v', '--verbose', action='store_true',
help='print verbose messages')
@@ -154,6 +161,10 @@ def check(args):
dir_paths = [path for path in sys.path
if os.path.isdir(path)]
+ options = []
+ if args.imports:
+ options.append('--import=' + args.imports)
+
filenames = dir_paths
completed_filenames = set()
@@ -198,7 +209,8 @@ def check(args):
verbose_message += '...'
sys.stderr.write(colored(verbose_message + '\n', YELLOW))
- if not run(os.path.join(name), verbose=args.verbose):
+ if not run(os.path.join(name), verbose=args.verbose,
+ options=options):
return False
except TimeoutException:
sys.stderr.write('Timed out\n')
|
Pass through "--imports"
|
myint_autoflake
|
train
|
c1a108443ece84f7b571e0e639085c2fa4681107
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -9,11 +9,12 @@ var nes = require('never-ending-stream')
, through = require('through2')
, assert = require('assert')
, chunks = [new Buffer('hello'), new Buffer('world')]
- , stream = nes(function() {
+ , stream = nes(function(cb) {
var source = [].concat(chunks)
var orig = from.obj(function(size, next) {
next(null, source.shift())
})
+ // or cb(null, orig)
return orig
})
, expected = [].concat(chunks).concat(chunks)
diff --git a/never-ending-stream.js b/never-ending-stream.js
index <HASH>..<HASH> 100644
--- a/never-ending-stream.js
+++ b/never-ending-stream.js
@@ -1,10 +1,11 @@
var through = require('through2')
var eos = require('end-of-stream')
-function neverEndingStream (build, opts) {
+function neverEndingStream (build) {
var result = through.obj({ highWatermark: 1 })
var stream = null
var stopped = false
+ var piped
var oldDestroy = result.destroy
@@ -23,9 +24,18 @@ function neverEndingStream (build, opts) {
return
}
- stream = build(opts)
- stream.pipe(result, { end: false })
- eos(stream, restart)
+ piped = false
+ next(null, build(next))
+ }
+
+ function next(err, s) {
+ if (err) return result.emit('error', err)
+ if (piped || !s) return
+
+ piped = true
+ s.pipe(result, { end: false })
+ eos(s, restart)
+ stream = s
}
}
diff --git a/test.js b/test.js
index <HASH>..<HASH> 100644
--- a/test.js
+++ b/test.js
@@ -47,6 +47,28 @@ function restartTest (name, chunks) {
cb()
}))
})
+
+ test('restarts asynchronously the stream ' + name, function(t) {
+ var stream = nes(function(cb) {
+ var source = [].concat(chunks)
+ var orig = from.obj(function(size, next) {
+ next(null, source.shift())
+ })
+
+ cb(null, orig)
+ })
+ var expected = [].concat(chunks).concat(chunks)
+
+ t.plan(expected.length)
+
+ stream.pipe(through.obj(function(chunk, enc, cb) {
+ if (expected.length === 0)
+ return stream.destroy()
+
+ t.equal(expected.shift(), chunk, 'chunk should be the same')
+ cb()
+ }))
+ })
}
restartTest('with buffers', [new Buffer('hello'), new Buffer('world')])
|
Added async callback.
|
mcollina_never-ending-stream
|
train
|
ff4f4ffd7d43026dc388daf7216e0614a88a304b
|
diff --git a/socket.client.js b/socket.client.js
index <HASH>..<HASH> 100644
--- a/socket.client.js
+++ b/socket.client.js
@@ -34,7 +34,7 @@ define(function()
onConnected && onConnected();
var observer;
while(observer = initQueue.shift())
- observer.call(self);
+ observer(self);
};
socket.onclose = function(event)
@@ -61,7 +61,7 @@ define(function()
this.connected = function(observer)
{
connected
- ? observer.call(self)
+ ? observer(self)
: initQueue.push(observer);
};
|
passing the socket as an argument to the promise instead of by "this"
|
superhero_js.websocket
|
train
|
e04af6d685662502553e010f1d8ad4bff51cc1dc
|
diff --git a/lib/instance/cook/audit_logger.rb b/lib/instance/cook/audit_logger.rb
index <HASH>..<HASH> 100644
--- a/lib/instance/cook/audit_logger.rb
+++ b/lib/instance/cook/audit_logger.rb
@@ -162,7 +162,7 @@ module RightScale
end # AuditLogger
end # RightScale
-# TEAL/IVORY HACK we have to monkey-patch Chef's Formatter & Outputter classes because
+# TEAL HACK we have to monkey-patch Chef's Formatter & Outputter classes because
# they exist as a channel containing important debugging information which is
# separate from the original (easily understandable) Chef::Log. the Outputter
# lacks log level but the Formatter knows when it is displaying an error. the
@@ -173,8 +173,8 @@ class Chef
class Base
def display_error(description)
section = description.sections && description.sections.first
- if section && ( section.keys.any? { |key| ['SystemExit','RightScale::Exceptions::Exec'].include?(key) } )
- # ignored due to rs_shutdown provider behavior or RightScripts exit
+ if section && section.keys.include?('SystemExit')
+ # ignored due to rs_shutdown provider behavior
else
last_output_log_level = output.output_log_level
begin
|
acu<I> - revert changes due to incompatibility with PowerShell script provider. RightScirpt and PowerShell providers use the same Exec Error Exceptions
|
rightscale_right_link
|
train
|
d5232f43d7c2c550de50c5ad4c37aeafe6abcc08
|
diff --git a/lib/winrm/winrm_service.rb b/lib/winrm/winrm_service.rb
index <HASH>..<HASH> 100644
--- a/lib/winrm/winrm_service.rb
+++ b/lib/winrm/winrm_service.rb
@@ -98,9 +98,6 @@ module WinRM
"#{NS_WIN_SHELL}:OutputStreams" => o_stream
}
shell_body["#{NS_WIN_SHELL}:WorkingDirectory"] = shell_opts[:working_directory] if shell_opts.has_key?(:working_directory)
- # TODO: research Lifetime a bit more: http://msdn.microsoft.com/en-us/library/cc251546(v=PROT.13).aspx
- #s.body["#{NS_WIN_SHELL}:Lifetime"] = Iso8601Duration.sec_to_dur(shell_opts[:lifetime]) if(shell_opts.has_key?(:lifetime) && shell_opts[:lifetime].is_a?(Fixnum))
- # @todo make it so the input is given in milliseconds and converted to xs:duration
shell_body["#{NS_WIN_SHELL}:IdleTimeOut"] = shell_opts[:idle_timeout] if(shell_opts.has_key?(:idle_timeout) && shell_opts[:idle_timeout].is_a?(String))
if(shell_opts.has_key?(:env_vars) && shell_opts[:env_vars].is_a?(Hash))
keys = shell_opts[:env_vars].keys
@@ -356,7 +353,6 @@ module WinRM
"#{NS_ADDRESSING}:MessageID" => "uuid:#{UUIDTools::UUID.random_create.to_s.upcase}",
"#{NS_WSMAN_DMTF}:Locale/" => '',
"#{NS_WSMAN_MSFT}:DataLocale/" => '',
- #"#{NS_WSMAN_CONF}:MaxTimeoutms" => 600, #TODO: research this a bit http://msdn.microsoft.com/en-us/library/cc251561(v=PROT.13).aspx
"#{NS_WSMAN_DMTF}:OperationTimeout" => @timeout,
:attributes! => {
"#{NS_WSMAN_DMTF}:MaxEnvelopeSize" => {'mustUnderstand' => true},
|
Removed TODOs which we're not doing
|
WinRb_WinRM
|
train
|
581b8bdecd65613ef3ea44abf81cca5e48571905
|
diff --git a/salt/modules/hosts.py b/salt/modules/hosts.py
index <HASH>..<HASH> 100644
--- a/salt/modules/hosts.py
+++ b/salt/modules/hosts.py
@@ -98,6 +98,34 @@ def set_host(ip, alias):
open(hfn, 'w+').writelines(lines)
return True
+def rm_host(ip, alias):
+ '''
+ Remove a host entry from the hosts file
+
+ CLI Example:
+ salt '*' hosts.rm_host <ip> <alias>
+ '''
+ if not has_pair(ip, alias):
+ return True
+ hfn = '/etc/hosts'
+ lines = open(hfn).readlines()
+ for ind in range(len(lines)):
+ tmpline = lines[ind].strip()
+ if not tmpline:
+ continue
+ if tmpline.startswith('#'):
+ continue
+ comps = tmpline.split()
+ if comps[0] == ip:
+ newline = comps[0] + '\t'
+ for existing in comps[1:]:
+ if existing == alias:
+ continue
+ newline += '\t' + existing
+ lines[ind] = newline
+ open(hfn, 'w+').writelines(lines)
+ return True
+
def add_host(ip, alias):
'''
Add a host to an existing entry, if the entry is not in place then create
|
Add rm_host to the hosts module
|
saltstack_salt
|
train
|
2a2b886e04b146dea9ac17e5d54eeb26ea00b771
|
diff --git a/test/servers/web.js b/test/servers/web.js
index <HASH>..<HASH> 100644
--- a/test/servers/web.js
+++ b/test/servers/web.js
@@ -273,7 +273,7 @@ describe('Server: Web', function(){
it('should respond to TRACE with parsed params received', function(done){
request({method: 'trace', url: url + '/api/x', form: {key: 'someKey', value: 'someValue'}}, function(err, response, body){
- body = JSON.parse(body);
+ body = JSON.parse(body);
response.statusCode.should.eql(200);
body.receivedParams.key.should.equal('someKey');
body.receivedParams.value.should.equal('someValue');
@@ -331,7 +331,7 @@ describe('Server: Web', function(){
before(function(done){
api.config.servers.web.returnErrorCodes = true;
-
+
api.actions.versions.statusTestAction = [1]
api.actions.actions.statusTestAction = {
'1': {
@@ -450,7 +450,7 @@ describe('Server: Web', function(){
done();
});
});
-
+
});
describe('files', function(){
@@ -500,16 +500,16 @@ describe('Server: Web', function(){
before(function(done){
fs.createReadStream(source).pipe(fs.createWriteStream('/tmp/testFile.html'));
api.config.general.paths.public.push('/tmp');
- process.nextTick(function(){
- done();
+ process.nextTick(function(){
+ done();
});
});
after(function(done){
fs.unlink('/tmp/testFile.html');
api.config.general.paths.public.pop();
- process.nextTick(function(){
- done();
+ process.nextTick(function(){
+ done();
});
});
@@ -573,7 +573,7 @@ describe('Server: Web', function(){
});
describe('routes', function(){
-
+
before(function(done){
api.actions.versions.mimeTestAction = [1]
api.actions.actions.mimeTestAction = {
@@ -622,7 +622,7 @@ describe('Server: Web', function(){
{ path: '/thing/stuff', action: 'thingStuff' }
],
post: [
- { path: '/login/:userID(^\\d{3}$)', action: 'login' }
+ { path: '/login/:userID(^(\\d{3}|admin)$)', action: 'login' }
]
});
@@ -650,7 +650,7 @@ describe('Server: Web', function(){
});
done();
})
-
+
it('unknown actions are still unknown', function(done){
request.get(url + '/api/a_crazy_action', function(err, response, body){
body = JSON.parse(body);
@@ -735,7 +735,7 @@ describe('Server: Web', function(){
request.get(url + '/api/thing', function(err, response, body){
body = JSON.parse(body);
body.requesterInformation.receivedParams.action.should.equal('thing')
-
+
request.get(url + '/api/thing/stuff', function(err, response, body){
body = JSON.parse(body);
body.requesterInformation.receivedParams.action.should.equal('thingStuff')
@@ -749,7 +749,13 @@ describe('Server: Web', function(){
body = JSON.parse(body);
body.requesterInformation.receivedParams.action.should.equal('login');
body.requesterInformation.receivedParams.userID.should.equal('123');
- done();
+
+ request.post(url + '/api/login/admin', function(err, response, body){
+ body = JSON.parse(body);
+ body.requesterInformation.receivedParams.action.should.equal('login');
+ body.requesterInformation.receivedParams.userID.should.equal('admin');
+ done();
+ });
});
});
|
add routes test of more complex regular expressions
|
actionhero_actionhero
|
train
|
62856feea917f8c32b82391ac43cc0db9d480a32
|
diff --git a/src/org/opencms/xml/types/CmsXmlVfsFileValue.java b/src/org/opencms/xml/types/CmsXmlVfsFileValue.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/xml/types/CmsXmlVfsFileValue.java
+++ b/src/org/opencms/xml/types/CmsXmlVfsFileValue.java
@@ -1,7 +1,7 @@
/*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/xml/types/CmsXmlVfsFileValue.java,v $
- * Date : $Date: 2010/01/18 15:17:17 $
- * Version: $Revision: 1.4 $
+ * Date : $Date: 2010/02/10 14:28:22 $
+ * Version: $Revision: 1.5 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
@@ -43,6 +43,7 @@ import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.page.CmsXmlPage;
+import org.opencms.xml.sitemap.CmsXmlSitemap;
import java.util.Locale;
@@ -56,7 +57,7 @@ import org.dom4j.Element;
*
* @author Michael Moossen
*
- * @version $Revision: 1.4 $
+ * @version $Revision: 1.5 $
*
* @since 7.0.0
*/
@@ -177,7 +178,11 @@ public class CmsXmlVfsFileValue extends A_CmsXmlContentValue {
CmsLinkUpdateUtil.updateType(linkElement, getContentDefinition().getContentHandler().getRelationType(getPath()));
CmsLink link = new CmsLink(linkElement);
// link management check
- link.checkConsistency(cms);
+ if (m_document instanceof CmsXmlSitemap) {
+ link.checkConsistency(cms, false);
+ } else {
+ link.checkConsistency(cms);
+ }
if (CmsStringUtil.isEmptyOrWhitespaceOnly(link.getTarget())) {
return null;
}
|
prevent sitemap link management in sitemaps
|
alkacon_opencms-core
|
train
|
c6761135116ab791eef951bb78108a7093c2e1b2
|
diff --git a/spec/support/backend.rb b/spec/support/backend.rb
index <HASH>..<HASH> 100644
--- a/spec/support/backend.rb
+++ b/spec/support/backend.rb
@@ -249,11 +249,39 @@ shared_examples "a Que backend" do
end
it "should lock the job it selects" do
- pending
+ $q1, $q2 = Queue.new, Queue.new
+
+ class AdvisoryLockJob < Que::Job
+ def run(*args)
+ $q1.push nil
+ $q2.pop
+ end
+ end
+
+ AdvisoryLockJob.queue
+ id = DB[:que_jobs].get(:job_id)
+ thread = Thread.new { Que::Job.work }
+
+ $q1.pop
+ DB[:pg_locks].where(:locktype => 'advisory', :objid => id).count.should be 1
+ $q2.push nil
+
+ thread.join
end
it "should not work jobs that are advisory-locked" do
- pending
+ class AdvisoryLockBlockJob < Que::Job
+ end
+
+ AdvisoryLockBlockJob.queue
+ id = DB[:que_jobs].get(:job_id)
+
+ begin
+ DB.select{pg_advisory_lock(id)}.single_value
+ Que::Job.work.should be nil
+ ensure
+ DB.select{pg_advisory_unlock(id)}.single_value
+ end
end
it "should handle subclasses of other jobs" do
|
Spec the use of advisory locks when locking jobs.
|
chanks_que
|
train
|
d70757d64a1b1e82a719780a00f4013a8cff0c53
|
diff --git a/blend/blend.go b/blend/blend.go
index <HASH>..<HASH> 100644
--- a/blend/blend.go
+++ b/blend/blend.go
@@ -347,8 +347,8 @@ func Blend(bg image.Image, fg image.Image, fn func(fcolor.RGBAF64, fcolor.RGBAF6
h = fgBounds.Dy()
}
- bgSrc := clone.AsRGBA(bg)
- fgSrc := clone.AsRGBA(fg)
+ bgSrc := clone.AsShallowRGBA(bg)
+ fgSrc := clone.AsShallowRGBA(fg)
dst := image.NewRGBA(image.Rect(0, 0, w, h))
parallel.Line(h, func(start, end int) {
diff --git a/clone/clone.go b/clone/clone.go
index <HASH>..<HASH> 100644
--- a/clone/clone.go
+++ b/clone/clone.go
@@ -28,6 +28,14 @@ func AsRGBA(src image.Image) *image.RGBA {
return img
}
+// AsShallowRGBA tries to cast to image.RGBA to get reference. Otherwise makes a copy
+func AsShallowRGBA(src image.Image) *image.RGBA {
+ if rgba, ok := src.(*image.RGBA); ok {
+ return rgba
+ }
+ return AsRGBA(src)
+}
+
// Pad returns an RGBA copy of the src image parameter with its edges padded
// using the supplied PadMethod.
// Parameter padX and padY correspond to the amount of padding to be applied
diff --git a/transform/resize.go b/transform/resize.go
index <HASH>..<HASH> 100644
--- a/transform/resize.go
+++ b/transform/resize.go
@@ -22,7 +22,7 @@ func Resize(img image.Image, width, height int, filter ResampleFilter) *image.RG
return image.NewRGBA(image.Rect(0, 0, 0, 0))
}
- src := clone.AsRGBA(img)
+ src := clone.AsShallowRGBA(img)
var dst *image.RGBA
// NearestNeighbor is a special case, it's faster to compute without convolution matrix.
@@ -45,7 +45,7 @@ func Resize(img image.Image, width, height int, filter ResampleFilter) *image.RG
// result := transform.Crop(img, image.Rect(0, 0, 512, 256))
//
func Crop(img image.Image, rect image.Rectangle) *image.RGBA {
- src := clone.AsRGBA(img)
+ src := clone.AsShallowRGBA(img)
return clone.AsRGBA(src.SubImage(rect))
}
|
Introduce new method for shallow copying image
|
anthonynsimon_bild
|
train
|
a74c511e7fa717c90b263fc9a83186dd6c178ae8
|
diff --git a/privacy/classes/local/sitepolicy/default_handler.php b/privacy/classes/local/sitepolicy/default_handler.php
index <HASH>..<HASH> 100644
--- a/privacy/classes/local/sitepolicy/default_handler.php
+++ b/privacy/classes/local/sitepolicy/default_handler.php
@@ -45,6 +45,11 @@ class default_handler extends handler {
*/
public static function is_defined($forguests = false) {
global $CFG;
+ if (!empty($CFG->sitepolicyhandler)) {
+ // This handler can also be used as a fallback in case of invalid $CFG->sitepolicyhandler,
+ // in this case assume that no site policy is set.
+ return false;
+ }
if (!$forguests) {
return !empty($CFG->sitepolicy);
} else {
@@ -76,6 +81,11 @@ class default_handler extends handler {
*/
public static function get_embed_url($forguests = false) {
global $CFG;
+ if (!empty($CFG->sitepolicyhandler)) {
+ // This handler can also be used as a fallback in case of invalid $CFG->sitepolicyhandler,
+ // in this case assume that no site policy is set.
+ return null;
+ }
if ($forguests && !empty($CFG->sitepolicyguest)) {
return new moodle_url($CFG->sitepolicyguest);
} else if (!$forguests && !empty($CFG->sitepolicy)) {
diff --git a/privacy/tests/sitepolicy_test.php b/privacy/tests/sitepolicy_test.php
index <HASH>..<HASH> 100644
--- a/privacy/tests/sitepolicy_test.php
+++ b/privacy/tests/sitepolicy_test.php
@@ -83,6 +83,13 @@ class sitepolicy_test extends advanced_testcase {
$CFG->sitepolicy = null;
$this->assertTrue($manager->is_defined(true));
$this->assertFalse($manager->is_defined(false));
+
+ // When non existing plugin is set as $CFG->sitepolicyhandler, assume that $CFG->sitepolicy* are all not set.
+ $CFG->sitepolicy = 'http://example.com/sitepolicy.html';
+ $CFG->sitepolicyguest = 'http://example.com/sitepolicyguest.html';
+ $CFG->sitepolicyhandler = 'non_existing_plugin_which_i_really_hope_will_never_exist';
+ $this->assertFalse($manager->is_defined(true));
+ $this->assertFalse($manager->is_defined(false));
}
/**
@@ -108,6 +115,13 @@ class sitepolicy_test extends advanced_testcase {
$CFG->sitepolicy = null;
$this->assertEquals($CFG->wwwroot.'/user/policy.php', $manager->get_redirect_url(true)->out(false));
$this->assertEquals(null, $manager->get_redirect_url(false));
+
+ // When non existing plugin is set as $CFG->sitepolicyhandler, assume that $CFG->sitepolicy* are all not set.
+ $CFG->sitepolicy = 'http://example.com/sitepolicy.html';
+ $CFG->sitepolicyguest = 'http://example.com/sitepolicyguest.html';
+ $CFG->sitepolicyhandler = 'non_existing_plugin_which_i_really_hope_will_never_exist';
+ $this->assertEquals(null, $manager->get_redirect_url(true));
+ $this->assertEquals(null, $manager->get_redirect_url(false));
}
/**
@@ -133,6 +147,13 @@ class sitepolicy_test extends advanced_testcase {
$CFG->sitepolicy = null;
$this->assertEquals($CFG->sitepolicyguest, $manager->get_embed_url(true)->out(false));
$this->assertEquals(null, $manager->get_embed_url(false));
+
+ // When non existing plugin is set as $CFG->sitepolicyhandler, assume that $CFG->sitepolicy* are all not set.
+ $CFG->sitepolicy = 'http://example.com/sitepolicy.html';
+ $CFG->sitepolicyguest = 'http://example.com/sitepolicyguest.html';
+ $CFG->sitepolicyhandler = 'non_existing_plugin_which_i_really_hope_will_never_exist';
+ $this->assertEquals(null, $manager->get_embed_url(true));
+ $this->assertEquals(null, $manager->get_embed_url(false));
}
/**
@@ -161,6 +182,15 @@ class sitepolicy_test extends advanced_testcase {
$this->assertTrue($manager->accept());
$this->assertEquals(1, $USER->policyagreed);
$this->assertEquals(1, $DB->get_field('user', 'policyagreed', ['id' => $USER->id]));
+
+ // When non existing plugin is set as $CFG->sitepolicyhandler, assume that $CFG->sitepolicy* are all not set.
+ $CFG->sitepolicy = 'http://example.com/sitepolicy.html';
+ $CFG->sitepolicyhandler = 'non_existing_plugin_which_i_really_hope_will_never_exist';
+ $user3 = $this->getDataGenerator()->create_user();
+ $this->setUser($user3);
+ $this->assertEquals(0, $USER->policyagreed);
+ $this->assertFalse($manager->accept());
+ $this->assertEquals(0, $USER->policyagreed);
}
/**
@@ -185,6 +215,13 @@ class sitepolicy_test extends advanced_testcase {
$this->assertTrue($manager->accept());
$this->assertEquals(1, $USER->policyagreed);
$this->assertEquals(0, $DB->get_field('user', 'policyagreed', ['id' => $USER->id]));
+
+ // When non existing plugin is set as $CFG->sitepolicyhandler, assume that $CFG->sitepolicy* are all not set.
+ $USER->policyagreed = 0; // Reset.
+ $CFG->sitepolicyguest = 'http://example.com/sitepolicyguest.html';
+ $CFG->sitepolicyhandler = 'non_existing_plugin_which_i_really_hope_will_never_exist';
+ $this->assertFalse($manager->accept());
+ $this->assertEquals(0, $USER->policyagreed);
}
/**
|
MDL-<I> admin: non-existing site policy handler means no policy
|
moodle_moodle
|
train
|
9ef66427af2163208ed641b0019f17a4c925f38d
|
diff --git a/falafel/config/specs.py b/falafel/config/specs.py
index <HASH>..<HASH> 100644
--- a/falafel/config/specs.py
+++ b/falafel/config/specs.py
@@ -202,6 +202,7 @@ static_specs = {
SimpleFileSpec("sos_commands/foreman/foreman-debug/satellite_version"),
SimpleFileSpec("satellite_version")]),
"scsi" : SimpleFileSpec("proc/scsi/scsi"),
+ "scheduler" : CommandSpec("/bin/cat {getblockscheduler}"),
"secure" : SimpleFileSpec("var/log/secure", large_content=True),
"selinux-config" : SimpleFileSpec("etc/selinux/config"),
"sestatus" : CommandSpec("/usr/sbin/sestatus -b"),
@@ -242,7 +243,8 @@ static_specs = {
pre_commands = {
"iface": "/sbin/ip -o link | awk -F ': ' '/.*link\\/ether/ {print $2}'",
"block": "/bin/ls /sys/block | awk '!/^ram|^\\.+$/ {print \"/dev/\" $1 \" unit s print\"}'",
- "module": "/bin/ls /sys/module"
+ "module": "/bin/ls /sys/module",
+ "getblockschedulers": "for device in $(ls /sys/block); do echo /sys/block/$device/queue/scheduler; done"
}
meta_files = {
|
Add IO scheduler to specs.py
Upcoming oracle rule will require grabbing the IO scheduler from
the systems. This will likely be handy for other rules for performance.
The new patternspec should grab the scheduler setting from each
device in /sys/block
|
RedHatInsights_insights-core
|
train
|
8bf6963f519f99d5349c403dbbe0b4c47ffde73a
|
diff --git a/src/modules/pixel-scroll-model/index.js b/src/modules/pixel-scroll-model/index.js
index <HASH>..<HASH> 100644
--- a/src/modules/pixel-scroll-model/index.js
+++ b/src/modules/pixel-scroll-model/index.js
@@ -95,6 +95,7 @@ module.exports = function (_grid) {
var scrollBarOffset = e[layerCoordField];
decorator._unbindDrag = grid.eventLoop.bind('grid-drag', function (e) {
+ grid.eventLoop.stopBubbling(e);
var gridCoord = viewPortClampFn(e[gridCoordField]);
var scrollBarRealClickCoord = gridCoord - scrollBarOffset;
var scrollCoord = getScrollPositionFromReal(scrollBarRealClickCoord, heightWidth, vertHorz);
|
only the scroll bar gets to handle it's drag
|
gridgrid_grid
|
train
|
738ff51e99cd64abb246489f5453e22e7532ca72
|
diff --git a/src/wormling/phparia/Client/Client.php b/src/wormling/phparia/Client/Client.php
index <HASH>..<HASH> 100644
--- a/src/wormling/phparia/Client/Client.php
+++ b/src/wormling/phparia/Client/Client.php
@@ -39,6 +39,11 @@ class Client
* @var \PestJSON
*/
protected $ariEndpoint;
+
+ /**
+ * @var string
+ */
+ protected $stasisApplication;
/**
* @var \React\EventLoop
@@ -128,6 +133,7 @@ class Client
*/
private function connect($ariUsername, $ariPassword, $stasisApplication, $ariServer = '127.0.0.1', $ariPort = '8088', $ariEndpoint = '', $amiUsername = 'admin', $amiPassword = 'admin', $amiServer = '127.0.0.1')
{
+ $this->stasisApplication = $stasisApplication;
$this->ariEndpoint = new \PestJSON('http://' . $ariServer . ':' . $ariPort . $ariEndpoint);
$this->ariEndpoint->setupAuth($ariUsername, $ariPassword, 'basic');
$this->stasisLoop = \React\EventLoop\Factory::create();
@@ -158,7 +164,7 @@ class Client
$this->logger->notice("Emitting ID event: {$event->getEventId()}");
$this->stasisClient->emit($event->getEventId(), array(
'event' => $event
- ));
+ ));
}
// Emit the general event
@@ -184,7 +190,7 @@ class Client
$this->stasisClient->emit($event->getName(), (array) $event);
});
}, function (\Exception $e) {
- $this->logger->err('Connection eror: ' . $e->getMessage());
+ $this->logger->err('Connection eror: ' . $e->getTraceAsString());
exit;
}
@@ -236,6 +242,14 @@ class Client
{
return $this->ariEndpoint;
}
+
+ /**
+ * @return string The name of the stasis application
+ */
+ public function getStasisApplication()
+ {
+ return $this->stasisApplication;
+ }
/**
* @return \Zend\Log\Logger
|
Exposed stasis application name from the client.
|
wormling_phparia
|
train
|
85925ebd7c6d785a1427c0a25b762bea82b5cd39
|
diff --git a/funfactory/log.py b/funfactory/log.py
index <HASH>..<HASH> 100644
--- a/funfactory/log.py
+++ b/funfactory/log.py
@@ -13,7 +13,10 @@ class AreciboHandler(logging.Handler):
arecibo = getattr(settings, 'ARECIBO_SERVER_URL', '')
if arecibo and hasattr(record, 'request'):
- from django_arecibo.tasks import post
+ if getattr(settings, 'ARECIBO_USES_CELERY', False):
+ from django_arecibo.tasks import post
+ else:
+ from django_arecibo.wrapper import post
post(record.request, 500)
diff --git a/funfactory/settings_base.py b/funfactory/settings_base.py
index <HASH>..<HASH> 100644
--- a/funfactory/settings_base.py
+++ b/funfactory/settings_base.py
@@ -221,8 +221,8 @@ INSTALLED_APPS = (
'jingo_minify',
'tower', # for ./manage.py extract (L10n)
'cronjobs', # for ./manage.py cron * cmd line tasks
-
-
+
+
# Django contrib apps
'django.contrib.auth',
'django_sha2', # Load after auth to monkey-patch it.
@@ -277,6 +277,10 @@ CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
# The task can catch that and recover but should exit ASAP.
CELERYD_TASK_SOFT_TIME_LIMIT = 60 * 2
+## Arecibo
+# when ARECIBO_SERVER_URL is set, it can use celery or the regular wrapper
+ARECIBO_USES_CELERY = True
+
# For absolute urls
try:
DOMAIN = socket.gethostname()
|
make it possible to disable arecibo to use Celery
|
mozilla_funfactory
|
train
|
0e21efd83c99c274a104f21b81eb70e9aface8c1
|
diff --git a/lib/attrtastic.rb b/lib/attrtastic.rb
index <HASH>..<HASH> 100644
--- a/lib/attrtastic.rb
+++ b/lib/attrtastic.rb
@@ -211,9 +211,11 @@ module Attrtastic
end
end
- #@@value_methods = %w/ to_label display_name full_name name title username login value to_s /
def value_of_attribute(method)
- record.send(method).to_s
+ value = record.send(method)
+ value_methods = [ :to_label, :display_name, :full_name, :name, :title, :username, :login, :value ]
+ value_method = value_methods.find { |m| value.respond_to?(m) } || :to_s
+ value.send(value_method)
end
end
diff --git a/test/test_attribute.rb b/test/test_attribute.rb
index <HASH>..<HASH> 100644
--- a/test/test_attribute.rb
+++ b/test/test_attribute.rb
@@ -33,6 +33,18 @@ class TestAttribute < Test::Unit::TestCase
assert_equal expected, actual
end
+ def test__attribute__with_value_as_object
+ expected = html <<-EOHTML
+ <li class="attribute">
+ <span class="label">Author</span>
+ <span class="value">Doe, John</span>
+ </li>
+ EOHTML
+
+ actual = @blog_builder.attribute(:author)
+ assert_equal expected, actual
+ end
+
def test__attribute__with_custom_label
expected = html <<-EOHTML
<li class="attribute">
|
Added support for objects as values (not only strings)
|
MBO_attrtastic
|
train
|
6bad3fb9d46fdfe7352636521f134724aec548f7
|
diff --git a/generators/generator-constants.js b/generators/generator-constants.js
index <HASH>..<HASH> 100644
--- a/generators/generator-constants.js
+++ b/generators/generator-constants.js
@@ -46,7 +46,7 @@ const JACKSON_DATABIND_NULLABLE_VERSION = '0.2.1';
// Version of docker images
const DOCKER_COMPOSE_FORMAT_VERSION = '3.8';
-const DOCKER_JHIPSTER_REGISTRY = 'jhipster/jhipster-registry:v7.0.0';
+const DOCKER_JHIPSTER_REGISTRY = 'ghcr.io/jhipster/jhipster-registry:main';
const DOCKER_JHIPSTER_CONTROL_CENTER = 'jhipster/jhipster-control-center:v0.5.0';
const DOCKER_JAVA_JRE = 'eclipse-temurin:11-jre-focal';
const DOCKER_MYSQL = 'mysql:8.0.26';
|
Temporary point to snapshot jhipster-registry
|
jhipster_generator-jhipster
|
train
|
129316227ff9415364fceec579351f1480950c43
|
diff --git a/Gruntfile.js b/Gruntfile.js
index <HASH>..<HASH> 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -1,10 +1,5 @@
module.exports = function(grunt) {
grunt.initConfig({
- json: {
- options: {
- dest: 'colors.json'
- }
- }
});
grunt.loadTasks('tasks');
diff --git a/lib/fetch.js b/lib/fetch.js
index <HASH>..<HASH> 100644
--- a/lib/fetch.js
+++ b/lib/fetch.js
@@ -1,5 +1,4 @@
var http = require('http');
-var fs = require('fs');
var cheerio = require('cheerio');
// Create an Object from an Array of objects.
@@ -56,4 +55,4 @@ function fetch(callback) {
}).on('error', callback);
}
-module.exports = fetch;
\ No newline at end of file
+module.exports = fetch;
diff --git a/tasks/generate.js b/tasks/generate.js
index <HASH>..<HASH> 100644
--- a/tasks/generate.js
+++ b/tasks/generate.js
@@ -1,13 +1,9 @@
-var fs = require('fs');
-var path = require('path');
-
function generate(grunt, fileType) {
- var colorSet = require(path.resolve(__dirname, '..', 'dist', 'colors.json'));
- var templatePath = path.resolve(__dirname, '..', 'templates', fileType + '.tmpl');
- var tmpl = fs.readFileSync(templatePath, { encoding: 'utf8' });
+ var colorSet = grunt.file.readJSON('dist/colors.json');
+ var tmpl = grunt.file.read('templates/' + fileType + '.tmpl');
var data = { colorSet: colorSet };
- var css = grunt.template.process(tmpl, { data: data });
- fs.writeFileSync(path.resolve(__dirname, '..', 'dist', 'colors.' + fileType), css);
+ var generated = grunt.template.process(tmpl, { data: data });
+ grunt.file.write('dist/colors.' + fileType, generated);
}
module.exports = function(grunt) {
diff --git a/tasks/json.js b/tasks/json.js
index <HASH>..<HASH> 100644
--- a/tasks/json.js
+++ b/tasks/json.js
@@ -1,5 +1,3 @@
-var fs = require('fs');
-var path = require('path');
var fetch = require('../lib/fetch');
module.exports = function(grunt) {
@@ -13,8 +11,7 @@ module.exports = function(grunt) {
}
var json = JSON.stringify(colorSet, null, 2);
- var jsonPath = path.resolve(__dirname, '..', 'dist', 'colors.json');
- fs.writeFileSync(jsonPath, json);
+ grunt.file.write('dist/colors.json', json);
done();
});
});
|
Refactor tasks with grunt.file methods.
|
shuhei_material-colors
|
train
|
22e9357d40f7f56fcb671e1076d8d7271316fcdf
|
diff --git a/flink-tests/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterStopWithSavepointITCase.java b/flink-tests/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterStopWithSavepointITCase.java
index <HASH>..<HASH> 100644
--- a/flink-tests/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterStopWithSavepointITCase.java
+++ b/flink-tests/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterStopWithSavepointITCase.java
@@ -19,6 +19,7 @@
package org.apache.flink.runtime.jobmaster;
import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Deadline;
@@ -38,6 +39,7 @@ import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration;
import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings;
+import org.apache.flink.runtime.testutils.CommonTestUtils;
import org.apache.flink.streaming.runtime.tasks.StreamTask;
import org.apache.flink.streaming.runtime.tasks.StreamTaskTest.NoOpStreamTask;
import org.apache.flink.streaming.runtime.tasks.mailbox.MailboxDefaultAction;
@@ -313,20 +315,15 @@ public class JobMasterStopWithSavepointITCase extends AbstractTestBase {
}
private void waitForJob() throws Exception {
- for (int i = 0; i < 60; i++) {
- try {
- final JobStatus jobStatus =
- clusterClient.getJobStatus(jobGraph.getJobID()).get(60, TimeUnit.SECONDS);
- assertThat(jobStatus.isGloballyTerminalState(), equalTo(false));
- if (jobStatus == JobStatus.RUNNING) {
- return;
- }
- } catch (ExecutionException ignored) {
- // JobManagerRunner is not yet registered in Dispatcher
- }
- Thread.sleep(1000);
- }
- throw new AssertionError("Job did not become running within timeout.");
+ Deadline deadline = Deadline.fromNow(Duration.ofMinutes(5));
+ JobID jobID = jobGraph.getJobID();
+ CommonTestUtils.waitForAllTaskRunning(
+ () ->
+ miniClusterResource
+ .getMiniCluster()
+ .getExecutionGraph(jobID)
+ .get(60, TimeUnit.SECONDS),
+ deadline);
}
/**
|
[FLINK-<I>][tests] Improve JobMasterStopWithSavepoint#waitForJob to wait for all tasks running
|
apache_flink
|
train
|
1fd30c36d91ffb08b24ab14465cd628bb3f62095
|
diff --git a/src/Controller.php b/src/Controller.php
index <HASH>..<HASH> 100644
--- a/src/Controller.php
+++ b/src/Controller.php
@@ -39,6 +39,10 @@ class Controller extends BaseController
{
$this->requireAcceptsJson();
+ // The behaviour of certain controller actions depends on whether Craft 3.0 or 3.1 is being used
+ // Figure out which Craft version is being used by checking whether the project config service class exists
+ $isCraft30 = !class_exists('craft\\services\\ProjectConfig');
+
$response = null;
$assetsService = Craft::$app->getAssets();
@@ -49,7 +53,10 @@ class Controller extends BaseController
$folderId = $requestService->getRequiredParam('folderId');
$embeddedAsset = EmbeddedAssets::$plugin->methods->requestUrl($url);
- $folder = $assetsService->findFolder(['uid' => $folderId]);
+
+ // Craft 3.0 requires finding the folder by its ID, whereas Craft 3.1 requires finding it by its UID
+ $folderIdProp = $isCraft30 ? 'id' : 'uid';
+ $folder = $assetsService->findFolder([$folderIdProp => $folderId]);
if (!$folder)
{
@@ -59,8 +66,8 @@ class Controller extends BaseController
$userTempFolder = !$folder->volumeId ? $assetsService->getCurrentUserTemporaryUploadFolder() : null;
if (!$userTempFolder || $folder->id != $userTempFolder->id)
{
- $volume = Craft::$app->getVolumes()->getVolumeById($folder->volumeId);
- $this->requirePermission('saveAssetInVolume:'. $volume->uid);
+ $volume = Craft::$app->getVolumes()->getVolumeById($folder->volumeId);
+ $this->requirePermission('saveAssetInVolume:'. $volume->$folderIdProp);
}
$asset = EmbeddedAssets::$plugin->methods->createAsset($embeddedAsset, $folder);
|
Maintain Craft <I> compatibility
|
spicywebau_craft-embedded-assets
|
train
|
77c2e9c6dc6f523f4fd2cb1467add4547cba7a91
|
diff --git a/brennus-asm/src/main/java/brennus/asm/ASMExpressionVisitor.java b/brennus-asm/src/main/java/brennus/asm/ASMExpressionVisitor.java
index <HASH>..<HASH> 100644
--- a/brennus-asm/src/main/java/brennus/asm/ASMExpressionVisitor.java
+++ b/brennus-asm/src/main/java/brennus/asm/ASMExpressionVisitor.java
@@ -1,5 +1,7 @@
package brennus.asm;
+import static brennus.model.Protection.PRIVATE;
+
import java.util.List;
import brennus.MethodContext;
@@ -18,6 +20,7 @@ import brennus.model.LiteralExpression;
import brennus.model.Method;
import brennus.model.Parameter;
import brennus.model.ParameterAccessType;
+import brennus.model.Protection;
import brennus.model.Type;
import brennus.model.UnaryExpression;
import brennus.model.VarAccessType;
@@ -90,11 +93,15 @@ class ASMExpressionVisitor implements Opcodes, ExpressionVisitor {
throw new RuntimeException("can't find method "+methodName+" with " + parameterCount + " parameters in hierarchy of "+lastExpressionType);
}
}
+ if (method.getFlags().isStatic()) {
+ throw new UnsupportedOperationException();
+ }
List<Expression> parameters = callMethodExpression.getParameters();
loadParameters(methodName, method, parameters);
methodByteCodeContext.addInstruction(
new MethodInsnNode(
- method.isInterfaceMethod() ? INVOKEINTERFACE : INVOKEVIRTUAL,
+ method.isInterfaceMethod() ? INVOKEINTERFACE :
+ method.getFlags().getProtection() == PRIVATE ? INVOKESPECIAL : INVOKEVIRTUAL,
method.getTypeName(),
methodName,
method.getSignature()),
|
add INVOKESPECIAL for private methods; fail for static methods for now
|
julienledem_brennus
|
train
|
f043e0dd4eca1b214bdd232452c9d74ac5319612
|
diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/cache/LoadBalancerCacheProperties.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/cache/LoadBalancerCacheProperties.java
index <HASH>..<HASH> 100644
--- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/cache/LoadBalancerCacheProperties.java
+++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/cache/LoadBalancerCacheProperties.java
@@ -62,11 +62,11 @@ public class LoadBalancerCacheProperties {
this.ttl = ttl;
}
- int getCapacity() {
+ public int getCapacity() {
return capacity;
}
- void setCapacity(int capacity) {
+ public void setCapacity(int capacity) {
this.capacity = capacity;
}
|
Making capacity getter and setter public. Fixes #<I>
|
spring-cloud_spring-cloud-commons
|
train
|
a00ac99ff05b05ec23a69ab79b2c852adbce12e1
|
diff --git a/salt/modules/hosts.py b/salt/modules/hosts.py
index <HASH>..<HASH> 100644
--- a/salt/modules/hosts.py
+++ b/salt/modules/hosts.py
@@ -27,6 +27,7 @@ def _list_hosts():
'''
Return the hosts found in the hosts file in as an OrderedDict
'''
+ count = 0
hfn = __get_hosts_filename()
ret = odict.OrderedDict()
if not os.path.isfile(hfn):
@@ -37,6 +38,8 @@ def _list_hosts():
if not line:
continue
if line.startswith('#'):
+ ret.setdefault('comment-{0}'.format(count), []).extend(line)
+ count += 1
continue
if '#' in line:
line = line[:line.index('#')].strip()
@@ -225,10 +228,14 @@ def add_host(ip, alias):
def _write_hosts(hosts):
lines = []
for ip, aliases in hosts.iteritems():
- line = '{0}\t\t{1}'.format(
- ip,
- '\t\t'.join(aliases)
- )
+ if ip:
+ if ip.startswith('comment'):
+ line = ''.join(aliases)
+ else:
+ line = '{0}\t\t{1}'.format(
+ ip,
+ '\t\t'.join(aliases)
+ )
lines.append(line)
hfn = __get_hosts_filename()
|
Fix #<I> - keep comments within the hosts file
|
saltstack_salt
|
train
|
48c926d81fe296edb193fb33128352d06b0e63a7
|
diff --git a/scratchpad.txt b/scratchpad.txt
index <HASH>..<HASH> 100644
--- a/scratchpad.txt
+++ b/scratchpad.txt
@@ -7,7 +7,8 @@ DONE Buffer management scheme
DONE Implement Zound.play() method
How do I exit from a thread gracefully?
"live" JACK tests
- - Why doesn't Zound.play() work?
+ - Why doesn't Zound.play() work for multiple levels of nesting?
+ - __add__ should be __and__
How do I update FrameSearch indexes continually?
Move tests that have nothing to do with data storage/access into the model package
diff --git a/zounds/data/test_pattern.py b/zounds/data/test_pattern.py
index <HASH>..<HASH> 100644
--- a/zounds/data/test_pattern.py
+++ b/zounds/data/test_pattern.py
@@ -1156,6 +1156,56 @@ class PatternTest(object):
def test_get_item_time_slice(self):
self.fail()
+ ## _LEAVES_ABSOLUTE ####################################################
+
+ def test_leaves_absolute_leaf(self):
+ leaf = Zound[self._pattern_id]
+ la = leaf._leaves_absolute()
+
+ self.assertEqual(1,len(la))
+ self.assertEqual(leaf._id,la.keys()[0])
+ self.assertEqual(1,len(la.values()[0]))
+
+ def test_leaves_absolute_nested_one_level(self):
+ leaf = Zound[self._pattern_id]
+ branch = Zound(source = 'Test')
+ branch.append(leaf,[Event(i) for i in range(4)])
+
+ la = branch._leaves_absolute()
+ self.assertEqual(1,len(la))
+ self.assertEqual(leaf._id,la.keys()[0])
+ self.assertEqual(4,len(la.values()[0]))
+
+ def test_leaves_absolute_nested_one_level_two_patterns(self):
+ l1 = self.make_leaf_pattern(1, 'l1', store = False)
+ l2 = self.make_leaf_pattern(2, 'l2', store = False)
+
+ branch = Zound(source = 'Test')
+ branch.append(l1,[Event(i) for i in range(4)])
+ branch.append(l2,[Event(i) for i in range(4,8)])
+
+ la = branch._leaves_absolute()
+
+ self.assertEqual(2,len(la))
+ self.assertTrue(l1._id in la)
+ self.assertTrue(l2._id in la)
+ self.assertEqual(4,len(la[l1._id]))
+ self.assertEqual(4,len(la[l2._id]))
+
+ def test_leaves_absolute_nested_two(self):
+ leaf = Zound[self._pattern_id]
+ b = Zound(source = 'Test',_id = 'branch')
+ b.append(leaf,[Event(i) for i in range(4)])
+ r = Zound(source = 'Test',_id = 'root')
+ r.append(b,[Event(i) for i in range(0,16,4)])
+
+ la = r._leaves_absolute()
+
+ self.assertEqual(1,len(la))
+ self.assertTrue(leaf._id in la)
+ events = la[leaf._id]
+ self.assertEqual(16,len(events))
+
class InMemoryTest(unittest.TestCase,PatternTest):
diff --git a/zounds/model/pattern.py b/zounds/model/pattern.py
index <HASH>..<HASH> 100644
--- a/zounds/model/pattern.py
+++ b/zounds/model/pattern.py
@@ -448,6 +448,12 @@ class Event(object):
# transform to calculate its new length?
return pattern.length_samples
+ def __str__(self):
+ return tostring(self,time = self.time)
+
+ def __repr__(self):
+ return self.__str__()
+
# TODO: Composable types with different atomic behaviors
class BaseTransform(object):
@@ -790,18 +796,22 @@ class Zound(Pattern):
if self.is_leaf:
return {self._id : [Event(offset)]}
- if not d:
+ if None is d:
d = dict()
if not patterns:
patterns = self.patterns
# BLEGH!! This is ugly!
+
+ # iterate over each child pattern
for k,v in self.pdata.iteritems():
p = patterns[k]
+ # iterate over the events for this pattern
for e in v:
l = p._leaves_absolute(\
d = d, patterns = patterns,offset = offset + e.time)
+ print k,e.time,l
for _id,events in l.iteritems():
try:
d[_id].extend(events)
@@ -810,6 +820,7 @@ class Zound(Pattern):
return d
+
def play(self,time = 0):
'''
play this pattern in realtime, starting time seconds from now
@@ -837,7 +848,6 @@ class Zound(Pattern):
put(audio,0,la,now + latency + (e.time * 1e6))
- # TODO: Tests
def audio_extractor(self,needs = None):
e = self.env()
return AudioFromMemory(e.samplerate,
|
Added tests for Zound._leaves_absolute(), one of which demonstrates errant behavior for patterns nested more than one level deep.
|
JohnVinyard_zounds
|
train
|
7ba08bdf0beb72c9afbf6c057809817fd1315ad4
|
diff --git a/ocrd/workspace.py b/ocrd/workspace.py
index <HASH>..<HASH> 100644
--- a/ocrd/workspace.py
+++ b/ocrd/workspace.py
@@ -174,9 +174,14 @@ class Workspace(object):
if coords is None:
return pil_image
if image_url not in self.image_cache['cv2']:
- self.image_cache['cv2'][image_url] = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
+ log.debug("Converting PIL to OpenCV: %s", image_url)
+ if pil_image.mode == '1':
+ self.image_cache['cv2'][image_url] = cv2.cvtColor(np.array(pil_image).astype(np.uint8), cv2.COLOR_GRAY2BGR)
+ else:
+ self.image_cache['cv2'][image_url] = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
cv2_image = self.image_cache['cv2'][image_url]
poly = np.array(coords, np.int32)
+ log.debug("Cutting region %s from %s", coords, image_url)
region_cut = cv2_image[
np.min(poly[:, 1]):np.max(poly[:, 1]),
np.min(poly[:, 0]):np.max(poly[:, 0])
diff --git a/test/test_resolver.py b/test/test_resolver.py
index <HASH>..<HASH> 100644
--- a/test/test_resolver.py
+++ b/test/test_resolver.py
@@ -32,6 +32,23 @@ class TestResolver(TestCase):
self.assertEqual(f.ID, 'FILE_0001_IMAGE')
# print(f)
+ def test_resolve_image(self):
+ workspace = self.resolver.workspace_from_url(METS_HEROLD)
+ input_files = workspace.mets.find_files(fileGrp='OCR-D-IMG')
+ f = input_files[0]
+ img_pil1 = workspace.resolve_image_as_pil(f.url)
+ self.assertEqual(img_pil1.size, (2875, 3749))
+ img_pil2 = workspace.resolve_image_as_pil(f.url, [[0, 0], [1, 1]])
+ self.assertEqual(img_pil2.size, (1, 1))
+
+ def test_resolve_image_bitonal(self):
+ img_url = assets.url_of('kant_aufklaerung_1784-binarized/kant_aufklaerung_1784_0017.bin.1bit.png')
+ workspace = self.resolver.workspace_from_url(METS_HEROLD)
+ img_pil1 = workspace.resolve_image_as_pil(img_url)
+ self.assertEqual(img_pil1.size, (1457, 2083))
+ img_pil2 = workspace.resolve_image_as_pil(img_url, [[0, 0], [1, 1]])
+ self.assertEqual(img_pil2.size, (1, 1))
+
def test_unpack_workspace(self):
workspace = self.resolver.unpack_workspace_from_filename(TEST_ZIP)
files = workspace.mets.find_files(mimetype='image/tiff')
|
support resolving 1bit bitonal images, fix #<I>
|
OCR-D_core
|
train
|
282b8cd3ffe105e13a9453e11e3e0b73f8df190d
|
diff --git a/lib/CalDAV/Backend/PDO.php b/lib/CalDAV/Backend/PDO.php
index <HASH>..<HASH> 100644
--- a/lib/CalDAV/Backend/PDO.php
+++ b/lib/CalDAV/Backend/PDO.php
@@ -789,8 +789,10 @@ SQL
// If start time OR the end time is not specified, we can do a
// 100% accurate mysql query.
- if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
- $requirePostFilter = false;
+ if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && $timeRange) {
+ if (!$timeRange['start'] || !$timeRange['end']) {
+ $requirePostFilter = false;
+ }
}
}
}
|
Proper Fix "Trying to access array offset on value of type bool"
Since php<I>, we must properly ensure that array is not null/false before checking any of its column ranges
This properly fixes the "Trying to access array offset on value of type bool" when no time range is specified to filter our calendar events. It also preserves the accurate filtering query when time range is specified
|
sabre-io_dav
|
train
|
67414039255905385e9a7ac80b49f01db5fb645f
|
diff --git a/libact/query_strategies/uncertainty_sampling.py b/libact/query_strategies/uncertainty_sampling.py
index <HASH>..<HASH> 100644
--- a/libact/query_strategies/uncertainty_sampling.py
+++ b/libact/query_strategies/uncertainty_sampling.py
@@ -1,7 +1,8 @@
""" Uncertainty Sampling
-This module contains a class that implements two of the most well-known uncertainty sampling
-query strategies, which are least confidence and smallest margin (margin sampling).
+This module contains a class that implements two of the most well-known
+uncertainty sampling query strategies: the least confidence method and the
+smallest margin method (margin sampling).
"""
import numpy as np
@@ -34,16 +35,16 @@ class UncertaintySampling(QueryStrategy):
Examples
--------
- Here is an example of declaring a HintSVM query_strategy object:
+ Here is an example of declaring a UncertaintySampling query_strategy object:
.. code-block:: python
from libact.query_strategies import UncertaintySampling
from libact.models import LogisticRegression
- qs = UmcertaintySampling(
- dataset, # Dataset object
- model=LogisticRegression(C=0.1)
+ qs = UncertaintySampling(
+ dataset, # Dataset object
+ model=LogisticRegression(C=0.1)
)
Note that the model given in the :code:`model` parameter must be a
diff --git a/libact/query_strategies/variance_reduction.py b/libact/query_strategies/variance_reduction.py
index <HASH>..<HASH> 100644
--- a/libact/query_strategies/variance_reduction.py
+++ b/libact/query_strategies/variance_reduction.py
@@ -23,13 +23,12 @@ class VarianceReduction(QueryStrategy):
Only Logistic regression are supported now.
sigma: float, >0, optional (default=100.0)
- The regularization term to be added to the diagonal of Fisher
- information matrix. 1/sigma will be added to the matrix.
+ 1/sigma is added to the diagonal of the Fisher information matrix as
+ regularization term.
optimality : {'trace', 'determinant', 'eigenvalue'}, optional (default='trace')
- Choosing what to optimize. These options optimize the trace,
- determinant, and maximum eigenvalue of the inverse Fisher information
- matrix.
+ The type of optimal design. The options are the trace, determinant, or
+ maximum eigenvalue of the inverse Fisher information matrix.
Only 'trace' are supported now.
@@ -39,7 +38,6 @@ class VarianceReduction(QueryStrategy):
References
----------
-
.. [1] Schein, Andrew I., and Lyle H. Ungar. "Active learning for logistic
regression: an evaluation." Machine Learning 68.3 (2007): 235-265.
|
correct uncertainty_sampling and variance_reduction's docstrings
|
ntucllab_libact
|
train
|
22239b4481918b09108d5e403971def266b1d64f
|
diff --git a/cake/libs/controller/components/security.php b/cake/libs/controller/components/security.php
index <HASH>..<HASH> 100644
--- a/cake/libs/controller/components/security.php
+++ b/cake/libs/controller/components/security.php
@@ -173,6 +173,16 @@ class SecurityComponent extends Component {
public $csrfExpires = '+30 minutes';
/**
+ * Controls whether or not CSRF tokens are use and burn. Set to false to not generate
+ * new tokens on each request. One token will be reused until it expires. This reduces
+ * the chances of users getting invalid requests because of token consumption.
+ * It has the side effect of making CSRF less secure, as tokens are reusable.
+ *
+ * @var boolean
+ */
+ public $csrfUseOnce = true;
+
+/**
* Other components used by the Security component
*
* @var array
@@ -677,16 +687,15 @@ class SecurityComponent extends Component {
'csrfTokens' => array()
);
- if ($this->csrfCheck) {
- $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
- }
-
+ $tokenData = array();
if ($this->Session->check('_Token')) {
$tokenData = $this->Session->read('_Token');
if (!empty($tokenData['csrfTokens'])) {
- $token['csrfTokens'] += $tokenData['csrfTokens'];
- $token['csrfTokens'] = $this->_expireTokens($token['csrfTokens']);
+ $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']);
}
+ }
+ if ($this->csrfCheck && ($this->csrfUseOnce || empty($tokenData['csrfTokens'])) ) {
+ $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires);
}
$controller->request->params['_Token'] = $token;
$this->Session->write('_Token', $token);
@@ -705,7 +714,9 @@ class SecurityComponent extends Component {
$token = $this->Session->read('_Token');
$requestToken = $controller->request->data('_Token.key');
if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) {
- $this->Session->delete('_Token.csrfTokens.' . $requestToken);
+ if ($this->csrfUseOnce) {
+ $this->Session->delete('_Token.csrfTokens.' . $requestToken);
+ }
return true;
}
return false;
diff --git a/cake/tests/cases/libs/controller/components/security.test.php b/cake/tests/cases/libs/controller/components/security.test.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/libs/controller/components/security.test.php
+++ b/cake/tests/cases/libs/controller/components/security.test.php
@@ -1407,4 +1407,26 @@ DIGEST;
$this->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed, 'fail() was not called.');
}
+
+/**
+ * test that csrfUseOnce = false works.
+ *
+ * @return void
+ */
+ function testCsrfNotUseOnce() {
+ $this->Security->validatePost = false;
+ $this->Security->csrfCheck = true;
+ $this->Security->csrfUseOnce = false;
+ $this->Security->csrfExpires = '+10 minutes';
+
+ // Generate one token
+ $this->Security->startup($this->Controller);
+ $token = $this->Security->Session->read('_Token.csrfTokens');
+ $this->assertEquals(1, count($token), 'Should only be one token.');
+
+ $this->Security->startup($this->Controller);
+ $token2 = $this->Security->Session->read('_Token.csrfTokens');
+ $this->assertEquals(1, count($token2), 'Should only be one token.');
+ $this->assertEquals($token, $token2, 'Tokens should not be different.');
+ }
}
|
Making the ability to use longer shared csrf tokens possible. This should make for fewer blackholed' requests when doing complicated javascript.
|
cakephp_cakephp
|
train
|
f6df4e02f678604530b20e985fdf6896a3d5a239
|
diff --git a/app/helpers/alchemy/admin/base_helper.rb b/app/helpers/alchemy/admin/base_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/alchemy/admin/base_helper.rb
+++ b/app/helpers/alchemy/admin/base_helper.rb
@@ -302,13 +302,13 @@ module Alchemy
def clipboard_select_tag(items, html_options = {})
options = [[t('Please choose'), ""]]
items.each do |item|
- options << [item.class.to_s == 'Element' ? item.display_name_with_preview_text : item.name, item.id]
+ options << [item.class.to_s == 'Alchemy::Element' ? item.display_name_with_preview_text : item.name, item.id]
end
select_tag(
'paste_from_clipboard',
!@page.new_record? && @page.can_have_cells? ? grouped_elements_for_select(items, :id) : options_for_select(options),
{
- :class => html_options[:class] + 'alchemy_selectbox',
+ :class => [html_options[:class], 'alchemy_selectbox'].join(' '),
:style => html_options[:style]
}
)
|
Fixing select box class of clipboard
|
AlchemyCMS_alchemy_cms
|
train
|
28ed04aacff5502552af0c8f9e724d0ee0023107
|
diff --git a/dimod/compatibility23.py b/dimod/compatibility23.py
index <HASH>..<HASH> 100644
--- a/dimod/compatibility23.py
+++ b/dimod/compatibility23.py
@@ -20,8 +20,6 @@ if _PY2:
zip_longest = itertools.izip_longest
- RecursionError_ = RuntimeError
-
else:
range_ = range
@@ -38,8 +36,3 @@ else:
return iter(d.keys())
zip_longest = itertools.zip_longest
-
- if sys.version_info.minor > 4:
- RecursionError_ = RecursionError
- else:
- RecursionError_ = RuntimeError
diff --git a/dimod/core/sampler.py b/dimod/core/sampler.py
index <HASH>..<HASH> 100644
--- a/dimod/core/sampler.py
+++ b/dimod/core/sampler.py
@@ -2,7 +2,6 @@
todo - describe how to use the dimod sampler template
"""
from dimod.binary_quadratic_model_convert import to_qubo, to_ising, from_qubo, from_ising
-from dimod.compatibility23 import RecursionError_
from dimod.exceptions import InvalidSampler
from dimod.vartypes import Vartype
|
Remove unnecessary RecursionError_ definition
We don't need cross-Python RecursionError_ definition anymore if
we're explicitly testing for cycles in Sampler base class.
|
dwavesystems_dimod
|
train
|
9c22ca3ef51d3c17e038b995b9aee93e02735e05
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,7 @@ const http = require('http')
process.env.NODE_ENV = 'development'
const server = http.createServer()
-server.listen(1337, serverSummary(server))
+server.listen(1337, serverSummary(server).pipe(process.stdout))
```
## Why?
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -15,12 +15,13 @@ function summary (server) {
const env = process.env.NODE_ENV || 'undefined'
const serialize = ndjson.serialize()
- serialize.pipe(process.stdout)
serialize.write({name: 'url', url: url, type: 'connect'})
serialize.write({name: 'port', message: port})
serialize.write({name: 'env', message: env})
serialize.write({name: 'pid', message: process.pid})
serialize.end()
+
+ return serialize
}
}
diff --git a/test.js b/test.js
index <HASH>..<HASH> 100644
--- a/test.js
+++ b/test.js
@@ -13,7 +13,7 @@ test('should log console output', function (t) {
const server = http.createServer()
server.listen(null, function () {
const sum = summary(server)
- sum()
+ sum().pipe(process.stdout)
t.pass('server called')
server.close()
})
|
stream: decouple from stdout
|
yoshuawuyts_server-summary
|
train
|
0e28cd40c42b10580351ec791bc0edaec4bd29ed
|
diff --git a/IPython/html/widgets/tests/test_interaction.py b/IPython/html/widgets/tests/test_interaction.py
index <HASH>..<HASH> 100644
--- a/IPython/html/widgets/tests/test_interaction.py
+++ b/IPython/html/widgets/tests/test_interaction.py
@@ -1,15 +1,7 @@
"""Test interact and interactive."""
-#-----------------------------------------------------------------------------
-# Copyright (C) 2014 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
@@ -18,7 +10,7 @@ from collections import OrderedDict
import nose.tools as nt
import IPython.testing.tools as tt
-# from IPython.core.getipython import get_ipython
+from IPython.kernel.comm import Comm
from IPython.html import widgets
from IPython.html.widgets import interact, interactive, Widget, interaction
from IPython.utils.py3compat import annotate
@@ -27,8 +19,9 @@ from IPython.utils.py3compat import annotate
# Utility stuff
#-----------------------------------------------------------------------------
-class DummyComm(object):
+class DummyComm(Comm):
comm_id = 'a-b-c-d'
+
def send(self, *args, **kwargs):
pass
@@ -37,10 +30,11 @@ class DummyComm(object):
_widget_attrs = {}
displayed = []
+undefined = object()
def setup():
- _widget_attrs['comm'] = Widget.comm
- Widget.comm = DummyComm()
+ _widget_attrs['_comm_default'] = getattr(Widget, '_comm_default', undefined)
+ Widget._comm_default = lambda self: DummyComm()
_widget_attrs['_ipython_display_'] = Widget._ipython_display_
def raise_not_implemented(*args, **kwargs):
raise NotImplementedError()
@@ -48,7 +42,10 @@ def setup():
def teardown():
for attr, value in _widget_attrs.items():
- setattr(Widget, attr, value)
+ if value is undefined:
+ delattr(Widget, attr)
+ else:
+ setattr(Widget, attr, value)
def f(**kwargs):
pass
|
avoid copious warnings in interact tests
comm was mocked out, but in a way that makes traitlets complain
|
jupyter-widgets_ipywidgets
|
train
|
dd923d697196572e0dc5979030b46c59ddf76b83
|
diff --git a/.eslintrc.js b/.eslintrc.js
index <HASH>..<HASH> 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -5,6 +5,7 @@ module.exports = {
'plugin:jest/recommended'
],
rules: {
- indent: ['error', 2, { MemberExpression: 'off' }]
+ indent: ['error', 2, { MemberExpression: 'off' }],
+ "no-undef": ["error"]
}
}
|
workflow: update eslint rule
|
vuejs_vuepress
|
train
|
130484315549a8f2da479a5458246760aafd6259
|
diff --git a/src/migrations/2013_07_25_145958_create_language_entries_table.php b/src/migrations/2013_07_25_145958_create_language_entries_table.php
index <HASH>..<HASH> 100644
--- a/src/migrations/2013_07_25_145958_create_language_entries_table.php
+++ b/src/migrations/2013_07_25_145958_create_language_entries_table.php
@@ -22,9 +22,8 @@ class CreateLanguageEntriesTable extends Migration {
$table->boolean('unstable')->default('0');
$table->timestamps();
$table->foreign('language_id')->references('id')->on('languages');
+ $table->unique(array('language_id', 'namespace', 'group', 'item'));
});
- // Unique index:
- DB::statement('ALTER TABLE `language_entries` ADD UNIQUE INDEX(`language_id`, `namespace`, `group`, `item`)');
}
/**
|
Refactored migration for compatibility with databases other than MySQL.
Code provided by <URL>
|
Waavi_translation
|
train
|
d55e8a2a4f5ef835a0168a6d1b07b7c86d8b8663
|
diff --git a/src/Illuminate/Database/Eloquent/FactoryBuilder.php b/src/Illuminate/Database/Eloquent/FactoryBuilder.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Database/Eloquent/FactoryBuilder.php
+++ b/src/Illuminate/Database/Eloquent/FactoryBuilder.php
@@ -264,7 +264,7 @@ class FactoryBuilder
protected function expandAttributes(array $attributes)
{
foreach ($attributes as &$attribute) {
- if (is_callable($attribute)) {
+ if (is_callable($attribute) && ! is_string($attribute)) {
$attribute = $attribute($attributes);
}
|
fix breaking change (#<I>)
|
laravel_framework
|
train
|
5715886ca4286da412418cd67825711af7fd9e82
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -18,5 +18,5 @@ export default function(content) {
translations = extractTranslations(this, content, options),
module = interpolateModule(this, translations, options);
- return generateContent(module, locale, translations);
+ return generateContent(module, locale, translations, options.requireAngular);
}
|
fix: passes `requireAngular` global option to `generateContent` (#<I>)
|
Fitbit_angular-translate-loader
|
train
|
c4e0951178405899bc28aacdbd17f1785a939966
|
diff --git a/lib/core/api/api-spaces.js b/lib/core/api/api-spaces.js
index <HASH>..<HASH> 100644
--- a/lib/core/api/api-spaces.js
+++ b/lib/core/api/api-spaces.js
@@ -18,18 +18,4 @@
availity.core.factory('avSpacesResource', SpacesFactory);
- var NavigationFactory = function(AvApiResource) {
-
- // sdk/platform/v1/spaces/10939061011461209623076300008435
- return new AvApiResource({
- path: '/api/sdk',
- level: '/platform',
- version: '/v1',
- url: '/navigation/spaces',
- });
-
- };
-
- availity.core.factory('avNavigationResource', NavigationFactory);
-
})(window);
|
Removing navigation resource since its not being used
|
Availity_availity-angular
|
train
|
ec6f74a7b3ac745bf235352f219fbb81f1eca53f
|
diff --git a/h2o-algos/src/main/java/hex/ensemble/StackedEnsembleMojoWriter.java b/h2o-algos/src/main/java/hex/ensemble/StackedEnsembleMojoWriter.java
index <HASH>..<HASH> 100644
--- a/h2o-algos/src/main/java/hex/ensemble/StackedEnsembleMojoWriter.java
+++ b/h2o-algos/src/main/java/hex/ensemble/StackedEnsembleMojoWriter.java
@@ -3,11 +3,11 @@ package hex.ensemble;
import hex.Model;
import hex.MultiModelMojoWriter;
import hex.StackedEnsembleModel;
+import water.DKV;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
-import water.DKV;
public class StackedEnsembleMojoWriter extends MultiModelMojoWriter<StackedEnsembleModel,
StackedEnsembleModel.StackedEnsembleParameters, StackedEnsembleModel.StackedEnsembleOutput> {
@@ -20,7 +20,7 @@ public class StackedEnsembleMojoWriter extends MultiModelMojoWriter<StackedEnsem
@Override
public String mojoVersion() {
- return "1.0";
+ return "1.00";
}
@Override
|
Changed Mojo version of StackedEnsemble from <I> to <I>. (#<I>)
|
h2oai_h2o-3
|
train
|
e1358eeb7671fffe311c51dc9dbbb8504c698530
|
diff --git a/pkg/services/live/pushhttp/push.go b/pkg/services/live/pushhttp/push.go
index <HASH>..<HASH> 100644
--- a/pkg/services/live/pushhttp/push.go
+++ b/pkg/services/live/pushhttp/push.go
@@ -89,6 +89,7 @@ func (g *Gateway) Handle(ctx *models.ReqContext) {
for _, mf := range metricFrames {
err := stream.Push(ctx.SignedInUser.OrgId, mf.Key(), mf.Frame())
if err != nil {
+ logger.Error("Error pushing frame", "error", err, "data", string(body))
ctx.Resp.WriteHeader(http.StatusInternalServerError)
return
}
diff --git a/pkg/services/live/pushws/push.go b/pkg/services/live/pushws/push.go
index <HASH>..<HASH> 100644
--- a/pkg/services/live/pushws/push.go
+++ b/pkg/services/live/pushws/push.go
@@ -191,6 +191,7 @@ func (s *Handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
for _, mf := range metricFrames {
err := stream.Push(user.OrgId, mf.Key(), mf.Frame())
if err != nil {
+ logger.Error("Error pushing frame", "error", err, "data", string(body))
return
}
}
|
live: better error logging in push API (#<I>)
|
grafana_grafana
|
train
|
f1e4f6e674f1cf022bb1591ae25b84a98f482b36
|
diff --git a/Session/Storage/Handler/RedisSessionHandler.php b/Session/Storage/Handler/RedisSessionHandler.php
index <HASH>..<HASH> 100644
--- a/Session/Storage/Handler/RedisSessionHandler.php
+++ b/Session/Storage/Handler/RedisSessionHandler.php
@@ -45,12 +45,12 @@ class RedisSessionHandler implements \SessionHandlerInterface
/**
* @var bool Indicates an sessions should be locked
*/
- private $locking;
+ protected $locking;
/**
* @var bool Indicates an active session lock
*/
- private $locked;
+ protected $locked;
/**
* @var string Session lock key
@@ -109,7 +109,7 @@ class RedisSessionHandler implements \SessionHandlerInterface
/**
* Lock the session data.
*/
- private function lockSession($sessionId)
+ protected function lockSession($sessionId)
{
$attempts = (1000000 / $this->spinLockWait) * $this->lockMaxWait;
|
We have a custom session handler that inherrits from RedisSessionHandler.
Changing these vars/methods to protected will allow us to avoid needing a custom fork.
|
snc_SncRedisBundle
|
train
|
867459efd461685abd6c44f6ac816ae21f11b382
|
diff --git a/bosh-director/lib/bosh/director/deployment_plan/placement_planner/static_availability_zone_picker2.rb b/bosh-director/lib/bosh/director/deployment_plan/placement_planner/static_availability_zone_picker2.rb
index <HASH>..<HASH> 100644
--- a/bosh-director/lib/bosh/director/deployment_plan/placement_planner/static_availability_zone_picker2.rb
+++ b/bosh-director/lib/bosh/director/deployment_plan/placement_planner/static_availability_zone_picker2.rb
@@ -9,6 +9,19 @@ module Bosh
desired_instances = desired_instances.dup
instance_plans = []
+ instance_plans += place_existing_instance_plans(desired_instances, existing_instance_models, job_networks, networks_to_static_ips, placed_instances, desired_azs)
+ instance_plans += place_new_instance_plans(desired_instances, job_networks, networks_to_static_ips, placed_instances, desired_azs)
+ instance_plans
+ end
+
+ private
+
+ def to_az(az_name, desired_azs)
+ desired_azs.to_a.find { |az| az.name == az_name }
+ end
+
+ def place_existing_instance_plans(desired_instances, existing_instance_models, job_networks, networks_to_static_ips, placed_instances, desired_azs)
+ instance_plans = []
existing_instance_models.each do |existing_instance_model|
instance_plan = nil
job_networks.each do |network|
@@ -66,17 +79,9 @@ module Bosh
end
end
-
- instance_plans += place_new_instance_plans(desired_instances, job_networks, networks_to_static_ips, placed_instances, desired_azs)
instance_plans
end
- private
-
- def to_az(az_name, desired_azs)
- desired_azs.to_a.find { |az| az.name == az_name }
- end
-
def place_new_instance_plans(desired_instances, job_networks, networks_to_static_ips, placed_instances, desired_azs)
instance_plans = []
networks_to_static_ips.distribute_evenly_per_zone
|
Split some logic to place_existing_instance_plans
|
cloudfoundry_bosh
|
train
|
2435d05c2af96f6c3bda7fcfa3af4692a4550d33
|
diff --git a/_pydevd_frame_eval/pydevd_modify_bytecode.py b/_pydevd_frame_eval/pydevd_modify_bytecode.py
index <HASH>..<HASH> 100644
--- a/_pydevd_frame_eval/pydevd_modify_bytecode.py
+++ b/_pydevd_frame_eval/pydevd_modify_bytecode.py
@@ -96,7 +96,7 @@ def _update_label_offsets(code_obj, breakpoint_offset, breakpoint_code_list):
offsets_for_modification.append(offset)
elif op in dis.hasjabs:
# change label for absolute jump if code was inserted before it
- if current_offset <= arg:
+ if current_offset < arg:
offsets_for_modification.append(offset)
for i in range(0, len(code_list), 2):
op = code_list[i]
|
Fix inserting breakpoints into borderline case (PY-<I>)
(cherry picked from commit <I>a6)
|
fabioz_PyDev.Debugger
|
train
|
14e7673da98bdd73ef11960cb0057d73af44c60a
|
diff --git a/plugins/tls.js b/plugins/tls.js
index <HASH>..<HASH> 100644
--- a/plugins/tls.js
+++ b/plugins/tls.js
@@ -104,7 +104,7 @@ exports.upgrade_connection = function (next, connection, params) {
if (called_next) return;
called_next = true;
clearTimeout(connection.notes.tls_timer);
- if (!disconnected) connection.logerror(plugin, 'timeout');
+ if (!disconnected) connection.lognotice(plugin, 'timeout');
plugin.set_notls(connection.remote.ip);
return next(DENYSOFTDISCONNECT);
}
|
lower log level for inbound TLS timeout: way too common occurrance (#<I>)
|
haraka_Haraka
|
train
|
5658a9451fc6ae061af5a6231c370dc2944e7e63
|
diff --git a/Branch-SDK/src/main/java/io/branch/referral/Branch.java b/Branch-SDK/src/main/java/io/branch/referral/Branch.java
index <HASH>..<HASH> 100644
--- a/Branch-SDK/src/main/java/io/branch/referral/Branch.java
+++ b/Branch-SDK/src/main/java/io/branch/referral/Branch.java
@@ -3079,7 +3079,7 @@ public class Branch implements BranchViewHandler.IBranchViewEvents, SystemObserv
Activity activity = branch.getCurrentActivity();
Intent intent = activity != null ? activity.getIntent() : null;
- if (activity != null && ActivityCompat.getReferrer(activity) != null) {
+ if (activity != null && intent != null && ActivityCompat.getReferrer(activity) != null) {
PrefHelper.getInstance(activity).setInitialReferrer(ActivityCompat.getReferrer(activity).toString());
}
|
[INTENG-<I>] Handled NPE
At some instance when getReferrer is being triggered incase if intent is null it lead to NPE, hence have added a null check.
|
BranchMetrics_android-branch-deep-linking
|
train
|
08b4316ed5fc3323ee474ff7f15a8999e69ce531
|
diff --git a/examples/Wkt.js b/examples/Wkt.js
index <HASH>..<HASH> 100644
--- a/examples/Wkt.js
+++ b/examples/Wkt.js
@@ -37,7 +37,7 @@ requirejs(['./WorldWindShim',
}
// Example showing the usage of Well Known Text collection in real life.
- var defaultLayer = new WorldWind.RenderableLayer("Wkt Shapes");
+ var defaultLayer = new WorldWind.RenderableLayer("WKT Geometry Collection");
new WorldWind.Wkt("" +
"GEOMETRYCOLLECTION(" +
" POLYGON ((40 -70, 45 -80, 40 -90)), " +
@@ -49,10 +49,10 @@ requirejs(['./WorldWindShim',
wwd.addLayer(defaultLayer);
// Using the callback mechanism presented in the Wkt parser to update the shapes as well as showing the information about the successful rendering.
- var customCallbackLayer = new WorldWind.RenderableLayer("Wkt Shapes");
+ var customCallbackLayer = new WorldWind.RenderableLayer("WKT Multi Polygon");
new WorldWind.Wkt("MULTIPOLYGON (((50 -60, 55 -70, 50 -80)),((30 -60, 35 -70, 30 -80)))").load(
function completionCallback(wkt, objects){
- // Once all the shapes are parsed, this function is called.
+ // Once all the shapes are parsed, this function is called.
console.log('Parsing of the Wkt was completed');
wkt.defaultParserCompletionCallback(wkt, objects);
@@ -71,9 +71,9 @@ requirejs(['./WorldWindShim',
wwd.addLayer(customCallbackLayer);
// Allow for parsing of your own Well known text data
- var wktLayer = new WorldWind.RenderableLayer('Wkt');
+ var wktLayer = new WorldWind.RenderableLayer('WKT Custom');
$('#showWkt').click(function(){
- new WorldWind.WktParser($('#wkt').val()).load(null, null, wktLayer);
+ new WorldWind.Wkt($('#wkt').val()).load(null, null, wktLayer);
});
wwd.addLayer(wktLayer);
|
Rename the layers so not two have the same name
Correct the name of the constructor used to parse the custom WKT string
|
NASAWorldWind_WebWorldWind
|
train
|
d4e9f51c17ad3cd92e1a39b9c43ca44530431962
|
diff --git a/api/src/main/java/org/datacleaner/metadata/ColumnMeaning.java b/api/src/main/java/org/datacleaner/metadata/ColumnMeaning.java
index <HASH>..<HASH> 100644
--- a/api/src/main/java/org/datacleaner/metadata/ColumnMeaning.java
+++ b/api/src/main/java/org/datacleaner/metadata/ColumnMeaning.java
@@ -51,9 +51,13 @@ public enum ColumnMeaning implements HasName, HasAliases {
PERSON_GENDER("Gender", "Sex"),
- PERSON_AGE("Age"),
+ PERSON_AGE("Age", "Customer age", "Contact age"),
- PERSON_BIRTHDATE("Birthdate"),
+ PERSON_BIRTHDATE("Birthdate", "Date of birth", "DoB"),
+
+ PERSON_REGISTRATION_NUMBER("Social security number", "Person number", "Person Identifier"),
+
+ PERSON_JOB_TITLE("Job title", "Person job title", "Title", "Employee title", "Employment role"),
// COMPANY oriented items
@@ -74,7 +78,8 @@ public enum ColumnMeaning implements HasName, HasAliases {
// MONEY oriented items
- MONEY_AMOUNT("Money amount", "Amount", "Price", "Cost", "Credit", "Buy price", "Payment amount"),
+ MONEY_AMOUNT("Money amount", "Amount", "Price", "Cost", "Credit", "Buy price", "Payment amount", "Total price",
+ "Unit price"),
MONEY_CURRENCY("Money currency", "Currency", "Valuta", "Exchange"),
diff --git a/components/basic-transformers/src/main/java/org/datacleaner/beans/transform/DateToAgeTransformer.java b/components/basic-transformers/src/main/java/org/datacleaner/beans/transform/DateToAgeTransformer.java
index <HASH>..<HASH> 100644
--- a/components/basic-transformers/src/main/java/org/datacleaner/beans/transform/DateToAgeTransformer.java
+++ b/components/basic-transformers/src/main/java/org/datacleaner/beans/transform/DateToAgeTransformer.java
@@ -47,50 +47,52 @@ import org.joda.time.Years;
* "http://kasper.eobjects.org/2010/09/developing-value-transformer-using.html"
* >Developing a value transformer</a>.
* </p>
- *
- *
*/
@Named("Date to age")
@Description("Turn a Date-column into columns of age (both in years and in days).")
@Categorized(DateAndTimeCategory.class)
public class DateToAgeTransformer implements Transformer {
- @Configured("Date column")
- InputColumn<Date> dateColumn;
+ public static final String PROPERTY_DATE_COLUMN = "Date column";
+ public static final String OUTPUT_COLUMN_AGE_DAYS = "Age in days";
+ public static final String OUTPUT_COLUMN_AGE_YEARS = "Age in years";
+
+ @Configured(PROPERTY_DATE_COLUMN)
+ InputColumn<Date> dateColumn;
- private Date today = new Date();
+ private Date today = new Date();
- @Override
- public OutputColumns getOutputColumns() {
- return new OutputColumns(Integer.class, "Age in days", "Age in years");
- }
+ @Override
+ public OutputColumns getOutputColumns() {
+ return new OutputColumns(Integer.class, OUTPUT_COLUMN_AGE_DAYS, OUTPUT_COLUMN_AGE_YEARS);
+ }
- @Override
- public Integer[] transform(InputRow inputRow) {
- Integer[] result = new Integer[2];
- Date date = inputRow.getValue(dateColumn);
+ @Override
+ public Integer[] transform(InputRow inputRow) {
+ Integer[] result = new Integer[2];
+ Date date = inputRow.getValue(dateColumn);
- if (date != null) {
- long diffMillis = today.getTime() - date.getTime();
- int diffDays = (int) (diffMillis / (1000 * 60 * 60 * 24));
+ if (date != null) {
+ long diffMillis = today.getTime() - date.getTime();
+ int diffDays = (int) (diffMillis / (1000 * 60 * 60 * 24));
- result[0] = diffDays;
+ result[0] = diffDays;
- // use Joda time to easily calculate the diff in years
- int diffYears = Years.yearsBetween(new DateTime(date), new DateTime(today)).getYears();
- result[1] = diffYears;
- }
+ // use Joda time to easily calculate the diff in years
+ int diffYears = Years.yearsBetween(new DateTime(date), new DateTime(today)).getYears();
+ result[1] = diffYears;
+ }
- return result;
- }
+ return result;
+ }
- // injection for testing purposes only
- public void setToday(Date today) {
- this.today = today;
- }
+ // injection for testing purposes only
+ public void setToday(Date today) {
+ this.today = today;
+ }
- // injection for testing purposes only
- public void setDateColumn(InputColumn<Date> dateColumn) {
- this.dateColumn = dateColumn;
- }
+ // injection for testing purposes only
+ public void setDateColumn(InputColumn<Date> dateColumn) {
+ this.dateColumn = dateColumn;
+ }
}
|
Added a few column meanings and column meaning aliases.
|
datacleaner_DataCleaner
|
train
|
05e2dc68a2e2b1df9df36d96f72133df80582f0d
|
diff --git a/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExAccountService.java b/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExAccountService.java
index <HASH>..<HASH> 100644
--- a/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExAccountService.java
+++ b/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExAccountService.java
@@ -4,15 +4,14 @@ import java.io.IOException;
import java.math.BigDecimal;
import com.xeiam.xchange.Exchange;
+import com.xeiam.xchange.coinbaseex.CoinbaseExAdapters;
import com.xeiam.xchange.dto.account.AccountInfo;
import com.xeiam.xchange.exceptions.ExchangeException;
import com.xeiam.xchange.exceptions.NotAvailableFromExchangeException;
import com.xeiam.xchange.exceptions.NotYetImplementedForExchangeException;
import com.xeiam.xchange.service.polling.account.PollingAccountService;
-/**
- * Created by Yingzhe on 4/6/2015.
- */
+
public class CoinbaseExAccountService extends CoinbaseExAccountServiceRaw implements PollingAccountService {
public CoinbaseExAccountService(Exchange exchange) {
@@ -24,23 +23,20 @@ public class CoinbaseExAccountService extends CoinbaseExAccountServiceRaw implem
public AccountInfo getAccountInfo() throws ExchangeException,
NotAvailableFromExchangeException,
NotYetImplementedForExchangeException, IOException {
-
- this.getCoinbaseExAccountInfo();
- // TODO: return adapted
- return null;
+ return CoinbaseExAdapters.adaptAccountInfo(getCoinbaseExAccountInfo());
}
@Override
public String withdrawFunds(String currency, BigDecimal amount, String address)
throws ExchangeException, NotAvailableFromExchangeException,
NotYetImplementedForExchangeException, IOException {
- return null;
+ throw new NotYetImplementedForExchangeException();
}
@Override
public String requestDepositAddress(String currency, String... args)
throws ExchangeException, NotAvailableFromExchangeException,
NotYetImplementedForExchangeException, IOException {
- return null;
+ throw new NotYetImplementedForExchangeException();
}
}
diff --git a/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExAccountServiceRaw.java b/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExAccountServiceRaw.java
index <HASH>..<HASH> 100644
--- a/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExAccountServiceRaw.java
+++ b/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExAccountServiceRaw.java
@@ -4,18 +4,17 @@ import java.io.IOException;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.coinbaseex.CoinbaseEx;
+import com.xeiam.xchange.coinbaseex.dto.account.CoinbaseExAccount;
public class CoinbaseExAccountServiceRaw extends CoinbaseExBasePollingService<CoinbaseEx> {
- public CoinbaseExAccountServiceRaw(Exchange exchange) {
+ public CoinbaseExAccountServiceRaw(Exchange exchange) {
- super(CoinbaseEx.class, exchange);
- }
+ super(CoinbaseEx.class, exchange);
+ }
- public void getCoinbaseExAccountInfo() throws IOException {
- coinbaseEx.getAccounts(apiKey, digest, String.valueOf(getTimestamp()), passphrase);
-
- return;
- }
+ public CoinbaseExAccount[] getCoinbaseExAccountInfo() throws IOException {
+ return coinbaseEx.getAccounts(apiKey, digest, getTimestamp(), passphrase);
+ }
}
diff --git a/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExBasePollingService.java b/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExBasePollingService.java
index <HASH>..<HASH> 100644
--- a/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExBasePollingService.java
+++ b/xchange-coinbaseex/src/main/java/com/xeiam/xchange/coinbaseex/service/polling/CoinbaseExBasePollingService.java
@@ -26,7 +26,7 @@ public class CoinbaseExBasePollingService<T extends CoinbaseEx> extends BaseExch
protected CoinbaseExBasePollingService(Class<T> type, Exchange exchange) {
- super(exchange);
+ super(exchange);
this.coinbaseEx = RestProxyFactory.createProxy(type, exchange.getExchangeSpecification().getSslUri());
this.digest = CoinbaseExDigest.createInstance(exchange.getExchangeSpecification().getSecretKey());
@@ -40,7 +40,7 @@ public class CoinbaseExBasePollingService<T extends CoinbaseEx> extends BaseExch
return exchange.getMetaData().getCurrencyPairs();
}
- protected long getTimestamp() {
- return System.currentTimeMillis() / 1000;
+ protected String getTimestamp() {
+ return String.format("%.3f", System.currentTimeMillis() / 1000.0);
}
}
|
Wiring through of calls, make timestamp with decimals
|
knowm_XChange
|
train
|
7a2b30dcc44107560c89421fa4f1774b90e768ff
|
diff --git a/builder/vmware/iso/builder.go b/builder/vmware/iso/builder.go
index <HASH>..<HASH> 100755
--- a/builder/vmware/iso/builder.go
+++ b/builder/vmware/iso/builder.go
@@ -200,9 +200,9 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe
dir = new(vmwcommon.LocalOutputDir)
}
- var localDir localOutputDir
+ localDir := localOutputDir{b.config.OutputDir}
+ log.Printf("b.config.OutputDir: %s, localDir: %s", b.config.OutputDir, localDir.dir)
if b.config.RemoteType != "" && b.config.Format != "" {
- localDir = localOutputDir{b.config.OutputDir}
b.config.OutputDir = b.config.VMName
}
dir.SetOutputDir(b.config.OutputDir)
diff --git a/builder/vmware/iso/step_export.go b/builder/vmware/iso/step_export.go
index <HASH>..<HASH> 100644
--- a/builder/vmware/iso/step_export.go
+++ b/builder/vmware/iso/step_export.go
@@ -60,7 +60,7 @@ func (s *StepExport) Run(state multistep.StateBag) multistep.StepAction {
// Export the VM
localDir := state.Get("localDir").(localOutputDir)
- outputPath := filepath.Join(fmt.Sprintf("%v", localDir), c.VMName+"."+s.Format)
+ outputPath := filepath.Join(localDir.dir, c.VMName+"."+s.Format)
if s.Format == "ova" {
os.MkdirAll(outputPath, 0755)
|
builder/vmware-iso: need to always set local output dir, or non-remote build exports will fail
|
hashicorp_packer
|
train
|
9871b4c5e8acef3b0d85c23bf76ff93658a23c0b
|
diff --git a/graylog2-server/src/main/java/org/graylog2/rest/resources/system/logs/LoggersResource.java b/graylog2-server/src/main/java/org/graylog2/rest/resources/system/logs/LoggersResource.java
index <HASH>..<HASH> 100644
--- a/graylog2-server/src/main/java/org/graylog2/rest/resources/system/logs/LoggersResource.java
+++ b/graylog2-server/src/main/java/org/graylog2/rest/resources/system/logs/LoggersResource.java
@@ -74,20 +74,33 @@ public class LoggersResource extends RestResource {
@GET @Timed
@Path("/subsystems")
- @ApiOperation(value = "List all logger subsystems")
+ @ApiOperation(value = "List all logger subsystems and their current levels")
@Produces(MediaType.APPLICATION_JSON)
public String subsytems() {
Map<String, Object> result = Maps.newHashMap();
+ Map<String, Object> subsystems = Maps.newHashMap();
for(Map.Entry<String, Subsystem> subsystem : SUBSYSTEMS.entrySet()) {
- Map<String, Object> info = Maps.newHashMap();
- info.put("title", subsystem.getValue().getTitle());
- info.put("category", subsystem.getValue().getCategory());
- info.put("description", subsystem.getValue().getDescription());
-
- result.put(subsystem.getKey(), info);
+ try {
+ Map<String, Object> info = Maps.newHashMap();
+ info.put("title", subsystem.getValue().getTitle());
+ info.put("category", subsystem.getValue().getCategory());
+ info.put("description", subsystem.getValue().getDescription());
+
+ // Get level.
+ Level effectiveLevel = Logger.getLogger(subsystem.getValue().getCategory()).getEffectiveLevel();
+ info.put("level", effectiveLevel.toString().toLowerCase());
+ info.put("level_syslog", effectiveLevel.getSyslogEquivalent());
+
+ subsystems.put(subsystem.getKey(), info);
+ } catch(Exception e) {
+ LOG.error("Error while listing logger subsystem.", e);
+ continue;
+ }
}
+ result.put("subsystems", subsystems);
+
return json(result);
}
|
include effective log level in subsystem list
Graylog2/graylog2-web-interface#<I>, Graylog2/graylog2-web-interface#<I>
|
Graylog2_graylog2-server
|
train
|
8d5a4c8c727bc119601770912cc1a9cf9808695e
|
diff --git a/aeron-cluster/src/test/java/io/aeron/cluster/ClusterTest.java b/aeron-cluster/src/test/java/io/aeron/cluster/ClusterTest.java
index <HASH>..<HASH> 100644
--- a/aeron-cluster/src/test/java/io/aeron/cluster/ClusterTest.java
+++ b/aeron-cluster/src/test/java/io/aeron/cluster/ClusterTest.java
@@ -17,6 +17,8 @@ package io.aeron.cluster;
import io.aeron.cluster.service.Cluster;
import org.agrona.collections.MutableInteger;
+import org.agrona.concurrent.IdleStrategy;
+import org.agrona.concurrent.YieldingIdleStrategy;
import org.agrona.concurrent.status.CountersReader;
import org.junit.*;
@@ -310,7 +312,7 @@ public class ClusterTest
}
@Test(timeout = 30_000)
- public void shouldAcceptMessagesAfterSingleNodeGoDownAndComeBackUpClean() throws Exception
+ public void shouldAcceptMessagesAfterSingleNodeCleanRestart() throws Exception
{
final int messageCount = 10;
@@ -395,7 +397,7 @@ public class ClusterTest
}
@Test(timeout = 30_000)
- public void shouldAcceptMessagesAfterTwoNodesGoDownAndComeBackUpClean() throws Exception
+ public void shouldAcceptMessagesAfterTwoNodeCleanRestart() throws Exception
{
final int messageCount = 10;
@@ -609,18 +611,18 @@ public class ClusterTest
}
@Test(timeout = 30_000)
- public void shouldCatchUpAfterFollowerMissesAMessage() throws Exception
+ public void shouldCatchUpAfterFollowerMissesOneMessage() throws Exception
{
- shouldCatchUpAfterFollowerMissesAMessageTo(TestMessages.NO_OP);
+ shouldCatchUpAfterFollowerMissesMessage(TestMessages.NO_OP);
}
@Test(timeout = 30_000)
public void shouldCatchUpAfterFollowerMissesTimerRegistration() throws Exception
{
- shouldCatchUpAfterFollowerMissesAMessageTo(TestMessages.REGISTER_TIMER);
+ shouldCatchUpAfterFollowerMissesMessage(TestMessages.REGISTER_TIMER);
}
- private void shouldCatchUpAfterFollowerMissesAMessageTo(final String message) throws InterruptedException
+ private void shouldCatchUpAfterFollowerMissesMessage(final String message) throws InterruptedException
{
try (TestCluster cluster = TestCluster.startThreeNodeStaticCluster(NULL_VALUE))
{
@@ -669,7 +671,7 @@ public class ClusterTest
final Thread thread = new Thread(
() ->
{
- //final IdleStrategy idleStrategy = new YieldingIdleStrategy();
+ final IdleStrategy idleStrategy = new YieldingIdleStrategy();
cluster.msgBuffer().putStringWithoutLengthAscii(0, MSG);
while (true)
@@ -681,12 +683,13 @@ public class ClusterTest
return;
}
- cluster.client().pollEgress();
- LockSupport.parkNanos(intervalNs);
+ if (0 == cluster.client().pollEgress())
+ {
+ LockSupport.parkNanos(intervalNs);
+ }
}
- cluster.client().pollEgress();
- //idleStrategy.idle();
+ idleStrategy.idle(cluster.client().pollEgress());
}
});
diff --git a/aeron-cluster/src/test/java/io/aeron/cluster/TestMessages.java b/aeron-cluster/src/test/java/io/aeron/cluster/TestMessages.java
index <HASH>..<HASH> 100644
--- a/aeron-cluster/src/test/java/io/aeron/cluster/TestMessages.java
+++ b/aeron-cluster/src/test/java/io/aeron/cluster/TestMessages.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2014-2019 Real Logic Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
package io.aeron.cluster;
class TestMessages
|
[Java] Tidy up after merge of PR #<I> and yield when message flow stalls.
|
real-logic_aeron
|
train
|
a2e26459d95bee91c7643e90faccb8ca16695f3d
|
diff --git a/components/chat.js b/components/chat.js
index <HASH>..<HASH> 100644
--- a/components/chat.js
+++ b/components/chat.js
@@ -42,9 +42,17 @@ SteamCommunity.prototype.chatLogon = function(interval, uiMode) {
var self = this;
this.getWebApiOauthToken(function(err, token) {
if(err) {
+ var fatal = err.message.indexOf('not authorized') != -1;
+
+ if (!fatal) {
+ self.chatState = SteamCommunity.ChatState.LogOnFailed;
+ setTimeout(self.chatLogon.bind(self), 5000);
+ } else {
+ self.chatState = SteamCommunity.ChatState.Offline;
+ }
+
+ self.emit('chatLogOnFailed', err, fatal);
self.emit('debug', "Cannot get oauth token: " + err.message);
- self.chatState = SteamCommunity.ChatState.LogOnFailed;
- setTimeout(self.chatLogon.bind(self), 5000);
return;
}
@@ -57,15 +65,17 @@ SteamCommunity.prototype.chatLogon = function(interval, uiMode) {
"json": true
}, function(err, response, body) {
if(err || response.statusCode != 200) {
- self.emit('debug', 'Error logging into webchat: ' + (err ? err.message : "HTTP error " + response.statusCode));
self.chatState = SteamCommunity.ChatState.LogOnFailed;
+ self.emit('chatLogOnFailed', err ? err : new Error("HTTP error " + response.statusCode), false);
+ self.emit('debug', 'Error logging into webchat: ' + (err ? err.message : "HTTP error " + response.statusCode));
setTimeout(self.chatLogon.bind(self), 5000);
return;
}
if(body.error != 'OK') {
- self.emit('debug', 'Error logging into webchat: ' + body.error);
self.chatState = SteamCommunity.ChatState.LogOnFailed;
+ self.emit('chatLogOnFailed', new Error(body.error), false);
+ self.emit('debug', 'Error logging into webchat: ' + body.error);
setTimeout(self.chatLogon.bind(self), 5000);
return;
}
|
Emit chatLogOnFailed on error, and handle fatal errors (fixes #<I>)
|
DoctorMcKay_node-steamcommunity
|
train
|
09cdbc4e1cd0b14b5aa63f67fbb4233b8542a557
|
diff --git a/src/ajax.js b/src/ajax.js
index <HASH>..<HASH> 100644
--- a/src/ajax.js
+++ b/src/ajax.js
@@ -7,9 +7,12 @@
$.ajaxJSONP = function(options){
var jsonpString;
jsonpString = 'jsonp' + ++jsonpID;
- window[jsonpString] = options.success;
+ window[jsonpString] = function() {
+ options.success();
+ delete window.jsonpString;
+ };
var script = document.createElement('script');
- $(script).attr({ src: options.url.replace(/callback=\?/, 'callback=' + jsonpString) });
+ $(script).attr({ src: options.url.replace(/=\?/, '=' + jsonpString) });
$('head').append(script);
};
@@ -17,7 +20,7 @@
// { type, url, data, success, dataType, contentType }
options = options || {};
- if (options.url && /callback=\?/.test(options.url))
+ if (options.url && /=\?/.test(options.url))
return $.ajaxJSONP(options);
var data = options.data,
|
* Removed JSON-P memory leak.
* Simpler, shorter and safer JSON-P callback regexp (not everybody uses callback=).
|
madrobby_zepto
|
train
|
31102c7a7192fee43ae3647d4a60f5c9bc3b091c
|
diff --git a/mbed_connector_api/mbed_connector_api.py b/mbed_connector_api/mbed_connector_api.py
index <HASH>..<HASH> 100755
--- a/mbed_connector_api/mbed_connector_api.py
+++ b/mbed_connector_api/mbed_connector_api.py
@@ -326,7 +326,7 @@ class connector:
result.status_code = data.status_code
return result
- def deleteEnpointSubscriptions(self,ep):
+ def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
|
fixing typo in name of deleteEndpointSubscriptions function
|
ARMmbed_mbed-connector-api-python
|
train
|
08328ba4f90cba2faf1807c74219832541294bb9
|
diff --git a/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java
+++ b/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java
@@ -208,7 +208,7 @@ public class DiskSupport extends AbstractVolumeSupport {
}
}
}
- throw new CloudException("The volume: " + volumeId + " could not be found");
+ return null;
} catch (IOException ex) {
logger.error(ex.getMessage());
if (ex.getClass() == GoogleJsonResponseException.class) {
|
getVolume now returns null rather than an exception when volume not
found. matches what StatefulVolumeTest.removeVolume is expecting.
|
dasein-cloud_dasein-cloud-google
|
train
|
de57ab83003164ffe881869800d3f0e0145ee81f
|
diff --git a/lib/View.js b/lib/View.js
index <HASH>..<HASH> 100644
--- a/lib/View.js
+++ b/lib/View.js
@@ -226,7 +226,9 @@ class View {
*/
static addDomainData(variable, data) {
if (_.isArray(data)) {
- _.merge(variable, data);
+ data.forEach(function(v) {
+ variable.push(v);
+ });
} else {
variable.push(data);
}
|
fix issues with view appending more arrays
|
SandJS_http
|
train
|
f6efcbcc24ea429fdb63c5d239b4be3d074c95b1
|
diff --git a/src/ol/interaction/modifyinteraction.js b/src/ol/interaction/modifyinteraction.js
index <HASH>..<HASH> 100644
--- a/src/ol/interaction/modifyinteraction.js
+++ b/src/ol/interaction/modifyinteraction.js
@@ -18,7 +18,7 @@ goog.require('ol.geom.MultiPoint');
goog.require('ol.geom.MultiPolygon');
goog.require('ol.geom.Point');
goog.require('ol.geom.Polygon');
-goog.require('ol.interaction.Drag');
+goog.require('ol.interaction.Pointer');
goog.require('ol.structs.RBush');
@@ -35,7 +35,7 @@ ol.interaction.SegmentDataType;
/**
* @constructor
- * @extends {ol.interaction.Drag}
+ * @extends {ol.interaction.Pointer}
* @param {olx.interaction.ModifyOptions} options Options.
*/
ol.interaction.Modify = function(options) {
@@ -126,7 +126,7 @@ ol.interaction.Modify = function(options) {
};
};
-goog.inherits(ol.interaction.Modify, ol.interaction.Drag);
+goog.inherits(ol.interaction.Modify, ol.interaction.Pointer);
/**
@@ -158,7 +158,7 @@ ol.interaction.Modify.prototype.addFeature_ = function(evt) {
if (goog.isDef(this.SEGMENT_WRITERS_[geometry.getType()])) {
this.SEGMENT_WRITERS_[geometry.getType()].call(this, feature, geometry);
}
- this.handleMouseAtPixel_(this.lastPixel_, this.getMap());
+ this.handlePointerAtPixel_(this.lastPixel_, this.getMap());
};
@@ -368,7 +368,7 @@ ol.interaction.Modify.prototype.createOrUpdateVertexFeature_ =
/**
* @inheritDoc
*/
-ol.interaction.Modify.prototype.handleDragStart = function(evt) {
+ol.interaction.Modify.prototype.handlePointerDown = function(evt) {
this.dragSegments_ = [];
var vertexFeature = this.vertexFeature_;
if (!goog.isNull(vertexFeature)) {
@@ -408,7 +408,7 @@ ol.interaction.Modify.prototype.handleDragStart = function(evt) {
/**
* @inheritDoc
*/
-ol.interaction.Modify.prototype.handleDrag = function(evt) {
+ol.interaction.Modify.prototype.handlePointerDrag = function(evt) {
var vertex = evt.coordinate;
for (var i = 0, ii = this.dragSegments_.length; i < ii; ++i) {
var dragSegment = this.dragSegments_[i];
@@ -458,7 +458,7 @@ ol.interaction.Modify.prototype.handleDrag = function(evt) {
/**
* @inheritDoc
*/
-ol.interaction.Modify.prototype.handleDragEnd = function(evt) {
+ol.interaction.Modify.prototype.handlePointerUp = function(evt) {
var segmentData;
for (var i = this.dragSegments_.length - 1; i >= 0; --i) {
segmentData = this.dragSegments_[i][0];
@@ -474,9 +474,8 @@ ol.interaction.Modify.prototype.handleDragEnd = function(evt) {
ol.interaction.Modify.prototype.handleMapBrowserEvent =
function(mapBrowserEvent) {
if (!mapBrowserEvent.map.getView().getHints()[ol.ViewHint.INTERACTING] &&
- !this.getDragging() &&
- mapBrowserEvent.type == ol.MapBrowserEvent.EventType.MOUSEMOVE) {
- this.handleMouseMove_(mapBrowserEvent);
+ mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERMOVE) {
+ this.handlePointerMove_(mapBrowserEvent);
}
goog.base(this, 'handleMapBrowserEvent', mapBrowserEvent);
return !this.modifiable_;
@@ -487,9 +486,9 @@ ol.interaction.Modify.prototype.handleMapBrowserEvent =
* @param {ol.MapBrowserEvent} evt Event.
* @private
*/
-ol.interaction.Modify.prototype.handleMouseMove_ = function(evt) {
+ol.interaction.Modify.prototype.handlePointerMove_ = function(evt) {
this.lastPixel_ = evt.pixel;
- this.handleMouseAtPixel_(evt.pixel, evt.map);
+ this.handlePointerAtPixel_(evt.pixel, evt.map);
};
@@ -498,7 +497,7 @@ ol.interaction.Modify.prototype.handleMouseMove_ = function(evt) {
* @param {ol.Map} map Map.
* @private
*/
-ol.interaction.Modify.prototype.handleMouseAtPixel_ = function(pixel, map) {
+ol.interaction.Modify.prototype.handlePointerAtPixel_ = function(pixel, map) {
var pixelCoordinate = map.getCoordinateFromPixel(pixel);
var sortByDistance = function(a, b) {
return ol.coordinate.squaredDistanceToSegment(pixelCoordinate, a.segment) -
|
The Modify interaction now uses pointer events
While dragging a vertex, the feature on the original layer is
not updated until the first pointer move after dragging. See
#<I>. Previously, the Modify interaction did not set the
interacting hint on the view, so the feature was also updated
on the original layer. But now, the interacting hint is set,
which exposes this behaviour.
|
openlayers_openlayers
|
train
|
6037c1a0d5cd749fee65819654f1d5d8a1ca341b
|
diff --git a/scripts/logfetch/s3_logs.py b/scripts/logfetch/s3_logs.py
index <HASH>..<HASH> 100644
--- a/scripts/logfetch/s3_logs.py
+++ b/scripts/logfetch/s3_logs.py
@@ -42,10 +42,10 @@ def download_s3_logs(args):
logfetch_base.log(colored('Starting {0} S3 Downloads with {1} parallel fetches\n'.format(len(async_requests), args.num_parallel_fetches), 'cyan'), args, False)
callbacks.goal = len(async_requests)
grequests.map(async_requests, stream=True, size=args.num_parallel_fetches)
- all_logs = modify_download_list(all_logs)
else:
logfetch_base.log(colored('No S3 logs to download\n', 'cyan'), args, False)
logfetch_base.log(colored('All S3 logs up to date\n', 'cyan'), args, False)
+ all_logs = modify_download_list(all_logs)
return all_logs
def modify_download_list(all_logs):
diff --git a/scripts/setup.py b/scripts/setup.py
index <HASH>..<HASH> 100644
--- a/scripts/setup.py
+++ b/scripts/setup.py
@@ -11,7 +11,7 @@ requirements = [
setup(
name='singularity-logfetch',
- version='0.26.0',
+ version='0.26.1',
description='Singularity log fetching and searching',
author="HubSpot",
author_email='singularity-users@googlegroups.com',
|
bug fix for finding previously downloaded files when no s3 downloads are run
|
HubSpot_Singularity
|
train
|
a60f03f28e462edb700239a9242c5e3ac2059725
|
diff --git a/control/Director.php b/control/Director.php
index <HASH>..<HASH> 100644
--- a/control/Director.php
+++ b/control/Director.php
@@ -87,11 +87,18 @@ class Director {
array_merge((array)$_POST, (array)$_FILES),
@file_get_contents('php://input')
);
-
- // @todo find better way to extract HTTP headers
- if(isset($_SERVER['HTTP_ACCEPT'])) $req->addHeader("Accept", $_SERVER['HTTP_ACCEPT']);
- if(isset($_SERVER['CONTENT_TYPE'])) $req->addHeader("Content-Type", $_SERVER['CONTENT_TYPE']);
- if(isset($_SERVER['HTTP_REFERER'])) $req->addHeader("Referer", $_SERVER['HTTP_REFERER']);
+
+ // Load the request headers. If we're not running on Apache, then we
+ // need to manually extract the headers from the $_SERVER array.
+ if (function_exists('apache_request_headers')) {
+ $headers = apache_request_headers();
+ } else {
+ $headers = self::extract_request_headers($_SERVER);
+ }
+
+ foreach ($headers as $header => $value) {
+ $req->addHeader($header, $value);
+ }
// Load the session into the controller
$session = new Session(isset($_SESSION) ? $_SESSION : null);
@@ -536,7 +543,31 @@ class Director {
$relativeUrl = Director::makeRelative($url);
return (bool)self::is_relative_url($relativeUrl);
}
+
+ /**
+ * Takes a $_SERVER data array and extracts HTTP request headers.
+ *
+ * @param array $data
+ * @return array
+ */
+ protected static function extract_request_headers(array $server) {
+ $headers = array();
+
+ foreach($server as $key => $value) {
+ if(substr($key, 0, 5) == 'HTTP_') {
+ $key = substr($key, 5);
+ $key = strtolower(str_replace('_', ' ', $key));
+ $key = str_replace(' ', '-', ucwords($key));
+ $headers[$key] = $value;
+ }
+ }
+
+ if(isset($server['CONTENT_TYPE'])) $headers['Content-Type'] = $server['CONTENT_TYPE'];
+ if(isset($server['CONTENT_LENGTH'])) $headers['Content-Length'] = $server['CONTENT_LENGTH'];
+ return $headers;
+ }
+
/**
* Given a filesystem reference relative to the site root, return the full file-system path.
*
diff --git a/tests/control/DirectorTest.php b/tests/control/DirectorTest.php
index <HASH>..<HASH> 100644
--- a/tests/control/DirectorTest.php
+++ b/tests/control/DirectorTest.php
@@ -225,6 +225,41 @@ class DirectorTest extends SapphireTest {
$this->assertFalse($output);
}
+ /**
+ * @covers Director::extract_request_headers()
+ */
+ public function testExtractRequestHeaders() {
+ $request = array(
+ 'REDIRECT_STATUS' => '200',
+ 'HTTP_HOST' => 'host',
+ 'HTTP_USER_AGENT' => 'User Agent',
+ 'HTTP_ACCEPT' => 'text/html',
+ 'HTTP_ACCEPT_LANGUAGE' => 'en-us',
+ 'HTTP_COOKIE' => 'PastMember=1',
+ 'SERVER_PROTOCOL' => 'HTTP/1.1',
+ 'REQUEST_METHOD' => 'GET',
+ 'REQUEST_URI' => '/',
+ 'SCRIPT_NAME' => '/sapphire/main.php',
+ 'CONTENT_TYPE' => 'text/xml',
+ 'CONTENT_LENGTH' => 10
+ );
+
+ $headers = array(
+ 'Host' => 'host',
+ 'User-Agent' => 'User Agent',
+ 'Accept' => 'text/html',
+ 'Accept-Language' => 'en-us',
+ 'Cookie' => 'PastMember=1',
+ 'Content-Type' => 'text/xml',
+ 'Content-Length' => '10'
+ );
+
+ $method = new ReflectionMethod('Director', 'extract_request_headers');
+ $method->setAccessible(true);
+
+ $this->assertEquals($headers, $method->invoke(null, $request));
+ }
+
}
class DirectorTestRequest_Controller extends Controller implements TestOnly {
|
ENHANCEMENT Sapphire Doesn't Read HTTP Headers (fixes #<I>)
|
silverstripe_silverstripe-framework
|
train
|
911b16325bfb3c8df053cceef20cb24c5c7f0367
|
diff --git a/spyder/widgets/calltip.py b/spyder/widgets/calltip.py
index <HASH>..<HASH> 100644
--- a/spyder/widgets/calltip.py
+++ b/spyder/widgets/calltip.py
@@ -127,13 +127,6 @@ class ToolTipWidget(QLabel):
"""
Attempts to show the specified tip at the current cursor location.
"""
- # Don't attempt to show it if it's already visible and the text
- # to be displayed is the same as the one displayed before.
- if self.tip == tip:
- if not self.isVisible():
- self.show()
- return
-
# Set the text and resize the widget accordingly.
self.tip = tip
self.setText(tip)
diff --git a/spyder/widgets/mixins.py b/spyder/widgets/mixins.py
index <HASH>..<HASH> 100644
--- a/spyder/widgets/mixins.py
+++ b/spyder/widgets/mixins.py
@@ -635,17 +635,19 @@ class BaseEditMixin(object):
html_signature, extra_text, _ = res
point = self.get_word_start_pos(at_point)
- # This is needed to get hover hints
- cursor = self.cursorForPosition(at_point)
- cursor.movePosition(QTextCursor.StartOfWord, QTextCursor.MoveAnchor)
- self._last_hover_cursor = cursor
-
- self.show_tooltip(signature=html_signature, text=extra_text,
- at_point=point, inspect_word=inspect_word,
- display_link=True, max_lines=max_lines,
- max_width=max_width, cursor=cursor,
- text_new_line=text_new_line,
- completion_doc=completion_doc)
+ # Only display hover hint if there is documentation
+ if extra_text is not None:
+ # This is needed to get hover hints
+ cursor = self.cursorForPosition(at_point)
+ cursor.movePosition(QTextCursor.StartOfWord, QTextCursor.MoveAnchor)
+ self._last_hover_cursor = cursor
+
+ self.show_tooltip(signature=html_signature, text=extra_text,
+ at_point=point, inspect_word=inspect_word,
+ display_link=True, max_lines=max_lines,
+ max_width=max_width, cursor=cursor,
+ text_new_line=text_new_line,
+ completion_doc=completion_doc)
def hide_tooltip(self):
"""
|
Add check to prevent hover with no docs
|
spyder-ide_spyder
|
train
|
a081ad63d9af8686f1a383f168dfb79cbccfbf18
|
diff --git a/torrent.go b/torrent.go
index <HASH>..<HASH> 100644
--- a/torrent.go
+++ b/torrent.go
@@ -227,7 +227,6 @@ func (t *torrent) setMetadata(md metainfo.Info, dataDir string, infoBytes []byte
util.CopyExact(piece.Hash[:], hash)
t.Pieces = append(t.Pieces, piece)
piece.bytesLeftElement = t.IncompletePiecesByBytesLeft.Insert(index)
- t.pendAllChunkSpecs(pp.Integer(index))
}
t.assertIncompletePiecesByBytesLeftOrdering()
for _, conn := range t.Conns {
|
Save memory by not pending chunks prematurely
|
anacrolix_torrent
|
train
|
6da35dff78a8818df5bcf6bac98dc3e30729e8b0
|
diff --git a/spyder/widgets/variableexplorer/tests/test_dataframeeditor.py b/spyder/widgets/variableexplorer/tests/test_dataframeeditor.py
index <HASH>..<HASH> 100644
--- a/spyder/widgets/variableexplorer/tests/test_dataframeeditor.py
+++ b/spyder/widgets/variableexplorer/tests/test_dataframeeditor.py
@@ -335,5 +335,66 @@ def test_dataframeeditor_edit_overflow(qtbot, monkeypatch):
dialog.get_value().as_matrix()) == len(expected_df)
+def test_dataframemodel_set_data_complex(monkeypatch):
+ """Unit test #6115: editing complex dtypes raises error in df editor"""
+ MockQMessageBox = Mock()
+ attr_to_patch = ('spyder.widgets.variableexplorer' +
+ '.dataframeeditor.QMessageBox')
+ monkeypatch.setattr(attr_to_patch, MockQMessageBox)
+
+ test_params = [(1, numpy.complex128), (2, numpy.complex64), (3, complex)]
+
+ for count, complex_type in test_params:
+ test_df = DataFrame(numpy.arange(10, 15), dtype=complex_type)
+ model = DataFrameModel(test_df.copy())
+ index = model.createIndex(2, 1)
+ assert not model.setData(index, '42')
+ MockQMessageBox.critical.assert_called_with(
+ ANY, "Error", ("Editing dtype {0!s} not yet supported."
+ .format(type(test_df.iloc[2, 0]).__name__)))
+ assert MockQMessageBox.critical.call_count == count
+ assert numpy.sum(test_df[0].as_matrix() ==
+ model.df.as_matrix()) == len(test_df)
+
+
+@flaky(max_runs=3)
+def test_dataframeeditor_edit_complex(qtbot, monkeypatch):
+ """Test for #6115: editing complex dtypes raises error in df editor"""
+ MockQMessageBox = Mock()
+ attr_to_patch = ('spyder.widgets.variableexplorer' +
+ '.dataframeeditor.QMessageBox')
+ monkeypatch.setattr(attr_to_patch, MockQMessageBox)
+
+ test_params = [(1, numpy.complex128), (2, numpy.complex64), (3, complex)]
+
+ for count, complex_type in test_params:
+ test_df = DataFrame(numpy.arange(10, 15), dtype=complex_type)
+ dialog = DataFrameEditor()
+ assert dialog.setup_and_check(test_df, 'Test Dataframe')
+ dialog.show()
+ qtbot.waitForWindowShown(dialog)
+ view = dialog.dataTable
+
+ qtbot.keyPress(view, Qt.Key_Right)
+ qtbot.keyPress(view, Qt.Key_Down)
+ qtbot.keyPress(view, Qt.Key_Space)
+ qtbot.keyClicks(view.focusWidget(), "42")
+ qtbot.keyPress(view.focusWidget(), Qt.Key_Down)
+ MockQMessageBox.critical.assert_called_with(
+ ANY, "Error", ("Editing dtype {0!s} not yet supported."
+ .format(type(test_df.iloc[1, 0]).__name__)))
+ assert MockQMessageBox.critical.call_count == count * 2 - 1
+ qtbot.keyPress(view, Qt.Key_Down)
+ qtbot.keyClick(view, '1')
+ qtbot.keyPress(view.focusWidget(), Qt.Key_Down)
+ MockQMessageBox.critical.assert_called_with(
+ ANY, "Error", ("Editing dtype {0!s} not yet supported."
+ .format(type(test_df.iloc[1, 0]).__name__)))
+ assert MockQMessageBox.critical.call_count == count * 2
+ qtbot.keyPress(view, Qt.Key_Return)
+ assert numpy.sum(test_df[0].as_matrix() ==
+ dialog.get_value().as_matrix()) == len(test_df)
+
+
if __name__ == "__main__":
pytest.main()
|
Add tests to ensure errors are handled for dfs with complex dtypes
|
spyder-ide_spyder
|
train
|
9ee9071680fde34562ff0e23b50c9546030260a2
|
diff --git a/build.gradle b/build.gradle
index <HASH>..<HASH> 100644
--- a/build.gradle
+++ b/build.gradle
@@ -93,7 +93,6 @@ configure(javaprojects) {
// add tasks for finding and publishing .xsd files
apply from: "$buildSrcDir/schema-publication.gradle"
- commonsCodecVersion = '1.5'
h2Version = '1.3.155'
httpComponentsVersion = '4.1.1'
jacksonVersion = '1.8.1'
@@ -102,7 +101,7 @@ configure(javaprojects) {
mockitoVersion = '1.8.5'
servletApiVersion = '2.5'
springVersion = '3.1.0.M2'
- springSecurityVersion = '3.1.0.RC2'
+ springSecurityVersion = '3.1.0.CI-SNAPSHOT'
sourceSets {
main {
@@ -143,8 +142,7 @@ project('spring-social-core') {
dependencies {
compile ("org.springframework:spring-jdbc:$springVersion") { optional = true }
compile ("org.springframework:spring-web:$springVersion")
- compile ("org.springframework.security:spring-security-core:$springSecurityVersion") { provided = true }
- compile ("commons-codec:commons-codec:$commonsCodecVersion") { optional = true }
+ compile ("org.springframework.security:spring-security-crypto:$springSecurityVersion") { provided = true }
compile ("org.apache.httpcomponents:httpclient:$httpComponentsVersion") { optional = true }
testCompile "com.h2database:h2:$h2Version"
}
diff --git a/spring-social-core/src/main/java/org/springframework/social/connect/ConnectionRepository.java b/spring-social-core/src/main/java/org/springframework/social/connect/ConnectionRepository.java
index <HASH>..<HASH> 100644
--- a/spring-social-core/src/main/java/org/springframework/social/connect/ConnectionRepository.java
+++ b/spring-social-core/src/main/java/org/springframework/social/connect/ConnectionRepository.java
@@ -53,7 +53,7 @@ public interface ConnectionRepository {
/**
* Returns true if the current user is connected to the provider of the given API type e.g. Facebook.class.
- * Useful as a strongly-typed alternative to {@link #isConnected(String))}.
+ * Useful as a strongly-typed alternative to {@link #isConnected(String)}.
* @param apiType the apiType e.g. Facebook
* @return true if yes, false otherwise
*/
diff --git a/spring-social-core/src/main/java/org/springframework/social/oauth1/SigningSupport.java b/spring-social-core/src/main/java/org/springframework/social/oauth1/SigningSupport.java
index <HASH>..<HASH> 100644
--- a/spring-social-core/src/main/java/org/springframework/social/oauth1/SigningSupport.java
+++ b/spring-social-core/src/main/java/org/springframework/social/oauth1/SigningSupport.java
@@ -36,11 +36,11 @@ import java.util.Set;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
-import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
+import org.springframework.security.crypto.codec.Base64;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@@ -188,7 +188,7 @@ class SigningSupport {
mac.init(spec);
byte[] text = signatureBaseString.getBytes(UTF8_CHARSET_NAME);
byte[] signatureBytes = mac.doFinal(text);
- signatureBytes = Base64.encodeBase64(signatureBytes);
+ signatureBytes = Base64.encode(signatureBytes);
String signature = new String(signatureBytes, UTF8_CHARSET_NAME);
return signature;
} catch (NoSuchAlgorithmException e) {
diff --git a/spring-social-web/src/main/java/org/springframework/social/connect/web/ConnectController.java b/spring-social-web/src/main/java/org/springframework/social/connect/web/ConnectController.java
index <HASH>..<HASH> 100644
--- a/spring-social-web/src/main/java/org/springframework/social/connect/web/ConnectController.java
+++ b/spring-social-web/src/main/java/org/springframework/social/connect/web/ConnectController.java
@@ -78,7 +78,7 @@ public class ConnectController {
* Constructs a ConnectController.
* @param applicationUrl the base secure URL for this application, used to construct the callback URL passed to the service providers at the beginning of the connection process.
* @param connectionFactoryLocator the locator for {@link ConnectionFactory} instances needed to establish connections
- * @param connectionRepositoryProvider the provider of the current user's {@link ConnectionRepository} needed to persist connections
+ * @param connectionRepository the current user's {@link ConnectionRepository} needed to persist connections; must be a proxy to a request-scoped bean
*/
@Inject
public ConnectController(String applicationUrl, ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
|
removed codec dependency in favor of spring security crypto
|
spring-projects_spring-social
|
train
|
9d36b140c8a360c3d2df2590639ba16bb603e4bf
|
diff --git a/demo/javascripts/vendor/jquery.hideseek.min.js b/demo/javascripts/vendor/jquery.hideseek.min.js
index <HASH>..<HASH> 100644
--- a/demo/javascripts/vendor/jquery.hideseek.min.js
+++ b/demo/javascripts/vendor/jquery.hideseek.min.js
@@ -4,7 +4,7 @@
* @copyright Copyright 2015, Dimitris Krestos
* @license Apache License, Version 2.0 (http://www.opensource.org/licenses/apache2.0.php)
* @link http://vdw.staytuned.gr
- * @version v0.7.0
+ * @version v0.7.1
*
* Dependencies are include in minified versions at the bottom:
* 1. Highlight v4 by Johann Burkard
diff --git a/hideseek.jquery.json b/hideseek.jquery.json
index <HASH>..<HASH> 100644
--- a/hideseek.jquery.json
+++ b/hideseek.jquery.json
@@ -9,7 +9,7 @@
"jquery",
"hideseek"
],
- "version": "0.7.0",
+ "version": "0.7.1",
"author": {
"name": "Dimitris Krestos",
"email": "dkrestos@gmail.com",
diff --git a/jquery.hideseek.js b/jquery.hideseek.js
index <HASH>..<HASH> 100644
--- a/jquery.hideseek.js
+++ b/jquery.hideseek.js
@@ -4,7 +4,7 @@
* @copyright Copyright 2015, Dimitris Krestos
* @license Apache License, Version 2.0 (http://www.opensource.org/licenses/apache2.0.php)
* @link http://vdw.staytuned.gr
- * @version v0.7.0
+ * @version v0.7.1
*
* Dependencies are include in minified versions at the bottom:
* 1. Highlight v4 by Johann Burkard
diff --git a/jquery.hideseek.min.js b/jquery.hideseek.min.js
index <HASH>..<HASH> 100644
--- a/jquery.hideseek.min.js
+++ b/jquery.hideseek.min.js
@@ -4,7 +4,7 @@
* @copyright Copyright 2015, Dimitris Krestos
* @license Apache License, Version 2.0 (http://www.opensource.org/licenses/apache2.0.php)
* @link http://vdw.staytuned.gr
- * @version v0.7.0
+ * @version v0.7.1
*
* Dependencies are include in minified versions at the bottom:
* 1. Highlight v4 by Johann Burkard
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "hideseek",
- "version": "0.7.0",
+ "version": "0.7.1",
"description": "A simple, yet customizable live search jQuery plugin.",
"main": "jquery.hideseek.js",
"repository": {
|
Bump up version
<I>
|
vdw_HideSeek
|
train
|
507ba06be6f34aba27289790bab94811e4e57427
|
diff --git a/src/mdptoolbox/__init__.py b/src/mdptoolbox/__init__.py
index <HASH>..<HASH> 100644
--- a/src/mdptoolbox/__init__.py
+++ b/src/mdptoolbox/__init__.py
@@ -7,11 +7,12 @@ descrete-time Markov Decision Processes.
Available modules
-----------------
-example
+
+:mod:`~mdptoolbox.example`
Examples of transition and reward matrices that form valid MDPs
-mdp
+:mod:`~mdptoolbox.mdp`
Makov decision process algorithms
-util
+:mod:`~mdptoolbox.util`
Functions for validating and working with an MDP
How to use the documentation
diff --git a/src/mdptoolbox/example.py b/src/mdptoolbox/example.py
index <HASH>..<HASH> 100644
--- a/src/mdptoolbox/example.py
+++ b/src/mdptoolbox/example.py
@@ -7,10 +7,13 @@ reward matrices.
Available functions
-------------------
-forest
+
+:func:`~mdptoolbox.example.forest`
A simple forest management example
-rand
+:func:`~mdptoolbox.example.rand`
A random example
+:func:`~mdptoolbox.example.small`
+ A very small example
"""
diff --git a/src/mdptoolbox/mdp.py b/src/mdptoolbox/mdp.py
index <HASH>..<HASH> 100644
--- a/src/mdptoolbox/mdp.py
+++ b/src/mdptoolbox/mdp.py
@@ -7,21 +7,21 @@ Decision Processes.
Available classes
-----------------
-MDP
+:class:`~mdptoolbox.mdp.MDP`
Base Markov decision process class
-FiniteHorizon
+:class:`~mdptoolbox.mdp.FiniteHorizon`
Backwards induction finite horizon MDP
-PolicyIteration
+:class:`~mdptoolbox.mdp.PolicyIteration`
Policy iteration MDP
-PolicyIterationModified
+:class:`~mdptoolbox.mdp.PolicyIterationModified`
Modified policy iteration MDP
-QLearning
+:class:`~mdptoolbox.mdp.QLearning`
Q-learning MDP
-RelativeValueIteration
+:class:`~mdptoolbox.mdp.RelativeValueIteration`
Relative value iteration MDP
-ValueIteration
+:class:`~mdptoolbox.mdp.ValueIteration`
Value iteration MDP
-ValueIterationGS
+:class:`~mdptoolbox.mdp.ValueIterationGS`
Gauss-Seidel value iteration MDP
"""
diff --git a/src/mdptoolbox/util.py b/src/mdptoolbox/util.py
index <HASH>..<HASH> 100644
--- a/src/mdptoolbox/util.py
+++ b/src/mdptoolbox/util.py
@@ -8,17 +8,18 @@ solved.
Available functions
-------------------
-check
+
+:func:`~mdptoolbox.util.check`
Check that an MDP is properly defined
-checkSquareStochastic
+:func:`~mdptoolbox.util.checkSquareStochastic`
Check that a matrix is square and stochastic
-getSpan
+:func:`~mdptoolbox.util.getSpan`
Calculate the span of an array
-isNonNegative
+:func:`~mdptoolbox.util.isNonNegative`
Check if a matrix has only non-negative elements
-isSquare
+:func:`~mdptoolbox.util.isSquare`
Check if a matrix is square
-isStochastic
+:func:`~mdptoolbox.util.isStochastic`
Check if a matrix is row stochastic
"""
|
Add directives to module docstrings
Link to the modules, classes or functions that each module provides in
the module level docstring.
|
sawcordwell_pymdptoolbox
|
train
|
e16d23bfcc356c25aa9d8887852d205474332684
|
diff --git a/core/src/main/java/hudson/model/Hudson.java b/core/src/main/java/hudson/model/Hudson.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/model/Hudson.java
+++ b/core/src/main/java/hudson/model/Hudson.java
@@ -154,6 +154,7 @@ import org.jvnet.hudson.reactor.ReactorListener;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
+import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
@@ -550,6 +551,24 @@ public final class Hudson extends Node implements ItemGroup<TopLevelItem>, Stapl
protected File getRootDirFor(String name) {
return Hudson.this.getRootDirFor(name);
}
+
+ /**
+ *send the browser to the config page
+ * use View to trim view/{default-view} from URL if possible
+ */
+ @Override
+ protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
+ String redirect = result.getUrl()+"configure";
+ List<Ancestor> ancestors = req.getAncestors();
+ for (int i = ancestors.size() - 1; i >= 0; i--) {
+ Object o = ancestors.get(i).getObject();
+ if (o instanceof View) {
+ redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect;
+ break;
+ }
+ }
+ return redirect;
+ }
};
@CLIResolver
diff --git a/core/src/main/java/hudson/model/ItemGroupMixIn.java b/core/src/main/java/hudson/model/ItemGroupMixIn.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/model/ItemGroupMixIn.java
+++ b/core/src/main/java/hudson/model/ItemGroupMixIn.java
@@ -117,6 +117,7 @@ public abstract class ItemGroupMixIn {
/**
* Creates a {@link TopLevelItem} from the submission of the '/lib/hudson/newFromList/formList'
+ * or throws an exception if it fails.
*/
public synchronized TopLevelItem createTopLevelItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
acl.checkPermission(Job.CREATE);
@@ -150,9 +151,8 @@ public abstract class ItemGroupMixIn {
else
throw new Failure("No such job: "+from);
}
- if (!(src instanceof TopLevelItem)) {
+ if (!(src instanceof TopLevelItem))
throw new Failure(from+" cannot be copied");
- }
result = copy((TopLevelItem) src,name);
} else {
@@ -169,22 +169,18 @@ public abstract class ItemGroupMixIn {
}
}
- // send the browser to the config page
- // use View to trim view/{default-view} from URL if possible
- String redirect = result.getUrl()+"configure";
- List<Ancestor> ancestors = req.getAncestors();
- for (int i = ancestors.size() - 1; i >= 0; i--) {
- Object o = ancestors.get(i).getObject();
- if (o instanceof View) {
- redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect;
- break;
- }
- }
- rsp.sendRedirect2(redirect);
+ rsp.sendRedirect2(redirectAfterCreateItem(req, result)+"configure");
return result;
}
/**
+ * Computes the redirection target URL for the newly created {@link TopLevelItem}.
+ */
+ protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
+ return req.getContextPath()+'/'+result.getUrl()+"configure";
+ }
+
+ /**
* Copies an existing {@link TopLevelItem} to a new name.
*
* The caller is responsible for calling {@link ItemListener#fireOnCopied(Item, Item)}. This method
|
Hudson does a very tricky redirection for Views. Shouldn't apply to the rest of ItemGroups
|
jenkinsci_jenkins
|
train
|
dfc4173e5bba15ba21e3fc24272c3a36f9e85859
|
diff --git a/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java b/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java
index <HASH>..<HASH> 100644
--- a/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java
+++ b/smack-core/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java
@@ -45,6 +45,12 @@ import java.util.List;
*/
public class ConnectionConfiguration implements Cloneable {
+ static {
+ // Ensure that Smack is initialized when ConnectionConfiguration is used, or otherwise e.g.
+ // SmackConfiguration.DEBUG_ENABLED may not be initialized yet.
+ SmackConfiguration.getVersion();
+ }
+
/**
* Hostname of the XMPP server. Usually servers use the same service name as the name
* of the server. However, there are some servers like google where host would be
diff --git a/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java b/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java
index <HASH>..<HASH> 100644
--- a/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java
+++ b/smack-core/src/main/java/org/jivesoftware/smack/SmackInitialization.java
@@ -120,7 +120,11 @@ public final class SmackInitialization {
// Use try block since we may not have permission to get a system
// property (for example, when an applet).
try {
- SmackConfiguration.DEBUG_ENABLED = Boolean.getBoolean("smack.debugEnabled");
+ // Only overwrite DEBUG_ENABLED if it is set via the 'smack.debugEnabled' property. To prevent DEBUG_ENABLED
+ // = true, which could be set e.g. via a static block from user code, from being overwritten by the property not set
+ if (Boolean.getBoolean("smack.debugEnabled")) {
+ SmackConfiguration.DEBUG_ENABLED = true;
+ }
}
catch (Exception e) {
// Ignore.
|
Fix initialization order issue with DEBUG_ENABLED
If a user enabled Smack debug via the property 'smack.debugEnabled', a
ConnectionConfiguration could be created where debuggerEnabled is
'false', because Smack is not yet initialized.
Also make sure that if the property is not set, it won't overwrite
DEBUG_ENABLED = true.
Thanks to William Murphy for providing a detailed issue description and
supposing a fix.
|
igniterealtime_Smack
|
train
|
152bb06d94e34510327165ceec79eac8ba2bfd72
|
diff --git a/argcomplete/my_shlex.py b/argcomplete/my_shlex.py
index <HASH>..<HASH> 100644
--- a/argcomplete/my_shlex.py
+++ b/argcomplete/my_shlex.py
@@ -147,8 +147,6 @@ class shlex:
return raw
def read_token(self):
- # Modified by argcomplete: Record last wordbreak position
- self.last_wordbreak_pos = None
quoted = False
escapedstate = ' '
while True:
@@ -294,6 +292,9 @@ class shlex:
print("shlex: raw token=" + repr(result))
else:
print("shlex: raw token=EOF")
+ # Modified by argcomplete: Record last wordbreak position
+ if self.state == ' ':
+ self.last_wordbreak_pos = None
return result
def sourcehook(self, newfile):
diff --git a/test/test.py b/test/test.py
index <HASH>..<HASH> 100755
--- a/test/test.py
+++ b/test/test.py
@@ -864,7 +864,12 @@ class TestSplitLine(unittest.TestCase):
self.assertEqual(self.wordbreak('a'), None)
self.assertEqual(self.wordbreak('a b:c'), 1)
self.assertEqual(self.wordbreak('a b:c=d'), 3)
+ self.assertEqual(self.wordbreak('a b:c=d '), None)
self.assertEqual(self.wordbreak('a b:c=d e'), None)
+ self.assertEqual(self.wordbreak('"b:c'), None)
+ self.assertEqual(self.wordbreak('"b:c=d'), None)
+ self.assertEqual(self.wordbreak('"b:c=d"'), None)
+ self.assertEqual(self.wordbreak('"b:c=d" '), None)
class _TestSh(object):
|
Fix completion after tokens with wordbreak chars (#<I>)
|
kislyuk_argcomplete
|
train
|
0bb9361b1a4ae429ce295c751a0c8348ec02525b
|
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index <HASH>..<HASH> 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -18,6 +18,13 @@ v0.5.3 (unreleased)
- Dataset variables are now written to netCDF files in order of appearance
when using the netcdf4 backend (:issue:`479`).
+
+Bug fixes
+~~~~~~~~~
+
+- Fixed aggregation functions (e.g., sum and mean) on big-endian arrays when
+ bottleneck is installed (:issue:`489`).
+
v0.5.2 (16 July 2015)
---------------------
diff --git a/xray/core/ops.py b/xray/core/ops.py
index <HASH>..<HASH> 100644
--- a/xray/core/ops.py
+++ b/xray/core/ops.py
@@ -287,7 +287,12 @@ def _create_nan_agg_method(name, numeric_only=False, coerce_strings=False):
'skipna=True not yet implemented for %s with dtype %s'
% (name, values.dtype))
nanname = 'nan' + name
- eager_module = np if isinstance(axis, tuple) else bn
+ if isinstance(axis, tuple) or not values.dtype.isnative:
+ # bottleneck can't handle multiple axis arguments or non-native
+ # endianness
+ eager_module = np
+ else:
+ eager_module = bn
func = _dask_or_eager_func(nanname, eager_module)
using_numpy_nan_func = eager_module is np
else:
diff --git a/xray/test/test_variable.py b/xray/test/test_variable.py
index <HASH>..<HASH> 100644
--- a/xray/test/test_variable.py
+++ b/xray/test/test_variable.py
@@ -709,6 +709,13 @@ class TestVariable(TestCase, VariableSubclassTestCases):
with self.assertRaisesRegexp(ValueError, 'cannot supply both'):
v.mean(dim='x', axis=0)
+ def test_big_endian_reduce(self):
+ # regression test for GH489
+ data = np.ones(5, dtype='>f4')
+ v = Variable(['x'], data)
+ expected = Variable([], 5)
+ self.assertVariableIdentical(expected, v.sum())
+
def test_reduce_funcs(self):
v = Variable('x', np.array([1, np.nan, 2, 3]))
self.assertVariableIdentical(v.mean(), Variable([], 2))
|
Fix aggregation on big-endian arrays with bottleneck installed
Fixes GH<I>
|
pydata_xarray
|
train
|
040aebe993b5815897dc3fadd9b6ccafca8c433e
|
diff --git a/src/Commands/Setup.php b/src/Commands/Setup.php
index <HASH>..<HASH> 100644
--- a/src/Commands/Setup.php
+++ b/src/Commands/Setup.php
@@ -3,6 +3,7 @@
namespace Kelunik\AcmeClient\Commands;
use Amp\CoroutineResult;
+use Amp\Dns\NoRecordException;
use Amp\Dns\Record;
use Amp\Dns\ResolutionException;
use InvalidArgumentException;
@@ -80,8 +81,10 @@ class Setup implements Command {
try {
yield \Amp\Dns\query($host, Record::MX);
- } catch (ResolutionException $e) {
+ } catch (NoRecordException $e) {
throw new AcmeException("No MX record defined for '{$host}'");
+ } catch (ResolutionException $e) {
+ throw new AcmeException("Dns query for an MX record on '{$host}' failed for the following reason: " . $e->getMessage(), null, $e);
}
}
|
Improve error message on timed out MX query
Any error, not only NoRecordExceptions, resulted in a MX record not found
error message. The previous message is now only shown if there's really no
record. Otherwise a more generic message is shown now.
Fixes #<I>.
|
kelunik_acme-client
|
train
|
6d54824e985f3c32f09b86f5d6eb867fe224ffff
|
diff --git a/test_pem.py b/test_pem.py
index <HASH>..<HASH> 100644
--- a/test_pem.py
+++ b/test_pem.py
@@ -162,9 +162,9 @@ class TestCertificateOptionsFromFiles(object):
ssl = pytest.importorskip('OpenSSL.SSL')
ctxFactory = pem.certificateOptionsFromFiles(
str(allFile),
- method=ssl.SSLv2_METHOD,
+ method=ssl.TLSv1_METHOD,
)
- assert ssl.SSLv2_METHOD == ctxFactory.method
+ assert ssl.TLSv1_METHOD == ctxFactory.method
def test_catchesMissingKey(self, tmpdir):
pytest.importorskip('twisted')
|
SSLv2_METHOD is gone
|
hynek_pem
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.