hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
521fb2830829ab4c86d687b5bcd7f8ed2cbb06a7
|
diff --git a/tasks/fontfactory.js b/tasks/fontfactory.js
index <HASH>..<HASH> 100644
--- a/tasks/fontfactory.js
+++ b/tasks/fontfactory.js
@@ -145,9 +145,8 @@ module.exports = function(grunt) {
// TODO: Handle possibility of no svg element
var svg = doc.getElementsByTagName("svg")[0];
- // TODO: Handle possibility of "px"
- var width = svg.getAttribute("width");
- var height = svg.getAttribute("height");
+ var width = parseFloat(svg.getAttribute("width"));
+ var height = parseFloat(svg.getAttribute("height"));
// TODO: Handle possibility of no/multiple paths
var path = svg.getElementsByTagName("path")[0];
|
Removing px from the end of width and height definitions in SVG input files
|
cameronhunter_grunt-fontfactory
|
train
|
89e6f9314592d130ef01a8cff6c95803f7c81428
|
diff --git a/src/main/java/com/xebia/incubator/xebium/ExtendedSeleniumCommand.java b/src/main/java/com/xebia/incubator/xebium/ExtendedSeleniumCommand.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/xebia/incubator/xebium/ExtendedSeleniumCommand.java
+++ b/src/main/java/com/xebia/incubator/xebium/ExtendedSeleniumCommand.java
@@ -206,7 +206,7 @@ public class ExtendedSeleniumCommand {
public String getSeleniumCommand() {
// for commands like "waitForCondition"
- if (WEB_DRIVER_COMMANDS.contains(methodName)) {
+ if (isSupportedByWebDriver(methodName)) {
return methodName;
}
|
Use accessor method instead of direct access.
|
xebia_Xebium
|
train
|
bc351e5450e16f00407369fb9bc1a88976213447
|
diff --git a/src/OutputFilter.php b/src/OutputFilter.php
index <HASH>..<HASH> 100644
--- a/src/OutputFilter.php
+++ b/src/OutputFilter.php
@@ -97,8 +97,8 @@ class OutputFilter
// Remove any '-' from the string since they will be used as concatenaters
$str = str_replace('-', ' ', $string);
- $lang = Language::getInstance();
- $str = $lang->transliterate($str);
+ $factory = new LanguageFactory();
+ $str = $factory->getLanguage()->transliterate($str);
// Trim white spaces at beginning and end of alias and make lowercase
$str = trim(StringHelper::strtolower($str));
|
Language <I> consistency
To be consistent with Language package <I>, ``OutputFilter::stringURLSafe()`` should use ``LanguageFactory::getLanguage()`` rather than ``Language::getInstance()``.
An issue would be to have an uninitialized LanguageFactory and throw the "The $path variable cannot be null when creating a new Language object" exception.
|
joomla-framework_filter
|
train
|
67119e8759a554f80d58f99bce3f8b1e21928a11
|
diff --git a/test/context/http/actions-test.js b/test/context/http/actions-test.js
index <HASH>..<HASH> 100644
--- a/test/context/http/actions-test.js
+++ b/test/context/http/actions-test.js
@@ -141,6 +141,64 @@ vows.describe('actions').addBatch({
},
},
+ 'redirect using framework function': {
+ topic: function() {
+ var self = this;
+ var mockRes = {};
+ mockRes.redirect = function(status, url) {
+ if (!url) {
+ url = status;
+ status = 302;
+ }
+ this.statusCode = status;
+ this.header = 'Location: ' + url;
+ self.callback(null, this);
+ }
+
+ var context = {};
+ context.res = mockRes;
+
+ var redirect = actions.redirect.bind(context);
+ process.nextTick(function () {
+ redirect('http://www.example.com/login', 303);
+ });
+ },
+
+ 'should redirect to url': function (err, res) {
+ assert.equal(res.statusCode, 303);
+ assert.equal(res.header, 'Location: http://www.example.com/login');
+ },
+ },
+
+ 'redirect with status code using framework function': {
+ topic: function() {
+ var self = this;
+ var mockRes = {};
+ mockRes.redirect = function(status, url) {
+ if (!url) {
+ url = status;
+ status = 302;
+ }
+ this.statusCode = status;
+ this.header = 'Location: ' + url;
+ self.callback(null, this);
+ }
+
+ var context = {};
+ context.res = mockRes;
+
+ var redirect = actions.redirect.bind(context);
+ process.nextTick(function () {
+ redirect('http://www.example.com/login');
+ });
+ },
+
+ 'should redirect to url': function (err, res) {
+ assert.equal(res.statusCode, 302);
+ assert.equal(res.header, 'Location: http://www.example.com/login');
+ },
+ },
+
'pass': {
topic: function() {
var self = this;
|
Test cases for using framework-provided redirect.
|
jaredhanson_passport
|
train
|
841e895186fe8bc143c7cd7e16fe9468891dbca2
|
diff --git a/lib/excon/socket.rb b/lib/excon/socket.rb
index <HASH>..<HASH> 100644
--- a/lib/excon/socket.rb
+++ b/lib/excon/socket.rb
@@ -25,11 +25,6 @@ module Excon
@read_buffer = ''
@eof = false
- @data[:family] ||= ::Socket::Constants::AF_UNSPEC
- if @data[:proxy]
- @data[:proxy][:family] ||= ::Socket::Constants::AF_UNSPEC
- end
-
connect
end
@@ -133,9 +128,11 @@ module Excon
exception = nil
addrinfo = if @data[:proxy]
- ::Socket.getaddrinfo(@data[:proxy][:host], @data[:proxy][:port], @data[:proxy][:family], ::Socket::Constants::SOCK_STREAM)
+ family = @data[:proxy][:family] || ::Socket::Constants::AF_UNSPEC
+ ::Socket.getaddrinfo(@data[:proxy][:host], @data[:proxy][:port], family, ::Socket::Constants::SOCK_STREAM)
else
- ::Socket.getaddrinfo(@data[:host], @data[:port], @data[:family], ::Socket::Constants::SOCK_STREAM)
+ family = @data[:family] || ::Socket::Constants::AF_UNSPEC
+ ::Socket.getaddrinfo(@data[:host], @data[:port], family, ::Socket::Constants::SOCK_STREAM)
end
addrinfo.each do |_, port, _, ip, a_family, s_type|
|
connection data can not be mutated for thread safety
|
excon_excon
|
train
|
da2fc7babe70a8940c04665220cdd4a6bd4492f0
|
diff --git a/firebirdsql/wireprotocol.py b/firebirdsql/wireprotocol.py
index <HASH>..<HASH> 100644
--- a/firebirdsql/wireprotocol.py
+++ b/firebirdsql/wireprotocol.py
@@ -138,8 +138,7 @@ class WireProtocol(object):
n += 4 - nbytes % 4 # 4 bytes word alignment
r = bs([])
while n:
- if (os.name != 'java'
- and self.timeout is not None
+ if (self.timeout is not None
and select.select([self.sock._sock], [], [], self.timeout)[0] == []):
break
b = self.sock.recv(n)
|
jython<I> support is deprecated
|
nakagami_pyfirebirdsql
|
train
|
8145d42e07770f3441b9e2a6b517ae0bf717842b
|
diff --git a/src/Objection/LiteObject.php b/src/Objection/LiteObject.php
index <HASH>..<HASH> 100644
--- a/src/Objection/LiteObject.php
+++ b/src/Objection/LiteObject.php
@@ -154,7 +154,9 @@ abstract class LiteObject {
$this->validateFieldAccess($name, AccessRestriction::NO_SET);
$value = ValueValidation::fixValue($this->data[$name], $value);
- $this->data[$name][SetupFields::VALUE] = $value;
+
+ if (!isset($this->data[$name][SetupFields::ACCESS]))
+ $this->data[$name][SetupFields::VALUE] = $value;
$this->invokeOnSet($name, $value);
}
diff --git a/src/Objection/Setup/ValueValidation.php b/src/Objection/Setup/ValueValidation.php
index <HASH>..<HASH> 100644
--- a/src/Objection/Setup/ValueValidation.php
+++ b/src/Objection/Setup/ValueValidation.php
@@ -55,7 +55,16 @@ class ValueValidation
break;
default:
- throw new \Exception("Invalid property type " . $fieldData[SetupFields::TYPE]);
+ if (!$value instanceof $fieldData[SetupFields::TYPE])
+ {
+ $type = (is_object($value) ? get_class($fieldData) : gettype($value));
+
+ throw new \Exception(
+ "Value must be of type {$fieldData[SetupFields::TYPE]}. " .
+ "Got {$type} instead");
+ }
+
+ break;
}
return $value;
|
Add support for properties of object type and SET only proeprties are not saved inside array
|
Oktopost_Objection
|
train
|
47ac579f092cef9128fa0c74798ecaffa2c888f9
|
diff --git a/cmd/web.go b/cmd/web.go
index <HASH>..<HASH> 100644
--- a/cmd/web.go
+++ b/cmd/web.go
@@ -206,7 +206,7 @@ func runWeb(ctx *cli.Context) {
m.Get("/issues", user.Issues)
}, reqSignIn)
- // API.
+ // ***** START: API *****
// FIXME: custom form error response.
m.Group("/api", func() {
m.Group("/v1", func() {
@@ -248,6 +248,7 @@ func runWeb(ctx *cli.Context) {
})
})
}, ignSignIn)
+ // ***** END: API *****
// ***** START: User *****
m.Group("/user", func() {
diff --git a/models/user.go b/models/user.go
index <HASH>..<HASH> 100644
--- a/models/user.go
+++ b/models/user.go
@@ -373,17 +373,9 @@ func CreateUser(u *User) (err error) {
} else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
sess.Rollback()
return err
- } else if err = sess.Commit(); err != nil {
- return err
}
- // Auto-set admin for the first user.
- if CountUsers() == 1 {
- u.IsAdmin = true
- u.IsActive = true
- _, err = x.Id(u.Id).AllCols().Update(u)
- }
- return err
+ return sess.Commit()
}
func countUsers(e Engine) int64 {
diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go
index <HASH>..<HASH> 100644
--- a/modules/middleware/auth.go
+++ b/modules/middleware/auth.go
@@ -80,7 +80,7 @@ func Toggle(options *ToggleOptions) macaron.Handler {
return
}
- if !options.SignOutRequire && !options.DisableCsrf && ctx.Req.Method == "POST" {
+ if !options.SignOutRequire && !options.DisableCsrf && ctx.Req.Method == "POST" && !auth.IsAPIPath(ctx.Req.URL.Path) {
csrf.Validate(ctx.Context, ctx.csrf)
if ctx.Written() {
return
diff --git a/routers/user/auth.go b/routers/user/auth.go
index <HASH>..<HASH> 100644
--- a/routers/user/auth.go
+++ b/routers/user/auth.go
@@ -220,7 +220,6 @@ func SignUpPost(ctx *middleware.Context, cpt *captcha.Captcha, form auth.Registe
Passwd: form.Password,
IsActive: !setting.Service.RegisterEmailConfirm || isOauth,
}
-
if err := models.CreateUser(u); err != nil {
switch {
case models.IsErrUserAlreadyExist(err):
@@ -242,6 +241,16 @@ func SignUpPost(ctx *middleware.Context, cpt *captcha.Captcha, form auth.Registe
}
log.Trace("Account created: %s", u.Name)
+ // Auto-set admin for the only user.
+ if models.CountUsers() == 1 {
+ u.IsAdmin = true
+ u.IsActive = true
+ if err := models.UpdateUser(u); err != nil {
+ ctx.Handle(500, "UpdateUser", err)
+ return
+ }
+ }
+
// Bind social account.
if isOauth {
if err := models.BindUserOauth2(u.Id, sid); err != nil {
|
only assign auto-admin when sign up by web
|
gogs_gogs
|
train
|
a54b2e28f7ec60ff91435590d34586be349215c1
|
diff --git a/tests/management/test_runner.py b/tests/management/test_runner.py
index <HASH>..<HASH> 100644
--- a/tests/management/test_runner.py
+++ b/tests/management/test_runner.py
@@ -1,55 +1,12 @@
-import copy
-import imp
-import os
-
-import mock
-from django.test import TestCase
-from whitenoise.django import DjangoWhiteNoise
-
-from localshop import wsgi
from localshop.runner import main
-manage_instance = mock.MagicMock()
-manage_mock = mock.MagicMock(return_value=manage_instance)
-
-
-class TestWSGI(TestCase):
- def test_init_wsgi_application(self):
- self.assertIsInstance(wsgi.application, DjangoWhiteNoise)
-
- def test_set_env_defaults(self):
- # backup and remove global environment vars
- oldenv = copy.copy(os.environ)
- del os.environ['DJANGO_SETTINGS_MODULE']
- imp.reload(wsgi)
- self.assertIn('DJANGO_SETTINGS_MODULE', os.environ)
- self.assertEqual(os.environ['DJANGO_SETTINGS_MODULE'], 'localshop.settings')
- os.environ = oldenv
-
-@mock.patch('django.core.management.ManagementUtility', manage_mock)
-class TestRunner(TestCase):
- def tearDown(self):
- manage_instance.reset_mock()
- manage_mock.reset_mock()
+def test_main(monkeypatch):
+ from django.core import management
- @mock.patch('sys.argv', [])
- def test_no_args_passed_manager(self):
- main()
- manage_mock.assert_called_once_with([])
- manage_instance.execute.assert_called_once_with()
+ def mock_exec(args):
+ return
- @mock.patch('sys.argv', ['init', '--no-superuser'])
- def test_args_passed_manager(self):
- main()
- manage_mock.assert_called_once_with(['init', '--no-superuser'])
- manage_instance.execute.assert_called_once_with()
+ monkeypatch.setattr(management, 'execute_from_command_line', mock_exec)
- def test_set_env_defaults(self):
- # backup and remove global environment vars
- oldenv = copy.copy(os.environ)
- del os.environ['DJANGO_SETTINGS_MODULE']
- main()
- self.assertIn('DJANGO_SETTINGS_MODULE', os.environ)
- self.assertEqual(os.environ['DJANGO_SETTINGS_MODULE'], 'localshop.settings')
- os.environ = oldenv
+ main()
|
Simplify tests for runner.py module
Less mocking, more easy :P
|
mvantellingen_localshop
|
train
|
b045fc0ad3587e8620fb42a0dea882cf8c08aef9
|
diff --git a/radix.go b/radix.go
index <HASH>..<HASH> 100644
--- a/radix.go
+++ b/radix.go
@@ -374,6 +374,38 @@ func (t *Tree) Walk(fn WalkFn) {
recursiveWalk(t.root, fn)
}
+// WalkPrefix is used to walk the tree under a prefix
+func (t *Tree) WalkPrefix(prefix string, fn WalkFn) {
+ n := t.root
+ search := prefix
+ for {
+ // Check for key exhaution
+ if len(search) == 0 {
+ recursiveWalk(n, fn)
+ return
+ }
+
+ // Look for an edge
+ n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if strings.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+
+ } else if strings.HasPrefix(n.prefix, search) {
+ // Child may be under our search prefix
+ recursiveWalk(n, fn)
+ return
+ } else {
+ break
+ }
+ }
+
+}
+
// recursiveWalk is used to do a pre-order walk of a node
// recursively. Returns true if the walk should be aborted
func recursiveWalk(n *node, fn WalkFn) bool {
diff --git a/radix_test.go b/radix_test.go
index <HASH>..<HASH> 100644
--- a/radix_test.go
+++ b/radix_test.go
@@ -3,6 +3,8 @@ package radix
import (
crand "crypto/rand"
"fmt"
+ "reflect"
+ "sort"
"testing"
)
@@ -112,6 +114,85 @@ func TestLongestPrefix(t *testing.T) {
}
}
+func TestWalkPrefix(t *testing.T) {
+ r := New()
+
+ keys := []string{
+ "foobar",
+ "foo/bar/baz",
+ "foo/baz/bar",
+ "foo/zip/zap",
+ "zipzap",
+ }
+ for _, k := range keys {
+ r.Insert(k, nil)
+ }
+ if r.Len() != len(keys) {
+ t.Fatalf("bad len: %v %v", r.Len(), len(keys))
+ }
+
+ type exp struct {
+ inp string
+ out []string
+ }
+ cases := []exp{
+ exp{
+ "f",
+ []string{"foobar", "foo/bar/baz", "foo/baz/bar", "foo/zip/zap"},
+ },
+ exp{
+ "foo",
+ []string{"foobar", "foo/bar/baz", "foo/baz/bar", "foo/zip/zap"},
+ },
+ exp{
+ "foob",
+ []string{"foobar"},
+ },
+ exp{
+ "foo/",
+ []string{"foo/bar/baz", "foo/baz/bar", "foo/zip/zap"},
+ },
+ exp{
+ "foo/b",
+ []string{"foo/bar/baz", "foo/baz/bar"},
+ },
+ exp{
+ "foo/ba",
+ []string{"foo/bar/baz", "foo/baz/bar"},
+ },
+ exp{
+ "foo/bar",
+ []string{"foo/bar/baz"},
+ },
+ exp{
+ "foo/bar/baz",
+ []string{"foo/bar/baz"},
+ },
+ exp{
+ "foo/bar/bazoo",
+ []string{},
+ },
+ exp{
+ "z",
+ []string{"zipzap"},
+ },
+ }
+
+ for _, test := range cases {
+ out := []string{}
+ fn := func(s string, v interface{}) bool {
+ out = append(out, s)
+ return false
+ }
+ r.WalkPrefix(test.inp, fn)
+ sort.Strings(out)
+ sort.Strings(test.out)
+ if !reflect.DeepEqual(out, test.out) {
+ t.Fatalf("mis-match: %v %v", out, test.out)
+ }
+ }
+}
+
// generateUUID is used to generate a random UUID
func generateUUID() string {
buf := make([]byte, 16)
|
Adding support for walking a prefix
|
armon_go-radix
|
train
|
fb86cd307275ad9ae093eea6cfd77f64b0d6b079
|
diff --git a/holoviews/plotting/bokeh/element.py b/holoviews/plotting/bokeh/element.py
index <HASH>..<HASH> 100644
--- a/holoviews/plotting/bokeh/element.py
+++ b/holoviews/plotting/bokeh/element.py
@@ -82,6 +82,9 @@ class ElementPlot(BokehPlot, GenericElementPlot):
* timeout - Timeout (in ms) for checking whether interactive
tool events are still occurring.""")
+ show_grid = param.Boolean(default=True, doc="""
+ Whether to show a Cartesian grid on the plot.""")
+
show_legend = param.Boolean(default=False, doc="""
Whether to show legend for the plot.""")
@@ -334,6 +337,10 @@ class ElementPlot(BokehPlot, GenericElementPlot):
plot.xaxis[0].set(**props['x'])
plot.yaxis[0].set(**props['y'])
+ if not self.show_grid:
+ plot.xgrid.grid_line_color = None
+ plot.ygrid.grid_line_color = None
+
def _update_ranges(self, element, ranges):
framewise = self.lookup_options(element, 'norm').options.get('framewise')
|
Added show_grid plot option to BokehPlot
|
pyviz_holoviews
|
train
|
017bde1ad41bdd37d87b0ad651ecab1b3d3da1d5
|
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index <HASH>..<HASH> 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -71,7 +71,7 @@ Timedelta
Timezones
^^^^^^^^^
--
+- Bug in :func:`date_range` was raising AmbiguousTimeError for valid input with `ambiguous=False` (:issue:`35297`)
-
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index <HASH>..<HASH> 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -418,9 +418,9 @@ class DatetimeArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps, dtl.DatelikeOps
# index is localized datetime64 array -> have to convert
# start/end as well to compare
if start is not None:
- start = start.tz_localize(tz).asm8
+ start = start.tz_localize(tz, ambiguous, nonexistent).asm8
if end is not None:
- end = end.tz_localize(tz).asm8
+ end = end.tz_localize(tz, ambiguous, nonexistent).asm8
else:
# Create a linearly spaced date_range in local time
# Nanosecond-granularity timestamps aren't always correctly
diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/indexes/datetimes/test_constructors.py
+++ b/pandas/tests/indexes/datetimes/test_constructors.py
@@ -787,6 +787,65 @@ class TestDatetimeIndex:
expected = DatetimeIndex([Timestamp("2018", tz=tz), pd.NaT])
tm.assert_index_equal(result, expected)
+ def test_constructor_with_ambiguous_keyword_arg(self):
+ # GH 35297
+
+ expected = DatetimeIndex(
+ ["2020-11-01 01:00:00", "2020-11-02 01:00:00"],
+ dtype="datetime64[ns, America/New_York]",
+ freq="D",
+ ambiguous=False,
+ )
+
+ # ambiguous keyword in start
+ timezone = "America/New_York"
+ start = pd.Timestamp(year=2020, month=11, day=1, hour=1).tz_localize(
+ timezone, ambiguous=False
+ )
+ result = pd.date_range(start=start, periods=2, ambiguous=False)
+ tm.assert_index_equal(result, expected)
+
+ # ambiguous keyword in end
+ timezone = "America/New_York"
+ end = pd.Timestamp(year=2020, month=11, day=2, hour=1).tz_localize(
+ timezone, ambiguous=False
+ )
+ result = pd.date_range(end=end, periods=2, ambiguous=False)
+ tm.assert_index_equal(result, expected)
+
+ def test_constructor_with_nonexistent_keyword_arg(self):
+ # GH 35297
+
+ timezone = "Europe/Warsaw"
+
+ # nonexistent keyword in start
+ start = pd.Timestamp("2015-03-29 02:30:00").tz_localize(
+ timezone, nonexistent="shift_forward"
+ )
+ result = pd.date_range(start=start, periods=2, freq="H")
+ expected = DatetimeIndex(
+ [
+ pd.Timestamp("2015-03-29 03:00:00+02:00", tz=timezone),
+ pd.Timestamp("2015-03-29 04:00:00+02:00", tz=timezone),
+ ]
+ )
+
+ tm.assert_index_equal(result, expected)
+
+ # nonexistent keyword in end
+ end = pd.Timestamp("2015-03-29 02:30:00").tz_localize(
+ timezone, nonexistent="shift_forward"
+ )
+ result = pd.date_range(end=end, periods=2, freq="H")
+ expected = DatetimeIndex(
+ [
+ pd.Timestamp("2015-03-29 01:00:00+01:00", tz=timezone),
+ pd.Timestamp("2015-03-29 03:00:00+02:00", tz=timezone),
+ ]
+ )
+
+ tm.assert_index_equal(result, expected)
+
def test_constructor_no_precision_raises(self):
# GH-24753, GH-24739
|
BUG: date_range doesn't propagate ambigous=False to tz_localize (#<I>)
|
pandas-dev_pandas
|
train
|
cc4e14e40b5b5b60d5e8b203985bbca3f8cbbe08
|
diff --git a/gerrit.go b/gerrit.go
index <HASH>..<HASH> 100644
--- a/gerrit.go
+++ b/gerrit.go
@@ -244,7 +244,11 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Requ
// Request compact JSON
// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
req.Header.Add("Accept", "application/json")
- req.Header.Add("Content-Type", "application/json")
+
+ // No need to send the content type if there is no content
+ if body != nil {
+ req.Header.Add("Content-Type", "application/json")
+ }
// TODO: Add gzip encoding
// Accept-Encoding request header is set to gzip
|
fix: no need to send content-type header if no header sent (#<I>)
* fix: no need to send content-type header if no header sent
close: #<I>
* Update gerrit.go
|
andygrunwald_go-gerrit
|
train
|
e181a1d97ad3453ba52786852eecd667ae4ba704
|
diff --git a/bundles/org.eclipse.orion.client.javascript/web/js-tests/javascript/testingWorker.js b/bundles/org.eclipse.orion.client.javascript/web/js-tests/javascript/testingWorker.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.javascript/web/js-tests/javascript/testingWorker.js
+++ b/bundles/org.eclipse.orion.client.javascript/web/js-tests/javascript/testingWorker.js
@@ -101,19 +101,34 @@ define([
f(_d);
delete _instance.callbacks[id];
} else if(_d.request === 'read') {
+ var url, req, _f;
if(_d.args && _d.args.file) {
- var _f = 'js-tests/javascript/';
- _f += _d.args.file.logical ? _d.args.file.logical : _d.args.file;
- if(!/\.js$/g.test(_f)) {
- _f += '.js';
+ if(typeof(_d.args.file) === 'object') {
+ _f = 'js-tests/javascript/';
+ _f += _d.args.file.logical ? _d.args.file.logical : _d.args.file;
+ if(!/\.js$/g.test(_f)) {
+ _f += '.js';
+ }
+ url = new URL(_f, window.location.href);
+ req = new XMLHttpRequest();
+ req.onload = function(response) {
+ _instance.postMessage({request: 'read', ternID: _d.ternID, args: {contents: response.target.response, file: response.target.responseURL, logical: _d.args.file.logical}});
+ };
+ req.open('GET', url, true);
+ req.send();
+ } else if(typeof(_d.args.file) === 'string') {
+ _f = _d.args.file;
+ if(!/\.js$/g.test(_f)) {
+ _f += '.js';
+ }
+ url = new URL(_f, window.location.href);
+ req = new XMLHttpRequest();
+ req.onload = function(response) {
+ _instance.postMessage({request: 'read', ternID: _d.ternID, args: {contents: response.target.response, file: response.target.responseURL}});
+ };
+ req.open('GET', url, true);
+ req.send();
}
- var url = new URL(_f, window.location.href);
- var req = new XMLHttpRequest();
- req.onload = function(response) {
- _instance.postMessage({request: 'read', ternID: _d.ternID, args: {contents: response.target.response, file: response.target.responseURL, logical: _d.args.file.logical}});
- };
- req.open('GET', url, true);
- req.send();
} else {
_instance.postMessage({request: 'read', ternID: _d.ternID, args: {contents: _instance._state.buffer, file: _instance._state.file}});
}
|
Bug <I> - Create cross-file unit tests - support non-logical reads
|
eclipse_orion.client
|
train
|
aa56d1b1c881e3a237ede7c4cd96e1fb1b96a542
|
diff --git a/azure-kusto-ingest/tests/e2e.py b/azure-kusto-ingest/tests/e2e.py
index <HASH>..<HASH> 100644
--- a/azure-kusto-ingest/tests/e2e.py
+++ b/azure-kusto-ingest/tests/e2e.py
@@ -38,8 +38,6 @@ from azure.kusto.ingest import (
ManagedStreamingIngestClient,
)
-CLEAR_DB_CACHE = ".clear database cache streamingingestion schema"
-
@pytest.fixture(params=["ManagedStreaming", "NormalClient"])
def is_managed_streaming(request):
@@ -207,6 +205,10 @@ class TestE2E:
cls.client.execute(cls.test_db, f".alter table {cls.test_table} policy streamingingestion enable ")
+ # Clear the cache to guarantee that subsequent streaming ingestion requests incorporate database and table schema changes
+ # See https://docs.microsoft.com/azure/data-explorer/kusto/management/data-ingestion/clear-schema-cache-command
+ cls.client.execute(cls.test_db, ".clear database cache streamingingestion schema")
+
@classmethod
def teardown_class(cls):
cls.client.execute(cls.test_db, ".drop table {} ifexists".format(cls.test_table))
@@ -359,8 +361,6 @@ class TestE2E:
)
client = self.streaming_ingest_client if is_managed_streaming else self.ingest_client
- if is_managed_streaming:
- self.client.execute(self.test_db, CLEAR_DB_CACHE)
for f in [self.csv_file_path, self.zipped_csv_file_path]:
client.ingest_from_file(f, csv_ingest_props)
@@ -434,8 +434,6 @@ class TestE2E:
zipped = io.BytesIO(pathlib.Path(self.zipped_json_file_path).read_bytes())
client = self.managed_streaming_ingest_client if is_managed_streaming else self.ingest_client
- if is_managed_streaming:
- self.client.execute(self.test_db, CLEAR_DB_CACHE)
client.ingest_from_stream(text, json_ingestion_props)
client.ingest_from_stream(StreamDescriptor(zipped, is_compressed=True), json_ingestion_props)
@@ -501,7 +499,6 @@ class TestE2E:
@pytest.mark.asyncio
async def test_streaming_ingest_from_opened_file(self, is_managed_streaming):
- self.client.execute(self.test_db, CLEAR_DB_CACHE)
ingestion_properties = IngestionProperties(database=self.test_db, table=self.test_table, data_format=DataFormat.CSV)
client = self.managed_streaming_ingest_client if is_managed_streaming else self.streaming_ingest_client
@@ -512,7 +509,6 @@ class TestE2E:
@pytest.mark.asyncio
async def test_streaming_ingest_from_csv_file(self):
- self.client.execute(self.test_db, CLEAR_DB_CACHE)
ingestion_properties = IngestionProperties(database=self.test_db, table=self.test_table, flush_immediately=True, data_format=DataFormat.CSV)
for f in [self.csv_file_path, self.zipped_csv_file_path]:
@@ -522,7 +518,6 @@ class TestE2E:
@pytest.mark.asyncio
async def test_streaming_ingest_from_json_file(self):
- self.client.execute(self.test_db, CLEAR_DB_CACHE)
ingestion_properties = IngestionProperties(
database=self.test_db,
table=self.test_table,
@@ -539,7 +534,6 @@ class TestE2E:
@pytest.mark.asyncio
async def test_streaming_ingest_from_csv_io_streams(self):
- self.client.execute(self.test_db, CLEAR_DB_CACHE)
ingestion_properties = IngestionProperties(database=self.test_db, table=self.test_table, data_format=DataFormat.CSV)
byte_sequence = b'0,00000000-0000-0000-0001-020304050607,0,0,0,0,0,0,0,0,0,0,2014-01-01T01:01:01.0000000Z,Zero,"Zero",0,00:00:00,,null'
bytes_stream = io.BytesIO(byte_sequence)
|
E2E - Only clear cache once (#<I>)
* Only clear cache once.
* Added comment
|
Azure_azure-kusto-python
|
train
|
8654c66522cd0a41b5dc86db54ec58d5298d3f92
|
diff --git a/demo/memory.php b/demo/memory.php
index <HASH>..<HASH> 100644
--- a/demo/memory.php
+++ b/demo/memory.php
@@ -12,7 +12,7 @@ Debugger::$showCalledFrom = false;
* Debugger utility functions
*/
function debug($data) {
- return Debugger::debug($data);
+ Debugger::debug($data);
}
/**
diff --git a/demo/timer.php b/demo/timer.php
index <HASH>..<HASH> 100644
--- a/demo/timer.php
+++ b/demo/timer.php
@@ -14,7 +14,7 @@ $scriptStart = microtime(true);
* Debugger utility functions
*/
function debug($data) {
- return Debugger::debug($data);
+ Debugger::debug($data);
}
/**
|
Correct use of the Debugger::debug in utility function
|
xicrow_php-debug
|
train
|
9f622596b4fb45183a5bf852fcecf1ad840883d7
|
diff --git a/src/Application/Routes.php b/src/Application/Routes.php
index <HASH>..<HASH> 100644
--- a/src/Application/Routes.php
+++ b/src/Application/Routes.php
@@ -73,6 +73,7 @@ class Routes {
$app->get($path . 'apps/modules', 'Hook\\Controllers\\ApplicationController:modules');
$app->get($path . 'apps/schema', 'Hook\\Controllers\\ApplicationController:schema');
$app->post($path . 'apps/schema', 'Hook\\Controllers\\ApplicationController:upload_schema');
+ $app->post($path . 'apps/evaluate', 'Hook\\Controllers\\ApplicationController:evaluate');
$app->notFound(function () use ($app) {
echo json_encode(array('error' => 'not_found'));
diff --git a/src/Controllers/ApplicationController.php b/src/Controllers/ApplicationController.php
index <HASH>..<HASH> 100644
--- a/src/Controllers/ApplicationController.php
+++ b/src/Controllers/ApplicationController.php
@@ -156,6 +156,10 @@ class ApplicationController extends HookController {
return array('success' => true);
}
+ public function evaluate() {
+ return eval(Input::get('code'));
+ }
+
public function delete() {
return array('success' => false);
}
|
add evaluate command for server-side REPL from cli
|
doubleleft_hook
|
train
|
c28728112f30d27507d71de0b0dbaf91c0cd7933
|
diff --git a/lib/minify/matthiasmullie-pathconverter/src/Converter.php b/lib/minify/matthiasmullie-pathconverter/src/Converter.php
index <HASH>..<HASH> 100644
--- a/lib/minify/matthiasmullie-pathconverter/src/Converter.php
+++ b/lib/minify/matthiasmullie-pathconverter/src/Converter.php
@@ -71,6 +71,14 @@ class Converter implements ConverterInterface
// deal with different operating systems' directory structure
$path = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $path), '/');
+ // remove leading current directory.
+ if (substr($path, 0, 2) === './') {
+ $path = substr($path, 2);
+ }
+
+ // remove references to current directory in the path.
+ $path = str_replace('/./', '/', $path);
+
/*
* Example:
* /home/forkcms/frontend/cache/compiled_templates/../../core/layout/css/../images/img.gif
|
MDL-<I> core: Upgrade pathconverter lib to <I>
|
moodle_moodle
|
train
|
902c023cb6faec9ec554cc9d8d99eb5fb35c14aa
|
diff --git a/tests/src/main/java/com/hazelcast/simulator/tests/external/ExternalClientStarterTest.java b/tests/src/main/java/com/hazelcast/simulator/tests/external/ExternalClientStarterTest.java
index <HASH>..<HASH> 100644
--- a/tests/src/main/java/com/hazelcast/simulator/tests/external/ExternalClientStarterTest.java
+++ b/tests/src/main/java/com/hazelcast/simulator/tests/external/ExternalClientStarterTest.java
@@ -11,6 +11,7 @@ import com.hazelcast.simulator.test.annotations.Setup;
import java.io.File;
import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
+import static com.hazelcast.simulator.utils.HostAddressPicker.pickHostAddress;
import static java.lang.String.format;
public class ExternalClientStarterTest {
@@ -21,19 +22,29 @@ public class ExternalClientStarterTest {
public String binaryName = "binaryName";
public String arguments = "";
public String logFileName = "external-client";
+ public int processCount = 1;
private final SimulatorProperties props = new SimulatorProperties();
private final Bash bash = new Bash(props);
+ private final String ipAddress = pickHostAddress();
@Setup
public void setUp(TestContext testContext) throws Exception {
- // delete the local binary, so it won't get downloaded
+ // delete the local binary, so it won't get downloaded again
deleteQuiet(new File(binaryName));
}
@Run
public void run() {
- LOGGER.info(format("Starting external client: %s %s >> %s.log", binaryName, arguments, logFileName));
- bash.execute(format("../upload/%s %s >> %s.log &", binaryName, arguments, logFileName));
+ for (int i = 1; i <= processCount; i++) {
+ String tmpArguments = arguments
+ .replace("$PROCESS_INDEX", String.valueOf(i))
+ .replace("$IP_ADDRESS", ipAddress);
+
+ String tmpLogFileName = logFileName + "_" + i;
+
+ LOGGER.info(format("Starting external client: %s %s >> %s.log", binaryName, tmpArguments, tmpLogFileName));
+ bash.execute(format("../upload/%s %s >> %s.log &", binaryName, tmpArguments, tmpLogFileName));
+ }
}
}
|
Made process count configurable in ExternalClientStarterTest. Added $PROCESS_INDEX and $IP_ADDRESS as variables for arguments.
|
hazelcast_hazelcast-simulator
|
train
|
b002f79c3254a0a780d103fcdcc8488b7d2dfadb
|
diff --git a/src/Manager.php b/src/Manager.php
index <HASH>..<HASH> 100644
--- a/src/Manager.php
+++ b/src/Manager.php
@@ -213,6 +213,13 @@ class Manager
ob_end_clean();
}
+ if ($this->enabled === false || $this->allowOutput === true) {
+ $this->response->addContent(ob_get_contents());
+ }
+ if (ob_get_status()) {
+ ob_end_clean();
+ }
+
if ($this->enabled === true) {
$handler = $this->handler ?: $this->getHandler();
$this->statusCode = $this->statusCode ?: $handler->getStatusCode();
@@ -220,13 +227,6 @@ class Manager
$this->response->addContent($handler->render());
}
- if ($this->enabled === false || $this->allowOutput === true) {
- echo ob_get_contents();
- }
- if (ob_get_status()) {
- ob_end_clean();
- }
-
$this->response->setStatusCode($this->statusCode ?: 200);
$this->response->send();
}
|
add buffered output to response before handler output
|
SlaxWeb_Output
|
train
|
2f498d8852a8e64e4912a5ef0b6274ba897a258e
|
diff --git a/grails-plugin-url-mappings/src/main/groovy/org/codehaus/groovy/grails/web/mapping/UrlMappingsHolderFactoryBean.java b/grails-plugin-url-mappings/src/main/groovy/org/codehaus/groovy/grails/web/mapping/UrlMappingsHolderFactoryBean.java
index <HASH>..<HASH> 100644
--- a/grails-plugin-url-mappings/src/main/groovy/org/codehaus/groovy/grails/web/mapping/UrlMappingsHolderFactoryBean.java
+++ b/grails-plugin-url-mappings/src/main/groovy/org/codehaus/groovy/grails/web/mapping/UrlMappingsHolderFactoryBean.java
@@ -155,7 +155,6 @@ public class UrlMappingsHolderFactoryBean implements FactoryBean<UrlMappingsHold
* if thrown by application context methods
* @see org.springframework.beans.factory.BeanInitializationException
*/
- @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
setGrailsApplication(applicationContext.getBean( GrailsApplication.APPLICATION_ID, GrailsApplication.class) );
|
remove @Override from interface method impl
|
grails_grails-core
|
train
|
a03194e32533cfa88e975d91032ff1beb73ccd59
|
diff --git a/src/main/java/com/codeborne/selenide/Configuration.java b/src/main/java/com/codeborne/selenide/Configuration.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/codeborne/selenide/Configuration.java
+++ b/src/main/java/com/codeborne/selenide/Configuration.java
@@ -86,6 +86,14 @@ public class Configuration {
public static String browser = System.getProperty("selenide.browser", System.getProperty("browser", FIREFOX));
/**
+ * Which browser version to use (for Internet Explorer).
+ * Can be configured either programmatically or by system property "-Dselenide.browser.version=8" or "-Dbrowser.version=8".
+ * <p/>
+ * Default value: none
+ */
+ public static String browserVersion = System.getProperty("selenide.browser.version", System.getProperty("browser.version"));
+
+ /**
* URL of remote web driver (in case of using Selenium Grid).
* Can be configured either programmatically or by system property "-Dremote=http://localhost:5678/hub".
*
diff --git a/src/main/java/com/codeborne/selenide/webdriver/WebDriverFactory.java b/src/main/java/com/codeborne/selenide/webdriver/WebDriverFactory.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/codeborne/selenide/webdriver/WebDriverFactory.java
+++ b/src/main/java/com/codeborne/selenide/webdriver/WebDriverFactory.java
@@ -28,6 +28,7 @@ public class WebDriverFactory {
public WebDriver createWebDriver(Proxy proxy) {
log.config("Configuration.browser=" + browser);
+ log.config("Configuration.browser.version=" + browserVersion);
log.config("Configuration.remote=" + remote);
log.config("Configuration.browserSize=" + browserSize);
log.config("Configuration.startMaximized=" + startMaximized);
@@ -69,6 +70,8 @@ public class WebDriverFactory {
if (proxy != null) {
browserCapabilities.setCapability(PROXY, proxy);
}
+ if(browserVersion != null && !browserVersion.isEmpty())
+ browserCapabilities.setVersion(browserVersion);
return browserCapabilities;
}
|
implement possibility to set browser version inside 'createCommonCapabilities'
|
selenide_selenide
|
train
|
835e557b5faea1bd22ae489dc2e00f316e64e965
|
diff --git a/CHANGELOG b/CHANGELOG
index <HASH>..<HASH> 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -17,7 +17,7 @@
* Fat Zebra: Fix xid 3D Secure field [curiousepic]
* SafeCharge: Mark support for European countries [curiousepic]
* Checkout V2: Pass customer ip option [curiousepic]
-
+* Realex: Map AVS and CVV response codes [davidsantoso] #2424
== Version 1.65.0 (April 26, 2017)
* Adyen: Add Adyen v18 gateway [adyenpayments] #2272
diff --git a/lib/active_merchant/billing/gateways/realex.rb b/lib/active_merchant/billing/gateways/realex.rb
index <HASH>..<HASH> 100644
--- a/lib/active_merchant/billing/gateways/realex.rb
+++ b/lib/active_merchant/billing/gateways/realex.rb
@@ -103,11 +103,8 @@ module ActiveMerchant
response,
:test => (response[:message] =~ %r{\[ test system \]}),
:authorization => authorization_from(response),
- :cvv_result => response[:cvnresult],
- :avs_result => {
- :street_match => response[:avspostcoderesponse],
- :postal_match => response[:avspostcoderesponse]
- }
+ avs_result: AVSResult.new(code: response[:avspostcoderesponse]),
+ cvv_result: CVVResult.new(response[:cvnresult])
)
end
diff --git a/test/remote/gateways/remote_realex_test.rb b/test/remote/gateways/remote_realex_test.rb
index <HASH>..<HASH> 100644
--- a/test/remote/gateways/remote_realex_test.rb
+++ b/test/remote/gateways/remote_realex_test.rb
@@ -57,7 +57,7 @@ class RemoteRealexTest < Test::Unit::TestCase
assert_not_nil response
assert_failure response
- assert_equal '506', response.params['result']
+ assert_equal '504', response.params['result']
assert_match %r{no such}i, response.message
end
@@ -75,7 +75,6 @@ class RemoteRealexTest < Test::Unit::TestCase
end
def test_realex_purchase_declined
-
[ @visa_declined, @mastercard_declined ].each do |card|
response = @gateway.purchase(@amount, card,
@@ -122,7 +121,6 @@ class RemoteRealexTest < Test::Unit::TestCase
end
def test_realex_purchase_coms_error
-
[ @visa_coms_error, @mastercard_coms_error ].each do |card|
response = @gateway.purchase(@amount, card,
@@ -178,8 +176,8 @@ class RemoteRealexTest < Test::Unit::TestCase
assert_not_nil response
assert_failure response
- assert_equal '502', response.params['result']
- assert_match(/missing/i, response.message)
+ assert_equal '506', response.params['result']
+ assert_match(/does not conform/i, response.message)
end
def test_cvn
@@ -289,6 +287,24 @@ class RemoteRealexTest < Test::Unit::TestCase
assert_equal 'Successful', rebate_response.message
end
+ def test_maps_avs_and_cvv_response_codes
+ [ @visa, @mastercard ].each do |card|
+
+ response = @gateway.purchase(@amount, card,
+ :order_id => generate_unique_id,
+ :description => 'Test Realex Purchase',
+ :billing_address => {
+ :zip => '90210',
+ :country => 'US'
+ }
+ )
+ assert_not_nil response
+ assert_success response
+ assert_equal "M", response.avs_result["code"]
+ assert_equal "M", response.cvv_result["code"]
+ end
+ end
+
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, @visa_declined,
|
Realex: Map AVS and CVV response codes
Closes #<I>
|
activemerchant_active_merchant
|
train
|
45d30e3ff671480dcc4bb4f87d9c8d54edf234f9
|
diff --git a/maven-plugin/src/main/java/net/revelc/code/formatter/FormatterMojo.java b/maven-plugin/src/main/java/net/revelc/code/formatter/FormatterMojo.java
index <HASH>..<HASH> 100644
--- a/maven-plugin/src/main/java/net/revelc/code/formatter/FormatterMojo.java
+++ b/maven-plugin/src/main/java/net/revelc/code/formatter/FormatterMojo.java
@@ -432,13 +432,13 @@ public class FormatterMojo extends AbstractMojo implements ConfigurationSource {
switch (result) {
case SKIPPED:
rc.skippedCount++;
- break;
+ return;
case SUCCESS:
rc.successCount++;
break;
case FAIL:
rc.failCount++;
- break;
+ return;
default:
break;
}
|
[bug] Skipped items counted twice and failed items attempted anyway
|
revelc_formatter-maven-plugin
|
train
|
c99fbda8dc060f385a0831caa40f9779bb100bd6
|
diff --git a/src/Element/WebformNominatim.php b/src/Element/WebformNominatim.php
index <HASH>..<HASH> 100644
--- a/src/Element/WebformNominatim.php
+++ b/src/Element/WebformNominatim.php
@@ -317,6 +317,9 @@ class WebformNominatim extends WebformLocationBase {
);
}
}
+ // Reset current selection, if any. That way we can deselect wrongly made options
+ // By researching.
+ $form_state->set($my_geosjonkey.'-table-option', NULL);
// Rebuild the form.
$form_state->setRebuild(TRUE);
}
|
Humble attempt at making nominatim better
This is a response to a detail that bothers me:
When you search for a place and then select, the option you selected sticks during the whole session. Let's say selection has 4 results and you select number 4, if you search again, the selected option is again number 4, independently that this is another place in earth. Things get serious when the response has only one! In that case you can no longer select anything because its already selected. I need to double check if i will have to also modify the user input here or not
|
esmero_webform_strawberryfield
|
train
|
a00c5858e7fb4510f625e8a36a2b32398b942522
|
diff --git a/metric_learn/nca.py b/metric_learn/nca.py
index <HASH>..<HASH> 100644
--- a/metric_learn/nca.py
+++ b/metric_learn/nca.py
@@ -11,8 +11,10 @@ from .base_metric import BaseMetricLearner
class NCA(BaseMetricLearner):
def __init__(self, max_iter=100, learning_rate=0.01):
- self.max_iter = max_iter
- self.learning_rate = learning_rate
+ self.params = {
+ 'max_iter': max_iter,
+ 'learning_rate': learning_rate,
+ }
self.A = None
def transformer(self):
@@ -32,7 +34,7 @@ class NCA(BaseMetricLearner):
dX = X[:,None] - X[None] # shape (n, n, d)
tmp = np.einsum('...i,...j->...ij', dX, dX) # shape (n, n, d, d)
masks = labels[:,None] == labels[None]
- for it in xrange(self.max_iter):
+ for it in xrange(self.params['max_iter']):
for i, label in enumerate(labels):
mask = masks[i]
Ax = A.dot(X.T).T # shape (n, d)
@@ -43,7 +45,7 @@ class NCA(BaseMetricLearner):
t = softmax[:, None, None] * tmp[i] # shape (n, d, d)
d = softmax[mask].sum() * t.sum(axis=0) - t[mask].sum(axis=0)
- A += self.learning_rate * A.dot(d)
+ A += self.params['learning_rate'] * A.dot(d)
self.X = X
self.A = A
|
NCA params moved to dictionary
|
metric-learn_metric-learn
|
train
|
ef3834dcfb027d757bc9cda48428f121bd510f45
|
diff --git a/lib/svtplay_dl/service/nrk.py b/lib/svtplay_dl/service/nrk.py
index <HASH>..<HASH> 100644
--- a/lib/svtplay_dl/service/nrk.py
+++ b/lib/svtplay_dl/service/nrk.py
@@ -2,12 +2,15 @@
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
from __future__ import absolute_import
import re
+import sys
+import json
from svtplay_dl.service import Service
from svtplay_dl.utils import get_http_data, subtitle_tt
from svtplay_dl.utils.urllib import urlparse
from svtplay_dl.fetcher.hds import download_hds
from svtplay_dl.fetcher.hls import download_hls
+from svtplay_dl.log import log
class Nrk(Service):
supported_domains = ['nrk.no', 'tv.nrk.no']
@@ -15,7 +18,22 @@ class Nrk(Service):
def get(self, options):
data = get_http_data(self.url)
match = re.search(r'data-media="(.*manifest.f4m)"', data)
- manifest_url = match.group(1)
+ if match:
+ manifest_url = match.group(1)
+ else:
+ match = re.search(r'data-video-id="(\d+)"', data)
+ if match is None:
+ log.error("Can't find video id.")
+ sys.exit(2)
+ vid = match.group(1)
+ match = re.search(r"PS_VIDEO_API_URL : '([^']*)',", data)
+ if match is None:
+ log.error("Can't find server address with media info")
+ sys.exit(2)
+ dataurl = "%smediaelement/%s" % (match.group(1), vid)
+ data = json.loads(get_http_data(dataurl))
+ manifest_url = data["mediaUrl"]
+ options.live = data["isLive"]
if options.hls:
manifest_url = manifest_url.replace("/z/", "/i/").replace("manifest.f4m", "master.m3u8")
download_hls(options, manifest_url)
|
nrk: better support for nrk.no
|
spaam_svtplay-dl
|
train
|
db4fd0a943782ee2070bfe1139891ebb359ac279
|
diff --git a/Tests/Integration/Traversable/IterationTest.php b/Tests/Integration/Traversable/IterationTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Integration/Traversable/IterationTest.php
+++ b/Tests/Integration/Traversable/IterationTest.php
@@ -57,6 +57,27 @@ class IterationTest extends TraversableTest
/**
* @dataProvider everything
*/
+ public function testThatIdenticalNonScalarKeysMapToTheSameScalarKey(\Pinq\ITraversable $traversable, array $data)
+ {
+ foreach([new \stdClass(), [], [1], fopen('php://input', 'r')] as $identicalNonScalar) {
+ $withNonScalarKeys = $traversable
+ ->indexBy(function () use ($identicalNonScalar) { return $identicalNonScalar; });
+
+ $this->assertSame(empty($data) ? [] : [0 => end($data)], $withNonScalarKeys->asArray());
+
+ if(is_object($identicalNonScalar) && !($traversable instanceof \Pinq\IQueryable)) {
+ //No longer identical, should map to individual keys
+ $withNonScalarKeys = $traversable
+ ->indexBy(function () use ($identicalNonScalar) { return clone $identicalNonScalar; });
+
+ $this->assertSame(array_values($data), $withNonScalarKeys->asArray());
+ }
+ }
+ }
+
+ /**
+ * @dataProvider everything
+ */
public function testThatNonScalarKeysAreReindexedWhenConvertingToArrayOrIteratingButNotForIterateMethodOrTrueIterator(\Pinq\ITraversable $traversable, array $data)
{
$nonScalarKeys = [
|
Added test for identical non scalar keys
|
TimeToogo_Pinq
|
train
|
3ccc017a85a07e975bbb015dcb31b4c5450820a8
|
diff --git a/shared/profile/pgp/index.js b/shared/profile/pgp/index.js
index <HASH>..<HASH> 100644
--- a/shared/profile/pgp/index.js
+++ b/shared/profile/pgp/index.js
@@ -6,7 +6,7 @@ import Finished from './finished-generating-pgp'
import PgpInfo from './add'
import {TypedConnector} from '../../util/typed-connect'
import {updatePgpInfo, generatePgp} from '../../actions/profile'
-import {navigateUp, navigateTo, navigateAppend} from '../../actions/route-tree'
+import {navigateUp, navigateAppend} from '../../actions/route-tree'
import * as Constants from '../../constants/profile'
import type {Props as ProvePgpChoiceProps, Options as ProvePgpChoiceOptions} from './prove-pgp-choice'
@@ -20,7 +20,7 @@ import type {TypedState} from '../../constants/reducer'
const choiceConnector: TypedConnector<TypedState, TypedDispatch<{}>, {}, ProvePgpChoiceProps> = new TypedConnector()
export const ConnectedChoice = choiceConnector.connect(
(state, dispatch, ownProps) => ({
- onCancel: () => { dispatch(navigateTo([])) },
+ onCancel: () => { dispatch(navigateUp()) },
onOptionClick: (type: ProvePgpChoiceOptions) => { dispatch(navigateAppend([type])) },
})
)(ProvePgpChoice)
|
Fix canceling from Add a PGP key leading to app front page
|
keybase_client
|
train
|
4d6b64ec49ef824c116b9cb795321552fe2859ce
|
diff --git a/docs/examples/patterns/navigation/_script.js b/docs/examples/patterns/navigation/_script.js
index <HASH>..<HASH> 100644
--- a/docs/examples/patterns/navigation/_script.js
+++ b/docs/examples/patterns/navigation/_script.js
@@ -1,25 +1,24 @@
/**
- Opens a given subnav by applying is-active class to it
+ Toggles visibility of given subnav by toggling is-active class to it
and setting aria-hidden attribute on dropdown contents.
@param {HTMLElement} subnav Root element of subnavigation to open.
*/
-function openSubnav(subnav) {
- subnav.classList.add('is-active');
- var toggle = subnav.querySelector('.p-subnav__toggle');
- var dropdown = document.getElementById(toggle.getAttribute('aria-controls'));
- dropdown.setAttribute('aria-hidden', 'true');
-}
+function toggleSubnav(subnav, open) {
+ if (open) {
+ subnav.classList.add('is-active');
+ } else {
+ subnav.classList.remove('is-active');
+ }
-/**
- Closes a given subnav by removing is-active class to it
- and setting aria-hidden attribute on dropdown contents.
- @param {HTMLElement} subnav Root element of subnavigation to open.
-*/
-function closeSubnav(subnav) {
- subnav.classList.remove('is-active');
var toggle = subnav.querySelector('.p-subnav__toggle');
- var dropdown = document.getElementById(toggle.getAttribute('aria-controls'));
- dropdown.setAttribute('aria-hidden', 'false');
+
+ if (toggle) {
+ var dropdown = document.getElementById(toggle.getAttribute('aria-controls'));
+
+ if (dropdown) {
+ dropdown.setAttribute('aria-hidden', open ? 'true' : false);
+ }
+ }
}
/**
@@ -28,7 +27,7 @@ function closeSubnav(subnav) {
function closeAllSubnavs() {
var subnavs = document.querySelectorAll('.p-subnav');
for (var i = 0, l = subnavs.length; i < l; i++) {
- closeSubnav(subnavs[i]);
+ toggleSubnav(subnavs[i], false);
}
}
@@ -46,7 +45,7 @@ function setupSubnavToggle(subnavToggle) {
closeAllSubnavs();
if (!isActive) {
- openSubnav(subnav);
+ toggleSubnav(subnav, true);
}
});
}
|
Updates to subnav example script.
|
canonical-web-and-design_vanilla-framework
|
train
|
dd469e2eddfb7db91a3e5c723acbd87d85050d6b
|
diff --git a/impl/src/main/java/org/jboss/weld/annotated/enhanced/jlr/AbstractEnhancedAnnotated.java b/impl/src/main/java/org/jboss/weld/annotated/enhanced/jlr/AbstractEnhancedAnnotated.java
index <HASH>..<HASH> 100644
--- a/impl/src/main/java/org/jboss/weld/annotated/enhanced/jlr/AbstractEnhancedAnnotated.java
+++ b/impl/src/main/java/org/jboss/weld/annotated/enhanced/jlr/AbstractEnhancedAnnotated.java
@@ -18,7 +18,6 @@ package org.jboss.weld.annotated.enhanced.jlr;
import static org.jboss.weld.logging.messages.ReflectionMessage.ANNOTATION_MAP_NULL;
import static org.jboss.weld.logging.messages.ReflectionMessage.DECLARED_ANNOTATION_MAP_NULL;
-import static org.jboss.weld.util.collections.WeldCollections.immutableMap;
import static org.jboss.weld.util.reflection.Reflections.EMPTY_ANNOTATIONS;
import java.lang.annotation.Annotation;
@@ -27,7 +26,6 @@ import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -114,7 +112,7 @@ public abstract class AbstractEnhancedAnnotated<T, S> implements EnhancedAnnotat
private final Map<Class<? extends Annotation>, Annotation> annotationMap;
// The meta-annotation map (annotation type -> set of annotations containing
// meta-annotation) of the item
- private final Map<Class<? extends Annotation>, List<Annotation>> metaAnnotationMap;
+ private final ArraySetMultimap<Class<? extends Annotation>, Annotation> metaAnnotationMap;
private final Class<T> rawType;
private final Type[] actualTypeArguments;
@@ -145,7 +143,7 @@ public abstract class AbstractEnhancedAnnotated<T, S> implements EnhancedAnnotat
addMetaAnnotations(metaAnnotationMap, annotation, annotation.annotationType().getAnnotations(), false);
addMetaAnnotations(metaAnnotationMap, annotation, classTransformer.getTypeStore().get(annotation.annotationType()), false);
}
- this.metaAnnotationMap = immutableMap(metaAnnotationMap);
+ this.metaAnnotationMap = metaAnnotationMap;
if (declaredAnnotationMap == null) {
throw new WeldException(DECLARED_ANNOTATION_MAP_NULL);
|
Do not wrap multimap with SharedObjectCache as it is slow and does not save an apreciable amount of memory
|
weld_core
|
train
|
01465894084c77e135115ab3108d10e142baec40
|
diff --git a/cobra/core/Reaction.py b/cobra/core/Reaction.py
index <HASH>..<HASH> 100644
--- a/cobra/core/Reaction.py
+++ b/cobra/core/Reaction.py
@@ -1,6 +1,6 @@
from __future__ import print_function
-from ..external.six import iteritems
+from ..external.six import string_types, iteritems
#Is it better to restrict a Reaction to a single model or
@@ -279,10 +279,19 @@ class Reaction(Object):
"""Remove a metabolite from the reaction and return the
stoichiometric coefficient.
- the_metabolite: A cobra.Metabolite that is in the reaction
-
-
+ the_metabolite: A cobra.Metabolite that is in the reaction or its id
+
"""
+ if isinstance(the_metabolite, string_types):
+ found_match = None
+ for possible_match in self._metabolites:
+ if possible_match.id == the_metabolite:
+ found_match = possible_match
+ break
+ if found_match is None:
+ raise KeyError("No metabolite named %s in the reaction" % the_metabolite)
+ else:
+ the_metabolite = found_match
the_coefficient = self._metabolites.pop(the_metabolite)
the_metabolite._reaction.remove(self)
return the_coefficient
|
Reaction.pop will accept a metabolite id
If a string is given to Reaction.pop, the function will find the
appropriate metabolite object and remove that from the reaction.
|
opencobra_cobrapy
|
train
|
52558e4f759b0825cfa35d84ec9088040fc0a89d
|
diff --git a/post-processor/vagrant-cloud/step_prepare_upload.go b/post-processor/vagrant-cloud/step_prepare_upload.go
index <HASH>..<HASH> 100644
--- a/post-processor/vagrant-cloud/step_prepare_upload.go
+++ b/post-processor/vagrant-cloud/step_prepare_upload.go
@@ -30,9 +30,13 @@ func (s *stepPrepareUpload) Run(state multistep.StateBag) multistep.StepAction {
resp, err := client.Get(path)
if err != nil || (resp.StatusCode != 200) {
- cloudErrors := &VagrantCloudErrors{}
- err = decodeBody(resp, cloudErrors)
- state.Put("error", fmt.Errorf("Error preparing upload: %s", cloudErrors.FormatErrors()))
+ if resp == nil || resp.Body == nil {
+ state.Put("error", "No response from server.")
+ } else {
+ cloudErrors := &VagrantCloudErrors{}
+ err = decodeBody(resp, cloudErrors)
+ state.Put("error", fmt.Errorf("Error preparing upload: %s", cloudErrors.FormatErrors()))
+ }
return multistep.ActionHalt
}
|
check for nil body from upload response
|
hashicorp_packer
|
train
|
98d97d59c711dbf7e84f0d60fb2e2bfaa34345ed
|
diff --git a/transitfeed/__init__.py b/transitfeed/__init__.py
index <HASH>..<HASH> 100644
--- a/transitfeed/__init__.py
+++ b/transitfeed/__init__.py
@@ -85,4 +85,4 @@ from stoptime import *
from transfer import *
from trip import *
-__version__ = '1.2.5'
+__version__ = '1.2.6'
|
Increasing the version number to <I> in preparation of the release
|
google_transitfeed
|
train
|
7292aa6d3b520d54baaa8b061c0241b1ce057d8f
|
diff --git a/cmd/fluxctl/args_test.go b/cmd/fluxctl/args_test.go
index <HASH>..<HASH> 100644
--- a/cmd/fluxctl/args_test.go
+++ b/cmd/fluxctl/args_test.go
@@ -20,14 +20,7 @@ func TestUserGitconfigMap(t *testing.T) {
core.repositoryformatversion=0
core.filemode=true
core.bare=false`
- expected := map[string]string{
- "push.default": "simple",
- "merge.conflictstyle": "diff3",
- "pull.ff": "only",
- "core.repositoryformatversion": "0",
- "core.filemode": "true",
- "core.bare": "false",
- }
+ expected := gitConfigMap(nil)
userGitconfigInfo := userGitconfigMap(d)
if len(userGitconfigInfo) != 6 {
@@ -50,15 +43,9 @@ func TestUserGitconfigMap_WithEmptyLines(t *testing.T) {
core.bare=false
`
- expected := map[string]string{
- "user.name": "Jane Doe",
- "push.default": "simple",
- "merge.conflictstyle": "diff3",
- "pull.ff": "only",
- "core.repositoryformatversion": "0",
- "core.filemode": "true",
- "core.bare": "false",
- }
+ expected := gitConfigMap(map[string]string{
+ "user.name": "Jane Doe",
+ })
userGitconfigInfo := userGitconfigMap(d)
if len(userGitconfigInfo) != 7 {
@@ -84,82 +71,45 @@ func TestUserGitconfigMap_WithNoKeys(t *testing.T) {
}
func TestGetCommitAuthor_BothNameAndEmail(t *testing.T) {
- input := map[string]string{
- "user.name": "Jane Doe",
- "user.email": "jd@j.d",
- "push.default": "simple",
- "merge.conflictstyle": "diff3",
- "pull.ff": "only",
- "core.repositoryformatversion": "0",
- "core.filemode": "true",
- "core.bare": "false",
- }
+ input := gitConfigMap(map[string]string{
+ "user.name": "Jane Doe",
+ "user.email": "jd@j.d",
+ })
checkAuthor(t, input, "Jane Doe <jd@j.d>")
}
func TestGetCommitAuthor_OnlyName(t *testing.T) {
- input := map[string]string{
- "user.name": "Jane Doe",
- "push.default": "simple",
- "merge.conflictstyle": "diff3",
- "pull.ff": "only",
- "core.repositoryformatversion": "0",
- "core.filemode": "true",
- "core.bare": "false",
- }
+ input := gitConfigMap(map[string]string{
+ "user.name": "Jane Doe",
+ })
checkAuthor(t, input, "Jane Doe")
}
func TestGetCommitAuthor_OnlyEmail(t *testing.T) {
- input := map[string]string{
- "user.email": "jd@j.d",
- "push.default": "simple",
- "merge.conflictstyle": "diff3",
- "pull.ff": "only",
- "core.repositoryformatversion": "0",
- "core.filemode": "true",
- "core.bare": "false",
- }
+ input := gitConfigMap(map[string]string{
+ "user.email": "jd@j.d",
+ })
checkAuthor(t, input, "jd@j.d")
}
func TestGetCommitAuthor_NoNameNoEmail(t *testing.T) {
- input := map[string]string{
- "push.default": "simple",
- "merge.conflictstyle": "diff3",
- "pull.ff": "only",
- "core.repositoryformatversion": "0",
- "core.filemode": "true",
- "core.bare": "false",
- }
+ input := gitConfigMap(nil)
checkAuthor(t, input, "")
}
func TestGetCommitAuthor_NameAndEmptyEmail(t *testing.T) {
- input := map[string]string{
- "user.name": "Jane Doe",
- "user.email": "",
- "push.default": "simple",
- "merge.conflictstyle": "diff3",
- "pull.ff": "only",
- "core.repositoryformatversion": "0",
- "core.filemode": "true",
- "core.bare": "false",
- }
+ input := gitConfigMap(map[string]string{
+ "user.name": "Jane Doe",
+ "user.email": "",
+ })
checkAuthor(t, input, "Jane Doe")
}
func TestGetCommitAuthor_EmailAndEmptyName(t *testing.T) {
- input := map[string]string{
- "user.name": "",
- "user.email": "jd@j.d",
- "push.default": "simple",
- "merge.conflictstyle": "diff3",
- "pull.ff": "only",
- "core.repositoryformatversion": "0",
- "core.filemode": "true",
- "core.bare": "false",
- }
+ input := gitConfigMap(map[string]string{
+ "user.name": "",
+ "user.email": "jd@j.d",
+ })
checkAuthor(t, input, "jd@j.d")
}
@@ -169,3 +119,18 @@ func checkAuthor(t *testing.T, input map[string]string, expected string) {
t.Fatalf("author %q does not match expected value %q", author, expected)
}
}
+
+func gitConfigMap(input map[string]string) map[string]string {
+ res := map[string]string{
+ "push.default": "simple",
+ "merge.conflictstyle": "diff3",
+ "pull.ff": "only",
+ "core.repositoryformatversion": "0",
+ "core.filemode": "true",
+ "core.bare": "false",
+ }
+ for k, v := range input {
+ res[k] = v
+ }
+ return res
+}
|
refactor: extract base git config map in tests
|
weaveworks_flux
|
train
|
1c8f1cb4a7f361784880f62c6c5e505e4f333b5b
|
diff --git a/core/src/main/java/org/jboss/jca/core/connectionmanager/pool/mcp/SemaphoreArrayListManagedConnectionPool.java b/core/src/main/java/org/jboss/jca/core/connectionmanager/pool/mcp/SemaphoreArrayListManagedConnectionPool.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/org/jboss/jca/core/connectionmanager/pool/mcp/SemaphoreArrayListManagedConnectionPool.java
+++ b/core/src/main/java/org/jboss/jca/core/connectionmanager/pool/mcp/SemaphoreArrayListManagedConnectionPool.java
@@ -70,13 +70,13 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
/** Whether debug is enabled */
private boolean debug;
-
+
/** Whether trace is enabled */
private boolean trace;
-
+
/** The bundle */
private static CoreBundle bundle = Messages.getBundle(CoreBundle.class);
-
+
/** The managed connection factory */
private ManagedConnectionFactory mcf;
@@ -95,7 +95,7 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
/** The pool */
private Pool pool;
- /**
+ /**
* Copy of the maximum size from the pooling parameters.
* Dynamic changes to this value are not compatible with
* the semaphore which cannot change be dynamically changed.
@@ -109,21 +109,21 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
private Semaphore permits;
/** The map of connection listeners which has a permit */
- private ConcurrentMap<ConnectionListener, ConnectionListener> clPermits =
+ private final ConcurrentMap<ConnectionListener, ConnectionListener> clPermits =
new ConcurrentHashMap<ConnectionListener, ConnectionListener>();
/** The checked out connections */
- private ArrayList<ConnectionListener> checkedOut = new ArrayList<ConnectionListener>();
+ private final ArrayList<ConnectionListener> checkedOut = new ArrayList<ConnectionListener>();
/** Whether the pool has been shutdown */
- private AtomicBoolean shutdown = new AtomicBoolean(false);
+ private final AtomicBoolean shutdown = new AtomicBoolean(false);
/** Statistics */
private ManagedConnectionPoolStatisticsImpl statistics;
/** Supports lazy association */
private Boolean supportsLazyAssociation;
-
+
/**
* Constructor
*/
@@ -163,7 +163,7 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
this.statistics = new ManagedConnectionPoolStatisticsImpl(maxSize);
this.permits = new Semaphore(maxSize, true, statistics);
this.supportsLazyAssociation = null;
-
+
// Check if connection manager supports lazy association
if (!(clf instanceof LazyAssociatableConnectionManager))
supportsLazyAssociation = Boolean.FALSE;
@@ -231,13 +231,13 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
//Register removal support
IdleRemover.getInstance().registerPool(this, poolConfiguration.getIdleTimeoutMinutes() * 1000L * 60);
}
-
+
if (poolConfiguration.isBackgroundValidation() && poolConfiguration.getBackgroundValidationMillis() > 0)
{
if (debug)
- log.debug("Registering for background validation at interval " +
+ log.debug("Registering for background validation at interval " +
poolConfiguration.getBackgroundValidationMillis());
-
+
//Register validation
ConnectionValidator.getInstance().registerPool(this, poolConfiguration.getBackgroundValidationMillis());
}
@@ -357,7 +357,7 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
cl = null;
}
- // We made it here, something went wrong and we should validate
+ // We made it here, something went wrong and we should validate
// if we should continue attempting to acquire a connection
if (poolConfiguration.isUseFastFail())
{
@@ -366,7 +366,7 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
"acquire connection from pool and a new connection will be created immeadiately");
break;
}
-
+
}
}
while (cls.size() > 0);
@@ -377,6 +377,11 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
// No, the pool was empty, so we have to make a new one.
cl = createConnectionEventListener(subject, cri);
+ if ((poolConfiguration.isPrefill() || poolConfiguration.isStrictMin()) &&
+ pool instanceof PrefillPool &&
+ poolConfiguration.getMinSize() > 0)
+ PoolFiller.fillPool(this);
+
synchronized (cls)
{
checkedOut.add(cl);
@@ -889,9 +894,9 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
* @return True if connections should be removed; otherwise false
*/
private boolean shouldRemove()
- {
+ {
boolean remove = true;
-
+
if (poolConfiguration.isStrictMin())
{
// Add 1 to min-pool-size since it is strict
@@ -900,10 +905,10 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
if (trace)
log.trace("StrictMin is active. Current connection will be removed is " + remove);
}
-
+
return remove;
}
-
+
/**
* {@inheritDoc}
*/
@@ -1089,20 +1094,20 @@ public class SemaphoreArrayListManagedConnectionPool implements ManagedConnectio
try
{
if (trace)
- log.tracef("Detach: %s", cl);
+ log.tracef("Detach: %s", cl);
DissociatableManagedConnection dmc = (DissociatableManagedConnection)cl.getManagedConnection();
dmc.dissociateConnections();
-
+
cl.unregisterConnections();
-
+
returnConnection(cl, false, false);
}
catch (Throwable t)
{
// Ok - didn't work; nuke it and disable
if (debug)
- log.debug("Exception during detach for: " + pool.getName(), t);
+ log.debug("Exception during detach for: " + pool.getName(), t);
supportsLazyAssociation = Boolean.FALSE;
returnConnection(cl, true, true);
|
JBJCA-<I> Pool is not prefilled after a database crash even if prefill option is set
|
ironjacamar_ironjacamar
|
train
|
4667c05fc9b2588d4c416b155716db2b5f82ae91
|
diff --git a/closure/goog/ui/editor/toolbarfactory.js b/closure/goog/ui/editor/toolbarfactory.js
index <HASH>..<HASH> 100644
--- a/closure/goog/ui/editor/toolbarfactory.js
+++ b/closure/goog/ui/editor/toolbarfactory.js
@@ -207,7 +207,7 @@ goog.ui.editor.ToolbarFactory.addFormatOption = function(button, caption, tag) {
var buttonDom = button.getDomHelper();
var option = new goog.ui.Option(
buttonDom.createDom(goog.dom.TagName.DIV, null, caption), tag, buttonDom);
- option.setId(tag);
+ option.setId(String(tag));
button.addItem(option);
};
|
Prepare for goog.dom.TagName type change.
To improve the type precision of created or accessed elements, the type of goog.dom.TagName members is going to change from string to object instance in cl/<I>. This CL prepares for that and wraps all string-only usages of goog.dom.TagName members into String().
RELNOTES: n/a
-------------
Created by MOE: <URL>
|
google_closure-library
|
train
|
dd8d521d91b1f73bcb897cb9f41fd942f1f7188e
|
diff --git a/mod/assignment/index.php b/mod/assignment/index.php
index <HASH>..<HASH> 100644
--- a/mod/assignment/index.php
+++ b/mod/assignment/index.php
@@ -56,7 +56,13 @@
$submitted = get_string("no");
}
$due = userdate($assignment->timedue);
- $link = "<A HREF=\"view.php?id=$assignment->coursemodule\">$assignment->name</A>";
+ if (!$assignment->visible) {
+ //Show dimmed if the mod is hidden
+ $link = "<A class=\"dimmed\" HREF=\"view.php?id=$assignment->coursemodule\">$assignment->name</A>";
+ } else {
+ //Show normal if the mod is visible
+ $link = "<A HREF=\"view.php?id=$assignment->coursemodule\">$assignment->name</A>";
+ }
if ($assignment->section) {
$section = "$assignment->section";
} else {
|
Changed to show the hidden assignments dimmed (bug #<I>)
|
moodle_moodle
|
train
|
e3a26c8b2c949badcf1f8b628fa6661d3bf86577
|
diff --git a/core/src/test/java/dagger/ModuleTest.java b/core/src/test/java/dagger/ModuleTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/dagger/ModuleTest.java
+++ b/core/src/test/java/dagger/ModuleTest.java
@@ -181,9 +181,14 @@ public final class ModuleTest {
@Module(includes = ModuleMissingModuleAnnotation.class)
static class ChildModuleMissingModuleAnnotation {}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void childModuleMissingModuleAnnotation() {
- ObjectGraph.createWith(new TestingLoader(), new TestingLoader(), new ChildModuleMissingModuleAnnotation());
+ try {
+ ObjectGraph.createWith(new TestingLoader(), new ChildModuleMissingModuleAnnotation());
+ } catch (IllegalArgumentException e) {
+ assertThat(e.getMessage())
+ .contains("No @Module on dagger.ModuleTest$ModuleMissingModuleAnnotation");
+ }
}
@Module
|
Fix (irrelevant) error in test, and strengthen it to ensure the right failure is being caught.
|
square_dagger
|
train
|
71744a6332524588bdfae271f762083ad0fe7e85
|
diff --git a/piplicenses.py b/piplicenses.py
index <HASH>..<HASH> 100644
--- a/piplicenses.py
+++ b/piplicenses.py
@@ -138,9 +138,9 @@ def get_packages(args):
pkg_dirname = "{}-{}.dist-info".format(
pkg.project_name.replace("-", "_"), pkg.version)
patterns = []
- [patterns.extend(glob.glob(os.path.join(pkg.location,
+ [patterns.extend(sorted(glob.glob(os.path.join(pkg.location,
pkg_dirname,
- f))) for f in file_names]
+ f)))) for f in file_names]
for test_file in patterns:
if os.path.exists(test_file):
included_file = test_file
|
Use sorted glob.glob() results #<I>
The 'LICENSE' is always selected when the following four LICENSE files exist:
LICENSE
LICENSE.APACHE
LICENSE.BSD
LICENSE.PSF
|
raimon49_pip-licenses
|
train
|
1e46aa758a1f34cd1ff9898d0377791aa7417987
|
diff --git a/lib/parser/document_parser.js b/lib/parser/document_parser.js
index <HASH>..<HASH> 100644
--- a/lib/parser/document_parser.js
+++ b/lib/parser/document_parser.js
@@ -225,7 +225,13 @@ function getValidations(field) {
}
function formatPatternValidation(value) {
- return value.split("'").join("\\'");
+ const chunks = value.split("'").map(chunk => {
+ if (!chunk.endsWith('\\')) {
+ return `${chunk}\\`;
+ }
+ return chunk;
+ });
+ return chunks.join("\\'");
}
function fillAssociations() {
|
Made sure all the quotes are escaped in regex validations
|
jhipster_jhipster-core
|
train
|
f078b6f5ff92b110b7bc2b67c2ab1a9a2faa066b
|
diff --git a/publishable/lang/zh_TW/bread.php b/publishable/lang/zh_TW/bread.php
index <HASH>..<HASH> 100644
--- a/publishable/lang/zh_TW/bread.php
+++ b/publishable/lang/zh_TW/bread.php
@@ -14,7 +14,7 @@ return [
'error_creating_bread' => '很抱歉,在建立 BREAD 時出現了問題',
'error_removing_bread' => '很抱歉,在刪除 BREAD 時出現了問題',
'error_updating_bread' => '很抱歉,在更新 BREAD 時出現了問題',
- 'error_tagging' => 'Sorry it appears there may have been a problem creating the record. Please make sure your table has defaults for other fields.',
+ 'error_tagging' => '很抱歉,在創建紀錄時出現了問題,請確認您的資料表中含有其他欄位的預設值.',
'success_created_bread' => '成功建立 BREAD',
'success_remove_bread' => '成功地從 :datatype 中移除 BREAD',
'success_update_bread' => '成功更新 :datatype BREAD',
@@ -36,13 +36,13 @@ return [
'order_column' => '順序欄位',
'order_column_ph' => '記錄順序的列',
'order_ident_column' => '顯示順序欄位',
- 'order_ident_column_ph' => 'The column which is displayed in the order page',
+ 'order_ident_column_ph' => '訂單頁面顯示列',
'ordering_not_set' => '您需要先定義順序',
'policy_class' => 'Policy 類別名',
'policy_name' => 'Policy 名',
'policy_name_ph' => '例如 \App\Policies\UserPolicy,如果留空則嘗試使用預設值',
'server_pagination' => '伺服器端分頁',
- 'updated_order' => 'Order updated successfully',
+ 'updated_order' => '訂單更新成功',
'url_slug' => 'URL Slug(必須是唯一的)',
'url_slug_ph' => 'URL Slug(例如文章)',
];
diff --git a/publishable/lang/zh_TW/generic.php b/publishable/lang/zh_TW/generic.php
index <HASH>..<HASH> 100644
--- a/publishable/lang/zh_TW/generic.php
+++ b/publishable/lang/zh_TW/generic.php
@@ -32,7 +32,7 @@ return [
'delete_this_confirm' => '是的,我要刪除!',
'deselect_all' => '反選全部',
'download' => '下載',
- 'drag_drop_info' => 'Drag and drop the Items below to re-arrange them.',
+ 'drag_drop_info' => '拖曳下方的項目以重新放置它們',
'edit' => '編輯',
'email' => '電子郵件',
'error_deleting' => '抱歉,在刪除過程中出現了問題',
@@ -47,7 +47,7 @@ return [
'key' => '鍵',
'last_modified' => '最近一次更改',
'length' => '長度',
- 'locale' => 'Locale',
+ 'locale' => '本地化',
'login' => '登錄',
'media' => '媒體',
'menu_builder' => '菜單生成器',
@@ -58,7 +58,7 @@ return [
'no_thanks' => '不,謝謝',
'none' => '無',
'not_null' => '非空',
- 'no_results' => 'No results',
+ 'no_results' => '沒有結果',
'options' => '選項',
'password' => '密碼',
'permissions' => '權限',
|
Translated 2 files for chinese (#<I>)
Translated 2 files for chinese
|
the-control-group_voyager
|
train
|
6ce188f6a6f7ba93fb4da9d8c3eebbfce070c481
|
diff --git a/lib/tf-idf-similarity/collection.rb b/lib/tf-idf-similarity/collection.rb
index <HASH>..<HASH> 100644
--- a/lib/tf-idf-similarity/collection.rb
+++ b/lib/tf-idf-similarity/collection.rb
@@ -156,12 +156,12 @@ class TfIdfSimilarity::Collection
NMatrix.refer matrix / NMath.sqrt((matrix ** 2).sum(1).reshape(documents.size, 1))
elsif nmatrix?
# @see https://github.com/SciRuby/nmatrix/issues/38
- # Is matrix.slice by reference, or do we need to rebuild the matrix?
- # (0...matrix.shape[0]).each do |i|
- # column = matrix.slice i, 0...matrix.shape[1]
- # norm = Math.sqrt(column.dot(column.transpose)[0,0])
- # column /= norm
- # end
+ (0...matrix.shape[1]).each do |j|
+ # @see https://github.com/SciRuby/nmatrix/pull/46
+ column = matrix.slice 0...matrix.shape[0], j
+ norm = Math.sqrt(column.transpose.dot(column)[0, 0])
+ # @todo update matrix
+ end
matrix.cast :yale, :float64
else
Matrix.columns matrix.column_vectors.map(&:normalize)
|
make some progress on NMatrix support
|
jpmckinney_tf-idf-similarity
|
train
|
c1cfa5ff41df9b380fbd8ce14b042183cb1204b6
|
diff --git a/Model/Page.php b/Model/Page.php
index <HASH>..<HASH> 100755
--- a/Model/Page.php
+++ b/Model/Page.php
@@ -705,7 +705,7 @@ abstract class Page implements PageInterface
*/
public function isHybrid()
{
- return $this->getRouteName() != self::PAGE_ROUTE_CMS_NAME && !$this->isInternal();
+ return $this->getRouteName() != self::PAGE_ROUTE_CMS_NAME && !$this->isInternal();
}
/**
diff --git a/Template/Matrix/Parser.php b/Template/Matrix/Parser.php
index <HASH>..<HASH> 100644
--- a/Template/Matrix/Parser.php
+++ b/Template/Matrix/Parser.php
@@ -72,10 +72,10 @@ class Parser
$area['x'] = $area['x'] / $colCount * 100;
$area['y'] = $area['y'] / $rowCount * 100;
- $area['width'] = $area['width'] / $colCount * 100;
+ $area['width'] = $area['width'] / $colCount * 100;
$area['height'] = $area['height'] / $rowCount * 100;
- $area['right'] = 100 - ($area['width'] + $area['x']);
+ $area['right'] = 100 - ($area['width'] + $area['x']);
$area['bottom'] = 100 - ($area['height'] + $area['y']);
}
|
Applied fixes from StyleCI (#<I>)
|
sonata-project_SonataPageBundle
|
train
|
f75e397492604060720d5138045701501ab19516
|
diff --git a/green/config.py b/green/config.py
index <HASH>..<HASH> 100644
--- a/green/config.py
+++ b/green/config.py
@@ -12,15 +12,55 @@ of the last place the setting is seen. So, for example, if a setting is turned
on in ~/.green and turned off by a command-line argument, then the setting will
be turned off.
"""
-try: # pragma: no cover
+try: # pragma: no cover
import configparser
-except: # pragma: no cover
+except: # pragma: no cover
import ConfigParser as configparser
-import copy # pragma: no cover
-import os # pragma: no cover
+import copy # pragma: no cover
+import os # pragma: no cover
+
+# Used for debugging output in cmdline, since we can't do debug output here.
+files_loaded = [] # pragma: no cover
+
+
+
+class ConfigFile(object): # pragma: no cover
+ """
+ Filehandle wrapper that adds a "[green]" section to the start of a config
+ file so that users don't actually have to manually add a [green] section.
+
+ Works with configparser versions from both Python 2 and 3
+ """
+
+
+ def __init__(self, filepath):
+ self.first = True
+ self.lines = open(filepath).readlines()
+
+
+ # Python 2
+ def readline(self):
+ try:
+ return self.__next__()
+ except StopIteration:
+ return ''
+
+
+ # Python 3
+ def __iter__(self):
+ return self
+
+
+ def __next__(self):
+ if self.first:
+ self.first = False
+ return "[green]\n"
+ if self.lines:
+ return self.lines.pop(0)
+ raise StopIteration
+
-files_loaded = []
# Since this must be imported before coverage is started, we get erroneous
# reports of not covering this function during our internal coverage tests.
@@ -56,7 +96,11 @@ def get_config(filepath=None): # pragma: no cover
if filepaths:
global files_loaded
files_loaded = filepaths
- parser.read(filepaths)
+ # Python 3 has parser.read_file(iterator) while Python2 has
+ # parser.readfp(obj_with_readline)
+ read_func = getattr(parser, 'read_file', getattr(parser, 'readfp'))
+ for filepath in filepaths:
+ read_func(ConfigFile(filepath))
return parser
diff --git a/green/test/test_config.py b/green/test/test_config.py
index <HASH>..<HASH> 100644
--- a/green/test/test_config.py
+++ b/green/test/test_config.py
@@ -64,7 +64,6 @@ class ConfigBase(unittest.TestCase):
self.default_version = False
self._write_file(self.default_filename,
["# this is a test config file for green",
- "[green]",
"logging = {}".format(str(self.default_logging)),
"version = {}".format(str(self.default_version)),
"omit = {}".format(self.default_filename),
@@ -74,7 +73,6 @@ class ConfigBase(unittest.TestCase):
self.env_html = False
self._write_file(self.env_filename,
["# this is a test config file for green",
- "[green]",
"logging = {}".format(str(self.env_logging)),
"omit = {}".format(self.env_filename),
"html = {}".format(self.env_html),
@@ -84,7 +82,6 @@ class ConfigBase(unittest.TestCase):
self.cmd_run_coverage = False
self._write_file(self.cmd_filename,
["# this is a test config file for green",
- "[green]",
"logging = {}".format(str(self.cmd_logging)),
"omit = {}".format(self.cmd_filename),
"run-coverage = {}".format(self.cmd_run_coverage),
|
Wrapped the config files so that they automatically have a '[green]' section so users don't actually have to add a section header.
|
CleanCut_green
|
train
|
67dab5f3abac1d9f9db03611dd08de94c8802a79
|
diff --git a/lib/reek/smells/boolean_parameter.rb b/lib/reek/smells/boolean_parameter.rb
index <HASH>..<HASH> 100644
--- a/lib/reek/smells/boolean_parameter.rb
+++ b/lib/reek/smells/boolean_parameter.rb
@@ -28,9 +28,10 @@ module Reek
method_ctx.parameters.default_assignments.select do |param, value|
[:true, :false].include?(value[0])
end.map do |param, value|
+ param_name = param.to_s
SmellWarning.new(SMELL_CLASS, method_ctx.full_name, [method_ctx.exp.line],
- "has boolean parameter '#{param.to_s}'",
- @source, SMELL_SUBCLASS, {PARAMETER_KEY => param.to_s})
+ "has boolean parameter '#{param_name}'",
+ @source, SMELL_SUBCLASS, {PARAMETER_KEY => param_name})
end
end
end
diff --git a/lib/reek/smells/unused_parameters.rb b/lib/reek/smells/unused_parameters.rb
index <HASH>..<HASH> 100644
--- a/lib/reek/smells/unused_parameters.rb
+++ b/lib/reek/smells/unused_parameters.rb
@@ -66,14 +66,15 @@ module Reek
end
def smell_warning(method_ctx, param)
+ param_name = param.to_s
SmellWarning.new(
SMELL_CLASS,
method_ctx.full_name,
[ method_ctx.exp.line ],
- "has unused parameter '#{param.to_s}'",
+ "has unused parameter '#{param_name}'",
@source,
SMELL_SUBCLASS,
- { PARAMETER_KEY => param.to_s }
+ { PARAMETER_KEY => param_name }
)
end
|
Avoid duplicate method calls
In support of #<I>, here's a little fix to take
a couple of things off that warning count!
|
troessner_reek
|
train
|
70b5b48c3e32c4f141198e9f8d0962aca8195aab
|
diff --git a/grade/report/outcomes/index.php b/grade/report/outcomes/index.php
index <HASH>..<HASH> 100644
--- a/grade/report/outcomes/index.php
+++ b/grade/report/outcomes/index.php
@@ -108,7 +108,7 @@ foreach ($report_info as $outcomeid => $outcomedata) {
if ($item->itemtype == 'mod') {
$cm = get_coursemodule_from_instance($item->itemmodule, $item->iteminstance, $item->courseid);
- $itemname = '<a href="'.$CFG->wwwroot.'/mod/'.$item->itemmodule.'/view.php?id='.$cm->id.'">'.$grade_item->get_name().'</a>';
+ $itemname = '<a href="'.$CFG->wwwroot.'/mod/'.$item->itemmodule.'/view.php?id='.$cm->id.'">'.format_string($cm->name, true, $cm->course).'</a>';
} else {
$itemname = $grade_item->get_name();
}
|
MDL-<I> Outcomes report display the name of the activity instead of the name of the outcome
Merged from <I>
|
moodle_moodle
|
train
|
707b97a04b1650c9d315bfa81a2027c98a247480
|
diff --git a/openquake/engine/calculators/risk/classical/core.py b/openquake/engine/calculators/risk/classical/core.py
index <HASH>..<HASH> 100644
--- a/openquake/engine/calculators/risk/classical/core.py
+++ b/openquake/engine/calculators/risk/classical/core.py
@@ -109,6 +109,13 @@ def save_individual_outputs(containers, outs, params):
(outs.loss_curves, outs.average_losses),
output_type="loss_curve")
+ if outs.insured_curves is not None:
+ containers.write(
+ outs.assets,
+ (outs.insured_curves, outs.average_insured_losses),
+ insured=True,
+ output_type="loss_curve")
+
containers.write_all(
"poe", params.conditional_loss_poes,
outs.loss_maps,
@@ -175,6 +182,21 @@ def save_statistical_output(containers, stats, params):
statistics="quantile", quantile=quantile,
variable="taxonomy")
+ # mean and quantile insured curves
+ if stats.mean_insured_curves is not None:
+ containers.write(
+ stats.assets, (stats.mean_insured_curves,
+ stats.mean_average_insured_losses),
+ output_type="loss_curve", statistics="mean", insured=True)
+
+ containers.write_all(
+ "quantile", params.quantiles,
+ [(c, a) for c, a in itertools.izip(
+ stats.quantile_insured_curves,
+ stats.quantile_average_insured_losses)],
+ stats.assets,
+ output_type="loss_curve", statistics="quantile", insured=True)
+
class ClassicalRiskCalculator(base.RiskCalculator):
"""
diff --git a/openquake/engine/calculators/risk/event_based/core.py b/openquake/engine/calculators/risk/event_based/core.py
index <HASH>..<HASH> 100644
--- a/openquake/engine/calculators/risk/event_based/core.py
+++ b/openquake/engine/calculators/risk/event_based/core.py
@@ -202,6 +202,21 @@ def save_statistical_output(containers, stats, params):
stats.assets, output_type="loss_map",
statistics="quantile", quantile=quantile)
+ # mean and quantile insured curves
+ if stats.mean_insured_curves is not None:
+ containers.write(
+ stats.assets, (stats.mean_insured_curves,
+ stats.mean_average_insured_losses),
+ output_type="loss_curve", statistics="mean", insured=True)
+
+ containers.write_all(
+ "quantile", params.quantiles,
+ [(c, a) for c, a in itertools.izip(
+ stats.quantile_insured_curves,
+ stats.quantile_average_insured_losses)],
+ stats.assets,
+ output_type="loss_curve", statistics="quantile", insured=True)
+
class DisaggregationOutputs(object):
def __init__(self, assets_disagg, magnitude_distance,
diff --git a/openquake/engine/calculators/risk/writers.py b/openquake/engine/calculators/risk/writers.py
index <HASH>..<HASH> 100644
--- a/openquake/engine/calculators/risk/writers.py
+++ b/openquake/engine/calculators/risk/writers.py
@@ -455,18 +455,41 @@ class LossCurveMapBuilder(OutputBuilder):
output_type='loss_curve'),
statistics='mean', loss_type=loss_type)]
+ if loss_type != "fatalities" and self.calc.rc.insured_losses:
+ mean_insured_loss_curve = [models.LossCurve.objects.create(
+ output=models.Output.objects.create_output(
+ job=self.calc.job,
+ display_name='mean insured curves. type=%s' % loss_type,
+ output_type='loss_curve'),
+ statistics='mean', insured=True, loss_type=loss_type)]
+ else:
+ mean_insured_loss_curve = []
+
quantile_loss_curves = []
+ quantile_insured_loss_curves = []
for quantile in self.calc.rc.quantile_loss_curves or []:
- name = 'quantile(%s) loss curves. type=%s' % (
- quantile, loss_type)
quantile_loss_curves.append(models.LossCurve.objects.create(
output=models.Output.objects.create_output(
job=self.calc.job,
- display_name=name,
+ display_name='quantile(%s) curves. type=%s' % (
+ quantile, loss_type),
output_type='loss_curve'),
statistics='quantile',
quantile=quantile,
loss_type=loss_type))
+ if loss_type != "fatalities" and self.calc.rc.insured_losses:
+ quantile_insured_loss_curves.append(
+ models.LossCurve.objects.create(
+ output=models.Output.objects.create_output(
+ job=self.calc.job,
+ display_name=(
+ 'quantile(%s) insured curves. type=%s' % (
+ quantile, loss_type)),
+ output_type='loss_curve'),
+ statistics='quantile',
+ insured=True,
+ quantile=quantile,
+ loss_type=loss_type))
mean_loss_maps = []
for poe in self.calc.rc.conditional_loss_poes or []:
@@ -496,7 +519,8 @@ class LossCurveMapBuilder(OutputBuilder):
poe=poe))
return (mean_loss_curve + quantile_loss_curves +
- mean_loss_maps + quantile_loss_maps)
+ mean_loss_maps + quantile_loss_maps +
+ mean_insured_loss_curve + quantile_insured_loss_curves)
class EventLossCurveMapBuilder(LossCurveMapBuilder):
|
first pass. implemented mean/quantile insured curves
Former-commit-id: a7d1e3bcd2b1fe6eb5d<I>d<I>c7abd<I>a1b0a6
|
gem_oq-engine
|
train
|
d6a253c2bd5dd15ca014eaaae182d758cca1c5a6
|
diff --git a/lib/vaulted_billing/gateway.rb b/lib/vaulted_billing/gateway.rb
index <HASH>..<HASH> 100644
--- a/lib/vaulted_billing/gateway.rb
+++ b/lib/vaulted_billing/gateway.rb
@@ -34,15 +34,15 @@ module VaultedBilling
raise NotImplementedError
end
- def authorize(customer, credit_card, amount)
+ def authorize(customer, credit_card, amount, options = {})
raise NotImplementedError
end
- def capture(transaction_id, amount)
+ def capture(transaction_id, amount, options = {})
raise NotImplementedError
end
- def purchase(customer, credit_card, amount)
+ def purchase(customer, credit_card, amount, options = {})
raise NotImplementedError
end
@@ -50,7 +50,7 @@ module VaultedBilling
raise NotImplementedError
end
- def void(transaction_id)
+ def void(transaction_id, options = {})
raise NotImplementedError
end
diff --git a/lib/vaulted_billing/gateways/authorize_net_cim.rb b/lib/vaulted_billing/gateways/authorize_net_cim.rb
index <HASH>..<HASH> 100644
--- a/lib/vaulted_billing/gateways/authorize_net_cim.rb
+++ b/lib/vaulted_billing/gateways/authorize_net_cim.rb
@@ -102,7 +102,7 @@ module VaultedBilling
respond_with(credit_card, result, :success => result.success?)
end
- def purchase(customer, credit_card, amount)
+ def purchase(customer, credit_card, amount, options = {})
customer = customer.to_vaulted_billing
credit_card = credit_card.to_vaulted_billing
data = build_request('createCustomerProfileTransactionRequest') { |xml|
@@ -120,7 +120,7 @@ module VaultedBilling
respond_with(new_transaction_from_response(result.body), result, :success => result.success?)
end
- def authorize(customer, credit_card, amount)
+ def authorize(customer, credit_card, amount, options = {})
customer = customer.to_vaulted_billing
credit_card = credit_card.to_vaulted_billing
data = build_request('createCustomerProfileTransactionRequest') { |xml|
@@ -138,7 +138,7 @@ module VaultedBilling
respond_with(new_transaction_from_response(result.body), result, :success => result.success?)
end
- def capture(transaction_id, amount)
+ def capture(transaction_id, amount, options = {})
data = build_request('createCustomerProfileTransactionRequest') { |xml|
xml.transaction do
xml.profileTransPriorAuthCapture do
@@ -171,7 +171,7 @@ module VaultedBilling
respond_with(new_transaction_from_response(result.body), result, :success => result.success?)
end
- def void(transaction_id)
+ def void(transaction_id, options = {})
data = build_request('createCustomerProfileTransactionRequest') { |xml|
xml.transaction do
xml.profileTransVoid do
diff --git a/lib/vaulted_billing/gateways/ipcommerce.rb b/lib/vaulted_billing/gateways/ipcommerce.rb
index <HASH>..<HASH> 100644
--- a/lib/vaulted_billing/gateways/ipcommerce.rb
+++ b/lib/vaulted_billing/gateways/ipcommerce.rb
@@ -145,7 +145,6 @@ module VaultedBilling
:success => (transaction.code == 1))
end
-
def capture(transaction_id, amount, options = {})
data = {
:"__type" => "Capture:http://schemas.ipcommerce.com/CWS/v2.0/Transactions/Rest",
@@ -272,6 +271,9 @@ module VaultedBilling
end
+ private
+
+
##
# Returns the name of the card company based on the given number, or
# nil if it is unrecognized.
@@ -284,8 +286,7 @@ module VaultedBilling
end
return 1
end
-
- private
+
def generate_order_number
(Time.now.to_f * 100000).to_i.to_s(36) + rand(60000000).to_s(36)
@@ -368,4 +369,4 @@ module VaultedBilling
end
end
end
-end
+end
\ No newline at end of file
diff --git a/lib/vaulted_billing/gateways/nmi_customer_vault.rb b/lib/vaulted_billing/gateways/nmi_customer_vault.rb
index <HASH>..<HASH> 100644
--- a/lib/vaulted_billing/gateways/nmi_customer_vault.rb
+++ b/lib/vaulted_billing/gateways/nmi_customer_vault.rb
@@ -75,7 +75,7 @@ module VaultedBilling
respond_with(credit_card, response, :success => response.success?)
end
- def purchase(customer, credit_card, amount)
+ def purchase(customer, credit_card, amount, options = {})
data = transaction_data('sale', {
:customer_vault_id => credit_card.to_vaulted_billing.vault_id,
:amount => amount
@@ -86,7 +86,7 @@ module VaultedBilling
:success => response.success?)
end
- def authorize(customer, credit_card, amount)
+ def authorize(customer, credit_card, amount, options = {})
data = transaction_data('auth', {
:customer_vault_id => credit_card.to_vaulted_billing.vault_id,
:amount => amount
@@ -97,7 +97,7 @@ module VaultedBilling
:success => response.success?)
end
- def capture(transaction_id, amount)
+ def capture(transaction_id, amount, options = {})
data = transaction_data('capture', {
:transactionid => transaction_id,
:amount => amount
@@ -119,7 +119,7 @@ module VaultedBilling
:success => response.success?)
end
- def void(transaction_id)
+ def void(transaction_id, options = {})
data = transaction_data('void', {
:transactionid => transaction_id
})
|
Match transaction method fingerprints across gateways
|
envylabs_vaulted_billing
|
train
|
e269bc8adabc9cb0374b3a9565da7b1c5f3e49ab
|
diff --git a/tensorflow_datasets/scripts/download_and_prepare.py b/tensorflow_datasets/scripts/download_and_prepare.py
index <HASH>..<HASH> 100644
--- a/tensorflow_datasets/scripts/download_and_prepare.py
+++ b/tensorflow_datasets/scripts/download_and_prepare.py
@@ -136,6 +136,7 @@ def main(_):
raise ValueError(
"--builder_config_id can only be used with datasets with configs")
config = builder.BUILDER_CONFIGS[FLAGS.builder_config_id]
+ logging.info("Running download_and_prepare for config: %s", config.name)
builder_for_config = tfds.builder(
builder.name, data_dir=FLAGS.data_dir, config=config)
download_and_prepare(builder_for_config)
|
tfds download_and_prepare: log config being used.
PiperOrigin-RevId: <I>
|
tensorflow_datasets
|
train
|
4f2d3d783a37ea2fffc988c42e8c67e36a6bfeef
|
diff --git a/tests/utils/test_preprocess.py b/tests/utils/test_preprocess.py
index <HASH>..<HASH> 100644
--- a/tests/utils/test_preprocess.py
+++ b/tests/utils/test_preprocess.py
@@ -175,8 +175,9 @@ class PreprocessTestCase(TestCase):
foo(not_int(1), 2, 3)
self.assertEqual(
e.exception.args[0],
- "tests.utils.test_preprocess.foo() expected a value of type "
+ "{modname}.foo() expected a value of type "
"int for argument 'a', but got {t} instead.".format(
+ modname=foo.__module__,
t=not_int.__name__,
)
)
@@ -197,9 +198,9 @@ class PreprocessTestCase(TestCase):
foo('1')
expected_message = (
- "tests.utils.test_preprocess.foo() expected a value of "
+ "{modname}.foo() expected a value of "
"type int or float for argument 'a', but got str instead."
- )
+ ).format(modname=foo.__module__)
self.assertEqual(e.exception.args[0], expected_message)
def test_expect_optional_types(self):
@@ -219,7 +220,7 @@ class PreprocessTestCase(TestCase):
foo('1')
expected_message = (
- "tests.utils.test_preprocess.foo() expected a value of "
+ "{modname}.foo() expected a value of "
"type int or NoneType for argument 'a', but got str instead."
- )
+ ).format(modname=foo.__module__)
self.assertEqual(e.exception.args[0], expected_message)
|
TEST: Template in module name.
Fixes failures when tests are invoked from different paths.
|
quantopian_zipline
|
train
|
97d96cb3b7feaf22ce9b813313cd8ae20b3589b9
|
diff --git a/fasthttpadaptor/adaptor.go b/fasthttpadaptor/adaptor.go
index <HASH>..<HASH> 100644
--- a/fasthttpadaptor/adaptor.go
+++ b/fasthttpadaptor/adaptor.go
@@ -62,7 +62,14 @@ func NewFastHTTPHandler(h http.Handler) fasthttp.RequestHandler {
hdr := make(http.Header)
ctx.Request.Header.VisitAll(func(k, v []byte) {
- hdr.Set(string(k), string(v))
+ sk := string(k)
+ sv := string(v)
+ switch sk {
+ case "Transfer-Encoding":
+ r.TransferEncoding = append(r.TransferEncoding, sv)
+ default:
+ hdr.Set(sk, sv)
+ }
})
r.Header = hdr
r.Body = &netHTTPBody{body}
diff --git a/fasthttpadaptor/adaptor_test.go b/fasthttpadaptor/adaptor_test.go
index <HASH>..<HASH> 100644
--- a/fasthttpadaptor/adaptor_test.go
+++ b/fasthttpadaptor/adaptor_test.go
@@ -20,6 +20,7 @@ func TestNewFastHTTPHandler(t *testing.T) {
expectedRequestURI := "/foo/bar?baz=123"
expectedBody := "body 123 foo bar baz"
expectedContentLength := len(expectedBody)
+ expectedTransferEncoding := "encoding"
expectedHost := "foobar.com"
expectedRemoteAddr := "1.2.3.4:6789"
expectedHeader := map[string]string{
@@ -53,6 +54,9 @@ func TestNewFastHTTPHandler(t *testing.T) {
if r.ContentLength != int64(expectedContentLength) {
t.Fatalf("unexpected contentLength %d. Expecting %d", r.ContentLength, expectedContentLength)
}
+ if len(r.TransferEncoding) != 1 || r.TransferEncoding[0] != expectedTransferEncoding {
+ t.Fatalf("unexpected transferEncoding %d. Expecting %d", r.TransferEncoding, expectedTransferEncoding)
+ }
if r.Host != expectedHost {
t.Fatalf("unexpected host %q. Expecting %q", r.Host, expectedHost)
}
@@ -91,6 +95,7 @@ func TestNewFastHTTPHandler(t *testing.T) {
req.Header.SetMethod(expectedMethod)
req.SetRequestURI(expectedRequestURI)
req.Header.SetHost(expectedHost)
+ req.Header.Add("Transfer-Encoding", expectedTransferEncoding)
req.BodyWriter().Write([]byte(expectedBody))
for k, v := range expectedHeader {
req.Header.Set(k, v)
|
Handle TransferEncoding in fasthttpadaptor (#<I>)
When incoming http.Request is constructed, "Transfer-Encoding" header
is removed, and http.Request.TransferEncoding is set instead.
This behaviour is now emulated in fasthttpadaptor.
|
valyala_fasthttp
|
train
|
436b662a71d21264a0fd66234d486e8e88f8c02f
|
diff --git a/packages/core/src/api/index.js b/packages/core/src/api/index.js
index <HASH>..<HASH> 100644
--- a/packages/core/src/api/index.js
+++ b/packages/core/src/api/index.js
@@ -10,16 +10,22 @@ const decode = text => new Buffer(text, "base64").toString();
const connect = (list, limit, previousList = []) => {
const hasNextPage = limit === undefined ? false : list.length >= limit;
const hasPreviousPage = previousList.length > 0;
+ const previousPageIsFirst = limit ? previousList.length <= limit : undefined;
+ // we are retrieving limit + 1 to know if there is more page or not
+ // so when getting the previous item, we need to check if we want the last
+ // item or the one before (since we added one to the limit)
+ const previousIndex = previousList.length - 1 - (previousPageIsFirst ? 0 : 1);
+ const nextIndex = list.length - 1;
return {
hasPreviousPage,
- previousPageIsFirst: limit ? previousList.length <= limit : null,
- previous: hasPreviousPage && previousList[previousList.length - 2]
- ? encode(previousList[previousList.length - 2].key)
- : null,
+ previousPageIsFirst,
+ previous: hasPreviousPage && previousList[previousIndex]
+ ? encode(previousList[previousIndex].key)
+ : undefined,
hasNextPage,
- next: hasNextPage && list[list.length - 1]
- ? encode(list[list.length - 1].key)
- : null,
+ next: hasNextPage && list[nextIndex]
+ ? encode(list[nextIndex].key)
+ : undefined,
list: list.slice(0, limit)
};
};
|
Fix pagination previous key
Previously, "previous" key was wrong when you are on the second page. Now "previous" key correctly point to the first element.
|
phenomic_phenomic
|
train
|
60d02fe5940154e3f52bb5dde2d018418c70d135
|
diff --git a/storage_s3/indico_storage_s3/storage.py b/storage_s3/indico_storage_s3/storage.py
index <HASH>..<HASH> 100644
--- a/storage_s3/indico_storage_s3/storage.py
+++ b/storage_s3/indico_storage_s3/storage.py
@@ -7,7 +7,6 @@
import hashlib
import hmac
-import sys
import threading
from base64 import b64encode
from contextlib import contextmanager
@@ -92,8 +91,8 @@ class S3StorageBase(Storage):
try:
s3_object = self.client.get_object(Bucket=bucket, Key=id_)['Body']
return BytesIO(s3_object.read())
- except Exception as e:
- raise None.with_traceback(sys.exc_info()[2])
+ except Exception as exc:
+ raise StorageError(f'Could not open "{file_id}": {exc}') from exc
@contextmanager
def get_local_path(self, file_id):
@@ -125,15 +124,15 @@ class S3StorageBase(Storage):
bucket, id_ = self._parse_file_id(file_id)
try:
self.client.delete_object(Bucket=bucket, Key=id_)
- except Exception as e:
- raise None.with_traceback(sys.exc_info()[2])
+ except Exception as exc:
+ raise StorageError(f'Could not delete "{file_id}": {exc}') from exc
def getsize(self, file_id):
bucket, id_ = self._parse_file_id(file_id)
try:
return self.client.head_object(Bucket=bucket, Key=id_)['ContentLength']
- except Exception as e:
- raise None.with_traceback(sys.exc_info()[2])
+ except Exception as exc:
+ raise StorageError(f'Could not get size of "{file_id}": {exc}') from exc
def send_file(self, file_id, content_type, filename, inline=True):
if self.proxy_downloads == ProxyDownloadsMode.local:
@@ -156,8 +155,8 @@ class S3StorageBase(Storage):
# bucket URL to the end user (since it is quite ugly and temporary)
response.headers['X-Accel-Redirect'] = '/.xsf/s3/' + url.replace('://', '/', 1)
return response
- except Exception as e:
- raise None.with_traceback(sys.exc_info()[2])
+ except Exception as exc:
+ raise StorageError(f'Could not send file "{file_id}": {exc}') from exc
def _create_bucket(self, name):
from indico_storage_s3.plugin import S3StoragePlugin
@@ -207,8 +206,8 @@ class S3Storage(S3StorageBase):
bucket = self._get_current_bucket_name()
checksum = self._save(bucket, name, content_type, fileobj)
return name, checksum
- except Exception as e:
- raise None.with_traceback(sys.exc_info()[2])
+ except Exception as exc:
+ raise StorageError(f'Could not save "{name}": {exc}') from exc
class DynamicS3Storage(S3StorageBase):
@@ -255,8 +254,8 @@ class DynamicS3Storage(S3StorageBase):
checksum = self._save(bucket, name, content_type, fileobj)
file_id = f'{bucket}//{name}'
return file_id, checksum
- except Exception as e:
- raise None.with_traceback(sys.exc_info()[2])
+ except Exception as exc:
+ raise StorageError(f'Could not save "{name}": {exc}') from exc
class ReadOnlyS3Storage(ReadOnlyStorageMixin, S3Storage):
|
Fix modernize/pyupgrade screwup
modernize converted it to six.reraise() and somehow pyupgrade converted
it to `raise None.with_traceback()` afterwards...
|
indico_indico-plugins
|
train
|
7a879ed91ccd6d74f235288d487fd6c406f5b5cc
|
diff --git a/opentracing-api/src/main/java/io/opentracing/tag/ShortTag.java b/opentracing-api/src/main/java/io/opentracing/tag/ShortTag.java
index <HASH>..<HASH> 100644
--- a/opentracing-api/src/main/java/io/opentracing/tag/ShortTag.java
+++ b/opentracing-api/src/main/java/io/opentracing/tag/ShortTag.java
@@ -13,6 +13,10 @@
*/
package io.opentracing.tag;
+/**
+ * @deprecated use {@link IntTag} instead.
+ */
+@Deprecated
public class ShortTag extends AbstractTag<Short> {
public ShortTag(String key) {
super(key);
diff --git a/opentracing-api/src/main/java/io/opentracing/tag/Tags.java b/opentracing-api/src/main/java/io/opentracing/tag/Tags.java
index <HASH>..<HASH> 100644
--- a/opentracing-api/src/main/java/io/opentracing/tag/Tags.java
+++ b/opentracing-api/src/main/java/io/opentracing/tag/Tags.java
@@ -88,7 +88,7 @@ public final class Tags {
/**
* SAMPLING_PRIORITY determines the priority of sampling this Span.
*/
- public static final ShortTag SAMPLING_PRIORITY = new ShortTag("sampling.priority");
+ public static final IntTag SAMPLING_PRIORITY = new IntTag("sampling.priority");
/**
* SPAN_KIND hints at the relationship between spans, e.g. client/server.
|
Define tag SAMPLING_PRIORITY as an integer (#<I>)
* Define tag SAMPLING_PRIORITY as an integer
* Deprecate ShortTag
* ShortTag deprecated javadoc
|
opentracing_opentracing-java
|
train
|
2004698e8b34a67c05a113626a9708ead182a97a
|
diff --git a/pythonforandroid/bootstraps/sdl2/build/src/org/kivy/android/PythonActivity.java b/pythonforandroid/bootstraps/sdl2/build/src/org/kivy/android/PythonActivity.java
index <HASH>..<HASH> 100644
--- a/pythonforandroid/bootstraps/sdl2/build/src/org/kivy/android/PythonActivity.java
+++ b/pythonforandroid/bootstraps/sdl2/build/src/org/kivy/android/PythonActivity.java
@@ -23,6 +23,7 @@ import android.os.PowerManager;
import android.graphics.PixelFormat;
import android.view.SurfaceHolder;
import android.content.Context;
+import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ApplicationInfo;
import android.content.Intent;
@@ -79,12 +80,23 @@ public class PythonActivity extends SDLActivity {
//
// Otherwise, we use the public data, if we have it, or the
// private data if we do not.
+ String app_root_dir = getAppRoot();
if (getIntent() != null && getIntent().getAction() != null &&
getIntent().getAction().equals("org.kivy.LAUNCH")) {
File path = new File(getIntent().getData().getSchemeSpecificPart());
Project p = Project.scanDirectory(path);
SDLActivity.nativeSetEnv("ANDROID_ENTRYPOINT", p.dir + "/main.py");
+ SDLActivity.nativeSetEnv("ANDROID_ARGUMENT", p.dir);
+ SDLActivity.nativeSetEnv("ANDROID_APP_PATH", p.dir);
+
+ if (p != null) {
+ if (p.landscape) {
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+ } else {
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ }
+ }
// Let old apps know they started.
try {
@@ -96,14 +108,13 @@ public class PythonActivity extends SDLActivity {
}
} else {
SDLActivity.nativeSetEnv("ANDROID_ENTRYPOINT", "main.pyo");
+ SDLActivity.nativeSetEnv("ANDROID_ARGUMENT", app_root_dir);
+ SDLActivity.nativeSetEnv("ANDROID_APP_PATH", app_root_dir);
}
- String app_root_dir = getAppRoot();
String mFilesDirectory = mActivity.getFilesDir().getAbsolutePath();
Log.v(TAG, "Setting env vars for start.c and Python to use");
SDLActivity.nativeSetEnv("ANDROID_PRIVATE", mFilesDirectory);
- SDLActivity.nativeSetEnv("ANDROID_ARGUMENT", app_root_dir);
- SDLActivity.nativeSetEnv("ANDROID_APP_PATH", app_root_dir);
SDLActivity.nativeSetEnv("PYTHONHOME", app_root_dir);
SDLActivity.nativeSetEnv("PYTHONPATH", app_root_dir + ":" + app_root_dir + "/lib");
SDLActivity.nativeSetEnv("PYTHONOPTIMIZE", "2");
diff --git a/pythonforandroid/recipes/python2/patches/custom-loader.patch b/pythonforandroid/recipes/python2/patches/custom-loader.patch
index <HASH>..<HASH> 100644
--- a/pythonforandroid/recipes/python2/patches/custom-loader.patch
+++ b/pythonforandroid/recipes/python2/patches/custom-loader.patch
@@ -17,8 +17,8 @@
+
+ /* Ensure we have access to libpymodules. */
+ if (libpymodules == -1) {
-+ printf("ANDROID_APP_PATH = %s\n", getenv("ANDROID_APP_PATH"));
-+ PyOS_snprintf(pathbuf, sizeof(pathbuf), "%s/libpymodules.so", getenv("ANDROID_APP_PATH"));
++ printf("ANDROID_PRIVATE = %s\n", getenv("ANDROID_PRIVATE"));
++ PyOS_snprintf(pathbuf, sizeof(pathbuf), "%s/app/libpymodules.so", getenv("ANDROID_PRIVATE"));
+ libpymodules = dlopen(pathbuf, RTLD_NOW);
+
+ if (libpymodules == NULL) {
diff --git a/testapps/testlauncher_setup/sdl2.py b/testapps/testlauncher_setup/sdl2.py
index <HASH>..<HASH> 100644
--- a/testapps/testlauncher_setup/sdl2.py
+++ b/testapps/testlauncher_setup/sdl2.py
@@ -7,8 +7,8 @@ options = {'apk': {'debug': None,
'requirements': (
'python2,sdl2,android,'
'sqlite3,docutils,pygments,kivy,pyjnius,plyer,'
- 'cymunk,lxml,pil,' # audiostream, ffmpeg, openssl,
- 'twisted,numpy'), # pyopenssl
+ 'cymunk,lxml,pil,openssl,pyopenssl,'
+ 'twisted'), # audiostream, ffmpeg, numpy
'android-api': 14,
'dist-name': 'launchertest_sdl2',
'name': 'TestLauncher-sdl2',
|
Fix orientation and app path
basically creating .kivy folder(logs), fetching files with paths relative to main.py and so on. ANDROID_APP_PATH has to be the folder of main.py file.
|
kivy_python-for-android
|
train
|
8f0731d51761f98422dd44bd39e10c34c91db52d
|
diff --git a/bootstrap.php b/bootstrap.php
index <HASH>..<HASH> 100644
--- a/bootstrap.php
+++ b/bootstrap.php
@@ -8,7 +8,6 @@
* For the full copyright and license information, please view the MIT license
*/
-
namespace Davis\SocialProfile;
use Illuminate\Contracts\Events\Dispatcher;
diff --git a/migrations/2016_01_14_000000_create_socialbuttons_table.php b/migrations/2016_01_14_000000_create_socialbuttons_table.php
index <HASH>..<HASH> 100644
--- a/migrations/2016_01_14_000000_create_socialbuttons_table.php
+++ b/migrations/2016_01_14_000000_create_socialbuttons_table.php
@@ -8,7 +8,6 @@
* For the full copyright and license information, please view the MIT license
*/
-
use Flarum\Database\Migration;
use Illuminate\Database\Schema\Blueprint;
diff --git a/migrations/2016_10_20_000000_create_socialbuttons_column.php b/migrations/2016_10_20_000000_create_socialbuttons_column.php
index <HASH>..<HASH> 100644
--- a/migrations/2016_10_20_000000_create_socialbuttons_column.php
+++ b/migrations/2016_10_20_000000_create_socialbuttons_column.php
@@ -8,7 +8,6 @@
* For the full copyright and license information, please view the MIT license
*/
-
use Flarum\Database\Migration;
return Migration::addColumns('users', [
diff --git a/migrations/2016_10_21_000000_migrate_data_to_user_column.php b/migrations/2016_10_21_000000_migrate_data_to_user_column.php
index <HASH>..<HASH> 100644
--- a/migrations/2016_10_21_000000_migrate_data_to_user_column.php
+++ b/migrations/2016_10_21_000000_migrate_data_to_user_column.php
@@ -8,7 +8,6 @@
* For the full copyright and license information, please view the MIT license
*/
-
use Illuminate\Database\ConnectionInterface;
return [
diff --git a/migrations/2016_10_22_000000_drop_socialbuttons_table.php b/migrations/2016_10_22_000000_drop_socialbuttons_table.php
index <HASH>..<HASH> 100644
--- a/migrations/2016_10_22_000000_drop_socialbuttons_table.php
+++ b/migrations/2016_10_22_000000_drop_socialbuttons_table.php
@@ -8,7 +8,6 @@
* For the full copyright and license information, please view the MIT license
*/
-
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;
diff --git a/src/Events/UserButtonsWereChanged.php b/src/Events/UserButtonsWereChanged.php
index <HASH>..<HASH> 100644
--- a/src/Events/UserButtonsWereChanged.php
+++ b/src/Events/UserButtonsWereChanged.php
@@ -8,7 +8,6 @@
* For the full copyright and license information, please view the MIT license
*/
-
namespace Davis\SocialProfile\Events;
use Flarum\Core\User;
|
Apply fixes from StyleCI (#<I>)
|
dav-is_flarum-ext-socialprofile
|
train
|
3d80d5eb9c74c8498101a3b333a7be39512ca6ad
|
diff --git a/tools/ContextGenerator.php b/tools/ContextGenerator.php
index <HASH>..<HASH> 100644
--- a/tools/ContextGenerator.php
+++ b/tools/ContextGenerator.php
@@ -193,7 +193,7 @@ class ContextGenerator
if ($i == 0) {
$ret .= str_repeat(' ', $spaces);
}
- $ret .= "'" . $word . "' => " . $type . ', ';
+ $ret .= sprintf('\'%s\' => %s, ', $word, $type);
if (++$i == $count) {
$ret .= "\n";
$i = 0;
|
Make more readable ContextGenerator.php
|
phpmyadmin_sql-parser
|
train
|
1b34ed2ed6c1d0b56891b5bd9b1850d9d31e1038
|
diff --git a/eth/catalyst/api.go b/eth/catalyst/api.go
index <HASH>..<HASH> 100644
--- a/eth/catalyst/api.go
+++ b/eth/catalyst/api.go
@@ -641,9 +641,9 @@ func (api *ConsensusAPI) heartbeat() {
}
} else {
if lastTransitionUpdate.IsZero() {
- message = "Merge is configured, but no beacon client seen. Please ensure you have one available before the transision arrives!"
+ message = "Merge is configured, but no beacon client seen. Please ensure you have one available before the transition arrives!"
} else {
- message = "Merge is configured, but previously seen beacon client is offline. Please ensure it is operational before the transision arrives!"
+ message = "Merge is configured, but previously seen beacon client is offline. Please ensure it is operational before the transition arrives!"
}
}
if eta == 0 {
|
eth: fix typo in catalyst api (#<I>)
eth: fix typo
|
ethereum_go-ethereum
|
train
|
a5b1e05108ef0817e856bde115b97f30c472b6ee
|
diff --git a/atx/device/__init__.py b/atx/device/__init__.py
index <HASH>..<HASH> 100644
--- a/atx/device/__init__.py
+++ b/atx/device/__init__.py
@@ -65,7 +65,9 @@ class Pattern(object):
if self._resolution is None:
m = re.search(r'\.(\d+)x(\d+)\.png$', self._name)
if m:
- self._resolution = map(int, (m.group(1), m.group(2)))
+ (w, h) = sorted(map(int, (m.group(1), m.group(2))))
+ # TODO(ssx): gcd(w, h), make sure the biggest < 20
+ self._resolution = (w, h)
def __str__(self):
return 'Pattern(name: {}, offset: {})'.format(strutils.encode(self._name), self.offset)
diff --git a/atx/ios/__main__.py b/atx/ios/__main__.py
index <HASH>..<HASH> 100644
--- a/atx/ios/__main__.py
+++ b/atx/ios/__main__.py
@@ -6,6 +6,7 @@ import sys
import inspect
from contextlib import contextmanager
+from PIL import Image
from atx import ioskit
@@ -29,7 +30,11 @@ def load_main(module_name):
def _screencap(args):
dev = ioskit.Device(args.udid)
- dev.screenshot(args.output)
+ image = dev.screenshot()
+ if args.rotate:
+ method = getattr(Image, 'ROTATE_{}'.format(args.rotate))
+ image = image.transpose(method)
+ image.save(args.output)
print 'Screenshot saved to "%s"' % args.output
@@ -49,6 +54,7 @@ def main():
with add_parser('screencap') as p:
p.add_argument('-o', '--output', default='screenshot.png', help='take iPhone screenshot')
+ p.add_argument('-r', '--rotate', type=int, choices=[0, 90, 180, 270], default=0, help='screen rotation')
p.set_defaults(func=_screencap)
args = ap.parse_args()
|
ios screenshot add rotate support
|
NetEaseGame_ATX
|
train
|
2efa11be35641bda5dcab35f176c0f66b25983d0
|
diff --git a/lib/inject.js b/lib/inject.js
index <HASH>..<HASH> 100644
--- a/lib/inject.js
+++ b/lib/inject.js
@@ -6,6 +6,7 @@ const fs = require('fs')
let script = null
, style = null
+ , scriptId = null
module.exports = function(chrome) {
@@ -17,7 +18,7 @@ module.exports = function(chrome) {
Promise.resolve().then(config.js.promise).then(injectJs).catch(log)
})
- init = init.then(config.js.promise).then(injectJs)
+ init = init.then(config.js.promise).then(injectJs).catch(log)
} else {
chrome.send('Page.reload', { ignoreCache: true })
}
@@ -28,7 +29,7 @@ module.exports = function(chrome) {
Promise.resolve().then(config.css.promise).then(injectCss).catch(log)
})
- init.then(config.css.promise).then(injectCss)
+ init.then(config.css.promise).then(injectCss).catch(log)
}
function injectJs(source) {
@@ -40,14 +41,34 @@ module.exports = function(chrome) {
if (err)
return log(err)
+ scriptId = result.identifier
chrome.send('Page.reload', { ignoreCache: true }, () => {
- chrome.once('Debugger.scriptParsed', s => script = s)
+ chrome.on('Debugger.scriptParsed', (s) => {
+ if (!s.isInternalScript)
+ script = s
+ })
setTimeout(resolve, 100)
})
})
return
}
+ chrome.send('Page.removeScriptToEvaluateOnLoad', {
+ identifier: scriptId
+ }, (err, result) => {
+ if (err)
+ return log(err)
+
+ chrome.send('Page.addScriptToEvaluateOnLoad', {
+ scriptSource: source
+ }, (err, result) => {
+ if (err)
+ return log(err)
+
+ scriptId = result.identifier
+ })
+ })
+
chrome.send('Debugger.setScriptSource', {
scriptId: script.scriptId,
scriptSource: source
@@ -72,6 +93,10 @@ module.exports = function(chrome) {
function injectCss(source) {
if (!style) {
+ chrome.once('Page.loadEventFired', (r) => {
+ style = null
+ Promise.resolve().then(config.css.promise).then(injectCss).catch(log)
+ })
chrome.once('CSS.styleSheetAdded', s => style = s.header)
chrome.send('Runtime.evaluate', {
expression: appendStylesheet(source)
|
Ensure state is correct if user refreshes in window
|
porsager_wright
|
train
|
1ff9363d357cc2123b6b1fb1f56127628e0f49f0
|
diff --git a/features/product/viewing_products/viewing_different_price_for_different_product_variants.feature b/features/product/viewing_products/viewing_different_price_for_different_product_variants.feature
index <HASH>..<HASH> 100644
--- a/features/product/viewing_products/viewing_different_price_for_different_product_variants.feature
+++ b/features/product/viewing_products/viewing_different_price_for_different_product_variants.feature
@@ -2,7 +2,7 @@
Feature: Viewing different price for different product variants
In order to see product variant price
As a Visitor
- I want to be able to see proper price for each product variant
+ I want to be able to see a proper price for each product variant
Background:
Given the store operates on a single channel in "United States"
diff --git a/features/product/viewing_products/viewing_different_price_for_different_product_variants_selected_with_options.feature b/features/product/viewing_products/viewing_different_price_for_different_product_variants_selected_with_options.feature
index <HASH>..<HASH> 100644
--- a/features/product/viewing_products/viewing_different_price_for_different_product_variants_selected_with_options.feature
+++ b/features/product/viewing_products/viewing_different_price_for_different_product_variants_selected_with_options.feature
@@ -2,7 +2,7 @@
Feature: Viewing different price for different product variants selected with options
In order to see product variant price
As a Visitor
- I want to be able to see proper price for each product variant
+ I want to be able to see a proper price for each product variant
Background:
Given the store operates on a single channel in "United States"
diff --git a/src/Sylius/Behat/Context/Setup/ProductContext.php b/src/Sylius/Behat/Context/Setup/ProductContext.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Behat/Context/Setup/ProductContext.php
+++ b/src/Sylius/Behat/Context/Setup/ProductContext.php
@@ -188,8 +188,7 @@ final class ProductContext implements Context
$product->setCode($code);
if ($this->sharedStorage->has('channel')) {
- $channel = $this->sharedStorage->get('channel');
- $product->addChannel($channel);
+ $product->addChannel($this->sharedStorage->get('channel'));
}
$this->saveProduct($product);
diff --git a/src/Sylius/Bundle/CoreBundle/Twig/ProductVariantsPricesExtension.php b/src/Sylius/Bundle/CoreBundle/Twig/ProductVariantsPricesExtension.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/CoreBundle/Twig/ProductVariantsPricesExtension.php
+++ b/src/Sylius/Bundle/CoreBundle/Twig/ProductVariantsPricesExtension.php
@@ -12,7 +12,6 @@
namespace Sylius\Bundle\CoreBundle\Twig;
use Sylius\Bundle\CoreBundle\Templating\Helper\ProductVariantsPricesHelper;
-use Sylius\Component\Core\Model\ProductInterface;
/**
* @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
@@ -38,21 +37,11 @@ final class ProductVariantsPricesExtension extends \Twig_Extension
public function getFunctions()
{
return [
- new \Twig_SimpleFunction('sylius_product_variant_prices', [$this, 'getVariantsPrices']),
+ new \Twig_SimpleFunction('sylius_product_variant_prices', [$this->productVariantsPricesHelper, 'getPrices']),
];
}
/**
- * @param ProductInterface $product
- *
- * @return array
- */
- public function getVariantsPrices(ProductInterface $product)
- {
- return $this->productVariantsPricesHelper->getPrices($product);
- }
-
- /**
* {@inheritdoc}
*/
public function getName()
diff --git a/src/Sylius/Bundle/CoreBundle/spec/Twig/ProductVariantsPricesExtensionSpec.php b/src/Sylius/Bundle/CoreBundle/spec/Twig/ProductVariantsPricesExtensionSpec.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/CoreBundle/spec/Twig/ProductVariantsPricesExtensionSpec.php
+++ b/src/Sylius/Bundle/CoreBundle/spec/Twig/ProductVariantsPricesExtensionSpec.php
@@ -39,22 +39,13 @@ final class ProductVariantsPricesExtensionSpec extends ObjectBehavior
$this->shouldHaveType(\Twig_Extension::class);
}
- function it_has_functions()
+ function it_has_functions(ProductVariantsPricesHelper $productVariantsPricesHelper)
{
$this->getFunctions()->shouldHaveFunction(
- new \Twig_SimpleFunction('sylius_product_variant_prices', [$this, 'getVariantsPrices'])
+ new \Twig_SimpleFunction('sylius_product_variant_prices', [$productVariantsPricesHelper, 'getPrices'])
);
}
- function it_uses_helper_to_get_variants_prices(
- ProductInterface $product,
- ProductVariantsPricesHelper $productVariantsPricesHelper
- ) {
- $productVariantsPricesHelper->getPrices($product)->willReturn([['color' => 'purple', 'value' => 12345]]);
-
- $this->getVariantsPrices($product)->shouldReturn([['color' => 'purple', 'value' => 12345]]);
- }
-
function it_has_name()
{
$this->getName()->shouldReturn('sylius_product_variant_prices');
|
[Core][Behat] Small changes in product variant prices display
|
Sylius_Sylius
|
train
|
17485767e43650389e19ea48f207663fda90e415
|
diff --git a/shared/actions/push.js b/shared/actions/push.js
index <HASH>..<HASH> 100644
--- a/shared/actions/push.js
+++ b/shared/actions/push.js
@@ -1,10 +1,7 @@
// @flow
import * as Constants from '../constants/push'
-
import {apiserverPostRpcPromise} from '../constants/types/flow-types'
-
-import {call, put, select} from 'redux-saga/effects'
-import {takeEvery, takeLatest} from 'redux-saga'
+import {call, put, select, takeEvery, takeLatest} from 'redux-saga/effects'
import type {SagaGenerator} from '../constants/types/saga'
import type {TypedState} from '../constants/reducer'
diff --git a/shared/util/saga.js b/shared/util/saga.js
index <HASH>..<HASH> 100644
--- a/shared/util/saga.js
+++ b/shared/util/saga.js
@@ -1,7 +1,7 @@
// @flow
import {mapValues, forEach} from 'lodash'
-import {buffers, channel, takeEvery, takeLatest} from 'redux-saga'
-import {take, call, put} from 'redux-saga/effects'
+import {buffers, channel} from 'redux-saga'
+import {take, call, put, takeEvery, takeLatest} from 'redux-saga/effects'
import {globalError} from '../constants/config'
import {convertToError} from '../util/errors'
|
remove warnings about redux-saga effects (#<I>)
|
keybase_client
|
train
|
454703ed731944edb3bbd2a11ca3a2e404d8b005
|
diff --git a/generators/setup-workspace/index.js b/generators/setup-workspace/index.js
index <HASH>..<HASH> 100644
--- a/generators/setup-workspace/index.js
+++ b/generators/setup-workspace/index.js
@@ -244,7 +244,28 @@ class Generator extends Base {
}
return this._mkdir(this.cwd + '/_backup')
.then(() => Promise.all(data.map((d) => this._downloadBackupFile(d, this.cwd + '/_backup'))))
- .then(this._spawnOrAbort.bind(this, './docker-backup', 'restore'));
+ .then(this._ifExecutable.bind(this, 'docker-compose', this._spawnOrAbort.bind(this, './docker-backup', 'restore'), 'please execute: "./docker-backup restore" manually'));
+ }
+
+ _ifExecutable(cmd, ifExists, extraMessage = '') {
+ const paths = process.env.PATH.split(path.delimiter);
+ const pathExt = (process.env.PATHEXT || '').split(path.delimiter);
+ let found = false;
+ outer: for (const p of paths) {
+ for (const ext of pathExt) {
+ const fullPath = `${p}${path.sep}${cmd}${ext}`;
+ if (fs.existsSync(fullPath)) {
+ this.log(`found ${cmd} at ${fullPath}`);
+ found = true;
+ break outer;
+ }
+ }
+ }
+ if (!found) {
+ this.log(chalk.red(`Error: ${cmd} not found${extraMessage}`));
+ return Promise.resolve(null);
+ }
+ return ifExists();
}
writing() {
@@ -280,12 +301,12 @@ class Generator extends Base {
.then(this._yo.bind(this, 'workspace'))
.then(this._customizeWorkspace.bind(this))
.then(this._downloadDataFiles.bind(this))
- .then(this._spawnOrAbort.bind(this, 'npm', 'install'))
+ //.then(this._spawnOrAbort.bind(this, 'npm', 'install'))
.then(this._downloadBackupFiles.bind(this))
.then(() => {
const l = this.fs.read(this.destinationPath(`${this.cwd}/docker-compose.yml`), {defaults: ''});
if (l.trim().length > 0) {
- return this._spawnOrAbort('docker-compose', 'build');
+ return this._ifExecutable('docker-compose', this._spawnOrAbort.bind(this, 'docker-compose', 'build'), ' please run "docker-compose build" manually"');
}
return null;
})
|
fix #<I> check if docker-compose is there
|
phovea_generator-phovea
|
train
|
edbf9d5cf89805f3d6c4bc7acd40d2b02b2d50b9
|
diff --git a/AnnotationReader.php b/AnnotationReader.php
index <HASH>..<HASH> 100644
--- a/AnnotationReader.php
+++ b/AnnotationReader.php
@@ -211,21 +211,6 @@ final class AnnotationReader implements Reader
$this->parser->setAnnotationNamespaceAlias($namespace, $alias);
}
- public function registerAnnotationNamespace($namespace, $dirs)
- {
- $this->parser->registerAutoloadNamespace($namespace, $dirs);
- }
-
- public function registerAnnotationNamespaces($namespaces)
- {
- $this->parser->registerAutoloadNamespaces($namespaces);
- }
-
- public function registerAnnotationFile($file)
- {
- $this->parser->registerAnnotationFile($file);
- }
-
/**
* Sets a flag whether to auto-load annotation classes or not.
*
|
Forgot to remove this code, which is not needed anymore
|
doctrine_annotations
|
train
|
fa35d635af9487497edf457b07a83a8f36f1ad79
|
diff --git a/tofu/imas2tofu/_def.py b/tofu/imas2tofu/_def.py
index <HASH>..<HASH> 100644
--- a/tofu/imas2tofu/_def.py
+++ b/tofu/imas2tofu/_def.py
@@ -266,7 +266,14 @@ _dshort = {
'1drhopn': {'str': 'profiles_1d[time].grid.rho_pol_norm',
'dim': 'rho', 'quant': 'rhopn', 'units': '-'},
'1dnW': {'str': 'profiles_1d[time].ion[identifier.label=W].density',
- 'dim': 'density', 'quant': 'nI', 'units': 'm^-3'}},
+ 'dim': 'density', 'quant': 'nI', 'units': 'm^-3'},
+ '1dTi_av': {
+ 'str': 'profiles_1d[time].t_i_average',
+ 'units': 'eV',
+ 'dim': 'temperature',
+ 'quant': 'Ti',
+ },
+ },
'edge_profiles': {
't': {'str': 'time', 'units': 's'}},
diff --git a/tofu/version.py b/tofu/version.py
index <HASH>..<HASH> 100644
--- a/tofu/version.py
+++ b/tofu/version.py
@@ -1,2 +1,2 @@
# Do not edit, pipeline versioning governed by git tags!
-__version__ = '1.5.0-230-g9a87be9f'
+__version__ = '1.5.0-231-g7be1717e'
|
[#<I>] core_profiles: added t_i_average (1dTi_av)
|
ToFuProject_tofu
|
train
|
8aec1e05c72d4775e83e24c5817b58c38ab8c472
|
diff --git a/presto-main/src/main/java/com/facebook/presto/byteCode/instruction/Constant.java b/presto-main/src/main/java/com/facebook/presto/byteCode/instruction/Constant.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/byteCode/instruction/Constant.java
+++ b/presto-main/src/main/java/com/facebook/presto/byteCode/instruction/Constant.java
@@ -19,6 +19,7 @@ import com.facebook.presto.byteCode.MethodGenerationContext;
import com.facebook.presto.byteCode.ParameterizedType;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
+import com.google.common.primitives.Primitives;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
@@ -611,7 +612,13 @@ public abstract class Constant
@Override
public void accept(MethodVisitor visitor, MethodGenerationContext generationContext)
{
- visitor.visitLdcInsn(Type.getType(value.getType()));
+ if (value.isPrimitive()) {
+ Class<?> wrapper = Primitives.wrap(value.getPrimitiveType());
+ getStaticInstruction(wrapper, "TYPE", Class.class).accept(visitor, generationContext);
+ }
+ else {
+ visitor.visitLdcInsn(Type.getType(value.getType()));
+ }
}
@Override
diff --git a/presto-main/src/test/java/com/facebook/presto/byteCode/expression/TestConstantByteCodeExpression.java b/presto-main/src/test/java/com/facebook/presto/byteCode/expression/TestConstantByteCodeExpression.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/test/java/com/facebook/presto/byteCode/expression/TestConstantByteCodeExpression.java
+++ b/presto-main/src/test/java/com/facebook/presto/byteCode/expression/TestConstantByteCodeExpression.java
@@ -64,5 +64,15 @@ public class TestConstantByteCodeExpression
assertByteCodeExpression(constantString("foo"), "foo", "\"foo\"");
assertByteCodeExpression(constantClass(List.class), List.class, "List.class");
+
+ assertByteCodeExpression(constantClass(boolean.class), boolean.class, "boolean.class");
+ assertByteCodeExpression(constantClass(byte.class), byte.class, "byte.class");
+ assertByteCodeExpression(constantClass(char.class), char.class, "char.class");
+ assertByteCodeExpression(constantClass(double.class), double.class, "double.class");
+ assertByteCodeExpression(constantClass(float.class), float.class, "float.class");
+ assertByteCodeExpression(constantClass(int.class), int.class, "int.class");
+ assertByteCodeExpression(constantClass(long.class), long.class, "long.class");
+ assertByteCodeExpression(constantClass(short.class), short.class, "short.class");
+ assertByteCodeExpression(constantClass(void.class), void.class, "void.class");
}
}
|
Fix compiling primitive class constants
|
prestodb_presto
|
train
|
3b3162cfd72936ae07f35bbe0b2f10f0a72d1bb3
|
diff --git a/eg/eg_config.py b/eg/eg_config.py
index <HASH>..<HASH> 100644
--- a/eg/eg_config.py
+++ b/eg/eg_config.py
@@ -218,14 +218,12 @@ def get_priority(first, second, third):
present, it will be returned. If only second and third, second will be
returned. If all three are absent, will return None.
"""
- if first:
+ if first is not None:
return first
- elif second:
+ elif second is not None:
return second
- elif third:
- return third
else:
- return None
+ return third
def _inform_if_path_does_not_exist(path):
diff --git a/test/eg_config_test.py b/test/eg_config_test.py
index <HASH>..<HASH> 100644
--- a/test/eg_config_test.py
+++ b/test/eg_config_test.py
@@ -295,3 +295,35 @@ def test_parse_bool_false_for_non_truthy_values():
assert_false(eg_config._parse_bool_from_raw_egrc_value(None))
assert_false(eg_config._parse_bool_from_raw_egrc_value('false'))
assert_false(eg_config._parse_bool_from_raw_egrc_value('False'))
+
+
+def test_get_priority_first():
+ """The first non-None value should always be returned."""
+ target = 'alpha'
+ actual = eg_config.get_priority(target, 'second', 'third')
+ assert_equal(target, actual)
+
+
+def test_get_priority_second():
+ """The second non-None should be returned if the first is None."""
+ target = 'beta'
+ actual = eg_config.get_priority(None, target, 'third')
+ assert_equal(target, actual)
+
+
+def test_get_priority_third():
+ """The last should be taken if the first two are None."""
+ target = 'gamma'
+ actual = eg_config.get_priority(None, None, target)
+ assert_equal(target, actual)
+
+
+def test_get_priority_respect_false():
+ """
+ We should accept False as a priority-worthy value.
+
+ False should be able to be specified and respected as non-None.
+ """
+ target = False
+ actual = eg_config.get_priority(False, 'second', 'third')
+ assert_equal(target, actual)
|
make get_priority respect False
|
srsudar_eg
|
train
|
33f832e208f80b2ea371f2c445c873b126ba4b80
|
diff --git a/tests/tests/kernel/classes/clusterfilehandlers/ezdfsfilehandler_test.php b/tests/tests/kernel/classes/clusterfilehandlers/ezdfsfilehandler_test.php
index <HASH>..<HASH> 100644
--- a/tests/tests/kernel/classes/clusterfilehandlers/ezdfsfilehandler_test.php
+++ b/tests/tests/kernel/classes/clusterfilehandlers/ezdfsfilehandler_test.php
@@ -33,6 +33,8 @@ class eZDFSFileHandlerTest extends ezpDatabaseTestCase
**/
protected $sqlFiles = array( 'tests/tests/kernel/classes/clusterfilehandlers/sql/cluster_dfs_schema.sql' );
+ protected $previousFileHandler;
+
public function __construct()
{
parent::__construct();
@@ -49,20 +51,21 @@ class eZDFSFileHandlerTest extends ezpDatabaseTestCase
{
parent::setUp();
- // We need to clear the existing handler if it was loaded before the INI
- // settings changes
- if ( isset( $GLOBALS['eZClusterFileHandler_chosen_handler'] ) and
- !$GLOBALS['eZClusterFileHandler_chosen_handler'] instanceof eZDFSFileHandler )
- unset( $GLOBALS['eZClusterFileHandler_chosen_handler'] );
-
if ( !( $this->sharedFixture instanceof eZMySQLDB ) )
{
self::markTestSkipped( "Not using mysql interface, skipping" );
}
+ // We need to clear the existing handler if it was loaded before the INI
+ // settings changes
+ if ( isset( $GLOBALS['eZClusterFileHandler_chosen_handler'] ) and
+ !$GLOBALS['eZClusterFileHandler_chosen_handler'] instanceof eZDFSFileHandler )
+ unset( $GLOBALS['eZClusterFileHandler_chosen_handler'] );
+
// Load database parameters for cluster
// The same DSN than the relational database is used
$fileINI = eZINI::instance( 'file.ini' );
+ $this->previousFileHandler = $fileINI->variable( 'ClusteringSettings', 'FileHandler', 'eZDFSFileHandler' );
$fileINI->setVariable( 'ClusteringSettings', 'FileHandler', 'eZDFSFileHandler' );
$dsn = ezpTestRunner::dsn()->parts;
@@ -87,6 +90,13 @@ class eZDFSFileHandlerTest extends ezpDatabaseTestCase
public function tearDown()
{
+ // restore the previous file handler
+ $fileINI = eZINI::instance( 'file.ini' );
+ $fileINI->setVariable( 'ClusteringSettings', 'FileHandler', $this->previousFileHandler );
+ $this->previousFileHandler = null;
+ if ( isset( $GLOBALS['eZClusterFileHandler_chosen_handler'] ) )
+ unset( $GLOBALS['eZClusterFileHandler_chosen_handler'] );
+
if ( $this->haveToRemoveDFSPath )
{
eZDir::recursiveDelete( $this->DFSPath );
|
- Tests: made sure that the previously active file handler is restored after
DFS tests are executed. Again: isolation.
git-svn-id: file:///home/patrick.allaert/svn-git/ezp-repo/ezpublish/trunk@<I> a<I>eee8c-daba-<I>-acae-fa<I>f<I>
|
ezsystems_ezpublish-legacy
|
train
|
bcfe3a95d284fae08f98ec4c84d924a32161272a
|
diff --git a/API.md b/API.md
index <HASH>..<HASH> 100644
--- a/API.md
+++ b/API.md
@@ -710,8 +710,11 @@ sig: Signature to add
resolves: undefined
```
-##### listmonitor (verbose)
+##### listmonitor ({verbose, current})
Setup a callback on all valid transports, so if anything is added to this list on the Dweb it will be called. This method then deduplicates, and if the event is new will call any callback added with addEventListener() with an event of type “insert” Note that the callback is called WITHOUT fetching the data referenced in the Sig, since it could be large, or a stream etc.
+```
+current if true, return existing as well as new entries
+```
### KeyValueTable - storage and retrieval of data by a key
Manages a KeyValue object intended for each field to be a separate item stored independently.
@@ -807,10 +810,14 @@ Delete the key from the map and on the net
fromNet Only delete locally - this request came from the net
```
-##### monitor(verbose)
+##### monitor({verbose, current})
+TODO - note this doesnt yet support the current flag from Transports.monitor
Add a monitor for each transport - note this means if multiple transports support it, then will get duplicate events back if everyone else is notifying all of them.
Note monitor() is synchronous, so it cannot do asynchronous things like connecting to the underlying transport
Stack: KVT()|KVT.p_new => KVT.monitor => (a: Transports.monitor => YJS.monitor)(b: dispatchEvent)
+```
+current if true, return existing as well as new entries
+```
### KeyValue extends SmartDict
TODO This is incomplete, will have a interface similar to KeyValueTable
diff --git a/CommonList.js b/CommonList.js
index <HASH>..<HASH> 100644
--- a/CommonList.js
+++ b/CommonList.js
@@ -93,8 +93,9 @@ class CommonList extends PublicPrivate {
:resolves: list of objects signed and added to the list
*/
try {
+ //TODO-GUN this should probably instead use listmonitor({current: true}) to get existing items more efficiently in GUN
await this.p_fetchlist(verbose);
- this.listmonitor(verbose); // Track any future objects - will call event Handler on any added
+ this.listmonitor({verbose}); // Track any future objects - will call event Handler on any added
return (await Promise.all(
Signature.filterduplicates(this._list) // Dont load multiple copies of items on list (might need to be an option?)
.map((sig) => sig.p_fetchdata({verbose, ignoreerrors}))))
@@ -168,7 +169,7 @@ class CommonList extends PublicPrivate {
// ----- Listener interface ----- see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget for the pattern
- listmonitor(verbose) {
+ listmonitor({verbose=false, current=false}={}) {
/*
Add a listmonitor for each transport - note this means if multiple transports support it, then will get duplicate events back if everyone else is notifying all of them.
*/
@@ -186,7 +187,7 @@ class CommonList extends PublicPrivate {
} else {
console.log("Rejected signature: ",sig);
}
- }, {verbose});
+ }, {verbose, current});
}
}
SmartDict.table2class["cl"] = CommonList;
diff --git a/KeyValueTable.js b/KeyValueTable.js
index <HASH>..<HASH> 100644
--- a/KeyValueTable.js
+++ b/KeyValueTable.js
@@ -200,7 +200,7 @@ class KeyValueTable extends PublicPrivate {
//get(name, default) cant be defined as overrides this.get()
// ----- Listener interface ----- see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget for the pattern
- monitor(verbose) {
+ monitor({verbose=false, current=false}={}) {
/*
Add a monitor for each transport - note this means if multiple transports support it, then will get duplicate events back if everyone else is notifying all of them.
Note monitor() is synchronous, so it cant do asynchronous things like connecting to the underlying transport
@@ -222,7 +222,7 @@ class KeyValueTable extends PublicPrivate {
}
this.dispatchEvent(new CustomEvent(event.type, {target: this, detail: event})); // Pass event on to application after updating local object
},
- verbose);
+ {verbose, current});
}
static async p_test(verbose) {
|
Update listmonitor and monitor to take {verbose, current}
|
internetarchive_dweb-objects
|
train
|
821d42795e0161d03dab1c7c3561127ef1a9390f
|
diff --git a/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/ComponentGrouping.java b/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/ComponentGrouping.java
index <HASH>..<HASH> 100644
--- a/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/ComponentGrouping.java
+++ b/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/ComponentGrouping.java
@@ -116,9 +116,11 @@ public final class ComponentGrouping implements Predicate<int[]> {
this.queryComponents = grouping;
this.targetComponents = targetComponents;
int max = 0;
- for (int i = 0; i < targetComponents.length; i++)
- if (targetComponents[i] > max)
- max = targetComponents[i];
+ if (targetComponents != null) {
+ for (int i = 0; i < targetComponents.length; i++)
+ if (targetComponents[i] > max)
+ max = targetComponents[i];
+ }
this.maxComponentIdx = max;
}
|
Watch out for null component ids.
|
cdk_cdk
|
train
|
b30a4c4f3ec1a743edb30bbb4c9aafbed2c70c68
|
diff --git a/lib/OpenLayers/Control/LayerSwitcher.js b/lib/OpenLayers/Control/LayerSwitcher.js
index <HASH>..<HASH> 100644
--- a/lib/OpenLayers/Control/LayerSwitcher.js
+++ b/lib/OpenLayers/Control/LayerSwitcher.js
@@ -115,6 +115,7 @@ OpenLayers.Control.LayerSwitcher.prototype =
*/
doubleClick: function(evt) {
Event.stop(evt);
+ return false;
},
/**
@@ -144,6 +145,7 @@ OpenLayers.Control.LayerSwitcher.prototype =
backdropLabel.layer = layer;
// set event handlers
+ backdropLabelOuter.onclick = this.doubleClick.bindAsEventListener(this);
backdropLabelOuter.ondblclick = this.doubleClick.bindAsEventListener(this);
backdropLabelOuter.onmousedown = this.singleClick.bindAsEventListener(this);
diff --git a/lib/OpenLayers/Control/PanZoom.js b/lib/OpenLayers/Control/PanZoom.js
index <HASH>..<HASH> 100644
--- a/lib/OpenLayers/Control/PanZoom.js
+++ b/lib/OpenLayers/Control/PanZoom.js
@@ -53,6 +53,7 @@ OpenLayers.Control.PanZoom.prototype =
btn.onmousedown = this.buttonDown.bindAsEventListener(btn);
btn.ondblclick = this.doubleClick.bindAsEventListener(btn);
+ btn.onclick = this.doubleClick.bindAsEventListener(btn);
btn.action = id;
btn.map = this.map;
@@ -63,6 +64,7 @@ OpenLayers.Control.PanZoom.prototype =
doubleClick: function (evt) {
Event.stop(evt);
+ return false;
},
buttonDown: function (evt) {
diff --git a/lib/OpenLayers/Control/PanZoomBar.js b/lib/OpenLayers/Control/PanZoomBar.js
index <HASH>..<HASH> 100644
--- a/lib/OpenLayers/Control/PanZoomBar.js
+++ b/lib/OpenLayers/Control/PanZoomBar.js
@@ -68,6 +68,7 @@ OpenLayers.Control.PanZoomBar.prototype =
this.sliderEvents.register("mousemove", this, this.zoomBarDrag);
this.sliderEvents.register("mouseup", this, this.zoomBarUp);
this.sliderEvents.register("dblclick", this, this.doubleClick);
+ this.sliderEvents.register("click", this, this.doubleClick);
sz = new OpenLayers.Size();
sz.h = this.zoomStopHeight*(this.map.getZoomLevels()+1);
@@ -96,6 +97,7 @@ OpenLayers.Control.PanZoomBar.prototype =
this.divEvents.register("mousedown", this, this.divClick);
this.divEvents.register("mousemove", this, this.passEventToSlider);
this.divEvents.register("dblclick", this, this.doubleClick);
+ this.divEvents.register("click", this, this.doubleClick);
this.div.appendChild(div);
|
Return false from DoubleClick and Click events in controls so that these events don't filter through and hit the onclick handlers that we might register on the map.
git-svn-id: <URL>
|
openlayers_openlayers
|
train
|
b5fabb891b10746be700d085ef2a05c83724ba86
|
diff --git a/input/tangy-location.js b/input/tangy-location.js
index <HASH>..<HASH> 100644
--- a/input/tangy-location.js
+++ b/input/tangy-location.js
@@ -443,7 +443,6 @@ class TangyLocation extends PolymerElement {
/* End of Materialize Select Styles */
</style>
<div id="container"></div>
- <slot></slot>
`;
}
@@ -470,6 +469,12 @@ class TangyLocation extends PolymerElement {
reflectToAttribute: true,
observer: 'render'
},
+ showMetaData: {
+ type: Boolean,
+ value: false,
+ reflectToAttribute: true,
+ observer: 'render'
+ },
locationSrc: {
type: String,
value: './assets/location-list.json',
@@ -514,10 +519,12 @@ class TangyLocation extends PolymerElement {
set locationList(locationList) {
this._locationList = locationList
+ this._flatLocationList = Loc.flatten(locationList)
}
async connectedCallback() {
super.connectedCallback();
+ this._template = this.innerHTML
if (this.filterByGlobal) this.filterBy = window.tangyLocationFilterBy
// When we hear change events, it's coming from users interacting with select lists.
this.shadowRoot.addEventListener('change', this.onSelectionChange.bind(this))
@@ -586,9 +593,21 @@ class TangyLocation extends PolymerElement {
<div class="mdc-select__bottom-line"></div>
</div>
- <div id="metadata">
- <!-- @TODO If last level is selected, show table of metadata of that last selected location. -->
- </div>
+ ${this.showMetaData && selection.value ? `
+ <div id="metadata">
+ ${
+ [this._flatLocationList.locations.find(node => node.id === selection.value)]
+ .map(node => this._template
+ ? eval(`\`${this._template}\``)
+ : Object.keys(node)
+ .map(key => key !== 'parent' && key !== 'children'
+ ? `<b>${key}</b>: ${node[key]}<br>`
+ : ''
+ ).join('')
+ ).join('')
+ }
+ </div>
+ `:``}
<br />
<br />
|
Add ability to show meta data of location list nodes
|
Tangerine-Community_tangy-form
|
train
|
2d84cbd3cc294cf1a25cde260702a344fd0031e2
|
diff --git a/libraries/core/classes/AppPermissionsRequest/RequestAppPermissionsRequest.js b/libraries/core/classes/AppPermissionsRequest/RequestAppPermissionsRequest.js
index <HASH>..<HASH> 100644
--- a/libraries/core/classes/AppPermissionsRequest/RequestAppPermissionsRequest.js
+++ b/libraries/core/classes/AppPermissionsRequest/RequestAppPermissionsRequest.js
@@ -3,7 +3,6 @@ import {
REQUEST_PERMISSIONS_COMMAND_NAME,
REQUEST_PERMISSIONS_RESPONSE_EVENT_NAME,
availablePermissionsIds,
- availableUsages,
} from '../../constants/AppPermissions';
/**
diff --git a/libraries/core/constants/AppPermissions.js b/libraries/core/constants/AppPermissions.js
index <HASH>..<HASH> 100644
--- a/libraries/core/constants/AppPermissions.js
+++ b/libraries/core/constants/AppPermissions.js
@@ -45,9 +45,11 @@ export const availableUsages = [
export const STATUS_DENIED = 'denied';
export const STATUS_GRANTED = 'granted';
export const STATUS_NOT_DETERMINED = 'notDetermined';
+export const STATUS_NOT_SUPPORTED = 'notSupported';
export const availableStatuses = [
STATUS_DENIED,
STATUS_GRANTED,
STATUS_NOT_DETERMINED,
+ STATUS_NOT_SUPPORTED,
];
|
CCP-<I>: addad "notSupported" usage
|
shopgate_pwa
|
train
|
063f4fb92d862d3f759fba95ae811880329804ca
|
diff --git a/odl/operator/tensor_ops.py b/odl/operator/tensor_ops.py
index <HASH>..<HASH> 100644
--- a/odl/operator/tensor_ops.py
+++ b/odl/operator/tensor_ops.py
@@ -342,8 +342,9 @@ class PointwiseNorm(PointwiseTensorFieldOperator):
for gi in inner_vf:
if self.exponent >= 2:
with np.errstate(invalid='ignore', divide='ignore'):
- gi /= vf_pwnorm_fac * gi ** (self.exponent - 2)
- gi = np.nan_to_num(x=gi)
+ tmp = vf_pwnorm_fac * gi ** (self.exponent - 2)
+ # Any component that is zero is not divided with
+ gi /= tmp if not tmp else 1
else:
gi /= vf_pwnorm_fac * gi ** (self.exponent - 2)
diff --git a/odl/test/operator/tensor_ops_test.py b/odl/test/operator/tensor_ops_test.py
index <HASH>..<HASH> 100644
--- a/odl/test/operator/tensor_ops_test.py
+++ b/odl/test/operator/tensor_ops_test.py
@@ -192,6 +192,65 @@ def test_pointwise_norm_weighted(exponent):
assert all_almost_equal(out, true_norm)
+def test_pointwise_norm_gradient_real(exponent):
+ # The operator is not differentiable for exponent 'inf'
+ if exponent == float('inf'):
+ fspace = odl.uniform_discr([0, 0], [1, 1], (2, 2))
+ vfspace = ProductSpace(fspace, 1)
+ pwnorm = PointwiseNorm(vfspace, exponent)
+ point = vfspace.one()
+ with pytest.raises(NotImplementedError):
+ pwnorm.derivative(point)
+ return
+
+ # TODO: implement good tests also for the 'normal behaviour'
+
+ # The gradient is only well-defined in all points if the exponent is >= 2
+ if exponent < 2:
+ pytest.skip('differential of operator has singularity for this '
+ 'exponent')
+
+ # 1d
+ fspace = odl.uniform_discr([0, 0], [1, 1], (2, 2))
+ vfspace = ProductSpace(fspace, 1)
+ pwnorm = PointwiseNorm(vfspace, exponent)
+
+ test_point = np.array([[[0, 0], # This makes the point singular for p < 2
+ [1, 2]]])
+ test_direction = np.array([[[1, 2],
+ [4, 5]]])
+
+ point = vfspace.element(test_point)
+ direction = vfspace.element(test_direction)
+ func_pwnorm = pwnorm.derivative(point)
+
+ assert not any(np.isnan(func_pwnorm(direction)))
+
+ # 3d
+ fspace = odl.uniform_discr([0, 0], [1, 1], (2, 2))
+ vfspace = ProductSpace(fspace, 3)
+ pwnorm = PointwiseNorm(vfspace, exponent)
+
+ test_point = np.array([[[0, 0], # This makes the point singular for p < 2
+ [1, 2]],
+ [[3, 4],
+ [0, 0]], # This makes the point singular for p < 2
+ [[5, 6],
+ [7, 8]]])
+ test_direction = np.array([[[0, 1],
+ [2, 3]],
+ [[4, 5],
+ [6, 7]],
+ [[8, 9],
+ [0, 1]]])
+
+ point = vfspace.element(test_point)
+ direction = vfspace.element(test_direction)
+ func_pwnorm = pwnorm.derivative(point)
+
+ assert not any(np.isnan(func_pwnorm(direction)))
+
+
# ---- PointwiseInner ----
|
BUG/TST: update derivative of PointwiseInner and add test for it.
|
odlgroup_odl
|
train
|
68e0752ddee0d4e90baf55afe935820d1bec45a6
|
diff --git a/src/lib/builtins.js b/src/lib/builtins.js
index <HASH>..<HASH> 100644
--- a/src/lib/builtins.js
+++ b/src/lib/builtins.js
@@ -57,16 +57,9 @@ export class FTLKeyword extends FTLBase {
}
export class FTLList extends Array {
- constructor(arr = [], opts) {
- super(arr.length);
- this.opts = opts;
- for (let [index, elem] of arr.entries()) {
- this[index] = elem;
- }
- }
toString(rc) {
const lf = rc.ctx._memoizeIntlObject(
- L20nIntl.ListFormat, rc.lang, this.opts
+ L20nIntl.ListFormat, rc.lang // XXX add this.opts
);
const elems = this.map(
elem => elem.toString(rc)
@@ -74,7 +67,7 @@ export class FTLList extends Array {
return lf.format(elems);
}
concat(elem) {
- return new FTLList([...this, elem]);
+ return FTLList.from([...this, elem]);
}
}
@@ -86,12 +79,10 @@ export default {
'NUMBER': ([arg], opts) => new FTLNumber(arg.valueOf(), valuesOf(opts)),
'PLURAL': ([arg], opts) => new FTLNumber(arg.valueOf(), valuesOf(opts)),
'DATETIME': ([arg], opts) => new FTLDateTime(arg.valueOf(), valuesOf(opts)),
- 'LIST': (args) => new FTLList(args),
'LEN': ([arg], opts) => new FTLNumber(arg.valueOf().length, valuesOf(opts)),
- 'TAKE': ([num, arg], opts) =>
- new FTLList(arg.value.slice(0, num.value), valuesOf(opts)),
- 'DROP': ([num, arg], opts) =>
- new FTLList(arg.value.slice(num.value), valuesOf(opts)),
+ 'LIST': (args) => FTLList.from(args),
+ 'TAKE': ([num, arg]) => FTLList.from(arg.valueOf().slice(0, num.value)),
+ 'DROP': ([num, arg]) => FTLList.from(arg.valueOf().slice(num.value)),
};
function valuesOf(opts) {
|
Make FTLList's constructor compatible with Array's
It's dangerous to change the signature of Array's subclasses' constructors. It
might be used by some of Array's methods, like map.
In this commit I removed support for defining formatting options for lists.
I'll add it back once we have a working polyfill for ListFormat.
|
l20n_l20n.js
|
train
|
49dc009422d8f084d297a4f9ac590e867235a7f1
|
diff --git a/pycosio/_core/io_buffered.py b/pycosio/_core/io_buffered.py
index <HASH>..<HASH> 100644
--- a/pycosio/_core/io_buffered.py
+++ b/pycosio/_core/io_buffered.py
@@ -53,6 +53,7 @@ class ObjectBufferedIOBase(BufferedIOBase, ObjectIOBase):
# Instantiate raw IO
self._raw = self._RAW_CLASS(
name, mode=mode, storage_parameters=storage_parameters)
+ self._raw._is_raw_of_buffered = True
# Link to RAW methods
self._mode = self._raw.mode
@@ -112,7 +113,7 @@ class ObjectBufferedIOBase(BufferedIOBase, ObjectIOBase):
# If closed and data lower than buffer size
# flush data with raw stream to reduce IO calls
elif self._buffer_seek:
- self.raw._write_buffer = self._write_buffer
+ self.raw._write_buffer = self._get_buffer()
self.raw._seek = self._buffer_seek
self.raw.flush()
diff --git a/pycosio/_core/io_raw.py b/pycosio/_core/io_raw.py
index <HASH>..<HASH> 100644
--- a/pycosio/_core/io_raw.py
+++ b/pycosio/_core/io_raw.py
@@ -55,6 +55,9 @@ class ObjectRawIOBase(RawIOBase, ObjectIOBase):
self._client_kwargs = self._system.get_client_kwargs(name)
self._client = self._system.client
+ # Mark as standalone RAW to avoid flush conflics on close
+ self._is_raw_of_buffered = False
+
# Configures write mode
if self._writable:
# In write mode, since it is not possible
@@ -84,6 +87,15 @@ class ObjectRawIOBase(RawIOBase, ObjectIOBase):
with handle_os_exceptions():
self._head()
+ def close(self):
+ """
+ Flush the write buffers of the stream if applicable and
+ close the object.
+ """
+ if self._writable and not self._is_raw_of_buffered:
+ with self._seek_lock:
+ self._flush()
+
def flush(self):
"""
Flush the write buffers of the stream if applicable and
@@ -99,6 +111,16 @@ class ObjectRawIOBase(RawIOBase, ObjectIOBase):
Flush the write buffers of the stream if applicable.
"""
+ def _get_buffer(self):
+ """
+ Get a memory view of the current write buffer
+ until its seek value.
+
+ Returns:
+ memoryview: buffer view.
+ """
+ return memoryview(self._write_buffer)
+
@property
@memoizedmethod
def _size(self):
diff --git a/pycosio/storage/s3.py b/pycosio/storage/s3.py
index <HASH>..<HASH> 100644
--- a/pycosio/storage/s3.py
+++ b/pycosio/storage/s3.py
@@ -206,7 +206,7 @@ class S3RawIO(_ObjectRawIOBase):
"""
# Sends to S3 the entire file at once
with _handle_client_error():
- self._put_object(Body=memoryview(self._write_buffer).tobytes(),
+ self._put_object(Body=self._get_buffer().tobytes(),
**self._client_kwargs)
diff --git a/pycosio/storage/swift.py b/pycosio/storage/swift.py
index <HASH>..<HASH> 100644
--- a/pycosio/storage/swift.py
+++ b/pycosio/storage/swift.py
@@ -158,7 +158,7 @@ class SwiftRawIO(_ObjectRawIOBase):
"""
container, obj = self._client_args
with _handle_client_exception():
- self._put_object(container, obj, memoryview(self._write_buffer))
+ self._put_object(container, obj, self._get_buffer())
class SwiftBufferedIO(_ObjectBufferedIOBase):
diff --git a/tests/test_io_raw.py b/tests/test_io_raw.py
index <HASH>..<HASH> 100644
--- a/tests/test_io_raw.py
+++ b/tests/test_io_raw.py
@@ -121,6 +121,7 @@ def test_object_raw_base_io():
object_io.seek(10)
assert object_io.write(10 * BYTE) == 10
assert object_io.tell() == 20
+ assert object_io._get_buffer().tobytes() == 20 * BYTE
# Test flush
assert not len(flushed)
|
Add _get_buffer to raw, and avoid raw + buffered flushs.
|
Accelize_pycosio
|
train
|
d22612f727406706bde3aff70c151007d2b3a919
|
diff --git a/src/main/java/com/googlecode/objectify/impl/translate/CollectionTranslatorFactory.java b/src/main/java/com/googlecode/objectify/impl/translate/CollectionTranslatorFactory.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/googlecode/objectify/impl/translate/CollectionTranslatorFactory.java
+++ b/src/main/java/com/googlecode/objectify/impl/translate/CollectionTranslatorFactory.java
@@ -2,6 +2,7 @@ package com.googlecode.objectify.impl.translate;
import com.google.cloud.datastore.ListValue;
import com.google.cloud.datastore.Value;
+import com.google.cloud.datastore.ValueType;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.impl.Path;
import com.googlecode.objectify.util.GenericUtils;
@@ -46,7 +47,7 @@ public class CollectionTranslatorFactory implements TranslatorFactory<Collection
public Collection<Object> loadInto(final Value<List<? extends Value<?>>> node, final LoadContext ctx, final Path path, Collection<Object> collection) throws SkipException {
// If the collection does not exist, skip it entirely. This mirrors the OLD underlying behavior
// of collections in the datastore; if they are empty, they don't exist.
- if (node == null)
+ if (node == null || node.getType() == ValueType.NULL)
throw new SkipException();
if (collection == null)
|
Ignore NULL value type as well as literal null
|
objectify_objectify
|
train
|
7e514e88e425b38cd51bdbe353b941b9cb1e50de
|
diff --git a/src/utils/theme_utils.js b/src/utils/theme_utils.js
index <HASH>..<HASH> 100644
--- a/src/utils/theme_utils.js
+++ b/src/utils/theme_utils.js
@@ -1,12 +1,13 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
+// @flow
-export function makeStyleFromTheme(getStyleFromTheme) {
+export function makeStyleFromTheme(getStyleFromTheme: (Object) => Object): (Object) => Object {
let lastTheme = null;
let style = null;
- return (theme) => {
- if (theme !== lastTheme) {
+ return (theme: Object) => {
+ if (!style || theme !== lastTheme) {
style = getStyleFromTheme(theme);
lastTheme = theme;
}
@@ -15,7 +16,7 @@ export function makeStyleFromTheme(getStyleFromTheme) {
};
}
-export function changeOpacity(oldColor, opacity) {
+function normalizeColor(oldColor: string): string {
let color = oldColor;
if (color.length && color[0] === '#') {
color = color.slice(1);
@@ -30,9 +31,42 @@ export function changeOpacity(oldColor, opacity) {
color += tempColor[2] + tempColor[2];
}
+ return color;
+}
+
+export function changeOpacity(oldColor: string, opacity: number): string {
+ const color = normalizeColor(oldColor);
+
const r = parseInt(color.substring(0, 2), 16);
const g = parseInt(color.substring(2, 4), 16);
const b = parseInt(color.substring(4, 6), 16);
- return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')';
+ return `rgba(${r},${g},${b},${opacity})`;
+}
+
+function blendComponent(background: number, foreground: number, opacity: number): number {
+ return ((1 - opacity) * background) + (opacity * foreground);
+}
+
+export function blendColors(background: string, foreground: string, opacity: number): string {
+ const backgroundNormalized = normalizeColor(background);
+ const foregroundNormalized = normalizeColor(foreground);
+
+ const r = blendComponent(
+ parseInt(backgroundNormalized.substring(0, 2), 16),
+ parseInt(foregroundNormalized.substring(0, 2), 16),
+ opacity
+ );
+ const g = blendComponent(
+ parseInt(backgroundNormalized.substring(2, 4), 16),
+ parseInt(foregroundNormalized.substring(2, 4), 16),
+ opacity
+ );
+ const b = blendComponent(
+ parseInt(backgroundNormalized.substring(4, 6), 16),
+ parseInt(foregroundNormalized.substring(4, 6), 16),
+ opacity
+ );
+
+ return `rgb(${r},${g},${b})`;
}
|
Added blendColors and added flow types to theme_utils (#<I>)
|
mattermost_mattermost-redux
|
train
|
7fb2516e36f3f2bb10d41567e2e064232c459e29
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -29,7 +29,8 @@ def read(filename):
"""
Get the long description from a file.
"""
- with codecs.open(filename, encoding='utf-8') as f:
+ fname = os.path.join(here, filename)
+ with codecs.open(fname, encoding='utf-8') as f:
return f.read()
|
small setup.py fix (readme path)
|
ransford_sllurp
|
train
|
a9fd0a5c0b3c248a2f2b42171d23b623cefc219a
|
diff --git a/src/gremlin.js b/src/gremlin.js
index <HASH>..<HASH> 100644
--- a/src/gremlin.js
+++ b/src/gremlin.js
@@ -279,8 +279,8 @@ var Gremlin = (function () {
Gremlin.prototype.orderMap = queryMain('orderMap');
/*** Filter ***/
- Gremlin.prototype.index = queryIndex(), //index(i;
- Gremlin.prototype.range = queryIndex(), //range('[i..j]';
+ Gremlin.prototype.index = queryIndex(); //index(i)
+ Gremlin.prototype.range = queryIndex(); //range('[i..j]')
Gremlin.prototype.and = queryPipes('and');
Gremlin.prototype.back = queryMain('back');
Gremlin.prototype.dedup = queryMain('dedup');
@@ -298,7 +298,7 @@ var Gremlin = (function () {
// Gremlin.prototype.aggregate //Not implemented
Gremlin.prototype.as = queryMain('as');
Gremlin.prototype.groupBy = queryMain('groupBy');
- Gremlin.prototype.groupCount = queryMain('groupCount'), //Not FullyImplemented ??;
+ Gremlin.prototype.groupCount = queryMain('groupCount'); //Not FullyImplemented ??
Gremlin.prototype.optional = queryMain('optional');
Gremlin.prototype.sideEffect = queryMain('sideEffect');
@@ -344,9 +344,9 @@ var Gremlin = (function () {
//Titan v0.4.0 specifics
Gremlin.prototype.single = queryMain('single');
Gremlin.prototype.list = queryMain('list');
- Gremlin.prototype.oneToMany = queryMain('oneToMany'), // replaces uniqueDirection.IN);
- Gremlin.prototype.manyToOne = queryMain('manyToOne'), // replaces uniqueDirection.OUT);
- Gremlin.prototype.oneToOne = queryMain('oneToOne'), // replaces uniqueDirection.IN).unique(Direction.OUT);
+ Gremlin.prototype.oneToMany = queryMain('oneToMany'); // replaces uniqueDirection.IN)
+ Gremlin.prototype.manyToOne = queryMain('manyToOne'); // replaces uniqueDirection.OUT)
+ Gremlin.prototype.oneToOne = queryMain('oneToOne'); // replaces uniqueDirection.IN).unique(Direction.OUT)
Gremlin.prototype.makeKey = queryMain('makeKey');
Gremlin.prototype.makeLabel = queryMain('makeLabel');
Gremlin.prototype.make = queryMain('make');
|
Fix Gremlin prototype commas at end of lines
|
jbmusso_grex
|
train
|
8a20a8b2403f054c7bb1e89b6b881ba69ec0d6c9
|
diff --git a/common/src/main/java/tachyon/worker/WorkerClient.java b/common/src/main/java/tachyon/worker/WorkerClient.java
index <HASH>..<HASH> 100644
--- a/common/src/main/java/tachyon/worker/WorkerClient.java
+++ b/common/src/main/java/tachyon/worker/WorkerClient.java
@@ -270,21 +270,21 @@ public final class WorkerClient extends ClientBase {
* @return the path of the block file locked
* @throws IOException
*/
- public synchronized String lockBlock(long blockId) throws IOException {
- connect();
-
+ public synchronized String lockBlock(final long blockId) throws IOException {
// TODO(jiri) Would be nice to have a helper method to execute this try-catch logic
try {
- return mClient.lockBlock(blockId, mSessionId);
- } catch (TachyonTException e) {
+ return retryRPC(new RpcCallableThrowsTachyonTException<String>() {
+ @Override
+ public String call() throws TachyonTException, TException {
+ return mClient.lockBlock(blockId, mSessionId);
+ }
+ });
+ } catch (TachyonException e) {
if (e.getType().equals(TachyonExceptionType.FILE_DOES_NOT_EXIST.name())) {
return null;
} else {
throw new IOException(e);
}
- } catch (TException e) {
- mConnected = false;
- throw new IOException(e);
}
}
@@ -310,17 +310,17 @@ public final class WorkerClient extends ClientBase {
*
* @param blockId The id of the block that will be promoted
* @return true if succeed, false otherwise
- * @throws IOException
+ * @throws IOException if an I/O error occurs
+ * @throws TachyonException if a Tachyon error occurs
*/
- public synchronized boolean promoteBlock(long blockId) throws IOException {
- connect();
-
- try {
- return mClient.promoteBlock(blockId);
- } catch (TException e) {
- mConnected = false;
- throw new IOException(e);
- }
+ public synchronized boolean promoteBlock(final long blockId) throws IOException,
+ TachyonException {
+ return retryRPC(new RpcCallableThrowsTachyonTException<Boolean>() {
+ @Override
+ public Boolean call() throws TachyonTException, TException {
+ return mClient.promoteBlock(blockId);
+ }
+ });
}
/**
@@ -331,21 +331,21 @@ public final class WorkerClient extends ClientBase {
* @return the temporary path of the block
* @throws IOException
*/
- public synchronized String requestBlockLocation(long blockId, long initialBytes)
+ public synchronized String requestBlockLocation(final long blockId, final long initialBytes)
throws IOException {
- connect();
-
try {
- return mClient.requestBlockLocation(mSessionId, blockId, initialBytes);
- } catch (TachyonTException e) {
+ return retryRPC(new RpcCallableThrowsTachyonTException<String>() {
+ @Override
+ public String call() throws TachyonTException, TException {
+ return mClient.requestBlockLocation(mSessionId, blockId, initialBytes);
+ }
+ });
+ } catch (TachyonException e) {
if (e.getType().equals(TachyonExceptionType.WORKER_OUT_OF_SPACE.name())) {
throw new IOException("Failed to request " + initialBytes, e);
} else {
throw new IOException(e);
}
- } catch (TException e) {
- mConnected = false;
- throw new IOException(e);
}
}
|
[TACHYON-<I>] Refactor WorkClient for methods lockBlock, promoteBlock, and requestBlockLocation
|
Alluxio_alluxio
|
train
|
f7aca803b1f566fb03c52bab4427c36f50faa7ec
|
diff --git a/pyrogram/client/types/message.py b/pyrogram/client/types/message.py
index <HASH>..<HASH> 100644
--- a/pyrogram/client/types/message.py
+++ b/pyrogram/client/types/message.py
@@ -71,6 +71,9 @@ class Message(Object):
text (``str``, *optional*):
For text messages, the actual UTF-8 text of the message, 0-4096 characters.
+ If the message contains entities (bold, italic, ...) you can access *text.markdown* or
+ *text.html* to get the marked up message text. In case there is no entity, the fields
+ will contain the same text as *text*.
entities (List of :obj:`MessageEntity <pyrogram.MessageEntity>`, *optional*):
For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text.
@@ -108,6 +111,9 @@ class Message(Object):
caption (``str``, *optional*):
Caption for the audio, document, photo, video or voice, 0-200 characters.
+ If the message contains caption entities (bold, italic, ...) you can access *caption.markdown* or
+ *caption.html* to get the marked up caption text. In case there is no caption entity, the fields
+ will contain the same text as *caption*.
contact (:obj:`Contact <pyrogram.Contact>`, *optional*):
Message is a shared contact, information about the contact.
|
Hint about text.markdown in docstrings
|
pyrogram_pyrogram
|
train
|
64e9cf9733b10d08ac42f1e14f4ab36a94fdffa2
|
diff --git a/api/allocations.go b/api/allocations.go
index <HASH>..<HASH> 100644
--- a/api/allocations.go
+++ b/api/allocations.go
@@ -91,6 +91,7 @@ type Allocation struct {
DeploymentID string
DeploymentStatus *AllocDeploymentStatus
PreviousAllocation string
+ NextAllocation string
CreateIndex uint64
ModifyIndex uint64
AllocModifyIndex uint64
diff --git a/nomad/state/state_store.go b/nomad/state/state_store.go
index <HASH>..<HASH> 100644
--- a/nomad/state/state_store.go
+++ b/nomad/state/state_store.go
@@ -1889,6 +1889,21 @@ func (s *StateStore) upsertAllocsImpl(index uint64, allocs []*structs.Allocation
return fmt.Errorf("alloc insert failed: %v", err)
}
+ if alloc.PreviousAllocation != "" {
+ prevAlloc, err := txn.First("allocs", "id", alloc.PreviousAllocation)
+ if err != nil {
+ return fmt.Errorf("alloc lookup failed: %v", err)
+ }
+ existingPrevAlloc, _ := prevAlloc.(*structs.Allocation)
+ if existingPrevAlloc != nil {
+ prevAllocCopy := existingPrevAlloc.Copy()
+ prevAllocCopy.NextAllocation = alloc.ID
+ if err := txn.Insert("allocs", prevAllocCopy); err != nil {
+ return fmt.Errorf("alloc insert failed: %v", err)
+ }
+ }
+ }
+
// If the allocation is running, force the job to running status.
forceStatus := ""
if !alloc.TerminalStatus() {
diff --git a/nomad/structs/structs.go b/nomad/structs/structs.go
index <HASH>..<HASH> 100644
--- a/nomad/structs/structs.go
+++ b/nomad/structs/structs.go
@@ -4910,6 +4910,9 @@ type Allocation struct {
// PreviousAllocation is the allocation that this allocation is replacing
PreviousAllocation string
+ // NextAllocation is the allocation that this allocation is being replaced by
+ NextAllocation string
+
// DeploymentID identifies an allocation as being created from a
// particular deployment
DeploymentID string
diff --git a/scheduler/generic_sched_test.go b/scheduler/generic_sched_test.go
index <HASH>..<HASH> 100644
--- a/scheduler/generic_sched_test.go
+++ b/scheduler/generic_sched_test.go
@@ -3443,7 +3443,7 @@ func TestGenericSched_ChainedAlloc(t *testing.T) {
}
sort.Strings(prevAllocs)
- // Ensure that the new allocations has their corresponging original
+ // Ensure that the new allocations has their corresponding original
// allocation ids
if !reflect.DeepEqual(prevAllocs, allocIDs) {
t.Fatalf("expected: %v, actual: %v", len(allocIDs), len(prevAllocs))
|
Add a field to track the next allocation during a replacement
|
hashicorp_nomad
|
train
|
410d23a6926e5203e6616cab6d18daa51c89d3da
|
diff --git a/lib/fitgem_oauth2/client.rb b/lib/fitgem_oauth2/client.rb
index <HASH>..<HASH> 100644
--- a/lib/fitgem_oauth2/client.rb
+++ b/lib/fitgem_oauth2/client.rb
@@ -57,12 +57,27 @@ module FitgemOauth2
parse_response(response)
end
+ # This method is a helper method (like get_call) for 1.2 version of the API_VERSION
+ # This method is needed because Fitbit API supports both versions as of current
+ # date (Nov 5, 2017)
+ def get_call_1_2(url)
+ url = "1.2/#{url}"
+ response = connection.get(url) {|request| set_headers(request)}
+ parse_response(response)
+ end
+
def post_call(url, params = {})
url = "#{API_VERSION}/#{url}"
response = connection.post(url, params) { |request| set_headers(request) }
parse_response(response)
end
+ def post_call_1_2(url, params = {})
+ url = "1.2/#{url}"
+ response = connection.post(url, params) { |request| set_headers(request) }
+ parse_response(response)
+ end
+
def delete_call(url)
url = "#{API_VERSION}/#{url}"
response = connection.delete(url) { |request| set_headers(request) }
diff --git a/lib/fitgem_oauth2/sleep.rb b/lib/fitgem_oauth2/sleep.rb
index <HASH>..<HASH> 100644
--- a/lib/fitgem_oauth2/sleep.rb
+++ b/lib/fitgem_oauth2/sleep.rb
@@ -8,7 +8,23 @@ module FitgemOauth2
# retrieve sleep logs for a date
# @param date date for which sleep logs needs to be accessed
def sleep_logs(date)
- get_call("user/#{user_id}/sleep/date/#{format_date(date)}.json")
+ get_call_1_2("user/#{user_id}/sleep/date/#{format_date(date)}.json")
+ end
+
+ def sleep_logs_by_date_range(start_date, end_date)
+ get_call_1_2("user/#{user_id}/sleep/date/#{format_date(start_date)}/#{format_date(end_date)}.json")
+ end
+
+ def sleep_logs_list(date, sort, limit)
+ date_param = format_date(date)
+ if sort == "asc"
+ date_param = "afterDate=#{date_param}"
+ elsif sort == "desc"
+ date_param = "beforeDate=#{date_param}"
+ else
+ raise FitgemOauth2::InvalidArgumentError, "sort can either be asc or desc"
+ end
+ get_call_1_2("user/#{user_id}/sleep/list.json?#{date_param}&offset=0&sort=#{sort}&limit=#{limit}")
end
# retrieve sleep goal for the user
@@ -54,7 +70,7 @@ module FitgemOauth2
# log sleep
# @param params POST params for creating sleep log
def log_sleep(params)
- post_call("user/#{user_id}/sleep.json", params)
+ post_call_1_2("user/#{user_id}/sleep.json", params)
end
# deleted sleep log
@@ -62,7 +78,5 @@ module FitgemOauth2
def delete_logged_sleep(log_id)
delete_call("user/#{user_id}/sleep/#{log_id}.json")
end
-
end
-
end
diff --git a/spec/sleep_spec.rb b/spec/sleep_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/sleep_spec.rb
+++ b/spec/sleep_spec.rb
@@ -15,9 +15,18 @@ describe FitgemOauth2::Client do
end
end
+ def get_1_2_test(url, method, *args)
+ expect(client).to receive(:get_call_1_2).with(url).and_return(response)
+ if args.size == 0
+ expect(client.public_send(method)).to eql(response)
+ else
+ expect(client.public_send(method, args[0])).to eql(response)
+ end
+ end
+
describe '#sleep_logs' do
it 'gets sleep on date' do
- get_test("user/#{user_id}/sleep/date/#{client.format_date(Date.today)}.json", 'sleep_logs', Date.today)
+ get_1_2_test("user/#{user_id}/sleep/date/#{client.format_date(Date.today)}.json", 'sleep_logs', Date.today)
end
end
@@ -89,7 +98,7 @@ describe FitgemOauth2::Client do
params = random_sequence
url = "user/#{user_id}/sleep.json"
response = random_sequence
- expect(client).to receive(:post_call).with(url, params).and_return(response)
+ expect(client).to receive(:post_call_1_2).with(url, params).and_return(response)
expect(client.log_sleep(params)).to eql(response)
end
end
|
added new methods and updated existing methods for the sleep API <I>
list of new methods added:
* sleep_logs_by_date_range
* sleep_logs_list
|
gupta-ankit_fitgem_oauth2
|
train
|
f6bca9a71bd57b778d4a948730c8dabd4f4c15af
|
diff --git a/lib/config/app-config.js b/lib/config/app-config.js
index <HASH>..<HASH> 100644
--- a/lib/config/app-config.js
+++ b/lib/config/app-config.js
@@ -101,7 +101,9 @@ function findConfig_p(appDir){
function merge(src, target){
for (var el in src){
- if (typeof src[el] === 'object') {
+ // if it's an object (and not an array), recurse.
+ if (typeof src[el] === 'object' &&
+ Object.prototype.toString.call(src[el]) !== '[object Array]') {
target[el] = merge(target[el], src[el]);
} else{
target[el] = src[el];
|
Don't try to merge arrays as objects.
|
rstudio_shiny-server
|
train
|
ef1ed928348861a55abb89c1ad17db313a9f1452
|
diff --git a/lib/orbacle/find_definition_under_position.rb b/lib/orbacle/find_definition_under_position.rb
index <HASH>..<HASH> 100644
--- a/lib/orbacle/find_definition_under_position.rb
+++ b/lib/orbacle/find_definition_under_position.rb
@@ -8,6 +8,7 @@ module Orbacle
ConstantResult = Struct.new(:const_ref)
MessageResult = Struct.new(:name, :position_range)
+ SuperResult = Struct.new(:nesting, :method_name)
def initialize(parser)
@parser = parser
@@ -81,11 +82,40 @@ module Orbacle
nil
end
+ def on_super(ast)
+ if build_position_range_from_parser_range(ast.loc.keyword).include_position?(@searched_position)
+ @result = SuperResult.new(@current_nesting, @current_method)
+ end
+ nil
+ end
+
+ def on_zsuper(ast)
+ if build_position_range_from_parser_range(ast.loc.keyword).include_position?(@searched_position)
+ @result = SuperResult.new(@current_nesting, @current_method)
+ end
+ nil
+ end
+
+ def on_def(ast)
+ method_name = ast.children.fetch(0)
+ with_analyzed_method(method_name) do
+ super
+ end
+ nil
+ end
+
def with_new_nesting(new_nesting)
previous_nesting = @current_nesting
@current_nesting = new_nesting
yield
@current_nesting = previous_nesting
end
+
+ def with_analyzed_method(new_method)
+ previous_method = @current_method
+ @current_method = new_method
+ yield
+ @current_method = previous_method
+ end
end
end
diff --git a/spec/find_definition_under_position_spec.rb b/spec/find_definition_under_position_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/find_definition_under_position_spec.rb
+++ b/spec/find_definition_under_position_spec.rb
@@ -177,6 +177,75 @@ module Orbacle
end
end
+ describe "definition of super" do
+ specify "zsuper" do
+ file = <<-END
+ class Foo
+ def bar
+ super
+ end
+ end
+ END
+
+ expected_nesting = Nesting
+ .empty
+ .increase_nesting_const(ConstRef.from_full_name("Foo", Nesting.empty))
+ super_result = FindDefinitionUnderPosition::SuperResult.new(expected_nesting, :bar)
+ expect(find_definition_under_position(file, 2, 11)).to eq(nil)
+ expect(find_definition_under_position(file, 2, 12)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 13)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 14)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 15)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 16)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 17)).to eq(nil)
+ end
+
+ specify "super" do
+ file = <<-END
+ class Foo
+ def bar
+ super(42)
+ end
+ end
+ END
+
+ expected_nesting = Nesting
+ .empty
+ .increase_nesting_const(ConstRef.from_full_name("Foo", Nesting.empty))
+ super_result = FindDefinitionUnderPosition::SuperResult.new(expected_nesting, :bar)
+ expect(find_definition_under_position(file, 2, 11)).to eq(nil)
+ expect(find_definition_under_position(file, 2, 12)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 13)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 14)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 15)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 16)).to eq(super_result)
+ expect(find_definition_under_position(file, 2, 17)).to eq(nil)
+ end
+
+ specify "twisted backtracing method case" do
+ file = <<-END
+ class Foo
+ def bar
+ def baz
+ super
+ end
+
+ super
+ end
+ end
+ END
+
+ expected_nesting = Nesting
+ .empty
+ .increase_nesting_const(ConstRef.from_full_name("Foo", Nesting.empty))
+ super_result = FindDefinitionUnderPosition::SuperResult.new(expected_nesting, :baz)
+ expect(find_definition_under_position(file, 3, 17)).to eq(super_result)
+
+ super_result = FindDefinitionUnderPosition::SuperResult.new(expected_nesting, :bar)
+ expect(find_definition_under_position(file, 6, 15)).to eq(super_result)
+ end
+ end
+
specify "check that error would be raised if wrong ast returned" do
finder = FindDefinitionUnderPosition.new(RubyParser.new)
expect(finder).to receive(:on_const).and_return(Parser::AST::Node.new(:const, [:something, :else]))
|
Add ability to find definition as super keyword
|
swistak35_orbacle
|
train
|
507738a70634316656a019b1c1cd9fed11a544ef
|
diff --git a/src/CodeMojo/Client/Services/LoyaltyService.php b/src/CodeMojo/Client/Services/LoyaltyService.php
index <HASH>..<HASH> 100644
--- a/src/CodeMojo/Client/Services/LoyaltyService.php
+++ b/src/CodeMojo/Client/Services/LoyaltyService.php
@@ -53,8 +53,17 @@ class LoyaltyService
* @throws \CodeMojo\OAuth2\Exception
*/
public function addLoyaltyPoints($user_id, $transaction_value, $platform = null, $expires_in_days = null, $transaction_id = null, $meta = null, $frozen = false){
- $result = $this->calculateLoyaltyPoints($user_id, $transaction_value, $platform, $expires_in_days, $transaction_id, $meta, $frozen);
- if(!empty($result)) {
+ $url = $this->authenticationService->getServerEndPoint() . Endpoints::VERSION . Endpoints::BASE_LOYALTY . Endpoints::LOYALTY_CALCULATE;
+
+ $params = array(
+ "customer_id" => $user_id, "value" => $transaction_value,
+ "expiry" => $expires_in_days, "platform" => $platform
+ );
+
+ $result = $this->authenticationService->getTransport()->fetch($url, $params,'PUT', array(), 0);
+
+ if($result['code'] == 200 && !empty($result['results'])) {
+ $result = $result['results'];
return $this->walletService->addBalance($user_id, $result['award'], @$result['expires_in_days'],
$transaction_id ? $transaction_id : 'loyalty_' . $result['id'] . '_' . time(), $meta, "Loyalty points credited", $frozen);
}
|
Critical fix for Loyalty layer meta data
Adding points to Loyalty from the previous added in the wallet but not
in the Loyalty layer due to misconfiguration on the SDK side.
|
codemojo-dr_startkit-php-sdk
|
train
|
ec663b75801b80fda14075b628fe3652529bcc96
|
diff --git a/lib/invoke.js b/lib/invoke.js
index <HASH>..<HASH> 100644
--- a/lib/invoke.js
+++ b/lib/invoke.js
@@ -26,7 +26,7 @@ module.exports = (config, params) => {
)
} else {
throw new Error(
- `Failed to invoke function ${params.functionId} and couldn't parse error message.`
+ `Failed to invoke function ${params.functionId} and couldn't parse error body.`
)
}
})
diff --git a/lib/listFunctions.js b/lib/listFunctions.js
index <HASH>..<HASH> 100644
--- a/lib/listFunctions.js
+++ b/lib/listFunctions.js
@@ -5,8 +5,20 @@ module.exports = config =>
.fetch(urlUtils.joinUrlWithPath(config.configurationUrl, '/v1/functions'))
.then(response => {
if (response.status !== 200) {
- // TODO improve throwed errors
- throw new Error('Failed to fetch the functions.')
+ let errorMessage = null
+ return response
+ .json()
+ .then(error => {
+ errorMessage = error.error
+ throw new Error(`Internal rethrow of ${error}`)
+ })
+ .catch(() => {
+ if (errorMessage) {
+ throw new Error(`Failed to fetch the function list due the error: ${errorMessage}`)
+ } else {
+ throw new Error("Failed to fetch the function list and couldn't parse error body.")
+ }
+ })
}
return response.json()
})
diff --git a/lib/listSubscriptions.js b/lib/listSubscriptions.js
index <HASH>..<HASH> 100644
--- a/lib/listSubscriptions.js
+++ b/lib/listSubscriptions.js
@@ -5,8 +5,24 @@ module.exports = config =>
.fetch(urlUtils.joinUrlWithPath(config.configurationUrl, '/v1/subscriptions'))
.then(response => {
if (response.status !== 200) {
- // TODO improve throwed errors
- throw new Error('Failed to fetch the functions.')
+ let errorMessage = null
+ return response
+ .json()
+ .then(error => {
+ errorMessage = error.error
+ throw new Error(`Internal rethrow of ${error}`)
+ })
+ .catch(() => {
+ if (errorMessage) {
+ throw new Error(
+ `Failed to fetch the subscriptions list due the error: ${errorMessage}`
+ )
+ } else {
+ throw new Error(
+ "Failed to fetch the subscriptions list and couldn't parse error body."
+ )
+ }
+ })
}
return response.json()
})
diff --git a/lib/registerFunction.js b/lib/registerFunction.js
index <HASH>..<HASH> 100644
--- a/lib/registerFunction.js
+++ b/lib/registerFunction.js
@@ -24,7 +24,7 @@ module.exports = (config, params) =>
)
} else {
throw new Error(
- `Failed to register the function ${funcId} and couldn't parse error message.`
+ `Failed to register the function ${funcId} and couldn't parse error body.`
)
}
})
|
improve error handling for listing functions and subscriptions
|
serverless_event-gateway-sdk
|
train
|
9913c3a44e0e12018e68268de91f53c84f3ea82d
|
diff --git a/phy/cluster/manual/clustering.py b/phy/cluster/manual/clustering.py
index <HASH>..<HASH> 100644
--- a/phy/cluster/manual/clustering.py
+++ b/phy/cluster/manual/clustering.py
@@ -113,6 +113,10 @@ class Clustering(object):
"""Number of different clusters."""
return len(self.cluster_labels)
+ def spikes_in_clusters(self, clusters):
+ """Return the spikes belonging to a set of clusters."""
+ return _spikes_in_clusters(self.spike_clusters, clusters)
+
# Actions
#--------------------------------------------------------------------------
diff --git a/phy/cluster/manual/tests/test_clustering.py b/phy/cluster/manual/tests/test_clustering.py
index <HASH>..<HASH> 100644
--- a/phy/cluster/manual/tests/test_clustering.py
+++ b/phy/cluster/manual/tests/test_clustering.py
@@ -75,6 +75,9 @@ def test_clustering():
clustering = Clustering(spike_clusters)
ae(clustering.spike_clusters, spike_clusters)
+ # Test clustering.spikes_in_clusters() function.:
+ assert np.all(spike_clusters[clustering.spikes_in_clusters([5])] == 5)
+
# Test cluster labels.
ae(clustering.cluster_labels, np.arange(n_clusters))
|
Added clustering.spikes_in_clusters() method.
|
kwikteam_phy
|
train
|
d34c835a18a7975690e6f8023041261a4295e63b
|
diff --git a/src/test/java/org/cactoos/map/MapEnvelopeTest.java b/src/test/java/org/cactoos/map/MapEnvelopeTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/cactoos/map/MapEnvelopeTest.java
+++ b/src/test/java/org/cactoos/map/MapEnvelopeTest.java
@@ -23,6 +23,7 @@
*/
package org.cactoos.map;
+import java.util.HashMap;
import java.util.Map;
import org.cactoos.func.FuncOf;
import org.hamcrest.MatcherAssert;
@@ -317,14 +318,43 @@ public final class MapEnvelopeTest {
@Test
@SuppressWarnings("unchecked")
+ public void emptyMapEnvelopeShouldBeEqualToEmptyDerivedMap() {
+ final MapEnvelope<Integer, String> base = new MapOf<>();
+ final DerivedMapEnvelope<Integer, String> derived =
+ new DerivedMapEnvelope<>(new HashMap<>());
+ new Assertion<>(
+ "EmpBase and derived MapEnvelope which are empty should be equal.",
+ () -> base,
+ new IsEqual<>(derived)
+ ).affirm();
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
public void mapEnvelopeShouldCompareDerivedClasses() {
- final MapEntry<Integer, String> entry = new MapEntry<>(1, "one");
+ final int key = 1;
+ final String value = "one";
+ final MapEntry<Integer, String> entry = new MapEntry<>(key, value);
final MapEnvelope<Integer, String> base = new MapOf<>(entry);
- final Solid<Integer, String> derived = new Solid<>(entry);
+ final Map<Integer, String> hashmap = new HashMap<>();
+ hashmap.put(key, value);
+ final DerivedMapEnvelope<Integer, String> derived =
+ new DerivedMapEnvelope<>(hashmap);
new Assertion<>(
"Base and derived MapEnvelope of same content should be equal.",
() -> base,
new IsEqual<>(derived)
- );
+ ).affirm();
+ }
+
+ /**
+ * Class derived from MapEnvelope to use in some tests.
+ * @param <K> - key type
+ * @param <V> - value type
+ */
+ private static class DerivedMapEnvelope<K, V> extends MapEnvelope<K, V> {
+ DerivedMapEnvelope(final Map<K, V> content) {
+ super(() -> content);
+ }
}
}
|
(#<I>) PR comment fix, refactoring
Inner `DerivedMapEnvelope` class introduced.
`Assertion.affirm()` call added.
Test `emptyMapEnvelopeShouldBeEqualToEmptyDerivedMap` added
|
yegor256_cactoos
|
train
|
62708ba7fc50c00944ff3e8b5fa7d59effe00aee
|
diff --git a/test_twarc2.py b/test_twarc2.py
index <HASH>..<HASH> 100644
--- a/test_twarc2.py
+++ b/test_twarc2.py
@@ -7,6 +7,8 @@ import logging
import datetime
import threading
+import pytest
+
dotenv.load_dotenv()
consumer_key = os.environ.get('CONSUMER_KEY')
consumer_secret = os.environ.get('CONSUMER_SECRET')
@@ -16,18 +18,53 @@ access_token_secret = os.environ.get('ACCESS_TOKEN_SECRET')
logging.basicConfig(filename="test.log", level=logging.INFO)
-# Implicitly test the constructor. This ensures that the tests don't depend on test
-# ordering, and allows using the pytest functionality to only run a single test at a
-# time.
-
+# Implicitly test the constructor in application auth mode. This ensures that the tests
+# don't depend on test ordering, and allows using the pytest functionality to only run a
+# single test at a time.
T = twarc.Twarc2(
- consumer_key,
- consumer_secret,
- access_token,
- access_token_secret
+ consumer_key=consumer_key,
+ consumer_secret=consumer_secret,
)
+def test_auth_types_interaction():
+ """Test the various options for configuration work as expected."""
+ # 1. bearer_token auth -> app auth
+ tw = twarc.Twarc2(bearer_token=bearer_token)
+ assert tw.auth_type == "application"
+
+ for response in tw.user_lookup(range(1, 101)):
+ assert response["data"]
+
+ tw.client.close()
+
+ # 2. consumer_keys
+ tw = twarc.Twarc2(consumer_key=consumer_key, consumer_secret=consumer_secret)
+ assert tw.auth_type == "application"
+
+ for response in tw.user_lookup(range(1, 101)):
+ assert response["data"]
+
+ tw.client.close()
+
+ # 3. Full user auth
+ tw = twarc.Twarc2(
+ access_token=access_token,
+ access_token_secret=access_token_secret,
+ consumer_key=consumer_key,
+ consumer_secret=consumer_secret
+ )
+ assert tw.auth_type == "user"
+
+ for response in tw.user_lookup(range(1, 101)):
+ assert response["data"]
+
+ tw.client.close()
+
+ with pytest.raises(twarc.client2.InvalidAuthType):
+ tw.sample()
+
+
def test_sample():
count = 0
@@ -49,12 +86,12 @@ def test_sample():
assert count == 11
-def test_search():
+def test_recent_search():
found_tweets = 0
pages = 0
- for response_page in T.search("#auspol"):
+ for response_page in T.recent_search("#auspol"):
pages += 1
tweets = response_page["data"]
found_tweets += len(tweets)
@@ -73,7 +110,7 @@ def test_search_times():
end = now - datetime.timedelta(seconds=60)
start = now - datetime.timedelta(seconds=61)
- for response_page in T.search("tweet", start_time=start,
+ for response_page in T.recent_search("tweet", start_time=start,
end_time=end):
for tweet in response_page["data"]:
found = True
|
Update client tests to consider different approaches to app and user auth
|
DocNow_twarc
|
train
|
3133a0cca9a68498a7c3f9a463b89adbcc64e9d6
|
diff --git a/auto_ml/_version.py b/auto_ml/_version.py
index <HASH>..<HASH> 100644
--- a/auto_ml/_version.py
+++ b/auto_ml/_version.py
@@ -1 +1 @@
-__version__ = "2.4.0"
+__version__ = "2.4.1"
|
<I> for catboost support
|
ClimbsRocks_auto_ml
|
train
|
4b4ffa5c7578e74bc495bba8dc3028c7fb0ce49a
|
diff --git a/lib/celluloid/actor.rb b/lib/celluloid/actor.rb
index <HASH>..<HASH> 100644
--- a/lib/celluloid/actor.rb
+++ b/lib/celluloid/actor.rb
@@ -149,17 +149,7 @@ module Celluloid
def run
begin
while @running
- begin
- message = @mailbox.receive(timeout)
- rescue ExitEvent => exit_event
- Task.new(:exit_handler) { handle_exit_event exit_event }.resume
- retry
- rescue NamingRequest => ex
- @name = ex.name
- retry
- rescue TerminationRequest
- break
- end
+ message = @mailbox.receive(timeout)
if message
handle_message message
@@ -169,6 +159,9 @@ module Celluloid
@receivers.fire_timers
end
end
+ rescue SystemEvent => event
+ handle_system_event event
+ retry
rescue MailboxShutdown
# If the mailbox detects shutdown, exit the actor
end
@@ -218,7 +211,7 @@ module Celluloid
end
end
- # Handle an incoming message
+ # Handle standard low-priority messages
def handle_message(message)
case message
when Call
@@ -231,6 +224,18 @@ module Celluloid
message
end
+ # Handle high-priority system event messages
+ def handle_system_event(event)
+ case event
+ when ExitEvent
+ Task.new(:exit_handler) { handle_exit_event event }.resume
+ when NamingRequest
+ @name = event.name
+ when TerminationRequest
+ @running = false
+ end
+ end
+
# Handle exit events received by this actor
def handle_exit_event(exit_event)
exit_handler = @subject.class.exit_handler
|
Factor system event handling into handle_system_event
|
celluloid_celluloid
|
train
|
7f33558714877d72a21c27e88fe140f264c9e7c9
|
diff --git a/swagger/model_builder.go b/swagger/model_builder.go
index <HASH>..<HASH> 100644
--- a/swagger/model_builder.go
+++ b/swagger/model_builder.go
@@ -43,6 +43,12 @@ func (b modelBuilder) addModelFrom(sample interface{}) {
}
func (b modelBuilder) addModel(st reflect.Type, nameOverride string) *Model {
+ // Turn pointers into simpler types so further checks are
+ // correct.
+ if st.Kind() == reflect.Ptr {
+ st = st.Elem()
+ }
+
modelName := b.keyFrom(st)
if nameOverride != "" {
modelName = nameOverride
diff --git a/swagger/model_builder_test.go b/swagger/model_builder_test.go
index <HASH>..<HASH> 100644
--- a/swagger/model_builder_test.go
+++ b/swagger/model_builder_test.go
@@ -860,7 +860,7 @@ func TestRegion_Issue113(t *testing.T) {
"||swagger.Region": {
"id": "||swagger.Region",
"properties": {}
- },
+ },
"swagger.Region": {
"id": "swagger.Region",
"required": [
@@ -921,6 +921,25 @@ func TestIssue158(t *testing.T) {
testJsonFromStruct(t, Customer{}, expected)
}
+func TestPointers(t *testing.T) {
+ type Vote struct {
+ What YesNo
+ }
+ testJsonFromStruct(t, &Vote{}, `{
+ "swagger.Vote": {
+ "id": "swagger.Vote",
+ "required": [
+ "What"
+ ],
+ "properties": {
+ "What": {
+ "type": "string"
+ }
+ }
+ }
+ }`)
+}
+
func TestSlices(t *testing.T) {
type Address struct {
Country string `json:"country,omitempty"`
|
Accept pointers passed to model builder for swagger
From a model perspective we treat "type.Struct" and "*type.Struct"
identically when nested, but if "*type.Struct" is passed to go-restful
via .Writes(). Since these are expected to be models, this is more
friendly to integrators.
|
emicklei_go-restful
|
train
|
b4fa17721a1aa5518143dfdd12c082ac7bfab465
|
diff --git a/Kwc/Form/Dynamic/Admin.php b/Kwc/Form/Dynamic/Admin.php
index <HASH>..<HASH> 100644
--- a/Kwc/Form/Dynamic/Admin.php
+++ b/Kwc/Form/Dynamic/Admin.php
@@ -30,6 +30,9 @@ class Kwc_Form_Dynamic_Admin extends Kwc_Abstract_Composite_Admin
foreach ($components as $c) {
$t = $c->getTitle();
if (!$t) $t = $c->getPage()->name;
+ if ($domain = $c->getParentByClass('Kwc_Root_DomainRoot_Domain_Component')) {
+ $t .= " - $domain->name";
+ }
$t = $name .' ('.$t.')';
$menuUrl = Kwc_Admin::getInstance($c->componentClass)
->getControllerUrl('Enquiries') . '?componentId=' . $c->dbId;
diff --git a/Kwf/Component/Abstract/MenuConfig/SameClass.php b/Kwf/Component/Abstract/MenuConfig/SameClass.php
index <HASH>..<HASH> 100644
--- a/Kwf/Component/Abstract/MenuConfig/SameClass.php
+++ b/Kwf/Component/Abstract/MenuConfig/SameClass.php
@@ -20,6 +20,9 @@ class Kwf_Component_Abstract_MenuConfig_SameClass extends Kwf_Component_Abstract
foreach ($components as $c) {
$t = $c->getTitle();
if (!$t) $t = $name;
+ if ($domain = $c->getParentByClass('Kwc_Root_DomainRoot_Domain_Component')) {
+ $t .= " ($domain->name)";
+ }
$acl->add(
new Kwf_Acl_Resource_Component_MenuUrl(
$c, array('text'=>$t, 'icon'=>$icon)
|
add domain name to resource name if domains are used
else it can happen that there non unique names
|
koala-framework_koala-framework
|
train
|
4b652fdfe9eb37095b58f909406654e33895d5dd
|
diff --git a/src/feat/agents/host/host_agent.py b/src/feat/agents/host/host_agent.py
index <HASH>..<HASH> 100644
--- a/src/feat/agents/host/host_agent.py
+++ b/src/feat/agents/host/host_agent.py
@@ -845,7 +845,7 @@ class StartAgentContractor(contractor.BaseContractor):
@replay.immutable
def _starting_failed(self, state, fail):
error.handle_failure(self, fail, 'Starting failed, cancelling')
- msg = message.Cancellation(reason=fail)
+ msg = message.Cancellation(reason=str(fail))
f = fiber.succeed()
f.add_callback(fiber.drop_param, self._release_allocation)
f.add_callback(fiber.drop_param, state.medium.defect,
|
When host agent fails to start the agent, don't send the actual failure
to the other side. Only send the error message.
|
f3at_feat
|
train
|
6808b47a8a199b756b36dafd2dc14ed418606fe1
|
diff --git a/includes/class-theme-updater.php b/includes/class-theme-updater.php
index <HASH>..<HASH> 100644
--- a/includes/class-theme-updater.php
+++ b/includes/class-theme-updater.php
@@ -84,7 +84,7 @@ class GitHub_Theme_Updater extends GitHub_Updater {
$response->homepage = $theme->uri;
$response->version = $theme->remote_version;
$response->sections = $theme->sections;
- $response->description = $theme->sections['description'];
+ $response->description = implode( "\n", $theme->sections );
$response->author = $theme->author;
$response->preview_url = $theme->sections['changelog'];
$response->requires = $theme->requires;
|
combine description and change log in theme view details, multisite only
|
afragen_github-updater
|
train
|
1273d7ddeee92152898eaa5f2ac0edd533bd5913
|
diff --git a/lib/weblib.php b/lib/weblib.php
index <HASH>..<HASH> 100644
--- a/lib/weblib.php
+++ b/lib/weblib.php
@@ -2957,6 +2957,16 @@ function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $force
}
}
+ if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
+ if ($reports = get_list_of_plugins('grade/report')) {
+ foreach ($reports as $report) {
+ if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
+ $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
+ }
+ }
+ }
+ }
+
if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
$files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
|
support for styles.php in grade reports
|
moodle_moodle
|
train
|
91d6fd4e04b0ef35ffe33b0a1da000cc1890fab0
|
diff --git a/lib/compact_index/gem_version.rb b/lib/compact_index/gem_version.rb
index <HASH>..<HASH> 100644
--- a/lib/compact_index/gem_version.rb
+++ b/lib/compact_index/gem_version.rb
@@ -14,7 +14,7 @@ module CompactIndex
number_comp = number <=> other.number
if number_comp.zero?
- [number, platform] <=> [other.number, other.platform]
+ [number, platform].compact <=> [other.number, other.platform].compact
else
number_comp
end
|
remove nil before comparison
value of platform was nil cause we are building version in test with
build_version(:number => "<I>") # if platform is not passed it is
set to nil
|
bundler_compact_index
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.