hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
dc8aabeed0fdc618dec3b246099a09b02c6006a6
|
diff --git a/packages/postcss-convert-values/CHANGELOG.md b/packages/postcss-convert-values/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/packages/postcss-convert-values/CHANGELOG.md
+++ b/packages/postcss-convert-values/CHANGELOG.md
@@ -1,3 +1,8 @@
+# 2.3.4
+
+* Does not convert `height:0%` to `height:0` (and the same for `max-height`), as
+ they produce different results.
+
# 2.3.3
* Updates postcss-value-parser to version 3 (thanks to @TrySound).
diff --git a/packages/postcss-convert-values/src/__tests__/index.js b/packages/postcss-convert-values/src/__tests__/index.js
index <HASH>..<HASH> 100644
--- a/packages/postcss-convert-values/src/__tests__/index.js
+++ b/packages/postcss-convert-values/src/__tests__/index.js
@@ -170,6 +170,14 @@ let tests = [{
message: 'should not remove unit with zero value in hsl and hsla functions',
fixture: 'h1{color:hsl(0, 0%, 244%); background:hsl(0, 0%, 0%)}',
expected: 'h1{color:hsl(0, 0%, 244%); background:hsl(0, 0%, 0%)}'
+}, {
+ message: 'should strip trailing zeroes from percentage heights',
+ fixture: 'h1{height:12.500%}',
+ expected: 'h1{height:12.5%}'
+}, {
+ message: 'should not strip the percentage from 0 in max-height & height props',
+ fixture: 'h1{height:0%;max-height:0%}',
+ expected: 'h1{height:0%;max-height:0%}'
}];
function process (css, options) {
diff --git a/packages/postcss-convert-values/src/index.js b/packages/postcss-convert-values/src/index.js
index <HASH>..<HASH> 100644
--- a/packages/postcss-convert-values/src/index.js
+++ b/packages/postcss-convert-values/src/index.js
@@ -32,7 +32,14 @@ function transform (opts) {
decl.value = valueParser(decl.value).walk(node => {
if (node.type === 'word') {
- parseWord(node, opts);
+ if (
+ (decl.prop === 'max-height' || decl.prop === 'height') &&
+ ~decl.value.indexOf('%')
+ ) {
+ parseWord(node, opts, true);
+ } else {
+ parseWord(node, opts);
+ }
} else if (node.type === 'function') {
if (node.value === 'calc' ||
node.value === 'hsl' ||
|
Don't convert height:0% to height:0.
|
cssnano_cssnano
|
train
|
eff3f6c90428ddd2d988c9b686d92488c6430b77
|
diff --git a/reflect.go b/reflect.go
index <HASH>..<HASH> 100644
--- a/reflect.go
+++ b/reflect.go
@@ -267,6 +267,9 @@ func (r *Reflector) reflectStructFields(st *Type, definitions Definitions, t ref
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
+ if t.Kind() != reflect.Struct {
+ return
+ }
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
// anonymous and exported type should be processed recursively
diff --git a/reflect_test.go b/reflect_test.go
index <HASH>..<HASH> 100644
--- a/reflect_test.go
+++ b/reflect_test.go
@@ -31,6 +31,8 @@ type SomeBaseType struct {
someUnexportedUntaggedBaseProperty bool
}
+type MapType map[string]interface{}
+
type nonExported struct {
PublicNonExported int
privateNonExported int
@@ -48,6 +50,7 @@ const (
type TestUser struct {
SomeBaseType
nonExported
+ MapType
ID int `json:"id" jsonschema:"required"`
Name string `json:"name" jsonschema:"required,minLength=1,maxLength=20,pattern=.*,description=this is a property,title=the name,example=joe,example=lucy,default=alex"`
|
fix: ignore anonymous fields if not of type struct
|
alecthomas_jsonschema
|
train
|
e964b9fb182351f55c815536e922a6c16e682b7e
|
diff --git a/lib/redfish/tasks/domain.rb b/lib/redfish/tasks/domain.rb
index <HASH>..<HASH> 100644
--- a/lib/redfish/tasks/domain.rb
+++ b/lib/redfish/tasks/domain.rb
@@ -180,6 +180,13 @@ module Redfish
# This line is probably not needed outside tests...
create_dir("#{context.domain_directory}/config", 0700)
+ # Setup a temp directory so can configure domain to write to this
+ # location rather than global temp directory
+ create_dir("#{context.domain_directory}/tmp", 0700)
+
+ # Setup preferences directory so preferences are stored within the domain dir
+ create_dir("#{context.domain_directory}/prefs", 0700)
+
pass_file = context.domain_password_file_location
File.open(pass_file, 'wb') do |f|
f.write <<-PASS
diff --git a/lib/redfish_plus/dsl.rb b/lib/redfish_plus/dsl.rb
index <HASH>..<HASH> 100644
--- a/lib/redfish_plus/dsl.rb
+++ b/lib/redfish_plus/dsl.rb
@@ -236,6 +236,8 @@ module RedfishPlus
# Standard configuration used across all of our GlassFish instances
def standard_domain_setup(domain)
set_payara_domain_template(domain)
+ set_user_prefs_dir(domain)
+ set_tmpdir(domain)
disable_update_tool(domain)
enable_implicit_cdi(domain)
setup_default_admin(domain)
@@ -336,6 +338,14 @@ module RedfishPlus
end
end
+ def set_user_prefs_dir(domain)
+ domain.data['jvm_options']['defines']['java.util.prefs.userRoot'] = '{{domain_directory}}/prefs'
+ end
+
+ def set_tmpdir(domain)
+ domain.data['jvm_options']['defines']['java.io.tmpdir'] = '{{domain_directory}}/tmp'
+ end
+
def disable_update_tool(domain)
domain.data['jvm_options']['defines']['com.sun.enterprise.tools.admingui.NO_NETWORK'] = 'true'
end
diff --git a/test/tasks/test_domain.rb b/test/tasks/test_domain.rb
index <HASH>..<HASH> 100644
--- a/test/tasks/test_domain.rb
+++ b/test/tasks/test_domain.rb
@@ -772,6 +772,8 @@ AS_ADMIN_PASSWORD=secret1
assert_domain_directory('lib', '755')
assert_domain_directory('lib/ext', '755')
assert_domain_directory('docroot', '755')
+ assert_domain_directory('tmp', '700')
+ assert_domain_directory('prefs', '700')
end
def assert_domain_directory(filename, mode)
|
Create tmp and prefs directories as part of domain and use them in the domain
|
realityforge_redfish
|
train
|
75cbc99c55a4e5d66c98bb7374edac83b61e80be
|
diff --git a/webwhatsapi/__init__.py b/webwhatsapi/__init__.py
index <HASH>..<HASH> 100755
--- a/webwhatsapi/__init__.py
+++ b/webwhatsapi/__init__.py
@@ -264,7 +264,7 @@ class WhatsAPIDriver(object):
# instead we use this (temporary) solution:
# return 'class="app _3dqpi two"' in self.driver.page_source
- return self.wapi_functions.isLoggedIn()
+ return self.driver.execute_script("if (document.querySelector('*[data-icon=chat]') !== null) { return true } else { return false }")
def is_connected(self):
"""Returns if user's phone is connected to the internet."""
diff --git a/webwhatsapi/wapi_js_wrapper.py b/webwhatsapi/wapi_js_wrapper.py
index <HASH>..<HASH> 100755
--- a/webwhatsapi/wapi_js_wrapper.py
+++ b/webwhatsapi/wapi_js_wrapper.py
@@ -63,15 +63,18 @@ class WapiJsWrapper(object):
script_path = os.path.dirname(os.path.abspath(__file__))
except NameError:
script_path = os.getcwd()
- with open(os.path.join(script_path, "js", "wapi.js"), "r") as script:
- self.driver.execute_script(script.read())
- result = self.driver.execute_script("return window.WAPI")
+ result = self.driver.execute_script("if (document.querySelector('*[data-icon=chat]') !== null) { return true } else { return false }")
if result:
- self.available_functions = result.keys()
- return self.available_functions
- else:
- return []
+ with open(os.path.join(script_path, "js", "wapi.js"), "r") as script:
+ self.driver.execute_script(script.read())
+
+ result = self.driver.execute_script("return window.WAPI")
+ if result:
+ self.available_functions = result.keys()
+ return self.available_functions
+ else:
+ return []
def quit(self):
self.new_messages_observable.stop()
|
Fix wapi.js injection (#<I>)
* Updated is_logged_in function
This function now support login verification even if WAPI.js wasn't injected
* Fix wapi.js injection
wapi.js can only be injected after user logged in
|
mukulhase_WebWhatsapp-Wrapper
|
train
|
ad6227fea620f0265207d011d626a5d5eff2a03a
|
diff --git a/test/lib/types/library/LibraryFormatter.js b/test/lib/types/library/LibraryFormatter.js
index <HASH>..<HASH> 100644
--- a/test/lib/types/library/LibraryFormatter.js
+++ b/test/lib/types/library/LibraryFormatter.js
@@ -166,6 +166,69 @@ test("validate: test invalid encoding", async (t) => {
`test. Must be either "ISO-8859-1" or "UTF-8".`, "Missing source directory caused error");
});
+test("format and validate non-ASCII project correctly", async (t) => {
+ const libraryØPath = path.join(__dirname, "..", "..", "..", "fixtures", "library.ø");
+ const myProject = {
+ id: "library.ø.id",
+ version: "1.0.0",
+ path: libraryØPath,
+ dependencies: [],
+ _level: 0,
+ _isRoot: true,
+ specVersion: "2.0",
+ type: "library",
+ metadata: {
+ name: "library.ø",
+ namespace: "library/ø",
+ copyright: "Some fancy copyright"
+ },
+ resources: {
+ configuration: {
+ paths: {
+ src: "máin/ßrc",
+ test: "máin/吉"
+ }
+ },
+ pathMappings: {
+ "/resources/": "máin/ßrc",
+ "/test-resources/": "máin/吉"
+ }
+ }
+ };
+ myProject.metadata.copyright = undefined;
+ const libraryFormatter = new LibraryFormatter({project: myProject});
+
+ await libraryFormatter.format();
+ t.deepEqual(myProject, {
+ id: "library.ø.id",
+ version: "1.0.0",
+ path: libraryØPath,
+ dependencies: [],
+ _level: 0,
+ _isRoot: true,
+ specVersion: "2.0",
+ type: "library",
+ metadata: {
+ name: "library.ø",
+ namespace: "library/ø",
+ copyright: "Some fancy copyright"
+ },
+ resources: {
+ configuration: {
+ paths: {
+ src: "máin/ßrc",
+ test: "máin/吉"
+ },
+ propertiesFileSourceEncoding: "UTF-8"
+ },
+ pathMappings: {
+ "/resources/": "máin/ßrc",
+ "/test-resources/": "máin/吉"
+ }
+ }
+ }, "Project got formatted correctly");
+});
+
test("format: copyright already configured", async (t) => {
const myProject = clone(libraryETree);
const libraryFormatter = new LibraryFormatter({project: myProject});
|
[INTERNAL] LibraryFormatter: Add test for library containing non-ASCII characters
|
SAP_ui5-builder
|
train
|
1e7913204c940f50256906bfb74d22a692b71088
|
diff --git a/tweetpony/api.py b/tweetpony/api.py
index <HASH>..<HASH> 100644
--- a/tweetpony/api.py
+++ b/tweetpony/api.py
@@ -240,7 +240,7 @@ class API(object):
except ValueError:
pass
elif type(value) in [str, unicode]:
- value = open(value, 'r')
+ value = open(value, 'rb')
del _params[key]
if key == 'media':
key = 'media[]'
@@ -309,7 +309,7 @@ class API(object):
missing_params = []
for param in data['required_params']:
- p = kwargs.get(param) or files.get(param)
+ p = files.get(param) or kwargs.get(param)
if p is None:
missing_params.append(param)
if missing_params:
|
update_status_with_media call change
Change 'r' to 'rb' mode to ensure filename/pathtofilename parameter (string) passed as media[] argument works
u'' or None instead of None or u'' will fix missing parameter status issue in case of empty tweet and valid photo file(passed as filename/pathtofilename mentioned above)
|
Mezgrman_TweetPony
|
train
|
9ba66f1b84200242519fc5f25fc5175809ddba4f
|
diff --git a/xds/internal/xdsclient/authority.go b/xds/internal/xdsclient/authority.go
index <HASH>..<HASH> 100644
--- a/xds/internal/xdsclient/authority.go
+++ b/xds/internal/xdsclient/authority.go
@@ -54,7 +54,9 @@ func (c *clientImpl) findAuthority(n *xdsresource.Name) (_ *authority, unref fun
if !ok {
return nil, nil, fmt.Errorf("xds: failed to find authority %q", authority)
}
- config = cfg.XDSServer
+ if cfg.XDSServer != nil {
+ config = cfg.XDSServer
+ }
}
a, err := c.newAuthorityLocked(config)
|
xdsclient: use top-level server list if authority specific list is empty (#<I>)
|
grpc_grpc-go
|
train
|
dbab46d5f8228f8dd56bbca2e63405e818c598f9
|
diff --git a/lib/oxidized/input/ssh.rb b/lib/oxidized/input/ssh.rb
index <HASH>..<HASH> 100644
--- a/lib/oxidized/input/ssh.rb
+++ b/lib/oxidized/input/ssh.rb
@@ -42,7 +42,7 @@ module Oxidized
unless @exec
shell_open @ssh
begin
- @username ? shell_login : expect(@node.prompt)
+ login
rescue Timeout::Error
raise PromptUndetect, [ @output, 'not matching configured prompt', @node.prompt ].join(' ')
end
@@ -102,13 +102,18 @@ module Oxidized
end
end
- # Cisco WCS has extremely dubious SSH implementation, SSH auth is always
- # success, it always opens shell and then run auth in shell. I guess
- # they'll never support exec() :)
- def shell_login
- expect username
- cmd @node.auth[:username], password
- cmd @node.auth[:password]
+ # some models have SSH auth or terminal auth based on version of code
+ # if SSH is configured for terminal auth, we'll still try to detect prompt
+ def login
+ if @username
+ match = expect username, @node.prompt
+ if match == username
+ cmd @node.auth[:username], password
+ cmd @node.auth[:password]
+ end
+ else
+ expect @node.prompt
+ end
end
def exec state=nil
@@ -123,14 +128,18 @@ module Oxidized
@output
end
- def expect regexp
- Oxidized.logger.debug "lib/oxidized/input/ssh.rb: expecting #{regexp.inspect} at #{node.name}"
+ def expect *regexps
+ regexps = [regexps].flatten
+ Oxidized.logger.debug "lib/oxidized/input/ssh.rb: expecting #{regexps.inspect} at #{node.name}"
Timeout::timeout(Oxidized.config.timeout) do
@ssh.loop(0.1) do
sleep 0.1
- not @output.match regexp
+ match = regexps.find { |regexp| @output.match regexp }
+ return match if match
+ true
end
end
end
+
end
end
|
support terminal and ssh auth for same model
Some boxes like prokurwa may authenticate via SSH (proper), or may have
no auth on SSH and use terminal auth (improper)
Even if SSH is configured for terminal auth, in this change we attempt
to detect prompt, so that we won't expect terminal auth, even when
requested, if it is not presented.
|
ytti_oxidized
|
train
|
97f3b7b22ce6f1626ca08f464f5152f557c2783f
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -19,10 +19,10 @@ The driver uses Cassandra's binary protocol which was introduced in Cassandra ve
## Using it
```javascript
-// Creating a new connection pool to multiple hosts.
+//Creating a new connection pool to multiple hosts.
var cql = require('node-cassandra-cql');
var client = new cql.Client({hosts: ['host1:9042', 'host2:9042'], keyspace: 'keyspace1'});
-// Reading
+//Reading
client.execute('SELECT key, email, last_name FROM user_profiles WHERE key=?', ['jbay'],
function(err, result) {
if (err) console.log('execute failed');
@@ -30,7 +30,7 @@ client.execute('SELECT key, email, last_name FROM user_profiles WHERE key=?', ['
}
);
-// Writing
+//Writing
client.execute('UPDATE user_profiles SET birth=? WHERE key=?', [new Date(1950, 5, 1), 'jbay'],
cql.types.consistencies.quorum,
function(err) {
@@ -39,8 +39,8 @@ client.execute('UPDATE user_profiles SET birth=? WHERE key=?', [new Date(1950, 5
}
);
-// Streaming query rows
-client.streamRows('SELECT event_time, temperature FROM temperature WHERE station_id=', ['abc'],
+//Streaming query rows
+client.eachRow('SELECT event_time, temperature FROM temperature WHERE station_id=', ['abc'],
function(n, row) {
//the callback will be invoked per each row as soon as they are received
console.log('temperature value', n, row.get('temperature'));
@@ -50,7 +50,7 @@ client.streamRows('SELECT event_time, temperature FROM temperature WHERE station
}
);
-// Streaming field
+//Streaming field
client.streamField('SELECT key, photo FROM user_profiles WHERE key=', ['jbay'],
function(err, row, photoStream) {
//the callback will be invoked per each row as soon as they are received.
@@ -119,7 +119,7 @@ Use one of the values defined in `types.consistencies` for `consistency`, defau
Callback should take two arguments err and result.
-#### client.streamRows(query, [params], [consistency], rowCallback, endCallback)
+#### client.eachRow(query, [params], [consistency], rowCallback, endCallback)
Prepares (the first time), executes the prepared query and streams the rows as soon as they are received.
@@ -129,19 +129,21 @@ It executes `endCallback(err, rowsCount)` when there are no more rows or there i
Use one of the values defined in `types.consistencies` for `consistency`, defaults to quorum.
-#### client.streamField(query, [params], [consistency], callback)
+#### client.streamField(query, [params], [consistency], rowCallback, [endCallback])
Prepares (the first time), executes the prepared query and streams the last field of each row.
-It executes `callback(err, row, streamField)` per each row as soon as the first chunk of the last field is received.
+It executes `rowCallback(n, row, streamField)` per each row as soon as the first chunk of the last field is received, where `n` is the index of the row.
The `stream` is a [Readable Streams2](http://nodejs.org/api/stream.html#stream_class_stream_readable) object that contains the raw bytes of the field value.
It can be **piped** downstream and provides automatic pause/resume logic (it buffers when not read).
-The `row` object is similar to the one provided on `streamRows`, except that it does not contain the definition of the last column.
+The `row` object is similar to the one provided on `eachRow`, except that it does not contain the definition of the last column.
Use one of the values defined in `types.consistencies` for `consistency`, defaults to quorum.
+It executes `endCallback(err, rowsCount)` when there are no more rows or there is an error retrieving the row.
+
#### client.shutdown([callback])
Disconnects the pool.
diff --git a/test/basicTests.js b/test/basicTests.js
index <HASH>..<HASH> 100644
--- a/test/basicTests.js
+++ b/test/basicTests.js
@@ -38,7 +38,6 @@ describe('types', function () {
}
assert.strictEqual(stringValue, expected);
}
- var stringifyValue = types.typeEncoder.stringifyValue;
testStringify(1, '1', dataTypes.int);
testStringify(1.1, '1.1', dataTypes.double);
testStringify("text", "'text'", dataTypes.text);
diff --git a/test/clientTests.js b/test/clientTests.js
index <HASH>..<HASH> 100644
--- a/test/clientTests.js
+++ b/test/clientTests.js
@@ -402,13 +402,23 @@ describe('Client', function () {
client.execute(queryStreamInsert, [id, blob], next);
},
function (next) {
- client.streamField(queryStreamSelect, [id], function (err, row, blobStream) {
+ client.streamField(queryStreamSelect, [id], function (n, row, blobStream) {
assert.strictEqual(row.get('id'), id, 'The row must be retrieved');
+ assert.strictEqual(n, 0);
assertStreamReadable(blobStream, blob, next);
});
}
], done);
});
+
+ it('should callback with error', function (done) {
+ client.streamField('SELECT TO FAIL MISSERABLY', function (n, row, stream) {
+ assert.ok(fail, 'It should never execute the row callback');
+ }, function (err) {
+ assert.ok(err, 'It should yield an error');
+ done();
+ });
+ });
it('should yield a null stream when the field is null', function (done) {
var id = 110;
|
client.streamRows: added endCallback
|
jorgebay_node-cassandra-cql
|
train
|
b13d5e421e81be59aebbd7ecdb8af3b4c3b79c63
|
diff --git a/lib/reports_kit/reports/data/utils.rb b/lib/reports_kit/reports/data/utils.rb
index <HASH>..<HASH> 100644
--- a/lib/reports_kit/reports/data/utils.rb
+++ b/lib/reports_kit/reports/data/utils.rb
@@ -73,11 +73,7 @@ module ReportsKit
keys = keys.sort
last_key = (dimension.last_key || keys.last).to_date
last_key = last_key.beginning_of_week(ReportsKit.configuration.first_day_of_week) if granularity == 'week'
-
- if granularity == 'week'
- beginning_of_current_week = Date.today.beginning_of_week(ReportsKit.configuration.first_day_of_week)
- last_key = [beginning_of_current_week, last_key].compact.max
- end
+ last_key ||= Date.today.beginning_of_week(ReportsKit.configuration.first_day_of_week) if granularity == 'week'
date = first_key
populated_keys = []
diff --git a/spec/reports_kit/reports/data/generate_spec.rb b/spec/reports_kit/reports/data/generate_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/reports_kit/reports/data/generate_spec.rb
+++ b/spec/reports_kit/reports/data/generate_spec.rb
@@ -85,6 +85,36 @@ describe ReportsKit::Reports::Data::Generate do
})
end
+ context 'with a old end date' do
+ let(:properties) do
+ {
+ measure: 'issue',
+ filters: [
+ {
+ key: 'opened_at',
+ criteria: {
+ operator: 'between',
+ value: "#{format_configuration_time(now - 2.weeks)} - #{format_configuration_time(now - 1.week)}"
+ }
+ }
+ ],
+ dimensions: %w(opened_at)
+ }
+ end
+
+ it 'returns the chart_data' do
+ expect(chart_data).to eq({
+ labels: [format_week_offset(2), format_week_offset(1)],
+ datasets: [
+ {
+ label: 'Issues',
+ data: [2, 0]
+ }
+ ]
+ })
+ end
+ end
+
context 'with zero results' do
let(:properties) do
{
|
Time dimension series should end at the end of the filter
|
tombenner_reports_kit
|
train
|
10c6a3b4e4230ed7dea76f3af20e3ebcd7075a36
|
diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java
index <HASH>..<HASH> 100644
--- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java
+++ b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java
@@ -23,6 +23,7 @@ import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
+import org.junit.Ignore;
import org.junit.Test;
import com.microsoft.windowsazure.services.core.ServiceException;
@@ -75,6 +76,7 @@ public class JobIntegrationTest extends IntegrationTestBase {
.setName("My encoding Task").setTaskBody(taskBody)));
}
+ @Ignore("due to issue 480")
@Test
public void createJobSuccess() throws Exception {
// Arrange
@@ -102,6 +104,7 @@ public class JobIntegrationTest extends IntegrationTestBase {
verifyJobInfoEqual("actualJob", expectedJob, actualJob);
}
+ @Ignore("due to issue 480")
@Test
public void getJobSuccess() throws Exception {
// Arrange
@@ -127,6 +130,7 @@ public class JobIntegrationTest extends IntegrationTestBase {
service.get(Job.get(invalidId));
}
+ @Ignore("due to issue 480")
@Test
public void listJobSuccess() throws ServiceException {
// Arrange
@@ -147,6 +151,7 @@ public class JobIntegrationTest extends IntegrationTestBase {
});
}
+ @Ignore("due to issue 480")
@Test
public void canListJobsWithOptions() throws ServiceException {
String[] assetNames = new String[] { testJobPrefix + "assetListOptionsA", testJobPrefix + "assetListOptionsB",
@@ -166,6 +171,7 @@ public class JobIntegrationTest extends IntegrationTestBase {
assertEquals(2, listJobsResult.size());
}
+ @Ignore("due to issue 480")
@Test
public void cancelJobSuccess() throws Exception {
// Arrange
@@ -192,6 +198,7 @@ public class JobIntegrationTest extends IntegrationTestBase {
// Assert
}
+ @Ignore("due to issue 480")
@Test
public void deleteJobSuccess() throws ServiceException {
// Arrange
|
disable failed unit tests tracked in issue <I>.
|
Azure_azure-sdk-for-java
|
train
|
a42ba297c7050e946aa2b68042e217929bfcfced
|
diff --git a/topologies/server.js b/topologies/server.js
index <HASH>..<HASH> 100644
--- a/topologies/server.js
+++ b/topologies/server.js
@@ -354,7 +354,7 @@ Server.prototype.connect = function(options) {
// Do not allow connect to be called on anything that's not disconnected
if(self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) {
- throw MongoError.create(f('server instance in invalid state %s', self.s.state));
+ throw MongoError.create(f('server instance in invalid state %s', self.s.pool.state));
}
// Create a pool
|
Minor fix to report the correct state on error
|
mongodb_node-mongodb-native
|
train
|
77af1a53791060187df001db06deb212eb6fd80e
|
diff --git a/app/controllers/cms/resources_controller.rb b/app/controllers/cms/resources_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/cms/resources_controller.rb
+++ b/app/controllers/cms/resources_controller.rb
@@ -71,7 +71,7 @@ module Cms
end
def resource_model
- controller_name.classify.constantize
+ controller_path.sub(/^cms\//, '').classify.constantize
end
def resource_params
|
Change resource_model method for resource controller to include namespaces
|
droptheplot_adminable
|
train
|
33c69cf9d48046587235099536e6f3cb386a3418
|
diff --git a/muffin_redis.py b/muffin_redis.py
index <HASH>..<HASH> 100644
--- a/muffin_redis.py
+++ b/muffin_redis.py
@@ -247,31 +247,33 @@ class Subscription():
# so leave all work to him
return (yield from self._queue.get())
- self._plugin._receiving = self
- while True:
- # first check if we already have some message
- # (it may be left from previous call
- # if message matched several rules)
- if not self._queue.empty():
- self._plugin._receiving = None
- return self._queue.get_nowait()
-
- # receive and unpickle next message
- msg = (yield from self._sub.next_published())
- if self._plugin.cfg.jsonpickle:
- # We overwrite 'hidden' field `_value` on the message received.
- # Hackish way, I know. How can we do it better? XXX
- if isinstance(msg.value, bytes):
- msg._value = jsonpickle.decode(msg.value.decode('utf-8'))
- if isinstance(msg._value, str):
- msg._value = jsonpickle.decode(msg.value)
-
- # notify all receivers for that message (including self, if any)
- for receiver in self._plugin._subscriptions.get((msg.channel, False), []):
- yield from receiver.put(msg)
-
- for receiver in self._plugin._subscriptions.get((msg.pattern, True), []):
- yield from receiver.put(msg)
+ try:
+ self._plugin._receiving = self
+ while True:
+ # first check if we already have some message
+ # (it may be left from previous call
+ # if message matched several rules)
+ if not self._queue.empty():
+ return self._queue.get_nowait()
+
+ # receive and unpickle next message
+ msg = (yield from self._sub.next_published())
+ if self._plugin.cfg.jsonpickle:
+ # We overwrite 'hidden' field `_value` on the message received.
+ # Hackish way, I know. How can we do it better? XXX
+ if isinstance(msg.value, bytes):
+ msg._value = jsonpickle.decode(msg.value.decode('utf-8'))
+ if isinstance(msg._value, str):
+ msg._value = jsonpickle.decode(msg.value)
+
+ # notify all receivers for that message (including self, if any)
+ for receiver in self._plugin._subscriptions.get((msg.channel, False), []):
+ yield from receiver.put(msg)
+
+ for receiver in self._plugin._subscriptions.get((msg.pattern, True), []):
+ yield from receiver.put(msg)
+ finally:
+ self._plugin._receiving = None
__aenter__ = open # alias
|
Fixed pubsub hang after forced connection closing
|
klen_muffin-redis
|
train
|
4f6ff6042c968f2e9a285e49ca442438d6e039bd
|
diff --git a/simulator/src/main/java/com/hazelcast/simulator/coordinator/remoting/AgentsClient.java b/simulator/src/main/java/com/hazelcast/simulator/coordinator/remoting/AgentsClient.java
index <HASH>..<HASH> 100644
--- a/simulator/src/main/java/com/hazelcast/simulator/coordinator/remoting/AgentsClient.java
+++ b/simulator/src/main/java/com/hazelcast/simulator/coordinator/remoting/AgentsClient.java
@@ -2,17 +2,16 @@ package com.hazelcast.simulator.coordinator.remoting;
import com.hazelcast.simulator.protocol.registry.AgentData;
import com.hazelcast.simulator.utils.CommandLineExitException;
+import com.hazelcast.simulator.utils.ThreadSpawner;
import org.apache.log4j.Logger;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
-import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.simulator.utils.CommonUtils.sleepSeconds;
-import static com.hazelcast.simulator.utils.CommonUtils.sleepSecondsThrowException;
import static com.hazelcast.simulator.utils.ExecutorFactory.createFixedThreadPool;
import static java.lang.String.format;
@@ -29,7 +28,7 @@ public class AgentsClient {
private final ExecutorService agentExecutor = createFixedThreadPool(100, AgentsClient.class);
private final List<AgentClient> agents = new LinkedList<AgentClient>();
- private Thread pokeThread;
+ private final PokeThread pokeThread = new PokeThread();
public AgentsClient(List<AgentData> agentDataList) {
for (AgentData agentData : agentDataList) {
@@ -42,18 +41,6 @@ public class AgentsClient {
awaitAgentsReachable();
// starts a poke thread which will repeatedly poke the agents to make sure they are not going to terminate themselves
- pokeThread = new Thread() {
- public void run() {
- for (; ; ) {
- try {
- sleepSecondsThrowException(AGENT_KEEP_ALIVE_INTERVAL_SECONDS);
- } catch (RuntimeException e) {
- break;
- }
- asyncExecuteOnAllWorkers();
- }
- }
- };
pokeThread.start();
}
@@ -107,24 +94,42 @@ public class AgentsClient {
}
public void shutdown() throws Exception {
- if (pokeThread != null) {
- pokeThread.interrupt();
- pokeThread.join();
- }
+ pokeThread.running = false;
+ pokeThread.interrupt();
+ pokeThread.join();
agentExecutor.shutdown();
agentExecutor.awaitTermination(EXECUTOR_TERMINATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
- private void asyncExecuteOnAllWorkers(final Object... args) {
- for (final AgentClient agentClient : agents) {
- agentExecutor.submit(new Callable<Object>() {
+ private class PokeThread extends Thread {
+
+ private volatile boolean running = true;
- @Override
- public Object call() throws Exception {
- return agentClient.execute(args);
+ public void run() {
+ while (running) {
+ sleepSeconds(AGENT_KEEP_ALIVE_INTERVAL_SECONDS);
+ if (running) {
+ executeOnAllWorkers();
}
- });
+ }
+ }
+
+ private void executeOnAllWorkers(final Object... args) {
+ ThreadSpawner spawner = new ThreadSpawner("AgentsClientExecuteOnAllWorkers", true);
+ for (final AgentClient agentClient : agents) {
+ spawner.spawn(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ agentClient.execute(args);
+ } catch (Exception e) {
+ throw new CommandLineExitException("Could not execute on " + agentClient.getPublicAddress(), e);
+ }
+ }
+ });
+ }
+ spawner.awaitCompletion();
}
}
}
|
Fixed "ignored exceptional return value" issue from SonarQube.
|
hazelcast_hazelcast-simulator
|
train
|
135ee360fd2570a91ac86126656b146e694b7cf6
|
diff --git a/src/walker/abstract_speech_generator.js b/src/walker/abstract_speech_generator.js
index <HASH>..<HASH> 100644
--- a/src/walker/abstract_speech_generator.js
+++ b/src/walker/abstract_speech_generator.js
@@ -23,25 +23,23 @@
goog.provide('sre.AbstractSpeechGenerator');
goog.require('sre.AuditoryDescription');
-goog.require('sre.DirectSpeechGenerator');
goog.require('sre.EnrichMathml');
goog.require('sre.RebuildStree');
+goog.require('sre.SpeechGeneratorInterface');
/**
* @constructor
- * @extends {sre.DirectSpeechGenerator}
+ * @implements {sre.SpeechGeneratorInterface}
*/
sre.AbstractSpeechGenerator = function() {
- goog.base(this);
/**
* @type {sre.RebuildStree}
*/
this.rebuilt = null;
};
-goog.inherits(sre.AbstractSpeechGenerator, sre.DirectSpeechGenerator);
/**
@@ -53,6 +51,24 @@ sre.AbstractSpeechGenerator.prototype.getRebuilt = function() {
/**
+ * @override
+ */
+sre.AbstractSpeechGenerator.prototype.getSpeech = goog.abstractMethod;
+
+
+/**
+ * @override
+ */
+sre.AbstractSpeechGenerator.prototype.start = function() { };
+
+
+/**
+ * @override
+ */
+sre.AbstractSpeechGenerator.prototype.end = function() { };
+
+
+/**
* Rebuilds the semantic tree given in the input xml element fully connected
* with maction elements.
* @param {!Node} node The target element of the event.
diff --git a/src/walker/abstract_walker.js b/src/walker/abstract_walker.js
index <HASH>..<HASH> 100644
--- a/src/walker/abstract_walker.js
+++ b/src/walker/abstract_walker.js
@@ -383,7 +383,10 @@ sre.AbstractWalker.prototype.restoreState = function() {
if (!this.highlighter) return;
var state = this.highlighter.getState(this.node.id);
if (!state) return;
- var node = this.generator.getRebuilt().nodeDict[state];
+ //TODO: Combine this better with the speech generator!
+ var rebuilt = new sre.RebuildStree(this.xml);
+ var stree = rebuilt.getTree();
+ var node = rebuilt.nodeDict[state];
var path = [];
while (node) {
path.push(node.id);
diff --git a/src/walker/direct_speech_generator.js b/src/walker/direct_speech_generator.js
index <HASH>..<HASH> 100644
--- a/src/walker/direct_speech_generator.js
+++ b/src/walker/direct_speech_generator.js
@@ -22,35 +22,20 @@
goog.provide('sre.DirectSpeechGenerator');
+goog.require('sre.AbstractSpeechGenerator');
goog.require('sre.EnrichMathml');
-goog.require('sre.SpeechGeneratorInterface');
goog.require('sre.WalkerUtil');
/**
* @constructor
- * @implements {sre.SpeechGeneratorInterface}
+ * @extends {sre.AbstractSpeechGenerator}
*/
-sre.DirectSpeechGenerator = function() { };
-
-
-/**
- * @override
- */
-sre.DirectSpeechGenerator.prototype.getRebuilt = function() { };
-
-
-/**
- * @override
- */
-sre.DirectSpeechGenerator.prototype.start = function() { };
-
-
-/**
- * @override
- */
-sre.DirectSpeechGenerator.prototype.end = function() { };
+sre.DirectSpeechGenerator = function() {
+ goog.base(this);
+};
+goog.inherits(sre.DirectSpeechGenerator, sre.AbstractSpeechGenerator);
/**
|
Rejigged the class structure for speech generators again.
|
zorkow_speech-rule-engine
|
train
|
5c3142ec98ff3e7f22daf694f3f466dd77f91a13
|
diff --git a/jquery.floatThead.js b/jquery.floatThead.js
index <HASH>..<HASH> 100644
--- a/jquery.floatThead.js
+++ b/jquery.floatThead.js
@@ -2,7 +2,7 @@
* jQuery.floatThead
* Copyright (c) 2012 Misha Koryak - https://github.com/mkoryak/floatThead
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
- * Date: 10/15/12
+ * Date: 10/17/12
*
* @projectDescription lock a table header in place while scrolling - without breaking styles or events bound to the header
*
@@ -16,7 +16,7 @@
* Tested on FF13+, Chrome 21, IE9, IE8, IE7 (but tables with colspans are not supported in ie7)
*
* @author Misha Koryak
- * @version 0.7
+ * @version 0.7.1
*/
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
@@ -207,23 +207,25 @@ $.fn.floatThead = function(map){
$table.css(layoutAuto);
$floatTable.css(layoutAuto);
for(i=0; i < numCols; i++){
- var $rowCell = $rowCells.eq(i);
- var rowWidth = $rowCell.outerWidth(true);
- //TODO: check this logic more
- if(i == 0 && $.browser.mozilla && ($rowCell.css('border-left-width') || $rowCell.css('border-right-width'))){
- rowWidth--;
- }
+ var $rowCell = $rowCells.eq(i);
+ var rowWidth = $rowCell.outerWidth(true);
+ //TODO: check this logic more
+ if(i == 0 && $.browser.mozilla && ($rowCell.css('border-left-width') || $rowCell.css('border-right-width'))){
+ rowWidth--;
+ }
$headerCells.eq(i).outerWidth(rowWidth);
$sizerCells.eq(i).outerWidth(rowWidth);
}
+ setHeaderHeight();
$floatTable.append($header); //append because colgroup must go first in chrome
$table.css(layoutFixed);
$floatTable.css(layoutFixed);
} else {
+ setHeaderHeight();
+ $floatTable.append($header);
$table.css(layoutAuto);
$floatTable.css(layoutAuto);
}
- setHeaderHeight();
};
flow();
return flow;
@@ -257,7 +259,6 @@ $.fn.floatThead = function(map){
$scrollContainer.scrollTop(scrollingContainerTop);
}
return function(){
- locked = scrollbarOffset.vertical > 0; //no scroll bars
var windowTop = $window.scrollTop();
scrollingContainerTop = $scrollContainer.scrollTop();
var top;
|
resolved issues when table had 0 rows in body. removed bad assumptions
|
mkoryak_floatThead
|
train
|
544a9797214b99628207b1918cc4295411a7cb6e
|
diff --git a/annotationengine/api.py b/annotationengine/api.py
index <HASH>..<HASH> 100644
--- a/annotationengine/api.py
+++ b/annotationengine/api.py
@@ -90,7 +90,7 @@ class Table(Resource):
}
table_name = table_name.lower()
schema_type = data.get("schema_type")
- table_name = table_name.lower()
+ table_name = table_name.lower().replace(" ", "_")
try:
table_info = db.create_annotation_table(
table_name, schema_type, **metadata_dict
|
fix(ref_annotation): enforce spaces as underscores
|
seung-lab_AnnotationEngine
|
train
|
2abf7e381be566dfbd13bd9cbad416c82107eb3f
|
diff --git a/synergy/supervisor/synergy_supervisor.py b/synergy/supervisor/synergy_supervisor.py
index <HASH>..<HASH> 100644
--- a/synergy/supervisor/synergy_supervisor.py
+++ b/synergy/supervisor/synergy_supervisor.py
@@ -1,7 +1,7 @@
__author__ = 'Bohdan Mushkevych'
from threading import Lock
-from subprocess import PIPE
+from subprocess import DEVNULL
import psutil
from psutil import TimeoutExpired
@@ -62,9 +62,9 @@ class Supervisor(SynergyProcess):
p = psutil.Popen([get_python(), PROJECT_ROOT + '/' + PROCESS_STARTER, box_config.process_name],
close_fds=True,
cwd=settings.settings['process_cwd'],
- stdin=PIPE,
- stdout=PIPE,
- stderr=PIPE)
+ stdin=DEVNULL,
+ stdout=DEVNULL,
+ stderr=DEVNULL)
box_config.pid = p.pid
self.logger.info(f'Started {box_config.process_name} with pid = {p.pid}')
except Exception:
diff --git a/synergy/system/process_helper.py b/synergy/system/process_helper.py
index <HASH>..<HASH> 100644
--- a/synergy/system/process_helper.py
+++ b/synergy/system/process_helper.py
@@ -1,6 +1,6 @@
__author__ = 'Bohdan Mushkevych'
-from subprocess import PIPE
+from subprocess import DEVNULL
import sys
import psutil
@@ -51,9 +51,9 @@ def start_process(process_name, *args):
p = psutil.Popen(cmd,
close_fds=True,
cwd=settings.settings['process_cwd'],
- stdin=PIPE,
- stdout=PIPE,
- stderr=PIPE)
+ stdin=DEVNULL,
+ stdout=DEVNULL,
+ stderr=DEVNULL)
sys.stdout.write(f'Started {process_name} with pid = {p.pid} \n')
except Exception as e:
sys.stderr.write(f'Exception on starting {process_name} : {e} \n')
|
Addressing issue with PIPE buffer overflow in the containerized deployments
|
mushkevych_scheduler
|
train
|
a00ffb7cf71c66fdecc67578331361a67cc0d0f0
|
diff --git a/apptentive/src/com/apptentive/android/sdk/module/messagecenter/view/MessageCenterActivityContent.java b/apptentive/src/com/apptentive/android/sdk/module/messagecenter/view/MessageCenterActivityContent.java
index <HASH>..<HASH> 100644
--- a/apptentive/src/com/apptentive/android/sdk/module/messagecenter/view/MessageCenterActivityContent.java
+++ b/apptentive/src/com/apptentive/android/sdk/module/messagecenter/view/MessageCenterActivityContent.java
@@ -959,7 +959,10 @@ public class MessageCenterActivityContent extends InteractionView<MessageCenterI
messageCenterListAdapter.clearWhoCard();
messageCenterListAdapter.notifyDataSetChanged();
saveWhoCardSetState();
- if (messages.size() == 1 && interaction.getWhoCardRequired()) {
+ // If Who card is required, it might be displayed before proceeding to composing, for instance
+ // when there was a contextual message or it was the first message. We need to resume composing
+ // after dismissing Who Card
+ if ((messages.size() == 1 || contextualMessage != null) && interaction.getWhoCardRequired()) {
addComposingArea();
messageCenterListAdapter.setForceShowKeyboard(true);
messageCenterViewHandler.sendEmptyMessageDelayed(MSG_MESSAGE_NOTIFY_UPDATE, DEFAULT_DELAYMILLIS);
|
Fix Composing not being shown after Who Card is dismissed from contextual message
|
apptentive_apptentive-android
|
train
|
4f8358f97c1b951ad89dd558b7de027fa3fd3f22
|
diff --git a/go/vt/srvtopo/keyspace_filtering_server_test.go b/go/vt/srvtopo/keyspace_filtering_server_test.go
index <HASH>..<HASH> 100644
--- a/go/vt/srvtopo/keyspace_filtering_server_test.go
+++ b/go/vt/srvtopo/keyspace_filtering_server_test.go
@@ -79,6 +79,10 @@ func TestFilteringServerReturnsUnderlyingServer(t *testing.T) {
if !got.IsReadOnly() {
t.Errorf("Got read-write topo.Server from FilteringServer -- must be read-only")
}
+ gotErr = got.CreateCellsAlias(stockCtx, "should_fail", &topodatapb.CellsAlias{Cells: []string{stockCell}})
+ if gotErr == nil {
+ t.Errorf("Were able to perform a write against the topo.Server from a FilteringServer -- it must be read-only")
+ }
}
func doTestGetSrvKeyspaceNames(
|
Add another check in the e2e test to be sure writes fail with FilteringServer
|
vitessio_vitess
|
train
|
2abc314a5501f800ca383beccf5d0d182c82f4d4
|
diff --git a/src/client.js b/src/client.js
index <HASH>..<HASH> 100644
--- a/src/client.js
+++ b/src/client.js
@@ -46,23 +46,23 @@ Client.prototype = {
this._request('nearest', this._formatLocs([latLng]), callback);
},
- match: function(latLngs, timestamps, callback) {
- if (timestamps) {
- if (timestamps.length != latLngs.length)
+ match: function(query, callback) {
+ if (query.timestamps) {
+ if (query.timestamps.length != query.coordinates.length)
{
- callback(new Error("Invalid number of timestamps! Is " + timestamps.length + " should be: " + latLngs.length));
+ callback(new Error("Invalid number of timestamps! Is " + query.timestamps.length + " should be: " + query.length));
}
- this._request('match', this._formatStampedLocs(latLngs, timestamps), callback);
+ this._request('match', this._formatStampedLocs(query.coordinates, query.timestamps), callback);
}
- else this._request('match', this._formatLocs(latLngs), callback);
+ else this._request('match', this._formatLocs(query.coordinates), callback);
},
- route: function(latLngs, callback) {
- this._request('viaroute', this._formatLocs(latLngs), callback);
+ route: function(query, callback) {
+ this._request('viaroute', this._formatLocs(query.coordinates), callback);
},
- table: function(latLngs, callback) {
- this._request('table', this._formatLocs(latLngs), callback);
+ table: function(query, callback) {
+ this._request('table', this._formatLocs(query.coordinates), callback);
},
};
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -31,7 +31,7 @@ tape('viaroute', function(t) {
t.plan(2);
var osrm = new OSRM();
- osrm.route(testCoords, function(error, response) {
+ osrm.route({coordinates: testCoords}, function(error, response) {
console.log("Response: " + JSON.stringify(response));
t.notOk(error);
t.ok(response.route_geometry);
@@ -43,7 +43,7 @@ tape('match', function(t) {
t.plan(2);
var osrm = new OSRM();
- osrm.match(testCoords, null, function(error, response) {
+ osrm.match({coordinates: testCoords}, function(error, response) {
console.log("Response: " + JSON.stringify(response));
t.notOk(error);
t.ok(response.traces);
@@ -54,7 +54,7 @@ tape('match with timestamps', function(t) {
t.plan(2);
var osrm = new OSRM();
- osrm.match(testCoords, [0, 1], function(error, response) {
+ osrm.match({coordinates: testCoords, timestamps: [0, 1]}, function(error, response) {
console.log("Response: " + JSON.stringify(response));
t.notOk(error);
t.ok(response.traces);
@@ -66,7 +66,7 @@ tape('table', function(t) {
t.plan(2);
var osrm = new OSRM();
- osrm.table(testCoords, function(error, response) {
+ osrm.table({coordinates: testCoords}, function(error, response) {
console.log("Response: " + JSON.stringify(response));
t.notOk(error);
t.ok(response.distance_table);
|
Make interface really compatible with node-osrm
|
Project-OSRM_osrm.js
|
train
|
63b49ed63b8f2e60d93cc92c3717ae0bed0a8337
|
diff --git a/src/react/get-changed-params.js b/src/react/get-changed-params.js
index <HASH>..<HASH> 100644
--- a/src/react/get-changed-params.js
+++ b/src/react/get-changed-params.js
@@ -1,9 +1,12 @@
import { paramsList } from './params-list';
-function getChangedParams(swiperParams, oldParams, childrenLength, oldChildrenLength) {
+function getChangedParams(swiperParams, oldParams, children, oldChildren) {
const keys = [];
if (!oldParams) return keys;
- if (oldChildrenLength !== childrenLength) keys.push('children');
+ const oldChildrenKeys = oldChildren.map((child) => child.key);
+ const childrenKeys = children.map((child) => child.key);
+ if (oldChildrenKeys.join('') !== childrenKeys.join('')) keys.push('children');
+ if (oldChildren.length !== children.length) keys.push('children');
const watchParams = paramsList.filter((key) => key[0] === '_').map((key) => key.replace(/_/, ''));
watchParams.forEach((key) => {
if (key in swiperParams && key in oldParams && swiperParams[key] !== oldParams[key]) {
diff --git a/src/react/swiper.js b/src/react/swiper.js
index <HASH>..<HASH> 100644
--- a/src/react/swiper.js
+++ b/src/react/swiper.js
@@ -23,7 +23,7 @@ const Swiper = ({
const swiperElRef = useRef(null);
const swiperRef = useRef(null);
const oldPassedParamsRef = useRef(null);
- const oldSlidesLength = useRef(null);
+ const oldSlides = useRef(null);
const nextElRef = useRef(null);
const prevElRef = useRef(null);
@@ -37,12 +37,12 @@ const Swiper = ({
const changedParams = getChangedParams(
passedParams,
oldPassedParamsRef.current,
- slides.length,
- oldSlidesLength.current,
+ slides,
+ oldSlides.current,
);
oldPassedParamsRef.current = passedParams;
- oldSlidesLength.current = slides.length;
+ oldSlides.current = slides;
Object.assign(swiperParams.on, {
_containerClasses(swiper, classes) {
|
React: watch for children changes
Ref #<I>
|
nolimits4web_swiper
|
train
|
451d22d0cc99e2a7fe065088b6787654767c5146
|
diff --git a/lib/yard/config.rb b/lib/yard/config.rb
index <HASH>..<HASH> 100644
--- a/lib/yard/config.rb
+++ b/lib/yard/config.rb
@@ -45,7 +45,41 @@ module YARD
# loaded with safe mode on, because plugins are properly namespaced with
# a 'yard-' prefix, must be installed as a gem, and therefore cannot be
# touched by the user. To specify safe mode, use the +safe_mode+ key.
- #
+ #
+ # == Plugin Specific Configuration
+ #
+ # Additional settings can be defined within the configuration file
+ # specifically to provide configuration for a plugin. A plugin that utilizes
+ # the YARD configuration is strongly encouraged to utilize namespacing of
+ # their configuration content.
+ #
+ # !!!yaml
+ # load_plugins: true # Auto-load plugins when YARD starts
+ # ignored_plugins:
+ # - yard-broken
+ # - broken2 # yard- prefix not necessary
+ # autoload_plugins:
+ # - yard-rspec
+ # # Plugin Specific Configuration
+ # yard-sample-plugin:
+ # show-results-inline: true
+ #
+ # As the configuration is available is available system wide, it can be
+ # accessed within the plugin code.
+ #
+ #
+ # if YARD::Config.options['yard-sample-plugin'] and
+ # YARD::Config.options['yard-sample-plugin']['show-results-inline']
+ # # ... perform the action that places the results inline ...
+ # else
+ # # ... do the default behavior of not showing the results inline ...
+ # end
+ #
+ # When accessing the configuration, be aware that this file is user managed
+ # so configuration keys and values may not be present. Make no assumptions and
+ # instead ensure that you check for the existence of keys before proceeding to
+ # retrieve values.
+ #
# @since 0.6.2
# @see options
class Config
|
YARD Configuration Documentation
Included example of using the YARD::Config from the point-of-view of plugin
designer.
|
lsegal_yard
|
train
|
b77ff061898f98e0cf50d1af1ab7ef6a520213c7
|
diff --git a/Minimal-J/src/main/java/org/minimalj/backend/db/AbstractTable.java b/Minimal-J/src/main/java/org/minimalj/backend/db/AbstractTable.java
index <HASH>..<HASH> 100644
--- a/Minimal-J/src/main/java/org/minimalj/backend/db/AbstractTable.java
+++ b/Minimal-J/src/main/java/org/minimalj/backend/db/AbstractTable.java
@@ -163,18 +163,11 @@ public abstract class AbstractTable<T> {
}
static PreparedStatement createStatement(Connection connection, String query, boolean returnGeneratedKeys) throws SQLException {
- if (returnGeneratedKeys) {
- if (sqlLogger.isLoggable(Level.FINE)) {
- return new LoggingPreparedStatement(connection, query, Statement.RETURN_GENERATED_KEYS, sqlLogger);
- } else {
- return connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
- }
+ int autoGeneratedKeys = returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS;
+ if (sqlLogger.isLoggable(Level.FINE)) {
+ return new LoggingPreparedStatement(connection, query, autoGeneratedKeys, sqlLogger);
} else {
- if (sqlLogger.isLoggable(Level.FINE)) {
- return new LoggingPreparedStatement(connection, query, sqlLogger);
- } else {
- return connection.prepareStatement(query);
- }
+ return connection.prepareStatement(query, autoGeneratedKeys);
}
}
diff --git a/Minimal-J/src/main/java/org/minimalj/backend/db/LoggingPreparedStatement.java b/Minimal-J/src/main/java/org/minimalj/backend/db/LoggingPreparedStatement.java
index <HASH>..<HASH> 100644
--- a/Minimal-J/src/main/java/org/minimalj/backend/db/LoggingPreparedStatement.java
+++ b/Minimal-J/src/main/java/org/minimalj/backend/db/LoggingPreparedStatement.java
@@ -19,7 +19,6 @@ import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
-import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
@@ -43,10 +42,6 @@ class LoggingPreparedStatement implements PreparedStatement {
private final Logger logger;
private final Map<Integer, String> parameters = new HashMap<>();
- public LoggingPreparedStatement(Connection connection, String query, Logger logger) throws SQLException {
- this(connection, query, Statement.NO_GENERATED_KEYS, logger);
- }
-
public LoggingPreparedStatement(Connection connection, String query, int autoGeneratedKeys, Logger logger) throws SQLException {
this.query = query;
this.logger = logger;
|
Persistence: With use of the constant Statement.NO_GENERATED_KEYS the
implemention can be shorter
|
BrunoEberhard_minimal-j
|
train
|
2b65ac5e6e72a513a07eae8fa5e33215457b19ba
|
diff --git a/provision/kubernetes/deploy_test.go b/provision/kubernetes/deploy_test.go
index <HASH>..<HASH> 100644
--- a/provision/kubernetes/deploy_test.go
+++ b/provision/kubernetes/deploy_test.go
@@ -3148,7 +3148,7 @@ func (s *S) TestCreatePodContainers(c *check.C) {
runAsUser := int64(1000)
c.Assert(containers[0], check.DeepEquals, apiv1.Container{
Name: "committer-cont",
- Image: "tsuru/deploy-agent:0.8.4",
+ Image: "tsuru/deploy-agent:0.10.1",
VolumeMounts: []apiv1.VolumeMount{
{Name: "dockersock", MountPath: dockerSockPath},
{Name: containerdRunVolume, MountPath: containerdRunDir},
@@ -3538,7 +3538,7 @@ func (s *S) TestCreateDeployPodContainers(c *check.C) {
c.Assert(containers, check.DeepEquals, []apiv1.Container{
{
Name: "committer-cont",
- Image: "tsuru/deploy-agent:0.8.4",
+ Image: "tsuru/deploy-agent:0.10.1",
VolumeMounts: []apiv1.VolumeMount{
{Name: "dockersock", MountPath: dockerSockPath},
{Name: containerdRunVolume, MountPath: containerdRunDir},
@@ -3779,7 +3779,7 @@ func (s *S) TestCreateImageBuildPodContainer(c *check.C) {
{Name: "BUILDKITD_FLAGS", Value: "--oci-worker-no-process-sandbox"},
{Name: "BUILDCTL_CONNECT_RETRIES_MAX", Value: "50"},
})
- c.Assert(containers[0].Image, check.DeepEquals, "tsuru/deploy-agent:0.8.4")
+ c.Assert(containers[0].Image, check.DeepEquals, "tsuru/deploy-agent:0.10.1")
cmds := cleanCmds(containers[0].Command[2])
c.Assert(cmds, check.Equals, `mkdir -p $(dirname /data/context.tar.gz) && cat >/data/context.tar.gz && tsuru_unit_agent`)
diff --git a/provision/kubernetes/provisioner.go b/provision/kubernetes/provisioner.go
index <HASH>..<HASH> 100644
--- a/provision/kubernetes/provisioner.go
+++ b/provision/kubernetes/provisioner.go
@@ -64,7 +64,7 @@ const (
defaultPodRunningTimeout = 10 * time.Minute
defaultDeploymentProgressTimeout = 10 * time.Minute
defaultAttachTimeoutAfterContainerFinished = time.Minute
- defaultSidecarImageName = "tsuru/deploy-agent:0.8.4"
+ defaultSidecarImageName = "tsuru/deploy-agent:0.10.1"
defaultPreStopSleepSeconds = 10
)
diff --git a/provision/kubernetes/provisioner_test.go b/provision/kubernetes/provisioner_test.go
index <HASH>..<HASH> 100644
--- a/provision/kubernetes/provisioner_test.go
+++ b/provision/kubernetes/provisioner_test.go
@@ -2426,8 +2426,8 @@ func (s *S) TestGetKubeConfigDefaults(c *check.C) {
config.Unset("kubernetes")
kubeConf := getKubeConfig()
c.Assert(kubeConf, check.DeepEquals, kubernetesConfig{
- deploySidecarImage: "tsuru/deploy-agent:0.8.4",
- deployInspectImage: "tsuru/deploy-agent:0.8.4",
+ deploySidecarImage: "tsuru/deploy-agent:0.10.1",
+ deployInspectImage: "tsuru/deploy-agent:0.10.1",
APITimeout: 60 * time.Second,
PodReadyTimeout: time.Minute,
PodRunningTimeout: 10 * time.Minute,
|
Upgrade deploy agent to <I>
|
tsuru_tsuru
|
train
|
c924c4f6639c5f19cacb6e4f394c1e3db60a9ec8
|
diff --git a/Rakefile b/Rakefile
index <HASH>..<HASH> 100644
--- a/Rakefile
+++ b/Rakefile
@@ -80,7 +80,7 @@ desc 'Run various benchmarks'
task :benchmark do
require 'benchmark'
require 'tempfile'
- require 'ole/file_system'
+ require 'ole/storage'
# should probably add some read benchmarks too
def write_benchmark opts={}
diff --git a/lib/ole/file_system.rb b/lib/ole/file_system.rb
index <HASH>..<HASH> 100644
--- a/lib/ole/file_system.rb
+++ b/lib/ole/file_system.rb
@@ -1,7 +1,7 @@
warn <<-end
-Use of ole/file_system is deprecated. Use ole/storage/file_system
-or better just ole/storage (file_system is recommended api and is
-enabled by default).
+Use of ole/file_system is deprecated. Use ole/storage (the file_system api
+is recommended and enabled by default).
end
-require 'ole/storage/file_system'
+require 'ole/storage'
+
diff --git a/lib/ole/storage/file_system.rb b/lib/ole/storage/file_system.rb
index <HASH>..<HASH> 100644
--- a/lib/ole/storage/file_system.rb
+++ b/lib/ole/storage/file_system.rb
@@ -31,8 +31,6 @@
# the filesystem api.
#
-require 'ole/storage'
-
module Ole # :nodoc:
class Storage
def file
diff --git a/lib/ole/support.rb b/lib/ole/support.rb
index <HASH>..<HASH> 100644
--- a/lib/ole/support.rb
+++ b/lib/ole/support.rb
@@ -27,13 +27,15 @@ end
class File # :nodoc:
# for interface consistency with StringIO etc (rather than adding #stat
# to them). used by RangesIO.
- def size
- stat.size
+ unless File.instance_methods.include?(:size)
+ def size
+ stat.size
+ end
end
end
class Symbol # :nodoc:
- unless :x.respond_to? :to_proc
+ unless Symbol.instance_methods.include?(:to_proc)
def to_proc
proc { |a| a.send self }
end
diff --git a/lib/ole/types/property_set.rb b/lib/ole/types/property_set.rb
index <HASH>..<HASH> 100644
--- a/lib/ole/types/property_set.rb
+++ b/lib/ole/types/property_set.rb
@@ -1,6 +1,5 @@
# encoding: ASCII-8BIT
-require 'ole/types'
require 'yaml'
module Ole
@@ -165,3 +164,4 @@ module Ole
end
end
end
+
diff --git a/test/test_filesystem.rb b/test/test_filesystem.rb
index <HASH>..<HASH> 100755
--- a/test/test_filesystem.rb
+++ b/test/test_filesystem.rb
@@ -23,7 +23,7 @@
TEST_DIR = File.dirname __FILE__
$:.unshift "#{TEST_DIR}/../lib"
-require 'ole/storage/file_system'
+require 'ole/storage'
require 'test/unit'
module ExtraAssertions
diff --git a/test/test_mbat.rb b/test/test_mbat.rb
index <HASH>..<HASH> 100755
--- a/test/test_mbat.rb
+++ b/test/test_mbat.rb
@@ -3,8 +3,7 @@
$: << File.dirname(__FILE__) + '/../lib'
require 'test/unit'
-require 'ole/storage/base'
-require 'ole/storage/file_system'
+require 'ole/storage'
require 'tempfile'
class TestWriteMbat < Test::Unit::TestCase
diff --git a/test/test_meta_data.rb b/test/test_meta_data.rb
index <HASH>..<HASH> 100644
--- a/test/test_meta_data.rb
+++ b/test/test_meta_data.rb
@@ -3,9 +3,7 @@
$: << File.dirname(__FILE__) + '/../lib'
require 'test/unit'
-require 'ole/storage/base'
-require 'ole/storage/meta_data'
-require 'ole/storage/file_system'
+require 'ole/storage'
class TestMetaData < Test::Unit::TestCase
def test_meta_data
diff --git a/test/test_property_set.rb b/test/test_property_set.rb
index <HASH>..<HASH> 100755
--- a/test/test_property_set.rb
+++ b/test/test_property_set.rb
@@ -3,7 +3,7 @@
$: << File.dirname(__FILE__) + '/../lib'
require 'test/unit'
-require 'ole/types/property_set'
+require 'ole/types'
class TestPropertySet < Test::Unit::TestCase
include Ole::Types
diff --git a/test/test_types.rb b/test/test_types.rb
index <HASH>..<HASH> 100755
--- a/test/test_types.rb
+++ b/test/test_types.rb
@@ -3,7 +3,7 @@
$: << File.dirname(__FILE__) + '/../lib'
require 'test/unit'
-require 'ole/types/base'
+require 'ole/types'
class TestTypes < Test::Unit::TestCase
include Ole::Types
|
Updates to suppress warnings on <I>.
- Guard defining File#size (same definition now exists).
- Remove recursive requires, and tweak requires in tests to use
top level requires only.
git-svn-id: <URL>
|
aquasync_ruby-ole
|
train
|
ac77e8aafea522582ebb1038b5a16a304d93695b
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,8 @@
+## v2.1.0
+
+- Add `Sapience::ErrorHandler:Sentry#capture`
+- Add `Sapience::ErrorHandler:Sentry#capture!`
+
## v2.0.5
- Add "flush" as an instance method in logger.
diff --git a/lib/sapience/error_handler/sentry.rb b/lib/sapience/error_handler/sentry.rb
index <HASH>..<HASH> 100644
--- a/lib/sapience/error_handler/sentry.rb
+++ b/lib/sapience/error_handler/sentry.rb
@@ -37,11 +37,11 @@ module Sapience
end
def capture_exception(exception, payload = {})
- capture(exception, payload)
+ capture_type(exception, payload)
end
def capture_message(message, payload = {})
- capture(message, payload)
+ capture_type(message, payload)
end
def user_context(options = {})
@@ -67,9 +67,42 @@ module Sapience
@configured = true
end
+ # Capture, process and reraise any exceptions from the given block.
+ #
+ # @example
+ # Raven.capture do
+ # MyApp.run
+ # end
+ def capture!(options = {})
+ fail ArgumentError unless block_given?
+
+ begin
+ yield
+ rescue StandardError => e
+ capture_type(e, options)
+ raise
+ end
+ end
+
+ # Capture, process and not reraise any exceptions from the given block.
+ #
+ # @example
+ # Raven.capture do
+ # MyApp.run
+ # end
+ def capture(options = {})
+ fail ArgumentError unless block_given?
+
+ begin
+ yield
+ rescue StandardError => e
+ capture_type(e, options)
+ end
+ end
+
private
- def capture(data, payload)
+ def capture_type(data, payload)
return false unless valid?
configure_sentry
diff --git a/spec/lib/sapience/error_handler/sentry_spec.rb b/spec/lib/sapience/error_handler/sentry_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/sapience/error_handler/sentry_spec.rb
+++ b/spec/lib/sapience/error_handler/sentry_spec.rb
@@ -1,16 +1,16 @@
require "spec_helper"
describe Sapience::ErrorHandler::Sentry do
- subject { described_class.new(options) }
+ subject { described_class.new(init_options) }
let(:level) { :trace }
let(:dsn) { "https://foobar:443" }
let(:message) { "Test message" }
force_config(backtrace_level: :error)
- let(:options) do
+ let(:init_options) do
{
level: level,
- dsn: dsn,
+ dsn: dsn,
}
end
@@ -20,7 +20,7 @@ describe Sapience::ErrorHandler::Sentry do
end
context "when options is not a hash" do
- let(:options) { 12_345 }
+ let(:init_options) { 12_345 }
specify do
expect { subject }.to raise_error(ArgumentError)
end
@@ -101,7 +101,7 @@ describe Sapience::ErrorHandler::Sentry do
end
describe "#user_context" do
- let(:options) { {foo: 'bar'} }
+ let(:options) { { foo: "bar" } }
it "passes the correct params" do
expect(Raven).to receive(:user_context).with(options)
@@ -110,11 +110,103 @@ describe Sapience::ErrorHandler::Sentry do
end
describe "#tags_context" do
- let(:options) { {foo: 'bar'} }
+ let(:options) { { foo: "bar" } }
it "passes the correct params" do
expect(Raven).to receive(:tags_context).with(options)
subject.tags_context(options)
end
end
+
+ describe "#capture!" do
+ let(:options) do
+ {
+ extra: {
+ foo: "bar",
+ },
+ }
+ end
+ let(:exception) { StandardError.new("My test exception") }
+
+ it "processes, captures and re-raises" do
+ expect do
+ subject.capture!(options) do
+ fail exception
+ end
+ end.to raise_error(exception)
+ end
+
+ it "passes param options to Raven" do
+ expect(Raven).to receive(:capture_type).with(exception, options)
+
+ begin
+ subject.capture!(options) do
+ fail exception
+ end
+ rescue # rubocop:disable Lint/HandleExceptions
+ end
+ end
+
+ context "when param options does not have key 'extra'" do
+ let(:options) do
+ {
+ foo: "bar",
+ }
+ end
+
+ it "passes options to Raven under key 'extra'" do
+ expect(Raven).to receive(:capture_type).with(exception, extra: options)
+
+ begin
+ subject.capture!(options) do
+ fail exception
+ end
+ rescue # rubocop:disable Lint/HandleExceptions
+ end
+ end
+ end
+ end
+
+ describe "#capture" do
+ let(:options) do
+ {
+ extra: {
+ foo: "bar",
+ },
+ }
+ end
+ let(:exception) { StandardError.new("My test exception") }
+
+ it "processes and does not raise an exception" do
+ expect do
+ subject.capture(options) do
+ fail exception
+ end
+ end.to_not raise_error
+ end
+
+ it "passes param 'options' to Raven" do
+ expect(Raven).to receive(:capture_type).with(exception, options)
+
+ subject.capture(options) do
+ fail exception
+ end
+ end
+
+ context "when param 'options' does not have key 'extra'" do
+ let(:options) do
+ {
+ foo: "bar",
+ }
+ end
+
+ it "passes options to Raven under key 'extra'" do
+ expect(Raven).to receive(:capture_type).with(exception, extra: options)
+
+ subject.capture(options) do
+ fail exception
+ end
+ end
+ end
+ end
end
|
Add capture and capture! methods for error handler
|
reevoo_sapience-rb
|
train
|
1c91c4213fd1e22123d0dd3b3f6de11fac838e21
|
diff --git a/Swat/SwatActions.php b/Swat/SwatActions.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatActions.php
+++ b/Swat/SwatActions.php
@@ -40,7 +40,7 @@ class SwatActions extends SwatControl implements SwatUIParent {
*/
public $auto_reset = true;
- private $actionfly;
+ private $action_flydown;
private $apply_button;
private $action_items;
@@ -59,30 +59,33 @@ class SwatActions extends SwatControl implements SwatUIParent {
// set the flydown back to its initial state (no persistence)
if ($this->auto_reset)
- $this->actionfly->reset();
+ $this->action_flydown->reset();
// select the current action item based upon the flydown value
- if (isset($this->action_items[$this->actionfly->value]))
- $this->selected = $this->action_items[$this->actionfly->value];
+ if (isset($this->action_items[$this->action_flydown->value]))
+ $this->selected = $this->action_items[$this->action_flydown->value];
else
$this->selected = null;
echo '<div class="swat-actions">';
$label = new SwatHtmlTag('label');
- $label->for = $this->id.'_actionfly';
+ $label->for = $this->id.'_action_flydown';
$label->open();
echo sprintf('%s: ', _S('Action'));
$label->close();
- $this->actionfly->display();
+ $this->action_flydown->display();
echo ' ';
$this->apply_button->display();
foreach ($this->action_items as $item) {
if ($item->widget !== null) {
$div = new SwatHtmlTag('div');
- $div->class = ($item == $this->selected)? 'swat-visible': 'swat-hidden';
+
+ $div->class = ($item == $this->selected) ?
+ 'swat-visible' : 'swat-hidden';
+
$div->id = $this->id.'_'.$item->id;
$div->open();
@@ -99,8 +102,8 @@ class SwatActions extends SwatControl implements SwatUIParent {
public function process() {
$this->createWidgets();
- $this->actionfly->process();
- $selected_id = $this->actionfly->value;
+ $this->action_flydown->process();
+ $selected_id = $this->action_flydown->value;
if (isset($this->action_items[$selected_id])) {
$this->selected = $this->action_items[$selected_id];
@@ -115,7 +118,9 @@ class SwatActions extends SwatControl implements SwatUIParent {
/**
* Add an action item.
+ *
* Adds a SwatActionItem to this SwatActions widget.
+ *
* @param SwatActionItem $item A reference to the item to add.
*/
public function addActionItem(SwatActionItem $item) {
@@ -123,16 +128,19 @@ class SwatActions extends SwatControl implements SwatUIParent {
}
private function createWidgets() {
- if ($this->created) return;
+ if ($this->created)
+ return;
$this->created = true;
- $this->actionfly = new SwatFlydown($this->id.'_actionfly');
- $this->actionfly->onchange = "swatActionsDisplay(this, '{$this->id}');";
- $this->actionfly->show_blank = $this->show_blank;
+ $this->action_flydown = new SwatFlydown($this->id.'_action_flydown');
+ $this->action_flydown->onchange =
+ "swatActionsDisplay(this, '{$this->id}');";
+
+ $this->action_flydown->show_blank = $this->show_blank;
foreach ($this->action_items as $item)
- $this->actionfly->options[$item->id] = $item->title;
+ $this->action_flydown->options[$item->id] = $item->title;
$this->apply_button = new SwatButton($this->id.'_apply_button');
$this->apply_button->setTitleFromStock('apply');
@@ -155,7 +163,6 @@ class SwatActions extends SwatControl implements SwatUIParent {
* @param $child A reference to a child object to add.
*/
public function addChild($child) {
-
if ($child instanceof SwatActionItem)
$this->addActionItem($child);
else
|
Tidy this file
- wrap lines at <I> chars
- rename $actionfly to $action_flydown
svn commit r<I>
|
silverorange_swat
|
train
|
fc47f8c27cc5d1c913ecee59dc995083a2d7d955
|
diff --git a/spec/controllers/system_group_events_controller_spec.rb b/spec/controllers/system_group_events_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/system_group_events_controller_spec.rb
+++ b/spec/controllers/system_group_events_controller_spec.rb
@@ -65,7 +65,7 @@ describe SystemGroupEventsController do
describe 'show' do
before (:each) do
- controller.stub!(:jobs).and_return([@job])
+ @group.stub_chain(:jobs, :where, :first).and_return(@job)
end
it "should render the show partial" do
|
<I> - fix spec test on system group events
|
Katello_katello
|
train
|
e06bf2ed5b9d06ee2fdc5c73bcdf3fb4e7cc6073
|
diff --git a/src/de/lmu/ifi/dbs/pca/LinearCorrelationPCA.java b/src/de/lmu/ifi/dbs/pca/LinearCorrelationPCA.java
index <HASH>..<HASH> 100644
--- a/src/de/lmu/ifi/dbs/pca/LinearCorrelationPCA.java
+++ b/src/de/lmu/ifi/dbs/pca/LinearCorrelationPCA.java
@@ -29,24 +29,8 @@ public class LinearCorrelationPCA extends AbstractCorrelationPCA {
List<Integer> ids) {
StringBuffer msg = new StringBuffer();
- // centroid
- DoubleVector centroid = Util.centroid(database, ids);
- msg.append("\ncentroid ");
- msg.append(centroid);
-
- // covariance matrixArray
- int columns = centroid.getDimensionality();
- int rows = ids.size();
- double[][] matrixArray = new double[rows][columns];
-
- for (int i = 0; i < rows; i++) {
- DoubleVector obj = database.get(ids.get(i));
- for (int d = 0; d < columns; d++) {
- matrixArray[i][d] = obj.getValue(d + 1) - centroid.getValue(d + 1);
- }
- }
- Matrix centeredMatrix = new Matrix(matrixArray);
- Matrix covariance = centeredMatrix.transpose().times(centeredMatrix);
+ // covariance matrix
+ Matrix covariance = Util.covarianceMatrix(database, ids);
msg.append("\ncov ");
msg.append(covariance);
diff --git a/src/de/lmu/ifi/dbs/utilities/Util.java b/src/de/lmu/ifi/dbs/utilities/Util.java
index <HASH>..<HASH> 100644
--- a/src/de/lmu/ifi/dbs/utilities/Util.java
+++ b/src/de/lmu/ifi/dbs/utilities/Util.java
@@ -3,12 +3,10 @@ package de.lmu.ifi.dbs.utilities;
import de.lmu.ifi.dbs.data.DoubleVector;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.Distance;
+import de.lmu.ifi.dbs.linearalgebra.Matrix;
import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.StringTokenizer;
+import java.util.*;
/**
* @version 0.1
@@ -63,7 +61,7 @@ public final class Util {
/**
* Formats the double d with the specified number format.
*
- * @param d the double array to be formatted
+ * @param d the double array to be formatted
* @param nf the number format to be used for formatting
* @return a String representing the double d
*/
@@ -116,10 +114,10 @@ public final class Util {
/**
* Formats the double array d with the specified number format.
*
- * @param d the double array to be formatted
- * @param sep the seperator between the single values of the double array,
- * e.g. ','
- * @param nf the number format to be used for formatting
+ * @param d the double array to be formatted
+ * @param sep the seperator between the single values of the double array,
+ * e.g. ','
+ * @param nf the number format to be used for formatting
* @return a String representing the double array d
*/
public static String format(double[] d, String sep, NumberFormat nf) {
@@ -214,6 +212,35 @@ public final class Util {
}
/**
+ * Determines the covarianvce matrix of the specified objects
+ * stored in the given database. The objects belonging to the specified ids
+ * must be instance of <code>DoubleVector</code>.
+ *
+ * @param database the database storing the objects
+ * @param ids the ids of the objects
+ * @return the covarianvce matrix of the specified objects
+ */
+ public static Matrix covarianceMatrix(Database<DoubleVector> database, List<Integer> ids) {
+ // centroid
+ DoubleVector centroid = centroid(database, ids);
+
+ // covariance matrixArray
+ int columns = centroid.getDimensionality();
+ int rows = ids.size();
+ double[][] matrixArray = new double[rows][columns];
+
+ for (int i = 0; i < rows; i++) {
+ DoubleVector obj = database.get(ids.get(i));
+ for (int d = 0; d < columns; d++) {
+ matrixArray[i][d] = obj.getValue(d + 1) - centroid.getValue(d + 1);
+ }
+ }
+ Matrix centeredMatrix = new Matrix(matrixArray);
+ Matrix covariance = centeredMatrix.transpose().times(centeredMatrix);
+ return covariance;
+ }
+
+ /**
* Returns a new <code>Double</code> array initialized to the values
* represented by the specified <code>String</code> and separated by comma, as performed
* by the <code>valueOf</code> method of class
|
new method covarianceMatrix
|
elki-project_elki
|
train
|
44e6a506b9b49150b2343022549131a513e9263a
|
diff --git a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go
index <HASH>..<HASH> 100644
--- a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go
+++ b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go
@@ -214,7 +214,16 @@ func (c *ManagedDiskController) DeleteManagedDisk(diskURI string) error {
return fmt.Errorf("failed to delete disk(%s) since it's in attaching or detaching state", diskURI)
}
- rerr := c.common.cloud.DisksClient.Delete(ctx, resourceGroup, diskName)
+ disk, rerr := c.common.cloud.DisksClient.Get(ctx, resourceGroup, diskName)
+ if rerr != nil {
+ return rerr.Error()
+ }
+
+ if disk.ManagedBy != nil {
+ return fmt.Errorf("disk(%s) already attached to node(%s), could not be deleted", diskURI, *disk.ManagedBy)
+ }
+
+ rerr = c.common.cloud.DisksClient.Delete(ctx, resourceGroup, diskName)
if rerr != nil {
return rerr.Error()
}
|
fix: check disk status before disk azure disk
|
kubernetes_kubernetes
|
train
|
226757a73cdbbf07ab20312c62ab6767971232cd
|
diff --git a/lib/ronin/database.rb b/lib/ronin/database.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/database.rb
+++ b/lib/ronin/database.rb
@@ -20,11 +20,9 @@
require 'ronin/database/database'
-module Ronin
- Database.upgrade do
- require 'ronin/author'
- require 'ronin/license'
- require 'ronin/arch'
- require 'ronin/os'
- end
+Ronin::Database.upgrade do
+ require 'ronin/author'
+ require 'ronin/license'
+ require 'ronin/arch'
+ require 'ronin/os'
end
diff --git a/lib/ronin/platform.rb b/lib/ronin/platform.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/platform.rb
+++ b/lib/ronin/platform.rb
@@ -24,10 +24,8 @@ require 'ronin/platform/overlay'
require 'ronin/platform/platform'
require 'ronin/database'
-module Ronin
- Database.upgrade do
- require 'ronin/platform/maintainer'
- require 'ronin/platform/cached_file'
- require 'ronin/platform/overlay'
- end
+Ronin::Database.upgrade do
+ require 'ronin/platform/maintainer'
+ require 'ronin/platform/cached_file'
+ require 'ronin/platform/overlay'
end
|
Don't require files within the Ronin namespace.
|
ronin-ruby_ronin
|
train
|
73ab708d30be6a324832db9b6ff78e3406fd3771
|
diff --git a/src/main/java/org/robolectric/res/AndroidResourcePathFinder.java b/src/main/java/org/robolectric/res/AndroidResourcePathFinder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/robolectric/res/AndroidResourcePathFinder.java
+++ b/src/main/java/org/robolectric/res/AndroidResourcePathFinder.java
@@ -3,12 +3,7 @@ package org.robolectric.res;
import android.R;
import org.robolectric.util.PropertiesHelper;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.List;
+import java.io.*;
import java.util.Properties;
public class AndroidResourcePathFinder {
@@ -37,7 +32,7 @@ public class AndroidResourcePathFinder {
return resourcePath;
}
- throw new RuntimeException("Unable to find path to Android SDK");
+ throw new RuntimeException("Unable to find path to Android SDK, (you probably need a local.properties file, see: http://pivotal.github.com/robolectric/resources.html");
}
private String getAndroidResourcePathFromLocalProperties() {
|
Point users to the website when their tests can't find Android.
|
robolectric_robolectric
|
train
|
a4e3544c889cd3145f37ab837adb70ad1ce04ac9
|
diff --git a/tests/specs/get-state.js b/tests/specs/get-state.js
index <HASH>..<HASH> 100644
--- a/tests/specs/get-state.js
+++ b/tests/specs/get-state.js
@@ -19,10 +19,22 @@ test('getState preserves "account" property', function (t) {
t.is(state.account.id, 'id1', 'account id is preserved')
})
+test('getState without "PouchDB" option', function (t) {
+ t.plan(1)
+
+ t.throws(function () {
+ getState({
+ url: 'http://localhost:1234/hoodie'
+ })
+ }, /options.PouchDB is required/, 'throws exception when "PouchDB" option is not defined')
+})
+
test('getState without "url" option', function (t) {
t.plan(1)
t.throws(function () {
- getState()
- }, /"url" option is not defined/, 'throws exception when "url" option is not defined')
+ getState({
+ PouchDB: function () {}
+ })
+ }, /options.url is required/, 'throws exception when "url" option is not defined')
})
diff --git a/tests/specs/init.js b/tests/specs/init.js
index <HASH>..<HASH> 100644
--- a/tests/specs/init.js
+++ b/tests/specs/init.js
@@ -163,10 +163,10 @@ test('hoodie.store gets initialized with options.PouchDB', function (t) {
}
}
})
+ var CustomStoreMock = simple.stub()
simple.mock(getApi.internals, 'Store', {
defaults: function () { return CustomStoreMock }
})
- var CustomStoreMock = simple.stub()
simple.mock(getApi.internals.Store, 'defaults').returnWith(CustomStoreMock)
var PouchDB = simple.stub()
|
test: adapt for `options.url` and `options.PouchDB`
|
hoodiehq_hoodie-client
|
train
|
1c82d9316a986642a0d4c26227ea902636b8bf29
|
diff --git a/libact/query_strategies/__init__.py b/libact/query_strategies/__init__.py
index <HASH>..<HASH> 100644
--- a/libact/query_strategies/__init__.py
+++ b/libact/query_strategies/__init__.py
@@ -1,9 +1,14 @@
"""
Concrete query strategy classes.
"""
+import logging
+logger = logging.getLogger(__name__)
from .active_learning_by_learning import ActiveLearningByLearning
-from .hintsvm import HintSVM
+try:
+ from .hintsvm import HintSVM
+except ImportError:
+ logger.warn('HintSVM library not found, not importing.')
from .uncertainty_sampling import UncertaintySampling
from .query_by_committee import QueryByCommittee
from .quire import QUIRE
|
hintsvm: not importing if library not found
|
ntucllab_libact
|
train
|
46c49ea0b92f4b479cd260d19bbdc8c9ae47bf76
|
diff --git a/lib/dm-core/collection.rb b/lib/dm-core/collection.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/collection.rb
+++ b/lib/dm-core/collection.rb
@@ -1101,7 +1101,7 @@ module DataMapper
if resource.saved?
@identity_map[resource.key] = resource
@orphans.delete(resource)
- else
+ elsif !resource.frozen?
resource.attributes = default_attributes
end
|
Do not set the default attributes when the resource is frozen
|
datamapper_dm-core
|
train
|
96b1f801d0a0a55fe38451f8374174908592e096
|
diff --git a/zappa/core.py b/zappa/core.py
index <HASH>..<HASH> 100644
--- a/zappa/core.py
+++ b/zappa/core.py
@@ -2136,6 +2136,7 @@ class Zappa(object):
'"detail": <detail>, ' \
'"version": <version>,' \
'"resources": <resources>,' \
+ '"id": <id>,' \
'"kwargs": %s' \
'}' % json.dumps(kwargs)
@@ -2156,7 +2157,8 @@ class Zappa(object):
'region': '$.region',
'detail': '$.detail',
'version': '$.version',
- 'resources': '$.resources'
+ 'resources': '$.resources',
+ 'id': '$.id'
},
'InputTemplate': input_template
}
|
added the id field. Now mirrors the event sample in
<URL>
|
Miserlou_Zappa
|
train
|
0662a9f40a19932741e41c608454f120dc44d2b7
|
diff --git a/src/watoki/deli/router/DynamicRouter.php b/src/watoki/deli/router/DynamicRouter.php
index <HASH>..<HASH> 100644
--- a/src/watoki/deli/router/DynamicRouter.php
+++ b/src/watoki/deli/router/DynamicRouter.php
@@ -63,7 +63,7 @@ class DynamicRouter implements Router {
}
}
- $nextContext = $request->getContext();
+ $nextContext = $request->getContext()->copy();
foreach (new Path($target->slice(0, $i)->toArray()) as $part) {
$nextContext->append($part);
}
diff --git a/src/watoki/deli/router/StaticRouter.php b/src/watoki/deli/router/StaticRouter.php
index <HASH>..<HASH> 100644
--- a/src/watoki/deli/router/StaticRouter.php
+++ b/src/watoki/deli/router/StaticRouter.php
@@ -98,7 +98,7 @@ class StaticRouter implements Router {
$object = $this->factory->getInstance($fullClassName);
$nextRequest = $request->copy();
- $nextContext = $request->getContext();
+ $nextContext = $request->getContext()->copy();
foreach ($currentTarget as $targetPart) {
$nextContext->append($targetPart);
}
|
Fixed: Routers didn't copy old context
|
watoki_deli
|
train
|
eb4bf651e58987ab0196ddfd58e286ce10fef702
|
diff --git a/tsdb/engine.go b/tsdb/engine.go
index <HASH>..<HASH> 100644
--- a/tsdb/engine.go
+++ b/tsdb/engine.go
@@ -208,8 +208,8 @@ type CompactionPlannerCreator func(cfg Config) interface{}
// be sure to observe every file that is added or removed even in the presence of process death.
type FileStoreObserver interface {
// FileFinishing is called before a file is renamed to it's final name.
- FileFinishing(path string) error
+ FileFinishing(id uint64, path string) error
// FileUnlinking is called before a file is unlinked.
- FileUnlinking(path string) error
+ FileUnlinking(id uint64, path string) error
}
diff --git a/tsdb/engine/tsm1/engine.go b/tsdb/engine/tsm1/engine.go
index <HASH>..<HASH> 100644
--- a/tsdb/engine/tsm1/engine.go
+++ b/tsdb/engine/tsm1/engine.go
@@ -205,7 +205,7 @@ func NewEngine(id uint64, idx tsdb.Index, path string, walPath string, sfile *ts
fs := NewFileStore(path)
if opt.FileStoreObserver != nil {
- fs.WithObserver(opt.FileStoreObserver)
+ fs.WithObserver(id, opt.FileStoreObserver)
}
cache := NewCache(uint64(opt.Config.CacheMaxMemorySize), path)
diff --git a/tsdb/engine/tsm1/file_store.go b/tsdb/engine/tsm1/file_store.go
index <HASH>..<HASH> 100644
--- a/tsdb/engine/tsm1/file_store.go
+++ b/tsdb/engine/tsm1/file_store.go
@@ -181,6 +181,7 @@ type FileStore struct {
currentTempDirID int
+ id uint64
obs tsdb.FileStoreObserver
}
@@ -228,7 +229,8 @@ func NewFileStore(dir string) *FileStore {
}
// WithObserver sets the observer for the file store.
-func (f *FileStore) WithObserver(obs tsdb.FileStoreObserver) {
+func (f *FileStore) WithObserver(id uint64, obs tsdb.FileStoreObserver) {
+ f.id = id
f.obs = obs
}
@@ -692,7 +694,7 @@ func (f *FileStore) replace(oldFiles, newFiles []string, updatedFn func(r []TSMF
// give the observer a chance to process the file first.
if f.obs != nil {
- if err := f.obs.FileFinishing(file); err != nil {
+ if err := f.obs.FileFinishing(f.id, file); err != nil {
return err
}
}
@@ -749,7 +751,7 @@ func (f *FileStore) replace(oldFiles, newFiles []string, updatedFn func(r []TSMF
// give the observer a chance to process the file first.
if f.obs != nil {
- if err := f.obs.FileUnlinking(file.Path()); err != nil {
+ if err := f.obs.FileUnlinking(f.id, file.Path()); err != nil {
return err
}
}
|
tsdb: add shard number to the observer
an observer may want to know what shard the file is part of. this
way, they don't have to rely on brittle file path parsing.
|
influxdata_influxdb
|
train
|
57a59962e68eaeadf1f37601d3af1880e0104357
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -6,24 +6,47 @@ Python library for the [NeverBounce API v3](https://neverbounce.com/) — a real
[Sign up](https://app.neverbounce.com/register) to get an [API username and key](https://app.neverbounce.com/settings/api) and 1000 free monthly verifications.
+### A single email verification
+
```python
from neverbounce import NeverBounce
neverbounce = NeverBounce('my_api_username', 'my_api_key')
-verified_email = neverbounce.verify_single('some.email@example.com')
+verified_email = neverbounce.verify('some.email@example.com')
-verified_email.result
+verified_email.result_text
# 'valid'
-verified_email.is_valid
-# True
-
verified_email.result_code
# 0
+verified_email.is_valid
+# True
+
str(verified_email)
# 'some.email@example.com: valid'
```
+
+### Bulk verification
+
+```python
+from neverbounce import NeverBounce
+
+neverbounce = NeverBounce('my_api_username', 'my_api_key')
+emails = ['some.email@example.com', 'john.doe@gmail.com']
+job_id = neverbounce.create_job(emails).job_id
+
+# Periodically poll for the verification results
+job_status = neverbounce.check_status(job_id)
+
+# Retrieve the results
+if job_status.is_completed:
+ verified_emails = neverbounce.retrieve_results(job_id)
+ for email in verified_emails:
+ print(str(email))
+```
+
+
## Documentation
* [Official docs for the NeverBounce RESTful API](https://docs.neverbounce.com/)
diff --git a/neverbounce/client.py b/neverbounce/client.py
index <HASH>..<HASH> 100644
--- a/neverbounce/client.py
+++ b/neverbounce/client.py
@@ -1,5 +1,5 @@
import requests
-
+from json import JSONDecodeError
from .exceptions import AccessTokenExpired, NeverBounceAPIError, InvalidResponseError
from .email import VerifiedEmail, VerifiedBulkEmail
from .account import Account
@@ -115,18 +115,19 @@ class NeverBounce:
# Handle the download.
if response.headers.get('Content-Type') == 'application/octet-stream':
return response.content.decode('utf-8')
- elif response.headers.get('Content-Type') == 'application/json':
- resp = response.json()
+ else:
+ try:
+ resp = response.json()
+ except JSONDecodeError:
+ raise InvalidResponseError('Failed to handle the response content-type {}.'.format(
+ response.headers.get('Content-Type'))
+ )
if 'success' in resp and not resp['success']:
if 'msg' in resp and resp['msg'] == 'Authentication failed':
raise AccessTokenExpired
else:
raise NeverBounceAPIError(response)
return resp
- else:
- raise InvalidResponseError('Failed to handle the response content-type {}.'.format(
- response.headers.get('Content-Type'))
- )
def _parse_csv(self, csv):
"""
diff --git a/neverbounce/job.py b/neverbounce/job.py
index <HASH>..<HASH> 100644
--- a/neverbounce/job.py
+++ b/neverbounce/job.py
@@ -46,3 +46,7 @@ class JobStatus(Job):
def __str__(self):
return '{} job: {}'.format(self.status, self.job_id)
+
+ @property
+ def is_completed(self):
+ return self.status_code == 4
diff --git a/test/test_job.py b/test/test_job.py
index <HASH>..<HASH> 100644
--- a/test/test_job.py
+++ b/test/test_job.py
@@ -58,6 +58,10 @@ def test_job_status_status_code(job_status):
assert job_status.status_code == 4
+def test_job_status_is_completed(job_status):
+ assert job_status.is_completed
+
+
def test_job_status_status(job_status):
assert job_status.status == 'completed'
|
Fixed the invalid content type handling.
Added docs for bulk verification.
|
martinkosir_neverbounce-python
|
train
|
3fbf298f5e21c8bd90b157c8b39552a2973a2d72
|
diff --git a/lib/que/web/sql.rb b/lib/que/web/sql.rb
index <HASH>..<HASH> 100644
--- a/lib/que/web/sql.rb
+++ b/lib/que/web/sql.rb
@@ -53,6 +53,7 @@ Que::Web::SQL = {
) locks ON (que_jobs.id=locks.job_id)
WHERE
job_class LIKE ($1)
+ OR que_jobs.args #>> '{0, job_class}' ILIKE ($1)
SQL
failing_jobs: <<-SQL.freeze,
SELECT que_jobs.*
@@ -62,7 +63,12 @@ Que::Web::SQL = {
FROM pg_locks
WHERE locktype = 'advisory'
) locks ON (que_jobs.id=locks.job_id)
- WHERE locks.job_id IS NULL AND error_count > 0 AND job_class LIKE ($3)
+ WHERE locks.job_id IS NULL
+ AND error_count > 0
+ AND (
+ job_class LIKE ($3)
+ OR que_jobs.args #>> '{0, job_class}' ILIKE ($3)
+ )
ORDER BY run_at
LIMIT $1::int
OFFSET $2::int
@@ -75,7 +81,12 @@ Que::Web::SQL = {
FROM pg_locks
WHERE locktype = 'advisory'
) locks ON (que_jobs.id=locks.job_id)
- WHERE locks.job_id IS NULL AND error_count = 0 AND job_class LIKE ($3)
+ WHERE locks.job_id IS NULL
+ AND error_count = 0
+ AND (
+ job_class LIKE ($3)
+ OR que_jobs.args #>> '{0, job_class}' ILIKE ($3)
+ )
ORDER BY run_at
LIMIT $1::int
OFFSET $2::int
|
Allow search by activejob class name (#<I>)
|
statianzo_que-web
|
train
|
15c2bba4cd42705907964dc4f3dac276226c87e2
|
diff --git a/lib/xcodeproj/workspace.rb b/lib/xcodeproj/workspace.rb
index <HASH>..<HASH> 100644
--- a/lib/xcodeproj/workspace.rb
+++ b/lib/xcodeproj/workspace.rb
@@ -71,7 +71,8 @@ module Xcodeproj
# @return [void]
#
def <<(projpath)
- @file_references << projpath
+ project_file_reference = Xcodeproj::Workspace::FileReference.new(projpath)
+ @file_references << project_file_reference
load_schemes_from_project File.expand_path(projpath)
end
|
Fixes adding a project to a workspace
Method “<<“ was missing a conversion from string path to FileReference
|
CocoaPods_Xcodeproj
|
train
|
206af39bb3b888eccadd66c71ec8d36c066bd5b9
|
diff --git a/socialregistration/contrib/twitter/client.py b/socialregistration/contrib/twitter/client.py
index <HASH>..<HASH> 100644
--- a/socialregistration/contrib/twitter/client.py
+++ b/socialregistration/contrib/twitter/client.py
@@ -13,6 +13,8 @@ class Twitter(OAuth):
access_token_url = 'https://api.twitter.com/oauth/access_token'
auth_url = 'https://api.twitter.com/oauth/authenticate'
+ info_url = 'https://api.twitter.com/1/account/verify_credentials.json'
+
def get_callback_url(self, **kwargs):
if self.is_https():
return urlparse.urljoin(
@@ -23,7 +25,7 @@ class Twitter(OAuth):
reverse('socialregistration:twitter:callback'))
def get_user_info(self):
- return self._access_token_dict
+ return self.request(self.info_url)
@staticmethod
def get_session_key():
|
use twitter's api to obtain user info
|
flashingpumpkin_django-socialregistration
|
train
|
085567231657efb3292bab88895692d2781d20eb
|
diff --git a/lib/autoprefixer-rails/sprockets.rb b/lib/autoprefixer-rails/sprockets.rb
index <HASH>..<HASH> 100644
--- a/lib/autoprefixer-rails/sprockets.rb
+++ b/lib/autoprefixer-rails/sprockets.rb
@@ -57,7 +57,7 @@ module AutoprefixerRails
end
# Sprockets 2 API new and render
- def render(_, _)
+ def render(*)
self.class.run(@filename, @source)
end
end
|
Workaround for Sorbet rbi generation (#<I>)
Please note we don't guarantee any support for sorbet.
|
ai_autoprefixer-rails
|
train
|
9eac1ab8192ab7aca7ee99f5302402c012f3b4fd
|
diff --git a/server-coreless/src/test/java/org/openqa/selenium/server/mock/MockPIFrameTest.java b/server-coreless/src/test/java/org/openqa/selenium/server/mock/MockPIFrameTest.java
index <HASH>..<HASH> 100644
--- a/server-coreless/src/test/java/org/openqa/selenium/server/mock/MockPIFrameTest.java
+++ b/server-coreless/src/test/java/org/openqa/selenium/server/mock/MockPIFrameTest.java
@@ -320,7 +320,7 @@ public class MockPIFrameTest extends TestCase {
frame.expectCommand("getTitle", "", "");
frame.sendResult("OK,foo");
// 3. driver receives "OK,foo"
- getTitle.expectResult("OK");
+ getTitle.expectResult("OK,foo");
// 4. browser waits around for another command that never arrives. In 10 seconds, server replies "retryLast"
frame.expectCommand("retryLast", "", "");
// 5. browser retries
|
Oops, last minute cleanup let a typo slip in
r<I>
|
SeleniumHQ_selenium
|
train
|
3d8c99c255711bd1934d013144e6fa1b2f940fcb
|
diff --git a/lifxlan/device.py b/lifxlan/device.py
index <HASH>..<HASH> 100644
--- a/lifxlan/device.py
+++ b/lifxlan/device.py
@@ -94,6 +94,9 @@ class Device(object):
def get_port(self):
return self.port
+ def get_ip_addr(self):
+ return self.ip_addr
+
def get_label(self):
try:
response = self.req_with_resp(GetLabel, StateLabel)
|
added get_ip_addr() to Device API
|
mclarkk_lifxlan
|
train
|
59e447c9e19c3daf359d68c49d7aa64c590f3589
|
diff --git a/slave/buildslave/runprocess.py b/slave/buildslave/runprocess.py
index <HASH>..<HASH> 100644
--- a/slave/buildslave/runprocess.py
+++ b/slave/buildslave/runprocess.py
@@ -355,7 +355,7 @@ class RunProcess:
self.environ = newenv
else: # not environ
self.environ = os.environ.copy()
- self.initialStdin = initialStdin
+ self.initialStdin = to_str(initialStdin)
self.logEnviron = logEnviron
self.timeout = timeout
self.ioTimeoutTimer = None
diff --git a/slave/buildslave/test/unit/test_runprocess.py b/slave/buildslave/test/unit/test_runprocess.py
index <HASH>..<HASH> 100644
--- a/slave/buildslave/test/unit/test_runprocess.py
+++ b/slave/buildslave/test/unit/test_runprocess.py
@@ -38,6 +38,10 @@ from buildslave.test.util.misc import BasedirMixin
from buildslave.test.util.misc import nl
+def catCommand():
+ return [sys.executable, '-c', 'import sys; sys.stdout.write(sys.stdin.read())']
+
+
def stdoutCommand(output):
return [sys.executable, '-c', 'import sys; sys.stdout.write("%s\\n")' % output]
@@ -203,6 +207,18 @@ class TestRunProcess(BasedirMixin, unittest.TestCase):
d.addCallback(check)
return d
+ def testInitialStdinUnicode(self):
+ b = FakeSlaveBuilder(False, self.basedir)
+ s = runprocess.RunProcess(b, catCommand(), self.basedir, initialStdin=u'hello')
+
+ d = s.start()
+
+ def check(ign):
+ self.failUnless({'stdout': nl('hello')} in b.updates, b.show())
+ self.failUnless({'rc': 0} in b.updates, b.show())
+ d.addCallback(check)
+ return d
+
def testMultiWordStringCommandQuotes(self):
b = FakeSlaveBuilder(False, self.basedir)
# careful! This command must execute the same on windows and UNIX
|
Fix slave hanging caused by sending unicode as initialStdin for shell command
|
buildbot_buildbot
|
train
|
3861da278c6d73081749003ef5c6e41fa16c5e89
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -20,7 +20,8 @@ var MEMBERSHIPS = 'j' // j for joined memberships..? :3
var MESSAGES = 'm'
var TOPICS = 't'
var USERS = 'u'
-var MODERATION = 'x'
+var MODERATION_AUTH = 'x'
+var MODERATION_INFO = 'y'
module.exports = Cabal
module.exports.databaseVersion = DATABASE_VERSION
@@ -93,8 +94,10 @@ function Cabal (storage, key, opts) {
this.kcore.use('users', createUsersView(
sublevel(this.db, USERS, { valueEncoding: json })))
this.kcore.use('moderation', createModerationView(
- this, sublevel(this.db, MODERATION, { valueEncoding: json }))
- )
+ this,
+ sublevel(this.db, MODERATION_AUTH, { valueEncoding: json }),
+ sublevel(this.db, MODERATION_INFO, { valueEncoding: json })
+ ))
this.messages = this.kcore.api.messages
this.channels = this.kcore.api.channels
diff --git a/views/moderation.js b/views/moderation.js
index <HASH>..<HASH> 100644
--- a/views/moderation.js
+++ b/views/moderation.js
@@ -10,9 +10,11 @@ var collect = require('collect-stream')
var duplexify = require('duplexify')
var { nextTick } = process
-module.exports = function (cabal, db) {
+const MOD = 'm!'
+
+module.exports = function (cabal, authDb, infoDb) {
var events = new EventEmitter()
- var auth = mauth(db)
+ var auth = mauth(authDb)
auth.on('update', function (update) {
events.emit('update', update)
})
@@ -159,6 +161,22 @@ module.exports = function (cabal, db) {
if (cb) collect(ro, cb)
return ro
}),
+ listModerationBy: function (core, key, cb) {
+ var r = infoDb.createReadStream({
+ gt: MOD + key + '@',
+ lt: MOD + key + '@\uffff'
+ })
+ var out = through.obj(function (row, enc, next) {
+ cabal.getMessage(row.key.slice(MOD.length), function (err, doc) {
+ if (err) return next(err)
+ next(null, doc)
+ })
+ })
+ pump(r, out)
+ var ro = readonly(out)
+ if (cb) collect(ro, cb)
+ return ro
+ },
// ^--- queries above | updates below ---v
setFlags: function (core, opts, cb) {
publishFlagUpdate(core, 'set', opts, cb)
@@ -237,12 +255,20 @@ module.exports = function (cabal, db) {
function map (rows, next) {
next = once(next)
var batch = []
+ var infoBatch = []
var pending = 1
rows.forEach(function (row) {
if (!row.value || !row.value.content) return
+ var id = row.value.content.id
+ if (!id) return
+ if (/^flags\/(set|add|remove)$/.test(row.value.type)) {
+ infoBatch.push({
+ type: 'put',
+ key: MOD + row.key + '@' + row.seq,
+ value: ''
+ })
+ }
if (row.value.type === 'flags/set') {
- var id = row.value.content.id
- if (!id) return
var group = row.value.content.channel || '@'
var flags = checkLocal(
id, group, row.key,
@@ -257,8 +283,6 @@ module.exports = function (cabal, db) {
flags
})
} else if (row.value.type === 'flags/add') {
- var id = row.value.content.id
- if (!id) return
var group = row.value.content.channel || '@'
pending++
auth.getFlags({ group, id }, function (err, prevFlags) {
@@ -280,8 +304,6 @@ module.exports = function (cabal, db) {
if (--pending === 0) done()
})
} else if (row.value.type === 'flags/remove') {
- var id = row.value.content.id
- if (!id) return
var group = row.value.content.channel || '@'
pending++
auth.getFlags({ group, id }, function (err, flags) {
@@ -308,9 +330,22 @@ module.exports = function (cabal, db) {
})
if (--pending === 0) done()
function done () {
+ var pending = 1
if (batch.length > 0) {
- auth.batch(batch, { skip: true }, next)
- } else next()
+ pending++
+ auth.batch(batch, { skip: true }, function (err) {
+ if (err) next(err)
+ else if (--pending === 0) next()
+ })
+ }
+ if (infoBatch.length > 0) {
+ pending++
+ infoDb.batch(infoBatch, function (err) {
+ if (err) next(err)
+ else if (--pending === 0) next()
+ })
+ }
+ if (--pending === 0) next()
}
}
|
listModerationBy function and secondary index
|
cabal-club_cabal-core
|
train
|
1a6d30c1eaa1b9ef1287ec54d63e4bb340a9ec6c
|
diff --git a/sisu-inject/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/URLClassSpace.java b/sisu-inject/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/URLClassSpace.java
index <HASH>..<HASH> 100644
--- a/sisu-inject/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/URLClassSpace.java
+++ b/sisu-inject/guice-bean/guice-bean-reflect/src/main/java/org/sonatype/guice/bean/reflect/URLClassSpace.java
@@ -20,7 +20,7 @@ import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
-import java.util.LinkedHashSet;
+import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.Manifest;
@@ -203,15 +203,18 @@ public final class URLClassSpace
final List<URL> searchPath = new ArrayList<URL>();
Collections.addAll( searchPath, classPath );
+ final List<URL> expandedPath = new ArrayList<URL>();
+ final Set<String> visited = new HashSet<String>();
+
// search path may grow, so use index not iterator
- final Set<URL> expandedPath = new LinkedHashSet<URL>();
for ( int i = 0; i < searchPath.size(); i++ )
{
final URL url = searchPath.get( i );
- if ( null == url || !expandedPath.add( url ) )
+ if ( null == url || !visited.add( url.toString() ) )
{
continue; // already processed
}
+ expandedPath.add( url );
final String[] classPathEntries;
try
{
|
Avoid potentially blocking call to URL.equals()
|
sonatype_sisu
|
train
|
94f26e01228a94819edfbb8c079de615272588ec
|
diff --git a/src/Ddeboer/Imap/Message/Headers.php b/src/Ddeboer/Imap/Message/Headers.php
index <HASH>..<HASH> 100644
--- a/src/Ddeboer/Imap/Message/Headers.php
+++ b/src/Ddeboer/Imap/Message/Headers.php
@@ -32,7 +32,11 @@ class Headers
if (isset($this->array['from'])) {
$from = current($this->array['from']);
- $this->array['from'] = new EmailAddress($from->mailbox, $from->host, \imap_utf8($from->personal));
+ $this->array['from'] = new EmailAddress(
+ $from->mailbox,
+ $from->host,
+ isset($from->personal) ? \imap_utf8($from->personal) : null
+ );
}
if (isset($this->array['to'])) {
@@ -41,7 +45,7 @@ class Headers
$recipients[] = new EmailAddress(
str_replace('\'', '', $to->mailbox),
str_replace('\'', '', $to->host),
- \imap_utf8($to->personal)
+ isset($from->personal) ? \imap_utf8($from->personal) : null
);
}
$this->array['to'] = $recipients;
|
Don't presuppose 'personal' is present
|
ddeboer_imap
|
train
|
c0e2349a144e7b76834e68daf272194c4b1b81ec
|
diff --git a/mapi/providers.py b/mapi/providers.py
index <HASH>..<HASH> 100644
--- a/mapi/providers.py
+++ b/mapi/providers.py
@@ -315,8 +315,8 @@ class TVDb(Provider):
yield result
elif series and date:
if not match(
- r'(19|20)\d{2}(-(?:0[1-9]|1[012])(-(?:[012][1-9]|3[01]))?)?',
- date
+ r'(19|20)\d{2}(-(?:0[1-9]|1[012])(-(?:[012][1-9]|3[01]))?)?',
+ date
):
raise MapiProviderException('Date must be in YYYY-MM-DD format')
for result in self._search_series_date(series, date):
@@ -349,7 +349,7 @@ class TVDb(Provider):
season=str(entry['airedSeason']),
episode=str(entry['airedEpisodeNumber']),
date=entry['firstAired'],
- title=entry['episodeName'],
+ title=entry['episodeName'].split(';', 1)[0],
synopsis=str(entry['overview'])
.replace('\r\n', '').replace(' ', '').strip(),
media='television',
@@ -407,7 +407,7 @@ class TVDb(Provider):
season=str(entry['airedSeason']),
episode=str(entry['airedEpisodeNumber']),
date=entry['firstAired'],
- title=entry['episodeName'],
+ title=entry['episodeName'].split(';', 1)[0],
synopsis=str(entry['overview']).replace('\r\n', '')
.replace(' ', '').strip(),
media='television',
|
Truncates long episode titles
... For certain variety or talk show series like the Daily show, Saturday Night Live, etc., the episode title will be crazily long with all the segments and acts in the title; this will truncate it to the featured guest name
|
jkwill87_mapi
|
train
|
d122a9c24b698acf1190f61ce5653d0c04741539
|
diff --git a/internal/action/setup.go b/internal/action/setup.go
index <HASH>..<HASH> 100644
--- a/internal/action/setup.go
+++ b/internal/action/setup.go
@@ -10,6 +10,7 @@ import (
"github.com/gopasspw/gopass/internal/backend"
"github.com/gopasspw/gopass/internal/backend/crypto/age"
"github.com/gopasspw/gopass/internal/backend/crypto/gpg"
+ gpgcli "github.com/gopasspw/gopass/internal/backend/crypto/gpg/cli"
"github.com/gopasspw/gopass/internal/out"
"github.com/gopasspw/gopass/internal/store/root"
"github.com/gopasspw/gopass/pkg/ctxutil"
@@ -112,7 +113,7 @@ func (s *Action) initCheckPrivateKeys(ctx context.Context, crypto backend.Crypto
func (s *Action) initGenerateIdentity(ctx context.Context, crypto backend.Crypto, name, email string) error {
out.Printf(ctx, "🧪 Creating cryptographic key pair (%s) ...", crypto.Name())
- if crypto.Name() == "gpgcli" {
+ if crypto.Name() == gpgcli.Name {
var err error
out.Printf(ctx, "🎩 Gathering information for the %s key pair ...", crypto.Name())
diff --git a/internal/backend/crypto/gpg/cli/gpg.go b/internal/backend/crypto/gpg/cli/gpg.go
index <HASH>..<HASH> 100644
--- a/internal/backend/crypto/gpg/cli/gpg.go
+++ b/internal/backend/crypto/gpg/cli/gpg.go
@@ -20,6 +20,8 @@ var (
Ext = "gpg"
// IDFile is the name of the recipients file used by this backend.
IDFile = ".gpg-id"
+ // Name is the name of this backend.
+ Name = "gpg"
)
// GPG is a gpg wrapper.
@@ -88,7 +90,7 @@ func (g *GPG) Initialized(ctx context.Context) error {
// Name returns gpg.
func (g *GPG) Name() string {
- return "gpg"
+ return Name
}
// Ext returns gpg.
|
Fix identity detection when using gpg (#<I>)
Fixes #<I>
RELEASE_NOTES=[BUGFIX] Fix gpg identity detection
|
gopasspw_gopass
|
train
|
7a6d7d30aeb2bd4c679c563a896120e23eb4a356
|
diff --git a/auto_ml/utils_model_training.py b/auto_ml/utils_model_training.py
index <HASH>..<HASH> 100644
--- a/auto_ml/utils_model_training.py
+++ b/auto_ml/utils_model_training.py
@@ -1,7 +1,7 @@
from collections import Iterable
import os
-from keras.callbacks import EarlyStopping
+from keras.callbacks import EarlyStopping, TerminateOnNaN
import numpy as np
import pandas as pd
import scipy
@@ -90,8 +90,12 @@ class FinalModelATC(BaseEstimator, TransformerMixin):
print('To measure validation accuracy, we will split off a random 10 percent of your data set')
X_fit, X_val, y, y_val = train_test_split(X_fit, y, test_size=0.1)
- early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1)
- self.model.fit(X_fit, y, callbacks=[early_stopping], validation_data=(X_val, y_val))
+ early_stopping = EarlyStopping(monitor='val_loss', patience=15, verbose=1)
+ terminate_on_nan = TerminateOnNaN()
+ # TODO: add in model checkpointer
+ self.model.fit(X_fit, y, callbacks=[early_stopping, terminate_on_nan], validation_data=(X_val, y_val))
+ # TODO: load best model from file, save to self.model
+ # TODO: delete temp file
else:
self.model.fit(X_fit, y)
@@ -105,6 +109,7 @@ class FinalModelATC(BaseEstimator, TransformerMixin):
print('Stopping training at this point because we heard a KeyboardInterrupt')
print('If the model is functional at this point, we will output the model in its latest form')
print('Note that not all models can be interrupted and still used, and that this feature generally is an unofficial beta-release feature that is known to fail on occasion')
+ # TODO: try to load the best model we had
pass
return self
|
adds early stopping for nans, and thoughts on more accurate model checkpointing that will let us bail early
|
ClimbsRocks_auto_ml
|
train
|
656b37760ad3594d9929ffb82ee710b96046b55d
|
diff --git a/lib/millstone.js b/lib/millstone.js
index <HASH>..<HASH> 100644
--- a/lib/millstone.js
+++ b/lib/millstone.js
@@ -10,8 +10,7 @@ var _ = require('underscore'),
get = require('get'),
zipfile = require('zipfile'),
Step = require('step'),
- utils = require('./util.js'),
- sqlite3 = require('sqlite3');
+ utils = require('./util.js');
// Known SRS values
var SRS = {
@@ -336,10 +335,12 @@ function resolve(options, callback) {
var group = this.group();
resolved.Layer.forEach(function(l, index) {
var d = l.Datasource;
- if (d.type == 'sqlite' && d.table) {
+ // mapnik's sqlite plugin resolves attached databases
+ // relative to the main database, but in tilemill we prefer
+ // to interpret relative to the project so we resolve here
+ if (d.type == 'sqlite' && d.table && d.attachdb) {
var next = group();
- if (!d.attachdb) d.attachdb = '';
- var db = new sqlite3.Database(d.file), dbs = d.attachdb.split(',');
+ var dbs = d.attachdb.split(',');
Step(function() {
var group = this.group();
for (i = 0; i < dbs.length; i++) (function(next) {
@@ -352,60 +353,13 @@ function resolve(options, callback) {
file = path.resolve(path.join(base, file));
dbs[i] = dbs[i].split('@').shift() + '@' + file;
}
-
- db.run("ATTACH DATABASE '" +
- file + "' AS " +
- dbs[i].split('@').shift(),
- function(err) {
- next(err);
- });
+ next();
+
})(group());
}, function(err) {
if (err) throw err;
d.attachdb = dbs.join(',');
- var self = this;
- // Attach databases.
- // If this query returns results, it's a Spatialite database.
- // Otherwise it's normal SQLite.
- db.all("SELECT name FROM sqlite_master WHERE type='table' AND name='geometry_columns_auth'",
- function(err, result) {
- if (err) throw err;
-
- if (result.length) {
- d.wkb_format = 'spatialite';
- }
- self();
- });
- }, function(err) {
- if (err) throw err;
- var group = this.group(),
- parts = d.table.replace(/^\(|\)$/g, '')
- .split(/WHERE/i).shift()
- .split(/LIMIT/i).shift()
- .split(/FROM/i).pop()
- .split(/(LEFT|INNER|RIGHT)\s+JOIN/i);
- _(parts).each(function(part, key) {
- if (key % 2 === 0) (function(next) {
- var table = part.split(/ON/i)
- .shift()
- .split('.')
- .pop()
- .replace(/^\s*|\s*$/g, '');
- // Query geometry table looking for pk to use as `key_field`.
- db.all('PRAGMA table_info(' + table + ')', function(err, result) {
- if (err) return next(err);
- _(result).each(function(row) {
- if (row.pk) {
- d.key_field = row.name;
- }
- });
- next();
- });
- })(group());
- });
- }, function(err) {
- db.close();
- next(err);
+ return next(err);
});
}
});
|
mapnik upstream now supports 1) detecting spatialite type geometries and detecting the primary key (key_field), so drop the brittle code in millstone that did lookahead inspection
|
tilemill-project_millstone
|
train
|
723bfb0eac3a70cca0673b79d9d151a9a85b5921
|
diff --git a/contractcourt/channel_arbitrator.go b/contractcourt/channel_arbitrator.go
index <HASH>..<HASH> 100644
--- a/contractcourt/channel_arbitrator.go
+++ b/contractcourt/channel_arbitrator.go
@@ -215,7 +215,7 @@ func NewChannelArbitrator(cfg ChannelArbitratorConfig,
// Start starts all the goroutines that the ChannelArbitrator needs to operate.
func (c *ChannelArbitrator) Start() error {
if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
- return fmt.Errorf("already started")
+ return nil
}
var (
@@ -287,12 +287,14 @@ func (c *ChannelArbitrator) Start() error {
// Stop signals the ChannelArbitrator for a graceful shutdown.
func (c *ChannelArbitrator) Stop() error {
if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
- return fmt.Errorf("already shutting down")
+ return nil
}
log.Debugf("Stopping ChannelArbitrator(%v)", c.cfg.ChanPoint)
- c.cfg.ChainEvents.Cancel()
+ if c.cfg.ChainEvents.Cancel != nil {
+ c.cfg.ChainEvents.Cancel()
+ }
for _, activeResolver := range c.activeResolvers {
activeResolver.Stop()
@@ -1346,6 +1348,13 @@ func (c *ChannelArbitrator) channelAttendant(bestHeight int32,
}),
)
+ // We've cooperatively closed the channel, so we're no longer
+ // needed.
+ case <-c.cfg.ChainEvents.CooperativeClosure:
+ log.Infof("ChannelArbitrator(%v) closing due to co-op "+
+ "closure", c.cfg.ChanPoint)
+ return
+
// The remote party has broadcast the commitment on-chain.
// We'll examine our state to determine if we need to act at
// all.
|
contractcourt: channel arbitrators now exit on co-op close of the channel
|
lightningnetwork_lnd
|
train
|
7f46d1b022f45731e3fe28097389c38d948b38b9
|
diff --git a/lib/Redmine/Api/Version.php b/lib/Redmine/Api/Version.php
index <HASH>..<HASH> 100644
--- a/lib/Redmine/Api/Version.php
+++ b/lib/Redmine/Api/Version.php
@@ -27,7 +27,7 @@ class Version extends AbstractApi
}
/**
- * Returns an array of projects with name/id pairs (or id/name if $reserse is false)
+ * Returns an array of name/id pairs (or id/name if not $reverse) of issue versions for $project.
*
* @param string|int $project project id or literal identifier
* @param boolean $forceUpdate to force the update of the projects var
@@ -48,7 +48,7 @@ class Version extends AbstractApi
}
/**
- * Get a category id given its name and related project
+ * Get an issue version id given its name and related project
*
* @param string|int $project project id or literal identifier
* @param string $name
@@ -65,7 +65,7 @@ class Version extends AbstractApi
}
/**
- * Get extended information about an issue category
+ * Get extended information about an issue version
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Versions#GET-2
*
* @param string $id the issue category id
@@ -77,7 +77,7 @@ class Version extends AbstractApi
}
/**
- * Create a new issue category of $project given an array of $params
+ * Create a new version for $project given an array of $params
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Versions#POST
*
* @param string|int $project project id or literal identifier
@@ -166,10 +166,10 @@ class Version extends AbstractApi
}
/**
- * Delete an issue category
+ * Delete a version.
* @link http://www.redmine.org/projects/redmine/wiki/Rest_Versions#DELETE
*
- * @param int $id id of the category
+ * @param int $id id of the version
* @return string
*/
public function remove($id)
|
Updates phpdoc (typos due du copypasting from categories).
|
kbsali_php-redmine-api
|
train
|
e560823be200b2e4f573bcc3da417876b443f488
|
diff --git a/CHANGELOG b/CHANGELOG
index <HASH>..<HASH> 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -23,6 +23,7 @@
* Paymentez: Add new gateway [bpollack] #2685
* PayU Latam: Provide a mechanism to override the amount in verify [dtykocki] #2688
* Mercado Pago: Support X-Device-Session-ID Header [bpollack] #2689
+* Mercado Pago: Support arbitrary additional_info JSON [bpollack] #2691
== Version 1.75.0 (November 9, 2017)
* Barclaycard Smartpay: Clean up test options hashes [bpollack] #2632
diff --git a/lib/active_merchant/billing/gateways/mercado_pago.rb b/lib/active_merchant/billing/gateways/mercado_pago.rb
index <HASH>..<HASH> 100644
--- a/lib/active_merchant/billing/gateways/mercado_pago.rb
+++ b/lib/active_merchant/billing/gateways/mercado_pago.rb
@@ -117,7 +117,8 @@ module ActiveMerchant #:nodoc:
post[:device_id] = options[:device_id] if options[:device_id]
post[:additional_info] = {
ip_address: options[:ip_address]
- }
+ }.merge(options[:additional_info] || {})
+
add_address(post, options)
add_shipping_address(post, options)
diff --git a/test/unit/gateways/mercado_pago_test.rb b/test/unit/gateways/mercado_pago_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/gateways/mercado_pago_test.rb
+++ b/test/unit/gateways/mercado_pago_test.rb
@@ -203,6 +203,20 @@ class MercadoPagoTest < Test::Unit::TestCase
assert_success response
end
+ def test_includes_additional_data
+ @options[:additional_info] = {'foo' => 'bar', 'baz' => 'quux'}
+ response = stub_comms do
+ @gateway.purchase(@amount, @credit_card, @options)
+ end.check_request do |endpoint, data, headers|
+ if data =~ /payment_method_id/
+ assert_match(/"foo":"bar"/, data)
+ assert_match(/"baz":"quux"/, data)
+ end
+ end.respond_with(successful_purchase_response)
+
+ assert_success response
+ end
+
private
def pre_scrubbed
|
Mercado Pago: add arbitrary additional_info parameters
Remote:
<I> tests, <I> assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
<I>% passed
Unit:
<I> tests, <I> assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
<I>% passed
Closes #<I>
|
activemerchant_active_merchant
|
train
|
2fe85a338028162b80b7a7f7436397457a10fa70
|
diff --git a/jwt/algorithms.py b/jwt/algorithms.py
index <HASH>..<HASH> 100644
--- a/jwt/algorithms.py
+++ b/jwt/algorithms.py
@@ -1,7 +1,7 @@
import hashlib
import hmac
-from .compat import constant_time_compare, string_types, text_type
+from .compat import binary_type, constant_time_compare, is_string_type
from .exceptions import InvalidKeyError
from .utils import der_to_raw_signature, raw_to_der_signature
@@ -112,10 +112,10 @@ class HMACAlgorithm(Algorithm):
self.hash_alg = hash_alg
def prepare_key(self, key):
- if not isinstance(key, string_types) and not isinstance(key, bytes):
+ if not is_string_type(key):
raise TypeError('Expecting a string- or bytes-formatted key.')
- if isinstance(key, text_type):
+ if not isinstance(key, binary_type):
key = key.encode('utf-8')
invalid_strings = [
@@ -156,8 +156,8 @@ if has_crypto:
isinstance(key, RSAPublicKey):
return key
- if isinstance(key, string_types):
- if isinstance(key, text_type):
+ if is_string_type(key):
+ if not isinstance(key, binary_type):
key = key.encode('utf-8')
try:
@@ -213,8 +213,8 @@ if has_crypto:
isinstance(key, EllipticCurvePublicKey):
return key
- if isinstance(key, string_types):
- if isinstance(key, text_type):
+ if is_string_type(key):
+ if not isinstance(key, binary_type):
key = key.encode('utf-8')
# Attempt to load key. We don't know if it's
diff --git a/jwt/compat.py b/jwt/compat.py
index <HASH>..<HASH> 100644
--- a/jwt/compat.py
+++ b/jwt/compat.py
@@ -11,14 +11,18 @@ PY3 = sys.version_info[0] == 3
if PY3:
- string_types = str,
text_type = str
binary_type = bytes
else:
- string_types = basestring,
text_type = unicode
binary_type = str
+string_types = (text_type, binary_type)
+
+
+def is_string_type(val):
+ return any([isinstance(val, typ) for typ in string_types])
+
def timedelta_total_seconds(delta):
try:
diff --git a/setup.cfg b/setup.cfg
index <HASH>..<HASH> 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,6 +1,8 @@
[flake8]
max-line-length = 119
-exclude = docs/
+exclude =
+ docs/,
+ .tox/
[wheel]
universal = 1
diff --git a/tests/test_algorithms.py b/tests/test_algorithms.py
index <HASH>..<HASH> 100644
--- a/tests/test_algorithms.py
+++ b/tests/test_algorithms.py
@@ -92,6 +92,13 @@ class TestAlgorithms:
algo.prepare_key(pem_key.read())
@pytest.mark.skipif(not has_crypto, reason='Not supported without cryptography library')
+ def test_rsa_should_accept_pem_private_key_bytes(self):
+ algo = RSAAlgorithm(RSAAlgorithm.SHA256)
+
+ with open(key_path('testkey_rsa'), 'rb') as pem_key:
+ algo.prepare_key(pem_key.read())
+
+ @pytest.mark.skipif(not has_crypto, reason='Not supported without cryptography library')
def test_rsa_should_accept_unicode_key(self):
algo = RSAAlgorithm(RSAAlgorithm.SHA256)
@@ -142,6 +149,13 @@ class TestAlgorithms:
algo.prepare_key(ensure_unicode(ec_key.read()))
@pytest.mark.skipif(not has_crypto, reason='Not supported without cryptography library')
+ def test_ec_should_accept_pem_private_key_bytes(self):
+ algo = ECAlgorithm(ECAlgorithm.SHA256)
+
+ with open(key_path('testkey_ec'), 'rb') as ec_key:
+ algo.prepare_key(ec_key.read())
+
+ @pytest.mark.skipif(not has_crypto, reason='Not supported without cryptography library')
def test_ec_verify_should_return_false_if_signature_invalid(self):
algo = ECAlgorithm(ECAlgorithm.SHA256)
|
Fix a bug where a PEM private key as bytes raises a TypeError
|
jpadilla_pyjwt
|
train
|
901180475e90eb189f20ed0d8d008d2c40601bae
|
diff --git a/js/lib/cli.js b/js/lib/cli.js
index <HASH>..<HASH> 100755
--- a/js/lib/cli.js
+++ b/js/lib/cli.js
@@ -131,7 +131,7 @@ var interpret = exports.interpret = function(argv, slice) {
cleanOptions(cc.env('jsbeautify_'), knownOpts),
parsed.config,
cc.find('.jsbeautifyrc'),
- cc.find(path.join(process.env.HOME, ".jsbeautifyrc")),
+ cc.find(path.join(process.env.HOME || "", ".jsbeautifyrc")),
__dirname + '/../config/defaults.json'
).snapshot;
|
Update cli.js
HOME environment variable usually not defined in windows.
|
beautify-web_js-beautify
|
train
|
1a06be62d933b5409c6418e4480987391da36dda
|
diff --git a/src/test/java/org/influxdb/InfluxDBTest.java b/src/test/java/org/influxdb/InfluxDBTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/influxdb/InfluxDBTest.java
+++ b/src/test/java/org/influxdb/InfluxDBTest.java
@@ -166,7 +166,7 @@ public class InfluxDBTest {
String dbName = "write_unittest_" + System.currentTimeMillis();
this.influxDB.createDatabase(dbName);
- BatchPoints batchPoints = BatchPoints.database(dbName).tag("async", "true").retentionPolicy("default").build();
+ BatchPoints batchPoints = BatchPoints.database(dbName).time(System.currentTimeMillis(), TimeUnit.MILLISECONDS).tag("async", "true").retentionPolicy("default").build();
Point point1 = Point
.measurement("cpu")
.tag("atag", "test")
@@ -183,4 +183,4 @@ public class InfluxDBTest {
Assert.assertFalse(result.getResults().get(0).getSeries().get(0).getTags().isEmpty());
this.influxDB.deleteDatabase(dbName);
}
-}
\ No newline at end of file
+}
|
Update InfluxDBTest.java
refer to my last change (I described the change but forgot to add it to the code..)
|
influxdata_influxdb-java
|
train
|
d48f7aa70324310403f7114bad0299f9d91af9a5
|
diff --git a/packages/openneuro-server/graphql/resolvers/snapshots.js b/packages/openneuro-server/graphql/resolvers/snapshots.js
index <HASH>..<HASH> 100644
--- a/packages/openneuro-server/graphql/resolvers/snapshots.js
+++ b/packages/openneuro-server/graphql/resolvers/snapshots.js
@@ -24,6 +24,19 @@ export const snapshot = (obj, { datasetId, tag }, context) => {
export const participantCount = async () => {
const aggregateResult = await SnapshotModel.aggregate([
{
+ $lookup: {
+ from: 'datasets',
+ localField: 'datasetId',
+ foreignField: 'id',
+ as: 'dataset',
+ },
+ },
+ {
+ $match: {
+ 'dataset.public': true,
+ },
+ },
+ {
$sort: {
created: -1,
},
|
Filter out private datasets from participant count query.
|
OpenNeuroOrg_openneuro
|
train
|
311b03f8daf33217696df2c1c959454497e6bc96
|
diff --git a/lib/attached/processor/audio.rb b/lib/attached/processor/audio.rb
index <HASH>..<HASH> 100644
--- a/lib/attached/processor/audio.rb
+++ b/lib/attached/processor/audio.rb
@@ -1,15 +1,16 @@
require 'attached/processor/base'
+require 'attached/processor/error'
module Attached
module Processor
class Audio < Base
-
-
+
+
attr_reader :path
attr_reader :extension
attr_reader :preset
-
+
# Create a processor.
#
# Parameters:
@@ -37,35 +38,35 @@ module Attached
# self.process
def process
-
+
result = Tempfile.new(["", self.extension])
result.binmode
-
- begin
+ begin
+
parameters = []
parameters << "--preset #{self.preset}" if self.preset
-
+
parameters << self.path
parameters << result.path
-
+
parameters = parameters.join(" ").squeeze(" ")
-
+
`lame #{parameters}`
-
- raise "Command 'lame' failed. Ensure file is an audio and attachment options are valid." unless $?.exitstatus == 0
-
+
rescue Errno::ENOENT
+ raise "command 'lame' not found: ensure LAME is installed"
+ end
- raise "Command 'lame' not found. Ensure 'LAME' is installed."
-
+ unless $?.exitstatus == 0
+ raise Attached::Processor::Error, "attachment file must be an audio file"
end
-
+
return result
-
+
end
-
+
end
end
end
|
added better exception handling and fixed some audio processor errors
|
ksylvest_attached
|
train
|
2977fea865688c2d2ba4a07087b676ffbb8efc98
|
diff --git a/bogo/valid_vietnamese.py b/bogo/valid_vietnamese.py
index <HASH>..<HASH> 100644
--- a/bogo/valid_vietnamese.py
+++ b/bogo/valid_vietnamese.py
@@ -77,6 +77,14 @@ def is_valid_combination(components):
for i in range(len(comps)):
comps[i] = utils.change_case(comps[i], 1)
+ # Allow 'đ' to appear in abbreviations like 'đm', 'đc', 'kgcđ', etc.
+ if comps[0] and not comps[1] and not comps[2] and \
+ not comps[0] in ('gi', 'qu'):
+ for c in comps[0]:
+ if not c in CONSONANTS:
+ return False
+ return True
+
# Check if our start sound is a proper consonant
if (comps[0] != u'') and (not (comps[0] in CONSONANTS)):
return False
|
Allow 'đ' to appear in abbreviations like 'đm', 'đc', 'kgcđ', etc.
|
BoGoEngine_bogo-python
|
train
|
6983c901163424d4695f39879386031f88088f53
|
diff --git a/scss/__init__.py b/scss/__init__.py
index <HASH>..<HASH> 100644
--- a/scss/__init__.py
+++ b/scss/__init__.py
@@ -52,7 +52,6 @@ import os.path
import re
import sys
import textwrap
-import time
from scss import config
from scss.cssdefs import (
@@ -64,7 +63,7 @@ from scss.cssdefs import (
_zero_units_re, _zero_re,
_escape_chars_re, _interpolate_re,
_spaces_re, _expand_rules_space_re, _collapse_properties_space_re,
- _variable_re, _undefined_re,
+ _undefined_re,
_strings_re, _prop_split_re, _skip_word_re,
)
from scss.expression import CalculatorScanner, eval_expr, interpolate
@@ -72,7 +71,7 @@ from scss.functions import ALL_BUILTINS_LIBRARY
from scss.functions.compass.sprites import sprite_map
from scss.rule import UnparsedBlock, SassRule
from scss.types import BooleanValue, ListValue, NumberValue, StringValue
-from scss.util import depar, dequote, normalize_var, split_params, to_str
+from scss.util import depar, dequote, normalize_var, split_params, to_str, profile, print_timing
log = logging.getLogger(__name__)
@@ -87,8 +86,6 @@ except ImportError:
################################################################################
-profiling = {}
-
_safe_strings = {
'^doubleslash^': '//',
@@ -139,59 +136,6 @@ _default_scss_opts = {
_default_search_paths = ['.']
-def print_timing(level=0):
- def _print_timing(func):
- if config.VERBOSITY:
- def wrapper(*args, **kwargs):
- if config.VERBOSITY >= level:
- t1 = time.time()
- res = func(*args, **kwargs)
- t2 = time.time()
- profiling.setdefault(func.func_name, 0)
- profiling[func.func_name] += (t2 - t1)
- return res
- else:
- return func(*args, **kwargs)
- return wrapper
- else:
- return func
- return _print_timing
-
-
-# Profiler decorator
-# import pstats
-# import cProfile
-# try:
-# from cStringIO import StringIO
-# except:
-# from StringIO import StringIO
-# def profile(fn):
-# def wrapper(*args, **kwargs):
-# profiler = cProfile.Profile()
-# stream = StringIO()
-# profiler.enable()
-# try:
-# res = fn(*args, **kwargs)
-# finally:
-# profiler.disable()
-# stats = pstats.Stats(profiler, stream=stream)
-# stats.sort_stats('time')
-# print >>stream, ""
-# print >>stream, "=" * 100
-# print >>stream, "Stats:"
-# stats.print_stats()
-# print >>stream, "=" * 100
-# print >>stream, "Callers:"
-# stats.print_callers()
-# print >>stream, "=" * 100
-# print >>stream, "Callees:"
-# stats.print_callees()
-# print >>sys.stderr, stream.getvalue()
-# stream.close()
-# return res
-# return wrapper
-
-
################################################################################
diff --git a/scss/util.py b/scss/util.py
index <HASH>..<HASH> 100644
--- a/scss/util.py
+++ b/scss/util.py
@@ -1,4 +1,16 @@
import re
+import sys
+import time
+
+import pstats
+import cProfile
+try:
+ from cStringIO import StringIO
+except:
+ from StringIO import StringIO
+
+from scss import config
+
def split_params(params):
params = params.split(',') or []
@@ -72,3 +84,56 @@ def normalize_var(var):
dashes.
"""
return var.replace('_', '-')
+
+
+################################################################################
+# Function timing decorator
+profiling = {}
+
+
+def print_timing(level=0):
+ def _print_timing(func):
+ if config.VERBOSITY:
+ def wrapper(*args, **kwargs):
+ if config.VERBOSITY >= level:
+ t1 = time.time()
+ res = func(*args, **kwargs)
+ t2 = time.time()
+ profiling.setdefault(func.func_name, 0)
+ profiling[func.func_name] += (t2 - t1)
+ return res
+ else:
+ return func(*args, **kwargs)
+ return wrapper
+ else:
+ return func
+ return _print_timing
+
+
+################################################################################
+# Profiler decorator
+def profile(fn):
+ def wrapper(*args, **kwargs):
+ profiler = cProfile.Profile()
+ stream = StringIO()
+ profiler.enable()
+ try:
+ res = fn(*args, **kwargs)
+ finally:
+ profiler.disable()
+ stats = pstats.Stats(profiler, stream=stream)
+ stats.sort_stats('time')
+ print >>stream, ""
+ print >>stream, "=" * 100
+ print >>stream, "Stats:"
+ stats.print_stats()
+ print >>stream, "=" * 100
+ print >>stream, "Callers:"
+ stats.print_callers()
+ print >>stream, "=" * 100
+ print >>stream, "Callees:"
+ stats.print_callees()
+ print >>sys.stderr, stream.getvalue()
+ stream.close()
+ return res
+ return wrapper
|
Print timing and profiler moved to the util module
|
Kronuz_pyScss
|
train
|
4994043c10f2293387e46105e00098fc81da4a56
|
diff --git a/apiserver/common/networkingcommon/networkconfigapi.go b/apiserver/common/networkingcommon/networkconfigapi.go
index <HASH>..<HASH> 100644
--- a/apiserver/common/networkingcommon/networkconfigapi.go
+++ b/apiserver/common/networkingcommon/networkconfigapi.go
@@ -53,7 +53,12 @@ func (api *NetworkConfigAPI) getOneMachineProviderNetworkConfig(m *state.Machine
}
interfaceInfos, err := netEnviron.NetworkInterfaces(instId)
- if err != nil {
+ if errors.IsNotSupported(err) {
+ // It's possible to have a networking environ, but not support
+ // NetworkInterfaces(). In leiu of adding SupportsNetworkInterfaces():
+ logger.Infof("provider network interfaces not supported: %v", err)
+ return nil, nil
+ } else if err != nil {
return nil, errors.Annotatef(err, "cannot get network interfaces of %q", instId)
}
if len(interfaceInfos) == 0 {
diff --git a/provider/openstack/networking.go b/provider/openstack/networking.go
index <HASH>..<HASH> 100644
--- a/provider/openstack/networking.go
+++ b/provider/openstack/networking.go
@@ -312,8 +312,8 @@ func (n *NeutronNetworking) Subnets(instId instance.Id, subnetIds []network.Id)
if instId != instance.UnknownId {
// TODO(hml): 2017-03-20
- // Implment Subnets() for case where instId is specified
- return nil, errors.NotImplementedf("neutron subnets with instance Id")
+ // Implement Subnets() for case where instId is specified
+ return nil, errors.NotSupportedf("neutron subnets with instance Id")
} else {
neutron := n.env.neutron()
subnets, err := neutron.ListSubnetsV2()
@@ -345,5 +345,5 @@ func (n *NeutronNetworking) Subnets(instId instance.Id, subnetIds []network.Id)
}
func (n *NeutronNetworking) NetworkInterfaces(instId instance.Id) ([]network.InterfaceInfo, error) {
- return nil, errors.NotImplementedf("neutron network interfaces")
+ return nil, errors.NotSupportedf("neutron network interfaces")
}
|
BUG <I>: Gracefully handle NetworkInterfaces() returning NotSupported
|
juju_juju
|
train
|
79c8088e9b50617ace13aa5769d529a4b0b350e7
|
diff --git a/lib/user_notifier/models/base.rb b/lib/user_notifier/models/base.rb
index <HASH>..<HASH> 100644
--- a/lib/user_notifier/models/base.rb
+++ b/lib/user_notifier/models/base.rb
@@ -23,7 +23,7 @@ class UserNotifier::Base < ActiveRecord::Base
end
def deliver!
- UserNotifier::EmailWorker.perform_async(self.class.name.to_s, self.id)
+ UserNotifier::EmailWorker.perform_at((self.try(:deliver_at) || Time.now), self.class.name.to_s, self.id)
end
def deliver_without_worker
diff --git a/spec/models/user_notifier/base_spec.rb b/spec/models/user_notifier/base_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/user_notifier/base_spec.rb
+++ b/spec/models/user_notifier/base_spec.rb
@@ -34,12 +34,12 @@ describe UserNotifier::Base do
end
it "should not create notification for same association and different template name" do
- UserNotification.notify_once('another_test', user)
+ UserNotification.notify_once('another_test', user)
expect(UserNotification.count(:all)).to eq 2
end
it "should not create duplicate notification for same association and template name" do
- UserNotification.notify_once('test', user)
+ UserNotification.notify_once('test', user)
expect(UserNotification.count(:all)).to eq 1
end
end
@@ -47,12 +47,27 @@ describe UserNotifier::Base do
describe ".notify" do
subject{ notification }
- it "should create notification in the database" do
- subject
- expect(UserNotification.last).to be_present
+ context "direct notification" do
+ it "should create notification in the database" do
+ subject
+ expect(UserNotification.last).to be_present
+ end
+
+ its(:template_name){ should eq 'test' }
+ its(:deliver_at){ should be_kind_of(Time) }
end
- its(:template_name){ should eq 'test' }
+ context "with scheduled notification" do
+ let(:deliver_at) { 3.days.from_now }
+ let(:notification) { UserNotification.notify('deliver_at_test', user, nil, {deliver_at: deliver_at}) }
+ it "should create notification in the database" do
+ subject
+ expect(UserNotification.last).to be_present
+ end
+
+ its(:template_name){ should eq 'deliver_at_test' }
+ its(:deliver_at){ should eq deliver_at }
+ end
end
describe "#deliver" do
|
deliver method should use deliver_at or time.now to deliver a notification
now all notifications should send via peform_at instead peform_async
|
diogob_user_notifier
|
train
|
051ec02226c65fd10a11cb624fa24577fab9d062
|
diff --git a/src/DayPickerInput.js b/src/DayPickerInput.js
index <HASH>..<HASH> 100644
--- a/src/DayPickerInput.js
+++ b/src/DayPickerInput.js
@@ -108,6 +108,7 @@ export default class DayPickerInput extends React.Component {
component: PropTypes.any,
overlayComponent: PropTypes.any,
+ style: PropTypes.object,
classNames: PropTypes.shape({
container: PropTypes.string,
overlayWrapper: PropTypes.string,
@@ -567,7 +568,7 @@ export default class DayPickerInput extends React.Component {
const Input = this.props.component;
const { inputProps } = this.props;
return (
- <div className={this.props.classNames.container}>
+ <div className={this.props.classNames.container} style={this.props.style}>
<Input
ref={el => (this.input = el)}
placeholder={this.props.placeholder}
|
Add style prop to DayPickerInput (#<I>)
* Add style prop to DayPickerInput
* Update style prop propType
|
gpbl_react-day-picker
|
train
|
9b11c5a06398255d50cc10f403ec5062decee6b9
|
diff --git a/lib/dm-core/property.rb b/lib/dm-core/property.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/property.rb
+++ b/lib/dm-core/property.rb
@@ -369,22 +369,52 @@ module DataMapper
unique?
end
- # Returns equality of properties. Properties are
- # comparable only if their models are equal and
- # both properties has the same name.
+ ##
+ # Compares another Property for equivalency
#
- # @param [Object] other
- # the object to compare self to
+ # TODO: needs example
+ #
+ # @param [Property] other
+ # the other Property to compare with
#
# @return [TrueClass, FalseClass]
- # Result of equality comparison.
+ # true if they are equivalent, false if not
#
- # @api public
+ # @api semipublic
+ def ==(other)
+ if equal?(other)
+ return true
+ end
+
+ unless other.respond_to?(:model) && other.respond_to?(:name)
+ return false
+ end
+
+ cmp?(other, :==)
+ end
+
+ ##
+ # Compares another Property for equality
+ #
+ # TODO: needs example
+ #
+ # @param [Property] other
+ # the other Property to compare with
+ #
+ # @return [TrueClass, FalseClass]
+ # true if they are equal, false if not
+ #
+ # @api semipublic
def eql?(other)
- return true if equal?(other)
- return false unless other.kind_of?(self.class)
+ if equal?(other)
+ return true
+ end
+
+ unless other.kind_of?(self.class)
+ return false
+ end
- model == other.model && name == other.name
+ cmp?(other, :eql?)
end
# Returns maximum property length (if applicable).
@@ -1023,5 +1053,29 @@ module DataMapper
now = Time.now
args.map { |arg| hash[arg] || hash[arg.to_s] || now.send(arg) }
end
+
+ ##
+ # Return true if +other+'s is equivalent or equal to +self+'s
+ #
+ # @param [Property] other
+ # The Property whose attributes are to be compared with +self+'s
+ # @param [Symbol] operator
+ # The comparison operator to use to compare the attributes
+ #
+ # @return [TrueClass, FalseClass]
+ # The result of the comparison of +other+'s attributes with +self+'s
+ #
+ # @api private
+ def cmp?(other, operator)
+ unless model.send(operator, other.model)
+ return false
+ end
+
+ unless name.send(operator, other.name)
+ return false
+ end
+
+ true
+ end
end # class Property
end # module DataMapper
diff --git a/lib/dm-core/query/direction.rb b/lib/dm-core/query/direction.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/query/direction.rb
+++ b/lib/dm-core/query/direction.rb
@@ -21,6 +21,10 @@ module DataMapper
cmp?(other, :eql?)
end
+ def hash
+ property.hash + direction.hash
+ end
+
def reverse!
@direction = @direction == :asc ? :desc : :asc
self
diff --git a/lib/dm-core/query/operator.rb b/lib/dm-core/query/operator.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/query/operator.rb
+++ b/lib/dm-core/query/operator.rb
@@ -21,6 +21,10 @@ module DataMapper
cmp?(other, :eql?)
end
+ def hash
+ target.hash + operator.hash
+ end
+
private
def initialize(target, operator)
diff --git a/lib/dm-core/query/path.rb b/lib/dm-core/query/path.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/query/path.rb
+++ b/lib/dm-core/query/path.rb
@@ -47,6 +47,10 @@ module DataMapper
cmp?(other, :eql?)
end
+ def hash
+ repository_name.hash + relationships.hash + model.hash + property.hash
+ end
+
private
def initialize(repository, relationships, model, property_name = nil)
diff --git a/spec/semipublic/query_spec.rb b/spec/semipublic/query_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/semipublic/query_spec.rb
+++ b/spec/semipublic/query_spec.rb
@@ -1669,7 +1669,52 @@ describe DataMapper::Query do
it { @query.should respond_to(:to_hash) }
describe '#to_hash' do
- it 'should be awesome'
+ describe 'when no raw conditions' do
+ before :all do
+ @query.update(:name => 'Dan Kubb')
+
+ @return = @query.to_hash
+ end
+
+ it { @return.should be_kind_of(Hash) }
+
+ it 'should return expected value' do
+ @return.should == {
+ :fields => [ @model.properties[:name], @model.properties[:referrer_name] ],
+ :offset => 0,
+ :limit => 3,
+ :order => [ DataMapper::Query::Direction.new(@model.properties[:name]) ],
+ :unique => false,
+ :add_reversed => false,
+ :reload => false,
+ DataMapper::Query::Operator.new(@model.properties[:name], :eql) => 'Dan Kubb',
+ }
+ end
+ end
+
+ describe 'when raw conditions' do
+ before :all do
+ @options.update(:conditions => [ 'name = ?', 'Dan Kubb' ])
+ @query = DataMapper::Query.new(@repository, @model, @options.freeze)
+
+ @return = @query.to_hash
+ end
+
+ it { @return.should be_kind_of(Hash) }
+
+ it 'should return expected value' do
+ @return.should == {
+ :fields => [ @model.properties[:name], @model.properties[:referrer_name] ],
+ :conditions => [ '(name = ?)', [ 'Dan Kubb' ] ],
+ :offset => 0,
+ :limit => 3,
+ :order => [ DataMapper::Query::Direction.new(@model.properties[:name]) ],
+ :unique => false,
+ :add_reversed => false,
+ :reload => false,
+ }
+ end
+ end
end
it { @query.should respond_to(:unique?) }
|
Added specs for Query#to_hash
* Fixed Propert#eql? and Property#== to properly compare two Property
objects
* Added #hash method to Property, Query::Direction, Query::Operator,
Query::Path to make it so when they are used in a Hash, they can
be matched up with similar objects and tested for equality/equivalence
|
datamapper_dm-core
|
train
|
dbcee563557ff3138a586a3b324c3bad6adcfda5
|
diff --git a/lib/ruby-progressbar/progressbar.rb b/lib/ruby-progressbar/progressbar.rb
index <HASH>..<HASH> 100644
--- a/lib/ruby-progressbar/progressbar.rb
+++ b/lib/ruby-progressbar/progressbar.rb
@@ -215,9 +215,9 @@ class ProgressBar
end
def set (count)
- if count < 0 || count > @total
- raise "invalid count: #{count} (total: #{@total})"
- end
+ count = 0 if count < 0
+ count = @total if count > @total
+
@current = count
show_if_needed
@previous = @current
|
Dont raise an exception when progress bar is out of range
|
wvanbergen_request-log-analyzer
|
train
|
8475d37c2aa1f721bbd4501978becb6986056043
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -32,6 +32,7 @@ setup(
"Framework :: Django",
"Framework :: Django :: 3.2",
"Framework :: Django :: 4.0",
+ "Framework :: Django :: 4.1",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
|
support Django <I>
|
grantmcconnaughey_django-avatar
|
train
|
ccadc72762154a3e2dc3400209aa07914fdc6204
|
diff --git a/examples/basic/src/index.js b/examples/basic/src/index.js
index <HASH>..<HASH> 100644
--- a/examples/basic/src/index.js
+++ b/examples/basic/src/index.js
@@ -33,7 +33,6 @@ const router = install({
const { component, outlet } = config
delete config.component
delete config.outlet
- console.log(config.path, component,outlet)
return {
...config,
getData: () => ({
@@ -81,6 +80,7 @@ const router = install({
canActivate: (route, navigation) => {
const { stores: { SessionStore } } = route.context
+ console.log('navigation', navigation)
if (SessionStore.isAuthenticated) {
return true
} else {
diff --git a/packages/mobx-little-router/src/Router.js b/packages/mobx-little-router/src/Router.js
index <HASH>..<HASH> 100644
--- a/packages/mobx-little-router/src/Router.js
+++ b/packages/mobx-little-router/src/Router.js
@@ -33,7 +33,7 @@ class Router {
const root = createRouteStateTreeNode({ path: '', match: 'partial' }, getContext) // Initial root.
this.initialChildren = config
this.store = new RouterStore(root)
- this.scheduler = new Scheduler(this.store, middleware)
+ this.scheduler = new Scheduler(this.store, middleware, getContext)
extendObservable(this, {
nextNavigation: computed(() => {
diff --git a/packages/mobx-little-router/src/scheduling/Scheduler.js b/packages/mobx-little-router/src/scheduling/Scheduler.js
index <HASH>..<HASH> 100644
--- a/packages/mobx-little-router/src/scheduling/Scheduler.js
+++ b/packages/mobx-little-router/src/scheduling/Scheduler.js
@@ -21,7 +21,7 @@ export default class Scheduler {
currentNavigation: Navigation
event: Event
- constructor(store: RouterStore, middleware: IMiddleware) {
+ constructor(store: RouterStore, middleware: IMiddleware, getContext: void | (() => any)) {
extendObservable(this, {
currentNavigation: new Navigation({
type: 'POP',
@@ -37,7 +37,7 @@ export default class Scheduler {
this.middleware = withQueryMiddleware
// Run custom middleware first before handing off to our own.
.concat(middleware)
- .concat(handleChildrenLoad)
+ .concat(handleChildrenLoad(getContext))
.concat(updateStore(store))
.concat(handleTransitionFailure(store))
}
@@ -84,10 +84,10 @@ export default class Scheduler {
})
}
-const handleChildrenLoad = transformEventType(EventTypes.CHILDREN_LOAD)(
+const handleChildrenLoad = (getContext: void | (() => any)) => transformEventType(EventTypes.CHILDREN_LOAD)(
action(evt => {
const { navigation, pathElements, leaf, children } = evt
- leaf.node.children.replace(children.map(createRouteStateTreeNode))
+ leaf.node.children.replace(children.map(x => createRouteStateTreeNode(x, getContext)))
if (navigation) {
return {
diff --git a/packages/mobx-little-router/src/scheduling/util/withQueryMiddleware.js b/packages/mobx-little-router/src/scheduling/util/withQueryMiddleware.js
index <HASH>..<HASH> 100644
--- a/packages/mobx-little-router/src/scheduling/util/withQueryMiddleware.js
+++ b/packages/mobx-little-router/src/scheduling/util/withQueryMiddleware.js
@@ -5,10 +5,10 @@ import transformNavigation from '../../middleware/transformNavigation'
export default transformNavigation(navigation => {
const { to } = navigation
if (to && typeof to.search === 'string') {
- return {
+ return navigation.next({
...navigation,
to: { ...to, query: QueryString.parse(to.search.substr(1)) }
- }
+ })
}
return navigation
})
|
Fixes context and navigation problems inside hooks.
|
mobx-little-router_mobx-little-router
|
train
|
e309706362511ad9e947c5e0e5191e2810a6f8be
|
diff --git a/lol_scraper/match_downloader.py b/lol_scraper/match_downloader.py
index <HASH>..<HASH> 100644
--- a/lol_scraper/match_downloader.py
+++ b/lol_scraper/match_downloader.py
@@ -191,7 +191,11 @@ def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf
sleep(10)
continue
except Exception as e:
- logger.exception("Encountered unexpected exception {}".format(e))
+ try:
+ possible_game = "(Possibly for game {})".format(match_id)
+ except:
+ possible_game = ""
+ logger.exception("Encountered unexpected exception {} {}".format(e, possible_game))
continue
finally:
|
Added log to suggest which match could have caused the exception
|
MakersF_LoLScraper
|
train
|
cbb62f9713b7cd65e99c5c791bc2c1befa4c4bbc
|
diff --git a/admin/controllers/Groups.php b/admin/controllers/Groups.php
index <HASH>..<HASH> 100644
--- a/admin/controllers/Groups.php
+++ b/admin/controllers/Groups.php
@@ -13,6 +13,7 @@
namespace Nails\Admin\Auth;
use Nails\Admin\Controller\DefaultController;
+use Nails\Common\Exception\ValidationException;
use Nails\Common\Resource;
use Nails\Factory;
@@ -34,7 +35,7 @@ class Groups extends DefaultController
/**
* Load data for the edit/create view
*
- * @param Resource $oItem The main item object
+ * @param Resource $oItem The main item object
*
* @return void
*/
@@ -76,12 +77,13 @@ class Groups extends DefaultController
/**
* Form validation for edit/create
*
- * @param array $aOverrides Any overrides for the fields; best to do this in the model's describeFields() method
+ * @param string $sMode The mode in which the validation is being run
+ * @param array $aOverrides Any overrides for the fields; best to do this in the model's describeFields() method
*
- * @throws ValidationException
* @return void
+ * @throws ValidationException
*/
- protected function runFormValidation(array $aOverrides = []): void
+ protected function runFormValidation(string $sMode, array $aOverrides = []): void
{
parent::runFormValidation([
'slug' => [
|
Brings admin/Groups in line with changes to Defaultcontroller
|
nails_module-auth
|
train
|
a49a29587c1350af3ed69ac6264a24c4aa5859e6
|
diff --git a/spec/router_spec.rb b/spec/router_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/router_spec.rb
+++ b/spec/router_spec.rb
@@ -59,7 +59,7 @@ module Jimson
namespace 'foo', RouterBarHandler.new
end
- router.jimson_methods.should == ['hi', 'foo.bye']
+ router.jimson_methods.sort.should == ['hi', 'foo.bye'].sort
end
end
|
fix minor spec issue for ruby <I>
|
chriskite_jimson
|
train
|
029c0a3ee9ed4723c203915b75f08d9fa40f38f4
|
diff --git a/src/js/remote.js b/src/js/remote.js
index <HASH>..<HASH> 100644
--- a/src/js/remote.js
+++ b/src/js/remote.js
@@ -698,11 +698,11 @@ Remote.prototype.request_transaction_entry = function (hash) {
.tx_hash(hash);
};
-Remote.prototype.request_ripple_lines_get = function (accountID, index) {
+Remote.prototype.request_account_lines = function (accountID, index) {
// XXX Does this require the server to be trusted?
//utils.assert(this.trusted);
- var request = new Request(this, 'ripple_lines_get');
+ var request = new Request(this, 'account_lines');
request.message.account = accountID;
|
add account_offers and refactor
|
ChainSQL_chainsql-lib
|
train
|
3d2b2eb460a5bf3b25e72a3454889b130b38388d
|
diff --git a/src/main/java/org/camunda/bpm/engine/test/needle/supplier/CamundaInstancesSupplier.java b/src/main/java/org/camunda/bpm/engine/test/needle/supplier/CamundaInstancesSupplier.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/camunda/bpm/engine/test/needle/supplier/CamundaInstancesSupplier.java
+++ b/src/main/java/org/camunda/bpm/engine/test/needle/supplier/CamundaInstancesSupplier.java
@@ -17,6 +17,7 @@ import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.impl.ProcessEngineImpl;
import org.camunda.bpm.engine.impl.interceptor.CommandExecutor;
import org.camunda.bpm.engine.impl.test.TestHelper;
+import org.camunda.bpm.engine.test.function.GetProcessEngineConfiguration;
import com.google.common.collect.Sets;
@@ -73,6 +74,7 @@ public class CamundaInstancesSupplier implements InjectionProviderInstancesSuppl
providers.add(providerFor(getManagementService()));
providers.add(providerFor(getAuthorizationService()));
providers.add(providerFor(getCommandExecutor()));
+ providers.add(providerFor(getProcessEngineConfiguration()));
}
@Override
@@ -115,6 +117,10 @@ public class CamundaInstancesSupplier implements InjectionProviderInstancesSuppl
return processEngine.getManagementService();
}
+ public ProcessEngineConfiguration getProcessEngineConfiguration() {
+ return GetProcessEngineConfiguration.INSTANCE.apply(processEngine);
+ }
+
@Deprecated
@Override
public void close() {
|
add functionality: needle now injects processEngineConfiguration
|
camunda_camunda-bpm-needle
|
train
|
b8e2147da60016080c175fbea580adaee8acdeb5
|
diff --git a/gwpy/timeseries/timeseries.py b/gwpy/timeseries/timeseries.py
index <HASH>..<HASH> 100644
--- a/gwpy/timeseries/timeseries.py
+++ b/gwpy/timeseries/timeseries.py
@@ -1390,7 +1390,7 @@ class TimeSeries(TimeSeriesBase):
>>> import numpy
>>> from gwpy.timeseries import TimeSeries
- >>> series = TimeSeries(np.ones(16384), sample_rate=16384)
+ >>> series = TimeSeries(numpy.ones(16384), sample_rate=16384)
>>> tapered = series.taper()
We can plot it to see how the ends now vary smoothly from 0 to 1:
@@ -1408,7 +1408,7 @@ class TimeSeries(TimeSeriesBase):
from scipy.special import expit
out = self.copy()
# build a Planck tapering window
- window = np.ones(self.size)
+ window = numpy.ones(self.size)
nsteps = int(tau * self.sample_rate.value)
t = self.times.value - self.t0.value
z = tau * (1./t[1:nsteps] + 1./(t[1:nsteps] - tau))
|
Typo in previous commit: np should be numpy
|
gwpy_gwpy
|
train
|
b886049a8fa4c84d5c53222bdc24118c433593a1
|
diff --git a/src/Dispatcher.php b/src/Dispatcher.php
index <HASH>..<HASH> 100644
--- a/src/Dispatcher.php
+++ b/src/Dispatcher.php
@@ -108,6 +108,8 @@ class Dispatcher
* @param \SlaxWeb\Router\Reponse $response Response object
* @param mixed $unknown Any further parameter is sent to Route action
* @return void
+ *
+ * @exceptions \SlaxWeb\Router\Exception\RouteNotFoundException
*/
public function dispatch(Request $request, Response $response)
{
@@ -120,7 +122,15 @@ class Dispatcher
"Trying to find match for ({$method}) '{$requestUri}'"
);
- $route = $this->findRoute($requestMethod, $requestUri);
+ if (($route = $this->findRoute($requestMethod, $requestUri)) === null) {
+ // no route could be found, time to bail out
+ $this->logger->error("No Route found, and no 404 Route defined");
+ throw new Exception\RouteNotFoundException(
+ "No Route definition found for Request URI '{$requestUri}' with"
+ . " HTTP Method '{$method}'"
+ );
+ }
+
// add query parameters if defined
if (empty($this->addQueryParams) === false) {
$request->addQuery($this->addQueryParams);
@@ -176,41 +186,52 @@ class Dispatcher
/**
* Find matching Route
*
- * Find the matching Route based on the Request Method and Request URI. If
- * no matching route is found, action from the 404 route is returned, if found.
- * If also the 404 Route is not found, the 'RouteNotFoundException' is thrown.
- * Otherwise the matching Route objects action Callable is returned.
+ * Try and obtain the route that bests fits the request and return it. If no
+ * such route is found, and no 404 route exists, nor is one returned from a
+ * 'routeNotFound' hook execution, null is returned.
*
* @param int $method Request Method
* @param string $uri Request Uri
- * @return \SlaxWeb\Router\Route
+ * @return \SlaxWeb\Router\Route|null
+ */
+ protected function findRoute(int $method, string $uri)
+ {
+ $route = null;
+ // if URI is empty and a default route is set, use it instead
+ if ($uri !== ""
+ || ($route = $this->routes->defaultRoute()) === null
+ ) {
+ $route = $this->checkContainer($method, $uri);
+ }
+
+ // if route is still null execute the 'routeNotFound' hook, and if no route
+ // is found, try and obtain the 404 route from the container
+ if ($route === null
+ && ($route = $this->routeNotFoundHook()) === null
+ ) {
+ $route = $this->routes->get404Route();
+ }
+ return $route;
+ }
+
+ /**
+ * Check Routes Container
*
- * @exceptions \SlaxWeb\Router\Exception\RouteNotFoundException
+ * Iterates the routes container and tries to match the request to a Route in
+ * the container. Returns the matching Route object if found, or null otherwise.
+ *
+ * @param int $method Request Method
+ * @param string $uri Request Uri
+ * @return \SlaxWeb\Router\Route|null
*/
- protected function findRoute(int $method, string $uri): Route
+ protected function checkContainer(int $method, string $uri)
{
- $notFoundRoute = null;
while (($route = $this->routes->next()) !== false) {
- if ($route->uri === "404RouteNotFound") {
- $notFoundRoute = $route;
- continue;
- }
-
if (($route->method & $method) !== $method) {
continue;
}
- // Default URI, check if default route?
- if ($uri === "" && $route->isDefault) {
- return $route;
- }
-
- $uriMatch = preg_match_all(
- $this->posix2Pcre($route->uri),
- $uri,
- $matches
- );
- if ($uriMatch === 0) {
+ if (preg_match_all($this->posix2Pcre($route->uri), $uri, $matches) === 0) {
continue;
}
@@ -221,7 +242,20 @@ class Dispatcher
return $route;
}
+ return null;
+ }
+ /**
+ * Execute Route Not Found Hook
+ *
+ * Execute the Route Not Found Hook definition with the help of the Hook component
+ * and return a valid Route object if it is found in the Hook execution return
+ * data.
+ *
+ * @return \SlaxWeb\Router\Route|null
+ */
+ public function routeNotFoundHook()
+ {
$result = $this->hooks->exec("router.dispatcher.routeNotFound");
// check if hook call produced a valid Route object
if ($result instanceof Route) {
@@ -235,15 +269,7 @@ class Dispatcher
}
}
}
-
- if ($notFoundRoute !== null) {
- return $notFoundRoute;
- }
- $this->logger->error("No Route found, and no 404 Route defined");
- throw new Exception\RouteNotFoundException(
- "No Route definition found for Request URI '{$uri}' with"
- . " HTTP Method '{$method}'"
- );
+ return null;
}
/**
@@ -272,8 +298,8 @@ class Dispatcher
$changed = "(?P<{$type}{$counters[$type]}>.+?)";
return $changed;
},
- $regex
- );
+ $regex
+ );
}
return $regex;
|
refactor obtain Route object logic
The logic is now more aggregated, and easier to extend.
|
SlaxWeb_Router
|
train
|
116442d040a95d92575a912a599359ac65fd4901
|
diff --git a/demo/src/screens/componentScreens/InputsScreen.js b/demo/src/screens/componentScreens/InputsScreen.js
index <HASH>..<HASH> 100644
--- a/demo/src/screens/componentScreens/InputsScreen.js
+++ b/demo/src/screens/componentScreens/InputsScreen.js
@@ -4,6 +4,17 @@ import {Assets, Constants, Button, Colors, Text, TextInput, TextArea, Typography
const LONG_TEXT = 'Concept, edition and design direction for the editorial piece “La Forma Bruta” by the photographer Martín Bollati. In this piece';
const INPUT_SPACING = 10;
+
+const transformPrice = (value) => {
+ let cleanValue;
+ let priceText = '';
+ if (value) {
+ [cleanValue] = value.match(/^(?:(?:-?(?:0|\d{1,9}))(?:\.\d{0,2})?)|-/) || [''];
+ priceText = cleanValue;
+ }
+ return priceText;
+};
+
export default class InputScreen extends Component {
constructor(props) {
super(props);
@@ -38,11 +49,19 @@ export default class InputScreen extends Component {
containerStyle={{marginBottom: INPUT_SPACING}}
/>
+ <TextInput
+ floatingPlaceholder
+ text70
+ placeholder="with price transformer"
+ value={this.state.value}
+ transformer={transformPrice}
+ />
+
<Text dark40>Text Area</Text>
<View style={{height: 150, borderWidth: 1, marginBottom: INPUT_SPACING, padding: 10, borderColor: Colors.dark60}}>
<TextArea placeholder="write something.."/>
</View>
-
+
<TextInput
text50
placeholder="Big Title Text"
@@ -69,6 +88,7 @@ export default class InputScreen extends Component {
placeholder="Centered"
containerStyle={{marginBottom: INPUT_SPACING}}
/>
+
</ScrollView>
);
}
diff --git a/src/components/inputs/TextInput.js b/src/components/inputs/TextInput.js
index <HASH>..<HASH> 100644
--- a/src/components/inputs/TextInput.js
+++ b/src/components/inputs/TextInput.js
@@ -38,6 +38,10 @@ export default class TextInput extends BaseInput {
* should the input expand to another text area modal
*/
expandable: PropTypes.bool,
+ /**
+ * transform function executed on value and return transformed value
+ */
+ transformer: PropTypes.func,
testId: PropTypes.string,
};
@@ -256,14 +260,20 @@ export default class TextInput extends BaseInput {
}
onChangeText(text) {
- _.invoke(this.props, 'onChangeText', text);
+ let transformedText = text;
+ const {transformer} = this.props;
+ if (_.isFunction(transformer)) {
+ transformedText = transformer(text);
+ }
+
+ _.invoke(this.props, 'onChangeText', transformedText);
this.setState({
- value: text,
+ value: transformedText,
}, this.updateFloatingPlaceholderState);
const {widthExtendBreaks, width} = this.state;
- if (text.length < _.last(widthExtendBreaks)) {
+ if (transformedText.length < _.last(widthExtendBreaks)) {
const typography = this.getTypography();
this.setState({
inputWidth: width - typography.fontSize,
|
add transformer to TextInput allowing to apply all kind of transformations on the text input value
|
wix_react-native-ui-lib
|
train
|
a909703bcde00f976a360b2a6947de254b731bfd
|
diff --git a/src/test/java/org/cactoos/io/TeeOutputTest.java b/src/test/java/org/cactoos/io/TeeOutputTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/cactoos/io/TeeOutputTest.java
+++ b/src/test/java/org/cactoos/io/TeeOutputTest.java
@@ -41,26 +41,15 @@ import org.junit.Test;
*/
public final class TeeOutputTest {
- /**
- * The CONTENT for copying of TeeOutput.
- */
- private static final String CONTENT = "Hello, товарищ!";
-
- /**
- * The TeeOutputTest.DESCRIPTION of failure test.
- */
- private static final String
- DESCRIPTION = "Can't copy Output to Output and return Input";
-
@Test
public void copiesContent() {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ByteArrayOutputStream copy = new ByteArrayOutputStream();
MatcherAssert.assertThat(
- TeeOutputTest.DESCRIPTION,
+ "Can't copy Output to Output and return Input",
new TextOf(
new TeeInput(
- new InputOf(TeeOutputTest.CONTENT),
+ new InputOf("Hello, товарищ!"),
new TeeOutput(
new OutputTo(baos),
new OutputTo(copy)
@@ -84,10 +73,10 @@ public final class TeeOutputTest {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ByteArrayOutputStream copy = new ByteArrayOutputStream();
MatcherAssert.assertThat(
- TeeOutputTest.DESCRIPTION,
+ "Can't copy Output with writer",
new TextOf(
new TeeInput(
- new InputOf(TeeOutputTest.CONTENT),
+ new InputOf("Hello, товарищ! writer"),
new TeeOutput(
new OutputTo(baos),
new WriterTo(copy)
@@ -111,10 +100,10 @@ public final class TeeOutputTest {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ByteArrayOutputStream copy = new ByteArrayOutputStream();
MatcherAssert.assertThat(
- TeeOutputTest.DESCRIPTION,
+ "Can't copy Output with writer and charset",
new TextOf(
new TeeInput(
- new InputOf(TeeOutputTest.CONTENT),
+ new InputOf("Hello, товарищ! writer and charset"),
new TeeOutput(
new OutputTo(baos),
new WriterTo(copy),
@@ -139,10 +128,10 @@ public final class TeeOutputTest {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final TempFile file = new TempFile();
MatcherAssert.assertThat(
- TeeOutputTest.DESCRIPTION,
+ "Can't copy Output with path",
new TextOf(
new TeeInput(
- new InputOf(TeeOutputTest.CONTENT),
+ new InputOf("Hello, товарищ! with path"),
new TeeOutput(
new OutputTo(baos),
file.value()
@@ -166,10 +155,10 @@ public final class TeeOutputTest {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final TempFile file = new TempFile();
MatcherAssert.assertThat(
- TeeOutputTest.DESCRIPTION,
+ "Can't copy Output with file",
new TextOf(
new TeeInput(
- new InputOf(TeeOutputTest.CONTENT),
+ new InputOf("Hello, товарищ! with file"),
new TeeOutput(
new OutputTo(baos),
file.value().toFile()
@@ -193,10 +182,10 @@ public final class TeeOutputTest {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ByteArrayOutputStream copy = new ByteArrayOutputStream();
MatcherAssert.assertThat(
- TeeOutputTest.DESCRIPTION,
+ "Can't copy Output with output stream",
new TextOf(
new TeeInput(
- new InputOf(TeeOutputTest.CONTENT),
+ new InputOf("Hello, товарищ! with output stream"),
new TeeOutput(
new OutputTo(baos),
copy
|
#<I> removed shared content across tests
|
yegor256_cactoos
|
train
|
c595bdd88a5030d6f595c79479bb7f208c81fcc1
|
diff --git a/test/require/empty.js b/test/require/empty.js
index <HASH>..<HASH> 100644
--- a/test/require/empty.js
+++ b/test/require/empty.js
@@ -1 +1,4 @@
-// Nothing
+// Nothing particular
+"use strict";
+
+gpf.context().test.empty = true;
|
Updates a flag to ensure loading and execution (#<I>)
|
ArnaudBuchholz_gpf-js
|
train
|
1f0726b53cfc9d3e198d987fd2ff425bd7a9f399
|
diff --git a/pgv_to_wt.php b/pgv_to_wt.php
index <HASH>..<HASH> 100644
--- a/pgv_to_wt.php
+++ b/pgv_to_wt.php
@@ -117,19 +117,9 @@ if ($error || empty($PGV_PATH)) {
if ($error) {
echo '<p class="bad">', $error, '</p>';
}
- echo
- '<form action="', WT_SCRIPT_NAME, '" method="post">',
- '<p>', i18n::translate('Where is your PhpGedView installation?'), '</p>',
- '<dl>',
- '<dt>',i18n::translate('Installation directory'), '</dt>',
- '<dd><input type="text" name="PGV_PATH" size="40" value="'.htmlspecialchars($PGV_PATH).'"><dd>',
- '</dl>';
- // Finish
- echo '<div class="center"><input type="submit" value="'.i18n::translate('next').'"></div>';
- echo '</form>';
// Look for PGV in some nearby directories
- $pgv_dirs=array();
+ $pgv_dirs='';
$dir=opendir(realpath('..'));
while (($subdir=readdir($dir))!==false) {
if (is_dir('../'.$subdir) && preg_match('/pgv|gedview/i', $subdir) && file_exists('../'.$subdir.'/config.php')) {
@@ -137,16 +127,23 @@ if ($error || empty($PGV_PATH)) {
}
}
closedir($dir);
+
+ echo
+ '<form action="', WT_SCRIPT_NAME, '" method="post">',
+ '<p>', i18n::translate('Where is your PhpGedView installation?'), '</p>',
+ '<dl>',
+ '<dt>',i18n::translate('Installation directory'), '</dt>',
+ '<dd><input type="text" name="PGV_PATH" size="40" value="'.htmlspecialchars($PGV_PATH).'">',
+ '</dd>';
if ($pgv_dirs) {
- echo '<hr/><p>', i18n::translate('The following directories might contain a PhpGedView installation'), '</p>';
- echo '<pre>';
- foreach ($pgv_dirs as $pgv_dir) {
- echo '<br/>', $pgv_dir;
- }
- echo '</pre>';
+ echo '<dt>', /* find better english before translating */'PhpGedView might be found in these locations', '</dt>';
+ echo '<dd>', implode('<br/>', $pgv_dirs), '</dd>';
}
-
- echo '</div>';
+ echo
+ '</dl>',
+ '<div class="center"><input type="submit" value="'.i18n::translate('next').'"></div>',
+ '</form>',
+ '</div>';
exit;
}
|
PGV wizard - search for possible existing PGV installations (slightly better layout)
|
fisharebest_webtrees
|
train
|
91f9fd38fd0aa968d79124ce5eae432987a6308f
|
diff --git a/tests/unit/modules/test_dockermod.py b/tests/unit/modules/test_dockermod.py
index <HASH>..<HASH> 100644
--- a/tests/unit/modules/test_dockermod.py
+++ b/tests/unit/modules/test_dockermod.py
@@ -45,11 +45,8 @@ class DockerTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
utils = salt.loader.utils(
salt.config.DEFAULT_MINION_OPTS,
- whitelist=['state']
+ whitelist=['args']
)
- # Force the LazyDict to populate its references. Otherwise the lookup
- # will fail inside the unit tests.
- list(utils)
return {docker_mod: {'__context__': {'docker.docker_version': ''},
'__utils__': utils}}
diff --git a/tests/unit/states/test_boto_cloudfront.py b/tests/unit/states/test_boto_cloudfront.py
index <HASH>..<HASH> 100644
--- a/tests/unit/states/test_boto_cloudfront.py
+++ b/tests/unit/states/test_boto_cloudfront.py
@@ -26,12 +26,9 @@ class BotoCloudfrontTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
utils = salt.loader.utils(
self.opts,
- whitelist=['boto3', 'dictdiffer', 'yamldumper'],
+ whitelist=['boto3', 'dictdiffer', 'yaml'],
context={},
)
- # Force the LazyDict to populate its references. Otherwise the lookup
- # will fail inside the unit tests.
- list(utils)
return {
boto_cloudfront: {
'__utils__': utils,
diff --git a/tests/unit/states/test_boto_sqs.py b/tests/unit/states/test_boto_sqs.py
index <HASH>..<HASH> 100644
--- a/tests/unit/states/test_boto_sqs.py
+++ b/tests/unit/states/test_boto_sqs.py
@@ -25,12 +25,9 @@ class BotoSqsTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
utils = salt.loader.utils(
self.opts,
- whitelist=['boto3', 'yamldumper'],
+ whitelist=['boto3', 'yaml'],
context={}
)
- # Force the LazyDict to populate its references. Otherwise the lookup
- # will fail inside the unit tests.
- list(utils)
return {
boto_sqs: {
'__utils__': utils,
|
Fix loader whitelists in unit tests
This resolves failed lazydict lookups in the tests due to improperly-set
whitelists.
|
saltstack_salt
|
train
|
5f16783d3d52e8f200e5876134a5a80ae2da0da3
|
diff --git a/screengrab/lib/screengrab/runner.rb b/screengrab/lib/screengrab/runner.rb
index <HASH>..<HASH> 100644
--- a/screengrab/lib/screengrab/runner.rb
+++ b/screengrab/lib/screengrab/runner.rb
@@ -187,16 +187,14 @@ module Screengrab
def uninstall_apks(device_serial, app_package_name, tests_package_name)
UI.message 'Uninstalling app APK'
- apk_uninstall_output = run_adb_command("adb -s #{device_serial} uninstall #{app_package_name}",
- print_all: true,
- print_command: true)
- UI.user_error! "App APK could not be uninstalled" if apk_uninstall_output.include?("Failure [")
+ run_adb_command("adb -s #{device_serial} uninstall #{app_package_name}",
+ print_all: true,
+ print_command: true)
UI.message 'Uninstalling tests APK'
- apk_uninstall_output = run_adb_command("adb -s #{device_serial} uninstall -r #{tests_package_name}",
- print_all: true,
- print_command: true)
- UI.user_error! "Tests APK could not be uninstalled" if apk_uninstall_output.include?("Failure [")
+ run_adb_command("adb -s #{device_serial} uninstall #{tests_package_name}",
+ print_all: true,
+ print_command: true)
end
def grant_permissions(device_serial)
|
Fix screengrab to doesn’t exit if the app could not be uninstalled (#<I>)
|
fastlane_fastlane
|
train
|
42de6fc05b94d043f2c0dd483cd3fb8e2a7f5b13
|
diff --git a/lib/carto/external.js b/lib/carto/external.js
index <HASH>..<HASH> 100644
--- a/lib/carto/external.js
+++ b/lib/carto/external.js
@@ -167,7 +167,9 @@ External.mkdirp = function mkdirP(p, mode, f) {
External.types = [
//for datafile: function(d, c) - d is an External object, c is a function taking (err, filename)
{
- extension: /\.zip/,
+ // Assume filepaths without extensions may be directories
+ // containing a shapefile.
+ extension: /\.zip|^[\s]*$/,
datafile: function(d, c) { d.findOneByExtension('.shp', c); },
ds_options: {
type: 'shape'
|
Treat non-extension paths as directories.
|
mapbox_carto
|
train
|
841f4f73cf92f9a44ae272dc3408b20ef9ee0795
|
diff --git a/breacharbiter_test.go b/breacharbiter_test.go
index <HASH>..<HASH> 100644
--- a/breacharbiter_test.go
+++ b/breacharbiter_test.go
@@ -219,6 +219,12 @@ var (
0x4f, 0x2f, 0x6f, 0x25, 0x88, 0xa3, 0xef, 0xb9,
0x6a, 0x49, 0x18, 0x83, 0x31, 0x98, 0x47, 0x53,
},
+ chainHash: [chainhash.HashSize]byte{
+ 0x4d, 0x92, 0x73, 0xd1, 0x90, 0x63, 0x81, 0xb4,
+ 0x4f, 0x2f, 0x6f, 0x25, 0x88, 0xa3, 0xef, 0xb9,
+ 0xb7, 0x94, 0x38, 0x5f, 0x2d, 0x1e, 0xf7, 0xab,
+ 0x6b, 0x49, 0x18, 0x83, 0x31, 0x98, 0x47, 0x53,
+ },
chanPoint: breachOutPoints[0],
capacity: btcutil.Amount(1e7),
settledBalance: btcutil.Amount(1e7),
@@ -232,6 +238,12 @@ var (
0x2d, 0xe7, 0x93, 0xe4, 0xb7, 0x25, 0xb8, 0x4d,
0x1f, 0xb, 0x4c, 0xf9, 0x9e, 0xc5, 0x8c, 0xe9,
},
+ chainHash: [chainhash.HashSize]byte{
+ 0x4f, 0x2f, 0x6f, 0x25, 0x88, 0xa3, 0xef, 0xb9,
+ 0xb7, 0x94, 0x39, 0x5f, 0x2d, 0x1e, 0xf7, 0xab,
+ 0x6b, 0x49, 0x18, 0x83, 0x31, 0x98, 0x47, 0x53,
+ 0x4d, 0x92, 0x73, 0xd1, 0x90, 0x63, 0x81, 0xb4,
+ },
chanPoint: breachOutPoints[1],
capacity: btcutil.Amount(1e7),
settledBalance: btcutil.Amount(1e7),
@@ -401,6 +413,7 @@ func copyRetInfo(retInfo *retributionInfo) *retributionInfo {
ret := &retributionInfo{
commitHash: retInfo.commitHash,
+ chainHash: retInfo.chainHash,
chanPoint: retInfo.chanPoint,
remoteIdentity: retInfo.remoteIdentity,
capacity: retInfo.capacity,
|
breacharbiter: update tests to add chainHash to retributionInfo in test data
|
lightningnetwork_lnd
|
train
|
6ce9a94932c8cb8e2740bec961c7e2751052e3ab
|
diff --git a/src/js/captions.js b/src/js/captions.js
index <HASH>..<HASH> 100644
--- a/src/js/captions.js
+++ b/src/js/captions.js
@@ -128,6 +128,7 @@ const captions = {
}
},
+ // Used internally for toggleCaptions()
toggle(input) {
// If there's no full support
if (!this.supported.ui) {
@@ -146,10 +147,19 @@ const captions = {
// Update state and trigger event
if (active !== this.captions.active) {
this.captions.active = active;
- triggerEvent.call(this, this.media, this.captions.active ? 'captionsenabled' : 'captionsdisabled');
+
+ // Update UI
+ controls.updateSetting.call(this, 'captions');
+
+ // Save to storage
+ this.storage.set({ captions: active });
+
+ // Trigger event (not used internally)
+ triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');
}
},
+ // Used internally for currentTrack setter
set(index, setLanguage = true, show = true) {
const tracks = captions.getTracks.call(this);
@@ -187,7 +197,13 @@ const captions = {
this.embed.enableTextTrack(language);
}
- // Trigger event
+ // Update UI
+ controls.updateSetting.call(this, 'captions');
+
+ // Save to storage
+ this.storage.set({ language });
+
+ // Trigger event (not used internally)
triggerEvent.call(this, this.media, 'languagechange');
}
@@ -202,6 +218,7 @@ const captions = {
}
},
+ // Used internally for language setter
setLanguage(language, show = true) {
if (!is.string(language)) {
this.debug.warn('Invalid language argument', language);
diff --git a/src/js/listeners.js b/src/js/listeners.js
index <HASH>..<HASH> 100644
--- a/src/js/listeners.js
+++ b/src/js/listeners.js
@@ -387,24 +387,6 @@ class Listeners {
controls.updateSetting.call(this.player, 'quality', null, event.detail.quality);
});
- // Caption language change
- on.call(this.player, this.player.media, 'languagechange', () => {
- // Update UI
- controls.updateSetting.call(this.player, 'captions');
-
- // Save to storage
- this.player.storage.set({ language: this.player.language });
- });
-
- // Captions toggle
- on.call(this.player, this.player.media, 'captionsenabled captionsdisabled', () => {
- // Update UI
- controls.updateSetting.call(this.player, 'captions');
-
- // Save to storage
- this.player.storage.set({ captions: this.player.captions.active });
- });
-
// Proxy events to container
// Bubble up key events for Edge
on.call(this.player, this.player.media, this.player.config.events.concat([
|
Move internal event listeners for captions with direct handling in the captions object
|
sampotts_plyr
|
train
|
024980306b3c299c79123cbda2ba538b7b52e974
|
diff --git a/lib/progress.rb b/lib/progress.rb
index <HASH>..<HASH> 100644
--- a/lib/progress.rb
+++ b/lib/progress.rb
@@ -229,6 +229,14 @@ class Progress
!@next_time_to_print || @next_time_to_print <= Time.now
end
+ def eta(current)
+ @eta.left(current)
+ end
+
+ def elapsed
+ @eta.elapsed
+ end
+
def print_message(options = {})
force = options[:force]
lock force do
@@ -253,9 +261,9 @@ class Progress
end
timing = if options[:finish]
- " (elapsed: #{@eta.elapsed})"
- elsif eta = @eta.left(current)
- " (ETA: #{eta})"
+ " (elapsed: #{elapsed})"
+ elsif eta_ = eta(current)
+ " (ETA: #{eta_})"
end
message = "#{parts.reverse * ' > '}#{timing}"
diff --git a/spec/progress_spec.rb b/spec/progress_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/progress_spec.rb
+++ b/spec/progress_spec.rb
@@ -11,6 +11,8 @@ describe Progress do
Progress.stub(:start_beeper)
Progress.stub(:time_to_print?).and_return(true)
+ Progress.stub(:eta)
+ Progress.stub(:elapsed).and_return('0s')
end
describe "integrity" do
|
extracted eta and elapsed, stubbed them in specs
|
toy_progress
|
train
|
5b4cc88b05d657e01aa7ffe960473ba8c88babc4
|
diff --git a/jlib-core/src/main/java/org/jlib/core/language/ExceptionMessageUtility.java b/jlib-core/src/main/java/org/jlib/core/language/ExceptionMessageUtility.java
index <HASH>..<HASH> 100644
--- a/jlib-core/src/main/java/org/jlib/core/language/ExceptionMessageUtility.java
+++ b/jlib-core/src/main/java/org/jlib/core/language/ExceptionMessageUtility.java
@@ -51,6 +51,10 @@ public final class ExceptionMessageUtility {
return message.toString() + ';' + ' ' + objectName + '=' + object;
}
+ public static ParametrizedMessage message(final CharSequence messageTemplate, final Object... messageArguments) {
+ return new ParametrizedMessage(messageTemplate, messageArguments);
+ }
+
private ExceptionMessageUtility() {
// no visible constructor
}
|
ParametrizedMessage factory method created
|
jlib-framework_jlib-operator
|
train
|
23c27780fd30b45a10c8a49d345b564a99ac3acf
|
diff --git a/gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/TransactionTest.java b/gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/TransactionTest.java
index <HASH>..<HASH> 100644
--- a/gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/TransactionTest.java
+++ b/gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/TransactionTest.java
@@ -8,12 +8,16 @@ import org.apache.commons.configuration.Configuration;
import org.junit.Test;
import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures.FEATURE_STRING_VALUES;
import static com.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures.FEATURE_FLOAT_VALUES;
import static com.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures.FEATURE_INTEGER_VALUES;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
@@ -265,4 +269,61 @@ public class TransactionTest extends AbstractGremlinTest {
graphProvider.clear(g1, configuration);
}
+ @Test
+ @FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_TRANSACTIONS)
+ public void shouldSupportTransactionIsolationCommitCheck() throws Exception {
+ // the purpose of this test is to simulate gremlin server access to a graph instance, where one thread modifies
+ // the graph and a separate thread cannot affect the transaction of the first
+ final Graph graph = g;
+
+ final CountDownLatch latchCommittedInOtherThread = new CountDownLatch(1);
+ final CountDownLatch latchCommitInOtherThread = new CountDownLatch(1);
+
+ final AtomicBoolean noVerticesInFirstThread = new AtomicBoolean(false);
+
+ // this thread starts a transaction then waits while the second thread tries to commit it.
+ final Thread threadTxStarter = new Thread() {
+ public void run() {
+ graph.addVertex();
+ latchCommitInOtherThread.countDown();
+
+ try {
+ latchCommittedInOtherThread.await();
+ } catch (InterruptedException ie) {
+ throw new RuntimeException(ie);
+ }
+
+ graph.tx().rollback();
+
+ // there should be no vertices here
+ noVerticesInFirstThread.set(!graph.V().hasNext());
+ }
+ };
+
+ threadTxStarter.start();
+
+ // this thread tries to commit the transaction started in the first thread above.
+ final Thread threadTryCommitTx = new Thread() {
+ public void run() {
+ try {
+ latchCommitInOtherThread.await();
+ } catch (InterruptedException ie) {
+ throw new RuntimeException(ie);
+ }
+
+ // try to commit the other transaction
+ graph.tx().commit();
+
+ latchCommittedInOtherThread.countDown();
+ }
+ };
+
+ threadTryCommitTx.start();
+
+ threadTxStarter.join();
+ threadTryCommitTx.join();
+
+ assertTrue(noVerticesInFirstThread.get());
+ AbstractGremlinSuite.assertVertexEdgeCounts(0, 0);
+ }
}
|
Add another transaction consistency test for multiple threads.
|
apache_tinkerpop
|
train
|
b615efa2d4c779c667ca991840561d28becafc48
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -20,7 +20,7 @@
from setuptools import setup, find_packages
-from launch_control import get_version
+from dashboard_app import get_version
setup(
|
Use dashboard_app for version information for setup.py
|
zyga_json-schema-validator
|
train
|
622554c86710b4b5db0364d3dd94bf2842a57866
|
diff --git a/lib/predictor/base.rb b/lib/predictor/base.rb
index <HASH>..<HASH> 100644
--- a/lib/predictor/base.rb
+++ b/lib/predictor/base.rb
@@ -267,6 +267,10 @@ module Predictor::Base
return self
end
+ def add_item(item)
+ Predictor.redis.sadd(redis_key(:all_items), item)
+ end
+
def delete_item!(item)
Predictor.redis.srem(redis_key(:all_items), item)
Predictor.redis.watch(redis_key(:similarities, item)) do
|
Add a helper method to add an item to the 'all_items' set
|
Pathgather_predictor
|
train
|
f702155edee11ce8f74b7334e44d55865ccc7fd2
|
diff --git a/src/main/java/hex/gbm/SharedTreeModelBuilder.java b/src/main/java/hex/gbm/SharedTreeModelBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/hex/gbm/SharedTreeModelBuilder.java
+++ b/src/main/java/hex/gbm/SharedTreeModelBuilder.java
@@ -415,13 +415,17 @@ public abstract class SharedTreeModelBuilder extends ValidatedJob {
public Score report( Sys tag, int ntree, DTree[] trees ) {
assert !Double.isNaN(_sum);
int lcnt=0;
- for( DTree t : trees ) if( t != null ) lcnt += t._len;
- long err=_snrows;
- for( int c=0; c<_nclass; c++ ) err -= _cm[c][c];
Log.info(tag,"============================================================== ");
- Log.info(tag,"Mean Squared Error is "+(_sum/_snrows)+", with "+ntree+"x"+_nclass+" trees (average of "+((float)lcnt/_nclass)+" nodes)");
- if( _nclass > 1 )
- Log.info(tag,"Total of "+err+" errors on "+_snrows+" rows, CM= "+Arrays.deepToString(_cm));
+ if (trees==null) {
+ Log.info("No trees...");
+ } else {
+ for( DTree t : trees ) if( t != null ) lcnt += t._len;
+ long err=_snrows;
+ for( int c=0; c<_nclass; c++ ) err -= _cm[c][c];
+ Log.info(tag,"Mean Squared Error is "+(_sum/_snrows)+", with "+ntree+"x"+_nclass+" trees (average of "+((float)lcnt/_nclass)+" nodes)");
+ if( _nclass > 1 )
+ Log.info(tag,"Total of "+err+" errors on "+_snrows+" rows, CM= "+Arrays.deepToString(_cm));
+ }
return this;
}
}
|
Fix for HEX-<I> - NPE in Score.report()
Report wasn't properly handle a situation when we have
zero trees.
|
h2oai_h2o-2
|
train
|
3dbdcf3c9d15f584ceb3c9ff6319ecaba20a319f
|
diff --git a/django_dowser/views.py b/django_dowser/views.py
index <HASH>..<HASH> 100644
--- a/django_dowser/views.py
+++ b/django_dowser/views.py
@@ -125,6 +125,11 @@ def trace_one(typename, objid):
rows = ["<h3>The object you requested is no longer "
"of the correct type.</h3>"]
else:
+ tree = ReferrerTree(obj)
+
+ # repr
+ rows.append("<p class='obj'>%s</p>" % get_repr(obj, 5000))
+
# Attributes
rows.append('<div class="obj"><h3>Attributes</h3>')
for k in dir(obj):
@@ -140,7 +145,6 @@ def trace_one(typename, objid):
rows.append('<p class="desc"><a href="%s">Show the '
'entire tree</a> of reachable objects</p>'
% ("../../tree/%s/%s" % (typename, objid)))
- tree = ReferrerTree(obj)
tree.ignore(all_objs)
for depth, parentid, parentrepr in tree.walk(maxdepth=1):
if parentid:
|
trace view: show repr of obj itself
|
munhitsu_django-dowser
|
train
|
90d382de32da0b7e85b3fcdf029a3202a547a0d1
|
diff --git a/lib/kimurai/capybara_ext/driver/base.rb b/lib/kimurai/capybara_ext/driver/base.rb
index <HASH>..<HASH> 100644
--- a/lib/kimurai/capybara_ext/driver/base.rb
+++ b/lib/kimurai/capybara_ext/driver/base.rb
@@ -1,3 +1,59 @@
+require 'pathname'
+
class Capybara::Driver::Base
attr_accessor :visited
+
+ def current_memory
+ driver_pid = pid
+ # if #driver hasn't been called yet, driver_pid will be nil.
+ # In this case we need to set memory to zero
+ # return 0 unless driver_pid
+ all = (get_descendant_processes(driver_pid) << driver_pid).uniq
+
+ # fix error, sometimes in get_descendant_processes appears pid of the command
+ # itself (ps -eo pid,ppid). Of course it's gone already when GetProcessMem
+ # tryining to find this process proc
+ all.map { |pid| get_process_memory(pid) }.sum
+ end
+
+ private
+
+ def get_descendant_processes(base)
+ descendants = Hash.new { |ht, k| ht[k] = [k] }
+ Hash[*`ps -eo pid,ppid`.scan(/\d+/).map(&:to_i)].each do |pid, ppid|
+ descendants[ppid] << descendants[pid]
+ end
+
+ descendants[base].flatten - [base]
+ end
+
+ # https://github.com/schneems/get_process_mem
+ # Note: for Linux takes PSS (not RSS) memory (I think PSS better fit in this case)
+ def get_process_memory(pid)
+ case @platform ||= Gem::Platform.local.os
+ when "linux"
+ begin
+ file = Pathname.new "/proc/#{pid}/smaps"
+ return 0 unless file.exist?
+
+ lines = file.each_line.select { |line| line.match(/^Pss/) }
+ return 0 if lines.empty?
+
+ lines.reduce(0) do |sum, line|
+ line.match(/(?<value>(\d*\.{0,1}\d+))\s+(?<unit>\w\w)/) do |m|
+ sum += m[:value].to_i
+ end
+
+ sum
+ end
+ rescue Errno::EACCES
+ 0
+ end
+ when "darwin"
+ mem = `ps -o rss= -p #{pid}`.strip
+ mem.empty? ? 0 : mem.to_i
+ else
+ raise "Can't check process memory, wrong type of platform: #{@platform}"
+ end
+ end
end
diff --git a/lib/kimurai/capybara_ext/mechanize/driver.rb b/lib/kimurai/capybara_ext/mechanize/driver.rb
index <HASH>..<HASH> 100644
--- a/lib/kimurai/capybara_ext/mechanize/driver.rb
+++ b/lib/kimurai/capybara_ext/mechanize/driver.rb
@@ -36,4 +36,11 @@ class Capybara::Mechanize::Driver
def quit
browser.agent.shutdown
end
+
+ ###
+
+ # Reset parent method `current_memory` for mechanize (we can't measure memory of mechanize engine)
+ def current_memory
+ nil
+ end
end
diff --git a/lib/kimurai/capybara_ext/poltergeist/driver.rb b/lib/kimurai/capybara_ext/poltergeist/driver.rb
index <HASH>..<HASH> 100644
--- a/lib/kimurai/capybara_ext/poltergeist/driver.rb
+++ b/lib/kimurai/capybara_ext/poltergeist/driver.rb
@@ -2,5 +2,12 @@ require_relative '../driver/base'
module Capybara::Poltergeist
class Driver
+ def pid
+ client_pid
+ end
+
+ def port
+ server.port
+ end
end
end
diff --git a/lib/kimurai/capybara_ext/selenium/driver.rb b/lib/kimurai/capybara_ext/selenium/driver.rb
index <HASH>..<HASH> 100644
--- a/lib/kimurai/capybara_ext/selenium/driver.rb
+++ b/lib/kimurai/capybara_ext/selenium/driver.rb
@@ -11,4 +11,6 @@ class Capybara::Selenium::Driver
def clear_cookies
browser.manage.delete_all_cookies
end
+
+ ###
end
|
Add current_memory feature to Capybara drivers
|
vifreefly_kimuraframework
|
train
|
44ad4454716a56b05be2dc8251af0f931e637dcd
|
diff --git a/client/html/tests/Client/Html/Basket/Mini/Main/DefaultTest.php b/client/html/tests/Client/Html/Basket/Mini/Main/DefaultTest.php
index <HASH>..<HASH> 100644
--- a/client/html/tests/Client/Html/Basket/Mini/Main/DefaultTest.php
+++ b/client/html/tests/Client/Html/Basket/Mini/Main/DefaultTest.php
@@ -93,7 +93,7 @@ class Client_Html_Basket_Mini_Main_DefaultTest extends MW_Unittest_Testcase
$this->assertStringStartsWith( '<div class="basket-mini-main">', $output );
$this->assertRegExp( '#9#smU', $output );
- $this->assertRegExp( '#162.00#smU', $output );
+ $this->assertRegExp( '#171.00#smU', $output );
}
|
Fixes test for small basket output after fixing the calculated value
|
Arcavias_arcavias-core
|
train
|
bb54697b1b3304590061c5a9722989deda4f18fb
|
diff --git a/lib/filelib.php b/lib/filelib.php
index <HASH>..<HASH> 100644
--- a/lib/filelib.php
+++ b/lib/filelib.php
@@ -1203,11 +1203,11 @@ function mimeinfo($element, $filename) {
} else {
$filename = 'unknown';
}
- $filename .= '-32.png';
- if (file_exists($CFG->dirroot.'/pix/f/'.$filename)) {
+ $filename .= '-32';
+ if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png')) {
return $filename;
} else {
- return 'unknown-32.png';
+ return 'unknown-32';
}
} else {
return $mimeinfo['xxx'][$element]; // By default
|
"MDL-<I>, fixed icons"
|
moodle_moodle
|
train
|
df35d6793c93e77c6e7b21a3b7c3e41dc494f1a2
|
diff --git a/charmhelpers/contrib/openstack/templating.py b/charmhelpers/contrib/openstack/templating.py
index <HASH>..<HASH> 100644
--- a/charmhelpers/contrib/openstack/templating.py
+++ b/charmhelpers/contrib/openstack/templating.py
@@ -229,7 +229,14 @@ class OSConfigRenderer(object):
# using a munged full path, eg:
# /etc/apache2/apache2.conf -> etc_apache2_apache2.conf
_tmpl = '_'.join(config_file.split('/')[1:])
- template = self._get_template(_tmpl)
+ try:
+ template = self._get_template(_tmpl)
+ except exceptions.TemplateNotFound as e:
+ log('Could not load template from %s by %s or %s.' %
+ (self.templates_dir, os.path.basename(config_file), _tmpl),
+ level=ERROR)
+ raise e
+
log('Rendering from template: %s' % _tmpl, level=INFO)
return template.render(ctxt)
|
Better logging when template is not found.
|
juju_charm-helpers
|
train
|
fa4329659759eadeef83b7c70b6dc64a07654c76
|
diff --git a/lib/access_control_config.py b/lib/access_control_config.py
index <HASH>..<HASH> 100644
--- a/lib/access_control_config.py
+++ b/lib/access_control_config.py
@@ -191,7 +191,8 @@ DEF_ACTIONS = (
('viewholdings', 'view holdings', 'collection', 'yes'),
('viewstatistics', 'view statistics', 'collection', 'yes'),
('runbibcirculation', 'run BibCirculation', '', 'no'),
- ('moderatecomments', 'moderate comments', 'collection', 'no')
+ ('moderatecomments', 'moderate comments', 'collection', 'no'),
+ ('runbatchuploader', 'run batchuploader', 'collection', 'yes')
)
# Default authorizations
@@ -222,7 +223,8 @@ DEF_DEMO_AUTHS = (
('submit_DEMOJRN_*', 'submit', {'doctype': 'DEMOJRN', 'act': 'SBI', 'categ': '*'}),
('submit_DEMOJRN_*', 'submit', {'doctype': 'DEMOJRN', 'act': 'MBI', 'categ': '*'}),
('submit_DEMOJRN_*', 'cfgwebjournal', {'name': 'AtlantisTimes', 'with_editor_rights': 'no'}),
- ('atlantiseditor', 'cfgwebjournal', {'name': 'AtlantisTimes', 'with_editor_rights': 'yes'})
+ ('atlantiseditor', 'cfgwebjournal', {'name': 'AtlantisTimes', 'with_editor_rights': 'yes'}),
+ ('referee_DEMOBOO_*', 'runbatchuploader', {'collection': 'Books'})
)
_ = gettext_set_language(CFG_SITE_LANG)
|
BibUpload: new batchuploader facility
* Added web interface for cataloguers to upload metadata
files.
* Added web interface for cataloguers to upload documents.
* Added web interface upload history for metadata files
and documents.
* Added robot web interface to upload marc files.
* Added batchuploader daemon for periodically uploading
documents and metadata.
|
inveniosoftware_invenio-access
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.