hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
395fcec5a72b7c976c3e8c480e4ec75848edd356 | diff --git a/packages/median/median.js b/packages/median/median.js
index <HASH>..<HASH> 100644
--- a/packages/median/median.js
+++ b/packages/median/median.js
@@ -37,40 +37,27 @@ let get_median = values => {
function get_median_for_raster(georaster, geom) {
try {
+
+ let geom_is_bbox = utils.is_bbox(geom);
- if (utils.is_bbox(geom)) {
- geom = convert_geometry('bbox', geom);
+ if (geom === null || geom === undefined || geom_is_bbox) {
- // grab array of values;
- let flat = false; // get values as a one dimensional flat array rather than as a table
- let values = get(georaster, geom, flat);
- //console.log("values:", values.length, values[0].length, values[0][0].length);
- let no_data_value = georaster.no_data_value;
+ if (geom_is_bbox) {
+
+ geom = convert_geometry('bbox', geom);
+
+ }
- // get median
- //return values
- // .map(band => band.filter(value => value !== no_data_value))
- // .map(get_median);
+ let values = get(georaster, geom);
+
+ let no_data_value = georaster.no_data_value;
// median values
let medians = []
for (let band_index = 0; band_index < values.length; band_index++) {
let band = values[band_index];
- let number_of_cells_with_values_in_band = 0;
- let number_of_rows = band.length;
- let counts = {};
- for (let row_index = 0; row_index < number_of_rows; row_index++) {
- let row = band[row_index];
- let number_of_cells = row.length;
- for (let column_index = 0; column_index < number_of_cells; column_index++) {
- let value = row[column_index];
- if (value !== no_data_value) {
- number_of_cells_with_values_in_band++;
- if (value in counts) counts[value]++;
- else counts[value] = 1;
- }
- }
- }
+ let counts = utils.count_values_in_table(band, no_data_value);
+ let number_of_cells_with_values_in_band = utils.sum(_.values(counts));
let sorted_counts = _.pairs(counts).sort((pair1, pair2) => Number(pair1[0]) - Number(pair2[0]));
//console.log("sorted_counts:", sorted_counts);
let middle = number_of_cells_with_values_in_band / 2; | replaced some code in median with calls to new utils functions and allow user to get median of whole raster | GeoTIFF_geoblaze | train |
e9bcc96ad27c3e583c6a417ddea6d204765e1ef1 | diff --git a/docs/client/repository_test.go b/docs/client/repository_test.go
index <HASH>..<HASH> 100644
--- a/docs/client/repository_test.go
+++ b/docs/client/repository_test.go
@@ -610,7 +610,7 @@ func addTestManifestWithEtag(repo, reference string, content []byte, m *testutil
*m = append(*m, testutil.RequestResponseMapping{Request: getReqWithEtag, Response: getRespWithEtag})
}
-func addTestManifest(repo, reference string, content []byte, m *testutil.RequestResponseMap) {
+func addTestManifest(repo, reference string, mediatype string, content []byte, m *testutil.RequestResponseMap) {
*m = append(*m, testutil.RequestResponseMapping{
Request: testutil.Request{
Method: "GET",
@@ -622,7 +622,7 @@ func addTestManifest(repo, reference string, content []byte, m *testutil.Request
Headers: http.Header(map[string][]string{
"Content-Length": {fmt.Sprint(len(content))},
"Last-Modified": {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
- "Content-Type": {schema1.MediaTypeSignedManifest},
+ "Content-Type": {mediatype},
}),
},
})
@@ -636,7 +636,7 @@ func addTestManifest(repo, reference string, content []byte, m *testutil.Request
Headers: http.Header(map[string][]string{
"Content-Length": {fmt.Sprint(len(content))},
"Last-Modified": {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
- "Content-Type": {schema1.MediaTypeSignedManifest},
+ "Content-Type": {mediatype},
}),
},
})
@@ -678,8 +678,9 @@ func TestV1ManifestFetch(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- addTestManifest(repo, dgst.String(), pl, &m)
- addTestManifest(repo, "latest", pl, &m)
+ addTestManifest(repo, dgst.String(), schema1.MediaTypeSignedManifest, pl, &m)
+ addTestManifest(repo, "latest", schema1.MediaTypeSignedManifest, pl, &m)
+ addTestManifest(repo, "badcontenttype", "text/html", pl, &m)
e, c := testServer(m)
defer c()
@@ -726,6 +727,19 @@ func TestV1ManifestFetch(t *testing.T) {
if err = checkEqualManifest(v1manifest, m1); err != nil {
t.Fatal(err)
}
+
+ manifest, err = ms.Get(ctx, dgst, WithTag("badcontenttype"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v1manifest, ok = manifest.(*schema1.SignedManifest)
+ if !ok {
+ t.Fatalf("Unexpected manifest type from Get: %T", manifest)
+ }
+
+ if err = checkEqualManifest(v1manifest, m1); err != nil {
+ t.Fatal(err)
+ }
}
func TestManifestFetchWithEtag(t *testing.T) { | If the media type for a manifest is unrecognized, default to schema1
This is needed for compatibility with some third-party registries that
send an inappropriate Content-Type header such as text/html. | docker_distribution | train |
2fe2d7bb4ff7d1c65b61570ac4cd3f294f214fec | diff --git a/handlers/email/email.go b/handlers/email/email.go
index <HASH>..<HASH> 100644
--- a/handlers/email/email.go
+++ b/handlers/email/email.go
@@ -45,6 +45,7 @@ type Email struct {
password string
from string
to []string
+ send bool
rw sync.RWMutex
once sync.Once
}
@@ -59,6 +60,7 @@ func New(host string, port int, username string, password string, from string, t
password: password,
from: from,
to: to,
+ send: true,
formatFunc: defaultFormatFunc,
}
e.SetTemplate(defaultTemplate)
@@ -67,6 +69,9 @@ func New(host string, port int, username string, password string, from string, t
// SetTemplate sets Email's html template to be used for email body
func (email *Email) SetTemplate(htmlTemplate string) {
+ email.rw.Lock()
+ defer email.rw.Unlock()
+
// parse email htmlTemplate, will panic if fails
email.template = template.Must(template.New("email").Funcs(
template.FuncMap{
@@ -96,12 +101,18 @@ func (email *Email) Template() *template.Template {
// SetTimestampFormat sets Email's timestamp output format
// Default is : "2006-01-02T15:04:05.000000000Z07:00"
func (email *Email) SetTimestampFormat(format string) {
+ email.rw.Lock()
+ defer email.rw.Unlock()
+
email.timestampFormat = format
}
// SetFormatFunc sets FormatFunc each worker will call to get
// a Formatter func
func (email *Email) SetFormatFunc(fn FormatFunc) {
+ email.rw.Lock()
+ defer email.rw.Unlock()
+
email.formatFunc = fn
}
@@ -119,6 +130,14 @@ func (email *Email) SetEmailConfig(host string, port int, username string, passw
email.formatter = email.formatFunc(email)
}
+// SetSend enables or disables the email handler sending emails
+func (email *Email) SetSend(send bool) {
+ email.rw.Lock()
+ defer email.rw.Unlock()
+
+ email.send = send
+}
+
func defaultFormatFunc(email *Email) Formatter {
b := new(bytes.Buffer)
@@ -146,6 +165,9 @@ func defaultFormatFunc(email *Email) Formatter {
// Log handles the log entry
func (email *Email) Log(e log.Entry) {
+ if !email.send {
+ return
+ }
email.once.Do(func() {
email.formatter = email.formatFunc(email)
})
diff --git a/handlers/email/email_test.go b/handlers/email/email_test.go
index <HASH>..<HASH> 100644
--- a/handlers/email/email_test.go
+++ b/handlers/email/email_test.go
@@ -104,6 +104,7 @@ func TestEmailHandler(t *testing.T) {
email.SetTimestampFormat("MST")
email.SetTemplate(defaultTemplate)
email.SetEmailConfig("localhost", 3041, "", "", "[email protected]", []string{"[email protected]"})
+ email.SetSend(true)
// email.SetFormatFunc(testFormatFunc)
log.AddHandler(email, log.InfoLevel, log.DebugLevel) | handlers/email: Ability to toggle sending emails or not | go-playground_log | train |
dc21daf21d97738a7ce2062afef24db678abdb2f | diff --git a/src/main/java/dtest/mobileactions/WaitForCondition.java b/src/main/java/dtest/mobileactions/WaitForCondition.java
index <HASH>..<HASH> 100644
--- a/src/main/java/dtest/mobileactions/WaitForCondition.java
+++ b/src/main/java/dtest/mobileactions/WaitForCondition.java
@@ -11,7 +11,7 @@ public class WaitForCondition extends MobileTestAction {
By locator = readLocatorArgument("locator");
String condition = readStringArgument("condition");
- int timeout = readIntArgument("timeout", 180);
+ int timeout = readIntArgument("timeout", 60);
System.out.println(String.format("Waiting for condition %s on %s",
condition, | Changed wait time from <I> to <I> in WaitForCondition | mcdcorp_opentest | train |
b4224161b7c4337c158b16e41e6874f3d451ceb1 | diff --git a/internal/signer/v4/v4.go b/internal/signer/v4/v4.go
index <HASH>..<HASH> 100644
--- a/internal/signer/v4/v4.go
+++ b/internal/signer/v4/v4.go
@@ -231,7 +231,7 @@ func (v4 *signer) buildCanonicalHeaders() {
}
func (v4 *signer) buildCanonicalString() {
- v4.Request.URL.RawQuery = v4.Query.Encode()
+ v4.Request.URL.RawQuery = strings.Replace(v4.Query.Encode(), "+", "%20", -1)
uri := v4.Request.URL.Opaque
if uri != "" {
uri = "/" + strings.Join(strings.Split(uri, "/")[3:], "/") | signer/v4: Encode "+" to "%<I>"
Query.Encode() will replace " " with "+", but the v4 spec calls for
replacing " " with "%<I>" instead.
Fixes #<I> | aws_aws-sdk-go | train |
9729981889890d5325c39025b47af59946279159 | diff --git a/pyang/yang_parser.py b/pyang/yang_parser.py
index <HASH>..<HASH> 100644
--- a/pyang/yang_parser.py
+++ b/pyang/yang_parser.py
@@ -26,7 +26,7 @@ class YangTokenizer(object):
self.pos.line += 1
self.offset = 0
if (self.max_line_len is not None and
- len(self.buf) > self.max_line_len):
+ len(unicode(self.buf, encoding="utf-8")) > self.max_line_len):
error.err_add(self.errors, self.pos, 'LONG_LINE',
(len(self.buf), self.max_line_len)) | Parser: fix wrong line length measurement
It didn't work for lines containing non-ASCII Unicode characters. | mbj4668_pyang | train |
75d91eba11daef2d48de6c3de74bb1273de3824d | diff --git a/src/cli/validate.js b/src/cli/validate.js
index <HASH>..<HASH> 100644
--- a/src/cli/validate.js
+++ b/src/cli/validate.js
@@ -1,3 +1,5 @@
+/* eslint-disable no-console */
+
import { existsSync, readFileSync } from 'fs';
import chalk from 'chalk'; | Allow console.log in cli tools | DirektoratetForByggkvalitet_losen | train |
beca1fde2cedbe590d4a634a8333ee105f49581b | diff --git a/tests/parser/syntax/test_msg_data.py b/tests/parser/syntax/test_msg_data.py
index <HASH>..<HASH> 100644
--- a/tests/parser/syntax/test_msg_data.py
+++ b/tests/parser/syntax/test_msg_data.py
@@ -2,7 +2,7 @@ import pytest
from eth_tester.exceptions import TransactionFailed
from vyper import compiler
-from vyper.exceptions import StateAccessViolation, SyntaxException
+from vyper.exceptions import StateAccessViolation, SyntaxException, TypeMismatch
def test_variable_assignment(get_contract, keccak):
@@ -48,6 +48,36 @@ def foo(bar: uint256) -> Bytes[36]:
assert contract.foo(42).hex() == expected_result
+def test_memory_pointer_advances_appropriately(get_contract, keccak):
+ code = """
+@external
+def foo() -> (uint256, Bytes[4], uint256):
+ a: uint256 = MAX_UINT256
+ b: Bytes[4] = slice(msg.data, 0, 4)
+ c: uint256 = MAX_UINT256
+
+ return (a, b, c)
+"""
+ contract = get_contract(code)
+
+ assert contract.foo() == [2 ** 256 - 1, bytes(keccak(text="foo()")[:4]), 2 ** 256 - 1]
+
+
+def test_assignment_to_storage(w3, get_contract, keccak):
+ code = """
+cache: public(Bytes[4])
+
+@external
+def foo():
+ self.cache = slice(msg.data, 0, 4)
+"""
+ acct = w3.eth.accounts[0]
+ contract = get_contract(code)
+
+ contract.foo(transact={"from": acct})
+ assert contract.cache() == bytes(keccak(text="foo()")[:4])
+
+
def test_get_len(get_contract):
code = """
@external
@@ -95,6 +125,15 @@ def foo() -> Bytes[4]:
""",
StateAccessViolation,
),
+ (
+ """
+@external
+def foo(bar: uint256) -> bytes32:
+ ret_val: bytes32 = slice(msg.data, 4, 32)
+ return ret_val
+ """,
+ TypeMismatch,
+ ),
] | test: additional cases for msg.data
- Assignment to storage
- Free memory pointer correctly goes to next position
- TypeMismatch Error for assignment to bytes<I> | ethereum_vyper | train |
a4ab5d9106e83438f64eb84919b14d20013ab9b2 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@
* Improved language overrides to merge only 'extra' translations [#1514](https://github.com/getgrav/grav/issues/1514)
* Improved support for Assets with query strings [#1451](https://github.com/getgrav/grav/issues/1451)
1. [](#bugfix)
+ * Fixed an issue where fallback was not supporting dynamic page generation
* Fixed issue with Image query string not being fully URL encoded [#1622](https://github.com/getgrav/grav/issues/1622)
* Fixed `Page::summary()` when using delimiter and multibyte UTF8 Characters [#1644](https://github.com/getgrav/grav/issues/1644)
* Fixed missing `.json` thumbnail throwing error when adding media [grav-plugin-admin#1156](https://github.com/getgrav/grav-plugin-admin/issues/1156)
diff --git a/system/src/Grav/Common/Grav.php b/system/src/Grav/Common/Grav.php
index <HASH>..<HASH> 100644
--- a/system/src/Grav/Common/Grav.php
+++ b/system/src/Grav/Common/Grav.php
@@ -500,5 +500,7 @@ class Grav extends Container
Utils::download($page->path() . DIRECTORY_SEPARATOR . $uri->basename(), $download);
}
}
+
+ return $page;
}
}
diff --git a/system/src/Grav/Common/Service/PageServiceProvider.php b/system/src/Grav/Common/Service/PageServiceProvider.php
index <HASH>..<HASH> 100644
--- a/system/src/Grav/Common/Service/PageServiceProvider.php
+++ b/system/src/Grav/Common/Service/PageServiceProvider.php
@@ -86,7 +86,7 @@ class PageServiceProvider implements ServiceProviderInterface
if (!$page || !$page->routable()) {
// Try fallback URL stuff...
- $c->fallbackUrl($path);
+ $page = $c->fallbackUrl($path);
if (!$page) {
$path = $c['locator']->findResource('system://pages/notfound.md');
@@ -94,7 +94,6 @@ class PageServiceProvider implements ServiceProviderInterface
$page->init(new \SplFileInfo($path));
$page->routable(false);
}
-
}
return $page; | Fixed an issue where fallback was not supporting dynamic page generation | getgrav_grav | train |
90dcbff83aecbee381a1c89f4dafc5379076e016 | diff --git a/speculator/features/so.py b/speculator/features/so.py
index <HASH>..<HASH> 100644
--- a/speculator/features/so.py
+++ b/speculator/features/so.py
@@ -24,7 +24,10 @@ def eval_algorithm(closing, low, high):
Returns:
Float SO between 0 and 100.
"""
- return 100 * (closing - low) / (high - low)
+ try:
+ return 100 * (closing - low) / (high - low)
+ except ZeroDivisionError: # High and low are the same
+ return 100 * (closing - low)
def get_poloniex(*args):
""" Gets SO of a currency pair from Poloniex.com exchange | Fix stochastic oscillator bug
When the high and low prices were the same, a ZeroDivisionError exception was raised. | amicks_Speculator | train |
8a16f4b7c2794692bbce214f0844f086122d3efd | diff --git a/src/ai/backend/client/cli/session.py b/src/ai/backend/client/cli/session.py
index <HASH>..<HASH> 100644
--- a/src/ai/backend/client/cli/session.py
+++ b/src/ai/backend/client/cli/session.py
@@ -531,6 +531,7 @@ def upload(session_id, files):
FILES: One or more paths to upload.
"""
if len(files) < 1:
+ print_warn("Please specify one or more file paths after session ID or name.")
return
with Session() as session:
try:
@@ -563,7 +564,7 @@ def download(session_id, files, dest):
FILES: One or more paths inside compute session.
"""
if len(files) < 1:
- print_warn("Please specify one or more file paths.")
+ print_warn("Please specify one or more file paths after session ID or name.")
return
with Session() as session:
try: | fix: A follow-up to be<I>d7 (#<I>) | lablup_backend.ai-client-py | train |
cd66465b5c58af8e488325a24ad1f23b6e97993c | diff --git a/tests/client.py b/tests/client.py
index <HASH>..<HASH> 100644
--- a/tests/client.py
+++ b/tests/client.py
@@ -28,6 +28,7 @@ class ClientBasicsTestCase(unittest2.TestCase):
self.assertEqual(client.host, 'example.com')
self.assertEqual(client.port, 8888)
self.assertEqual(client.prefix, 'pystatsd.tests')
+ self.assertEqual(client.addr, self.addr)
def test_basic_client_incr(self):
stat = 'pystatsd.unittests.test_basic_client_incr' | Also make sure client.addr is tested | sivy_pystatsd | train |
a00f28cde51ec76cac0445d37a22db567867ff15 | diff --git a/addon/adapters/ilios.js b/addon/adapters/ilios.js
index <HASH>..<HASH> 100644
--- a/addon/adapters/ilios.js
+++ b/addon/adapters/ilios.js
@@ -22,7 +22,6 @@ export default RESTAdapter.extend(DataAdapterMixin, {
return this.ajax(url, 'GET', {
data: {
filters: { id: ids },
- limit: 1000000
}
});
},
diff --git a/addon/components/dashboard-calendar.js b/addon/components/dashboard-calendar.js
index <HASH>..<HASH> 100644
--- a/addon/components/dashboard-calendar.js
+++ b/addon/components/dashboard-calendar.js
@@ -128,7 +128,6 @@ export default Component.extend({
school: school.get('id'),
year: year.get('title')
},
- limit: 1000
}).then((courses) => {
resolve(courses.sortBy('title'));
});
diff --git a/addon/components/single-event.js b/addon/components/single-event.js
index <HASH>..<HASH> 100644
--- a/addon/components/single-event.js
+++ b/addon/components/single-event.js
@@ -118,7 +118,6 @@ export default Component.extend(SortableByPosition, {
filters: {
course: course.get('id')
},
- limit: 1000
}).then((courseLearningMaterials) => {
let sortedMaterials = courseLearningMaterials.toArray().sort(this.positionSortingCallback);
map(sortedMaterials, clm => {
@@ -198,7 +197,6 @@ export default Component.extend(SortableByPosition, {
filters: {
session: session.get('id')
},
- limit: 1000
}).then((sessionLearningMaterials) => {
let sortedMaterials = sessionLearningMaterials.toArray().sort(this.positionSortingCallback);
map(sortedMaterials, slm => {
diff --git a/addon/models/school.js b/addon/models/school.js
index <HASH>..<HASH> 100644
--- a/addon/models/school.js
+++ b/addon/models/school.js
@@ -29,7 +29,6 @@ export default Model.extend({
filters: {
schools: [this.get('id')]
},
- limit: 1000
});
}
}).readOnly(), | Remove limits that were not real
These limits were being used to ensure that we got all data when the API
had a default limit of <I> items. They are no longer necessary since the
API now returns all data starting in <I>. | ilios_common | train |
23898c66cffc3d9c523c5add354766443a39638d | diff --git a/code/extensions/CMSMainTaggingExtension.php b/code/extensions/CMSMainTaggingExtension.php
index <HASH>..<HASH> 100644
--- a/code/extensions/CMSMainTaggingExtension.php
+++ b/code/extensions/CMSMainTaggingExtension.php
@@ -25,7 +25,7 @@ class CMSMainTaggingExtension extends Extension {
$form->setFormAction(null);
$form->Actions()->replaceField('action_doSearch', FormAction::create(
- 'updateSearchFilters',
+ 'pageFilter',
_t('CMSMain_left_ss.APPLY_FILTER', 'Apply Filter')
)->addExtraClass('ss-ui-action-constructive'));
}
@@ -36,7 +36,7 @@ class CMSMainTaggingExtension extends Extension {
* @parameter <{SEARCH_FORM_DATA}> array
*/
- public function updateSearchFilters($data) {
+ public function pageFilter($data) {
$link = $this->owner->Link();
$separator = '?'; | Implementing the ability to search content tagging in the CMS. | nglasl_silverstripe-fusion | train |
56c650333c44d88328ce1ec996895e470086e974 | diff --git a/pyecore/resources/resource.py b/pyecore/resources/resource.py
index <HASH>..<HASH> 100644
--- a/pyecore/resources/resource.py
+++ b/pyecore/resources/resource.py
@@ -225,7 +225,6 @@ class Resource(object):
if x.can_resolve(path, self)), None)
uri, _ = self._is_external(path)
if not decoder and uri:
- uri = URI(uri).normalize()
raise TypeError('Resource "{0}" cannot be resolved'.format(uri))
return decoder if decoder else self
diff --git a/tests/resources/test_resources.py b/tests/resources/test_resources.py
index <HASH>..<HASH> 100644
--- a/tests/resources/test_resources.py
+++ b/tests/resources/test_resources.py
@@ -7,6 +7,23 @@ from pyecore.resources.resource import HttpURI
from os import path
[email protected](scope='module')
+def simplemm():
+ A = EClass('A')
+ B = EClass('B')
+ Root = EClass('Root')
+ Root.eStructuralFeatures.append(EReference('a', A, containment=True,
+ upper=-1))
+ Root.eStructuralFeatures.append(EReference('b', B, containment=True,
+ upper=-1))
+
+ A.eStructuralFeatures.append(EReference('tob', B, upper=-1))
+
+ pack = EPackage('pack', nsURI='http://pack/1.0', nsPrefix='pack')
+ pack.eClassifiers.extend([Root, A, B])
+ return pack
+
+
def test_init_globalregistry():
assert global_registry
assert global_registry[Ecore.nsURI]
@@ -136,5 +153,38 @@ def test_globaluridecoder():
assert Global_URI_decoder.can_resolve('http://simple.ecore#//test') is True
+def test_resource_load_proxy_missinghref(simplemm):
+ rset = ResourceSet()
+ rset.metamodel_registry[simplemm.nsURI] = simplemm
+ root = rset.get_resource('tests/xmi/xmi-tests/a1.xmi').contents[0]
+ assert isinstance(root.a[0].tob[0], EProxy)
+ with pytest.raises(TypeError):
+ root.a[0].tob[0].eClass
+
+
+def test_resource_load_proxy_href(simplemm):
+ rset = ResourceSet()
+ rset.metamodel_registry[simplemm.nsURI] = simplemm
+ root = rset.get_resource('tests/xmi/xmi-tests/a1.xmi').contents[0]
+ rset.get_resource('tests/xmi/xmi-tests/b1.xmi')
+ assert isinstance(root.a[0].tob[0], EProxy)
+ B = simplemm.getEClassifier('B')
+ root.a[0].tob[0].eClass # We force the proxy resolution
+ assert isinstance(root.a[0].tob[0], B.python_class)
+ assert EcoreUtils.isinstance(root.a[0].tob[0], B)
+
+
+def test_resource_load_proxy_href_inner(simplemm):
+ rset = ResourceSet()
+ rset.metamodel_registry[simplemm.nsURI] = simplemm
+ root = rset.get_resource('tests/xmi/xmi-tests/a2.xmi').contents[0]
+ rset.get_resource('tests/xmi/xmi-tests/inner/b2.xmi')
+ assert isinstance(root.a[0].tob[0], EProxy)
+ B = simplemm.getEClassifier('B')
+ root.a[0].tob[0].eClass # We force the proxy resolution
+ assert isinstance(root.a[0].tob[0], B.python_class)
+ assert EcoreUtils.isinstance(root.a[0].tob[0], B)
+
+
# def test_fileuridecoder():
# assert File_URI_decoder.can_resolve('file://simple.ecore#//test') is True
diff --git a/tests/xmi/test_xmi_serialization.py b/tests/xmi/test_xmi_serialization.py
index <HASH>..<HASH> 100644
--- a/tests/xmi/test_xmi_serialization.py
+++ b/tests/xmi/test_xmi_serialization.py
@@ -4,6 +4,7 @@ import pyecore.ecore as Ecore
from pyecore.resources import *
from pyecore.resources.xmi import XMIResource
+
@pytest.fixture(scope='module')
def lib():
package = Ecore.EPackage('mypackage') | Add unit/integration tests for EProxy support | pyecore_pyecore | train |
3b41fc9149488a6dbe4030046fef182c37918bf3 | diff --git a/src/main/java/org/springframework/hateoas/Resource.java b/src/main/java/org/springframework/hateoas/Resource.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/springframework/hateoas/Resource.java
+++ b/src/main/java/org/springframework/hateoas/Resource.java
@@ -16,6 +16,7 @@
package org.springframework.hateoas;
import java.util.Arrays;
+import java.util.Collection;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
@@ -58,6 +59,7 @@ public class Resource<T> extends ResourceSupport {
public Resource(T content, Iterable<Link> links) {
Assert.notNull(content, "Content must not be null!");
+ Assert.isTrue(!(content instanceof Collection), "Content must not be a collection! Use Resources instead!");
this.content = content;
this.add(links);
}
diff --git a/src/test/java/org/springframework/hateoas/ResourceUnitTest.java b/src/test/java/org/springframework/hateoas/ResourceUnitTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/springframework/hateoas/ResourceUnitTest.java
+++ b/src/test/java/org/springframework/hateoas/ResourceUnitTest.java
@@ -18,6 +18,8 @@ package org.springframework.hateoas;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
+import java.util.Collections;
+
import org.junit.Test;
/**
@@ -64,4 +66,9 @@ public class ResourceUnitTest {
assertThat(left, is(not(right)));
assertThat(right, is(not(left)));
}
+
+ @Test(expected = IllegalArgumentException.class)
+ public void rejectsCollectionContent() {
+ new Resource<Object>(Collections.emptyList());
+ }
}
diff --git a/src/test/java/org/springframework/hateoas/hal/Jackson2HalIntegrationTest.java b/src/test/java/org/springframework/hateoas/hal/Jackson2HalIntegrationTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/springframework/hateoas/hal/Jackson2HalIntegrationTest.java
+++ b/src/test/java/org/springframework/hateoas/hal/Jackson2HalIntegrationTest.java
@@ -274,7 +274,7 @@ public class Jackson2HalIntegrationTest extends AbstractJackson2MarshallingInteg
}
/**
- * @see #126
+ * @see #125
*/
@Test
public void rendersCuriesCorrectly() throws Exception {
@@ -285,6 +285,9 @@ public class Jackson2HalIntegrationTest extends AbstractJackson2MarshallingInteg
assertThat(getCuriedObjectMapper().writeValueAsString(resources), is(CURIED_DOCUMENT));
}
+ /**
+ * @see #125
+ */
@Test
public void doesNotRenderCuriesIfNoLinkIsPresent() throws Exception { | #<I> - Added guard to Resource to shield it from being used with Collection content.
Fixed ticket links in Jackson2HalIntegrationTests. | spring-projects_spring-hateoas | train |
0a69b90354e4b3c84fc399ef11e2e4d4e0066572 | diff --git a/npm.js b/npm.js
index <HASH>..<HASH> 100644
--- a/npm.js
+++ b/npm.js
@@ -6,6 +6,54 @@ var fs = require('fs')
, npmdir = path.join(require.resolve('npm'), '../..', 'doc')
, jitsudir = path.join(require.resolve('nodejitsu-handbook'), '..', 'content/npm');
+/**
+ * Representation of a single HELP document.
+ *
+ * @constructor
+ * @param {String} filename The name of the help file.
+ * @param {String} path The absolute location of the file.
+ * @param {Object} github Github user/repo of the help files.
+ * @param {Function} preprocess Optional content pre-processor.
+ * @api public
+ */
+function Help(filename, path, github, preprocess) {
+ if (!(this instanceof Help)) return new Help(filename, path, preprocess);
+
+ this.path = path;
+ this.github = github;
+ this.filename = filename;
+ this.preprocess = preprocess;
+ this.url = filename.slice(0, -3);
+ this.title = filename.slice(0, -3).replace(/\-/g, ' ');
+}
+
+/**
+ * Parse the markdown files.
+ *
+ * @param {Function} fn Callback
+ * @api public
+ */
+Help.prototype.render = function render(fn) {
+ if (this.html) return fn(undefined, this.html);
+
+ var content = fs.readFileSync(this.path, 'utf-8')
+ , help = this;
+
+ if (this.preprocess) content = this.preprocess(content);
+
+ renderme({
+ readmeFilename: this.filename,
+ readme: content
+ }, {
+ trimmed: Infinity,
+ github: this.github
+ }, function rendered(err, html) {
+ if (err) return fn(err);
+
+ fn(err, help.html = html);
+ });
+};
+
//
// Expose the items.
//
@@ -22,28 +70,20 @@ fs.readdirSync(npmdir).forEach(function each(folder) {
fs.readdirSync(path.join(npmdir, folder)).filter(function filter(file) {
return '.md' === path.extname(file);
}).forEach(function each(item) {
- var title = item.slice(0, -3).replace(/\-/g, ' ')
- , url = item.slice(0, -3);
-
- items[folder][url] = {
- url: url,
- html: '',
- title: title,
- filename: item,
- path: path.join(npmdir, folder, item),
- render: function render(fn) {
- renderme({
- readmeFilename: this.filename,
- readme: fs.readFileSync(this.path, 'utf-8'),
- }, {
- trimmed: Infinity,
- github: {
- user: 'npm',
- repo: 'npm'
- }
- }, fn);
+ var help = new Help(item, path.join(npmdir, folder, item), {
+ user: 'npm',
+ repo: 'npm'
+ }, function preprocess(content) {
+ var index;
+
+ if (~(index = content.indexOf('## SEE ALSO'))) {
+ content = content.slice(0, index).trim();
}
- };
+
+ return content;
+ });
+
+ items[folder][help.url] = help;
});
});
@@ -53,28 +93,12 @@ fs.readdirSync(npmdir).forEach(function each(folder) {
fs.readdirSync(jitsudir).filter(function filter(file) {
return '.md' === path.extname(file);
}).forEach(function each(item) {
- var title = item.slice(0, -3).replace(/\-/g, ' ')
- , url = item.slice(0, -3);
-
- items.private[url] = {
- url: url,
- html: '',
- title: title,
- filename: item,
- path: path.join(jitsudir, item),
- render: function render(fn) {
- renderme({
- readmeFilename: this.filename,
- readme: fs.readFileSync(this.path, 'utf-8')
- }, {
- trimmed: Infinity,
- github: {
- user: 'nodejitsu',
- repo: 'handbook/content/npm'
- }
- }, fn);
- }
- };
+ var help = new Help(item, path.join(jitsudir, item), {
+ user: 'nodejitsu',
+ repo: 'handbook/content/npm'
+ });
+
+ items.private[help.url] = help;
});
// | [fix] Code re-use
[fix] Nuke the horrible `SEE ALSO` from the npm documents. | nodejitsu_npm-documentation-pagelet | train |
6afd87d85be053e2694cceef91b089085ddea40a | diff --git a/collectors/admin.php b/collectors/admin.php
index <HASH>..<HASH> 100644
--- a/collectors/admin.php
+++ b/collectors/admin.php
@@ -16,6 +16,10 @@ class QM_Collector_Admin extends QM_Collector {
public function get_concerned_actions() {
$actions = array(
'current_screen',
+ 'admin_notices',
+ 'all_admin_notices',
+ 'network_admin_notices',
+ 'user_admin_notices',
);
if ( ! empty( $this->data['list_table'] ) ) { | Add the admin notice hooks to the list of concerned filters for the Admin Screen panel. | johnbillion_query-monitor | train |
849493aafc6439a8774fc5bdaee226148c517f28 | diff --git a/lib/entitiescreator.js b/lib/entitiescreator.js
index <HASH>..<HASH> 100644
--- a/lib/entitiescreator.js
+++ b/lib/entitiescreator.js
@@ -83,19 +83,9 @@ EntitiesCreator.prototype.initializeEntities = function() {
var initializedEntity={
"relationships" : [],
"fields" : [],
- "fieldsContainOwnerOneToOne": false,
- "fieldsContainOwnerManyToMany": false,
- "fieldsContainOneToMany" : false,
- "fieldsContainLocalDate": false,
- "fieldsContainCustomTime": false,
- "fieldsContainBigDecimal": false,
- "fieldsContainDateTime": false,
- "fieldsContainDate": false,
- "fieldsContainBlob": false,
"changelogDate": this.getChangelogDate(classId),
"dto": "no",
- "pagination": (this.onDiskEntities[classId] !== undefined ) ? this.onDiskEntities[classId].pagination : "no",
- "validation": false
+ "pagination": (this.onDiskEntities[classId] !== undefined ) ? this.onDiskEntities[classId].pagination : "no"
};
initializedEntity = this.setDTO( | root level clean up, should not build | jhipster_jhipster-uml | train |
a6760d578220fc85b4878e5347a8e2549205f108 | diff --git a/test/AlexaSmartHome/Request/RequestTest.php b/test/AlexaSmartHome/Request/RequestTest.php
index <HASH>..<HASH> 100644
--- a/test/AlexaSmartHome/Request/RequestTest.php
+++ b/test/AlexaSmartHome/Request/RequestTest.php
@@ -3,6 +3,7 @@
namespace Tests\AlexaSmartHome\Request;
use \InternetOfVoice\LibVoice\AlexaSmartHome\Request\Request;
+use \InvalidArgumentException;
use \PHPUnit\Framework\TestCase;
/**
@@ -13,8 +14,6 @@ use \PHPUnit\Framework\TestCase;
*/
class RequestTest extends TestCase {
/**
- * testRequest
- *
* @group smarthome
*/
public function testRequest() {
@@ -29,4 +28,12 @@ class RequestTest extends TestCase {
$this->assertEquals('BearerToken', $request->getDirective()->getPayload()->getScope()->getType());
$this->assertEquals('access-token-send-by-skill', $request->getDirective()->getPayload()->getScope()->getToken());
}
+
+ /**
+ * @group smarthome
+ */
+ public function testMissingDirective() {
+ $this->expectException(InvalidArgumentException::class);
+ new Request([]);
+ }
} | Smart home: Extend RequestTest | internetofvoice_libvoice | train |
1f169fb83f2d60c37166294269816d404f1e5fcf | diff --git a/nomad/leader.go b/nomad/leader.go
index <HASH>..<HASH> 100644
--- a/nomad/leader.go
+++ b/nomad/leader.go
@@ -251,28 +251,41 @@ func (s *Server) schedulePeriodic(stopCh chan struct{}) {
jobGC := time.NewTicker(s.config.JobGCInterval)
defer jobGC.Stop()
- for {
+ // getLatest grabs the latest index from the state store. It returns true if
+ // the index was retrieved successfully.
+ getLatest := func() (uint64, bool) {
// Snapshot the current state
snap, err := s.fsm.State().Snapshot()
if err != nil {
s.logger.Printf("[ERR] nomad: failed to snapshot state for periodic GC: %v", err)
- continue
+ return 0, false
}
// Store the snapshot's index
snapshotIndex, err := snap.LatestIndex()
if err != nil {
s.logger.Printf("[ERR] nomad: failed to determine snapshot's index for periodic GC: %v", err)
- continue
+ return 0, false
}
+ return snapshotIndex, true
+ }
+
+ for {
+
select {
case <-evalGC.C:
- s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobEvalGC, snapshotIndex))
+ if index, ok := getLatest(); ok {
+ s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobEvalGC, index))
+ }
case <-nodeGC.C:
- s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobNodeGC, snapshotIndex))
+ if index, ok := getLatest(); ok {
+ s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobNodeGC, index))
+ }
case <-jobGC.C:
- s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobJobGC, snapshotIndex))
+ if index, ok := getLatest(); ok {
+ s.evalBroker.Enqueue(s.coreJobEval(structs.CoreJobJobGC, index))
+ }
case <-stopCh:
return
} | tighter index bound when creating GC evals | hashicorp_nomad | train |
ec00be8fa68694dc2057d2f68d80ace1549d9930 | diff --git a/packages/perspective-viewer-d3fc/src/js/axis/crossAxis.js b/packages/perspective-viewer-d3fc/src/js/axis/crossAxis.js
index <HASH>..<HASH> 100644
--- a/packages/perspective-viewer-d3fc/src/js/axis/crossAxis.js
+++ b/packages/perspective-viewer-d3fc/src/js/axis/crossAxis.js
@@ -42,6 +42,13 @@ const flattenArray = array => {
}
};
+const getMinimumGap = (data, dataMap) =>
+ data
+ .map(dataMap)
+ .sort((a, b) => a - b)
+ .filter((d, i, a) => i === 0 || d !== a[i - 1])
+ .reduce((acc, d, i, src) => (i === 0 || acc <= d - src[i - 1] ? acc : d - src[i - 1]));
+
export const domain = settings => {
let valueName = "crossValue";
let settingName = "crossValues";
@@ -55,9 +62,7 @@ export const domain = settings => {
const flattenedData = flattenArray(data);
switch (axisType(settings, settingName)) {
case AXIS_TYPES.time:
- const dataStart = flattenedData[0][valueName];
- const dataNext = flattenedData.find(d => d[valueName] !== dataStart);
- const dataWidth = dataNext ? dataNext[valueName] - dataStart : 0;
+ const dataWidth = getMinimumGap(flattenedData, d => new Date(d[valueName]).getTime());
return extentTime.pad([dataWidth / 2, dataWidth / 2])(flattenedData);
default:
return [...new Set(flattenedData.map(d => d[valueName]))]; | Implemented more robust bar width calculation | finos_perspective | train |
7f773a4fcb60ed7417caaf1d18badbb8bf9035bc | diff --git a/test/relations/HtmlDnsPrefetchLink.js b/test/relations/HtmlDnsPrefetchLink.js
index <HASH>..<HASH> 100644
--- a/test/relations/HtmlDnsPrefetchLink.js
+++ b/test/relations/HtmlDnsPrefetchLink.js
@@ -1,11 +1,11 @@
/*global describe, it*/
-var expect = require('../unexpected-with-plugins'),
- AssetGraph = require('../../lib/AssetGraph');
+const expect = require('../unexpected-with-plugins');
+const AssetGraph = require('../../lib/AssetGraph');
describe('relations/HtmlDnsPrefetchLink', function () {
function getHtmlAsset(htmlString) {
- var graph = new AssetGraph({ root: __dirname });
- var htmlAsset = new AssetGraph.Html({
+ const graph = new AssetGraph({ root: __dirname });
+ const htmlAsset = new AssetGraph.Html({
text: htmlString || '<!doctype html><html><head></head><body></body></html>',
url: 'file://' + __dirname + 'doesntmatter.html'
});
@@ -17,7 +17,7 @@ describe('relations/HtmlDnsPrefetchLink', function () {
describe('#inline', function () {
it('should throw', function () {
- var relation = new AssetGraph.HtmlDnsPrefetchLink({
+ const relation = new AssetGraph.HtmlDnsPrefetchLink({
to: { url: 'index.html' }
});
@@ -37,28 +37,21 @@ describe('relations/HtmlDnsPrefetchLink', function () {
return new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlDnsPrefetchLink/'})
.loadAssets('index.html')
.queue(function (assetGraph) {
- expect(assetGraph, 'to contain relation including unresolved', 'HtmlDnsPrefetchLink');
-
- var link = assetGraph.findRelations({ type: 'HtmlDnsPrefetchLink' }, true)[0];
+ expect(assetGraph, 'to contain relation', 'HtmlDnsPrefetchLink');
- link.to.url = 'foo.bar';
- // This is necessary because link.to is an asset config object, not a real asset that will
- // propagate url changes:
- link.refreshHref();
+ const link = assetGraph.findRelations({ type: 'HtmlDnsPrefetchLink' }, true)[0];
+ link.hrefType = 'relative';
+ link.to.url = assetGraph.root + 'foo.bar';
- expect(link, 'to satisfy', {
- href: 'foo.bar'
- });
+ expect(link, 'to satisfy', { href: 'foo.bar' });
});
});
describe('when programmatically adding a relation', function () {
it('should handle crossorigin url', function () {
- var htmlAsset = getHtmlAsset();
- var relation = new AssetGraph.HtmlDnsPrefetchLink({
- to: {
- url: 'http://assetgraph.org'
- }
+ const htmlAsset = getHtmlAsset();
+ const relation = new AssetGraph.HtmlDnsPrefetchLink({
+ to: { url: 'http://assetgraph.org' }
});
relation.attachToHead(htmlAsset, 'first'); | WIP, <I> failing [ci skip] | assetgraph_assetgraph | train |
78d6d3dc7762d48fad57c3fc2c81fed47071a217 | diff --git a/src/main/java/net/malisis/core/renderer/Parameter.java b/src/main/java/net/malisis/core/renderer/Parameter.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/malisis/core/renderer/Parameter.java
+++ b/src/main/java/net/malisis/core/renderer/Parameter.java
@@ -131,7 +131,7 @@ public class Parameter<T> implements Cloneable
@Override
public String toString()
{
- return value.toString() + " [" + defaultValue.toString() + "]";
+ return value + " [" + defaultValue + "]";
}
@Override | Fixed NPE in toString() | Ordinastie_MalisisCore | train |
731a01a1a284d206845d47cc9bef3eb81f1b500d | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -4,12 +4,12 @@ from distutils.core import setup
setup(name='aiolifx',
packages=['aiolifx'],
- version='0.4.1',
+ version='0.4.1.post1',
author='François Wautier',
author_email='[email protected]',
description='API for local communication with LIFX devices over a LAN with asyncio.',
url='http://github.com/frawau/aiolifx',
- download_url='http://github.com/frawau/aiolifx/archive/aiolifx/0.4.1.tar.gz',
+ download_url='http://github.com/frawau/aiolifx/archive/aiolifx/0.4.1.post1.tar.gz',
keywords = ['lifx', 'light', 'automation'],
license='MIT',
install_requires=[ | So for PyPi we MUST have a new version | frawau_aiolifx | train |
f1e3f20c887ac5605ab28fe9265addd9dc8472e2 | diff --git a/spec/_redistat_spec.rb b/spec/_redistat_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/_redistat_spec.rb
+++ b/spec/_redistat_spec.rb
@@ -2,9 +2,23 @@ require "spec_helper"
describe Redistat do
- it "should create a valid redis connection to correct server" do
- Redistat.redis.should_not be_nil
- Redistat.redis.client.port.should == 8379
+ it "should have a valid redis client instance" do
+ redis.should_not be_nil
+ end
+
+ it "should be connected to the testing server" do
+ redis.client.port.should == 8379
+ redis.client.host.should == "127.0.0.1"
+ end
+
+ it "should be able to set and get data" do
+ redis.set "hello", "world"
+ redis.get("hello").should == "world"
+ redis.del("hello").should be_true
+ end
+
+ def redis
+ Redistat.redis
end
end
\ No newline at end of file
diff --git a/spec/label_spec.rb b/spec/label_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/label_spec.rb
+++ b/spec/label_spec.rb
@@ -9,4 +9,21 @@ describe Redistat::Label do
label.hash.should == Digest::SHA1.hexdigest(name)
end
+ it "should store a label hash lookup key" do
+ name = "/about/us"
+ label = Redistat::Label.new(name)
+ label.save
+ label.saved?.should be_true
+ redis.get("Redistat:lables:#{label.hash}").should == name
+
+ name = "/contact/us"
+ label = Redistat::Label.create(name)
+ label.saved?.should be_true
+ redis.get("Redistat:lables:#{label.hash}").should == name
+ end
+
+ def redis
+ Redistat.redis
+ end
+
end
\ No newline at end of file | more specs for Redistat and Redistat::Label | jimeh_redistat | train |
b2adaf61c6b2188d95ae9654ba8f55841c3050aa | diff --git a/neo/bin/prompt.py b/neo/bin/prompt.py
index <HASH>..<HASH> 100755
--- a/neo/bin/prompt.py
+++ b/neo/bin/prompt.py
@@ -239,7 +239,7 @@ class PromptInterface:
print("Wallet file not found")
return
- passwd = prompt("[password]> ", is_password=True)
+ passwd = self.prompt("[password]> ", is_password=True)
password_key = to_aes_key(passwd)
try:
@@ -268,8 +268,8 @@ class PromptInterface:
print("File already exists")
return
- passwd1 = prompt("[password]> ", is_password=True)
- passwd2 = prompt("[password again]> ", is_password=True)
+ passwd1 = self.prompt("[password]> ", is_password=True)
+ passwd2 = self.prompt("[password again]> ", is_password=True)
if passwd1 != passwd2 or len(passwd1) < 10:
print("Please provide matching passwords that are at least 10 characters long")
@@ -356,7 +356,7 @@ class PromptInterface:
print("Please supply a valid NEP2 encrypted private key")
return
- nep2_passwd = prompt("[key password]> ", is_password=True)
+ nep2_passwd = self.prompt("[key password]> ", is_password=True)
try:
prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd)
@@ -408,7 +408,7 @@ class PromptInterface:
if not address:
return print("Please specify an address")
- passwd = prompt("[wallet password]> ", is_password=True)
+ passwd = self.prompt("[wallet password]> ", is_password=True)
if not self.Wallet.ValidatePassword(passwd):
return print("Incorrect password")
@@ -427,15 +427,15 @@ class PromptInterface:
if not address:
return print("Please specify an address")
- passwd = prompt("[wallet password]> ", is_password=True)
+ passwd = self.prompt("[wallet password]> ", is_password=True)
if not self.Wallet.ValidatePassword(passwd):
return print("Incorrect password")
- nep2_passwd1 = prompt("[key password]> ", is_password=True)
+ nep2_passwd1 = self.prompt("[key password]> ", is_password=True)
if len(nep2_passwd1) < 10:
return print("Please provide a password with at least 10 characters")
- nep2_passwd2 = prompt("[key password again]> ", is_password=True)
+ nep2_passwd2 = self.prompt("[key password again]> ", is_password=True)
if nep2_passwd1 != nep2_passwd2:
return print("Passwords do not match")
@@ -774,7 +774,7 @@ class PromptInterface:
tx.Attributes = invoke_attrs
- passwd = prompt("[password]> ", is_password=True)
+ passwd = self.prompt("[password]> ", is_password=True)
if not self.Wallet.ValidatePassword(passwd):
return print("Incorrect password")
@@ -816,7 +816,7 @@ class PromptInterface:
"-------------------------------------------------------------------------------------------------------------------------------------\n")
print("Enter your password to continue and deploy this contract")
- passwd = prompt("[password]> ", is_password=True)
+ passwd = self.prompt("[password]> ", is_password=True)
if not self.Wallet.ValidatePassword(passwd):
return print("Incorrect password")
@@ -929,6 +929,8 @@ class PromptInterface:
style=self.token_style,
refresh_interval=3
)
+ self.prompt = session.prompt
+
while self.go_on:
try: | Fix prompt() calls, especially for asking for passwords (#<I>) | CityOfZion_neo-python | train |
ccb960848ddea12020ea61a5d7bcb0b286140803 | diff --git a/master/buildbot/clients/tryclient.py b/master/buildbot/clients/tryclient.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/clients/tryclient.py
+++ b/master/buildbot/clients/tryclient.py
@@ -514,10 +514,10 @@ class RemoteTryPP(protocol.ProcessProtocol):
self.transport.closeStdin()
def outReceived(self, data):
- sys.stdout.write(data)
+ sys.stdout.write(bytes2unicode(data))
def errReceived(self, data):
- sys.stderr.write(data)
+ sys.stderr.write(bytes2unicode(data))
def processEnded(self, status_object):
sig = status_object.value.signal
diff --git a/master/buildbot/test/unit/test_clients_tryclient.py b/master/buildbot/test/unit/test_clients_tryclient.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/test/unit/test_clients_tryclient.py
+++ b/master/buildbot/test/unit/test_clients_tryclient.py
@@ -15,7 +15,9 @@
import json
+import sys
+from twisted.python.compat import unicode
from twisted.trial import unittest
from buildbot.clients import tryclient
@@ -141,3 +143,25 @@ class createJobfile(unittest.TestCase):
self.assertEqual(sse.branch, "origin/master")
sse.fixBranch(b'origin\n')
self.assertEqual(sse.branch, "master")
+
+ class RemoteTryPP_TestStream(object):
+ def __init__(self):
+ self.writes = []
+
+ def write(self, data):
+ self.writes.append(data)
+
+ def test_RemoteTryPP_encoding(self):
+ rmt = tryclient.RemoteTryPP("job")
+ for streamname in "out", "err":
+ sys_streamattr = "std" + streamname
+ rmt_methodattr = streamname + "Received"
+ teststream = self.RemoteTryPP_TestStream()
+ saved_stream = getattr(sys, sys_streamattr)
+ try:
+ setattr(sys, sys_streamattr, teststream)
+ getattr(rmt, rmt_methodattr)(b"data")
+ finally:
+ setattr(sys, sys_streamattr, saved_stream)
+ self.assertEqual(len(teststream.writes), 1)
+ self.assertTrue(isinstance(teststream.writes[0], unicode)) | tryclient: Use bytes2unicode in RemoteTryPP.{out,err}Received | buildbot_buildbot | train |
10f5520b3e5a3d69b486fe07bc9e61a3af47ca32 | diff --git a/spanner/setup.py b/spanner/setup.py
index <HASH>..<HASH> 100644
--- a/spanner/setup.py
+++ b/spanner/setup.py
@@ -51,7 +51,7 @@ SETUP_BASE = {
REQUIREMENTS = [
'google-cloud-core >= 0.23.1, < 0.24dev',
- 'grpcio >= 1.0.2, < 2.0dev',
+ 'grpcio >= 1.2.0, < 2.0dev',
'gapic-google-cloud-spanner-v1 >= 0.15.0, < 0.16dev',
'gapic-google-cloud-spanner-admin-database-v1 >= 0.15.0, < 0.16dev',
'gapic-google-cloud-spanner-admin-instance-v1 >= 0.15.0, < 0.16dev',
diff --git a/spanner/unit_tests/test_session.py b/spanner/unit_tests/test_session.py
index <HASH>..<HASH> 100644
--- a/spanner/unit_tests/test_session.py
+++ b/spanner/unit_tests/test_session.py
@@ -847,15 +847,15 @@ class _SpannerApi(_GAXBaseAPI):
def _trailing_metadata(self):
from google.protobuf.duration_pb2 import Duration
from google.rpc.error_details_pb2 import RetryInfo
- from grpc._common import cygrpc_metadata
+ from grpc._common import to_cygrpc_metadata
if self._commit_abort_retry_nanos is None:
- return cygrpc_metadata(())
+ return to_cygrpc_metadata(())
retry_info = RetryInfo(
retry_delay=Duration(
seconds=self._commit_abort_retry_seconds,
nanos=self._commit_abort_retry_nanos))
- return cygrpc_metadata([
+ return to_cygrpc_metadata([
('google.rpc.retryinfo-bin', retry_info.SerializeToString())])
def commit(self, session, mutations, | Adjust Spanner tests for grpcio <I> (#<I>) | googleapis_google-cloud-python | train |
3cd148de1311984325ef023d8550d2210227478b | diff --git a/great_expectations/dataset/base.py b/great_expectations/dataset/base.py
index <HASH>..<HASH> 100644
--- a/great_expectations/dataset/base.py
+++ b/great_expectations/dataset/base.py
@@ -774,6 +774,41 @@ class DataSet(object):
"""
raise NotImplementedError
+ def expect_column_most_common_value_to_be(self, column, value, ties_okay=None, output_format=None, include_config=False, catch_exceptions=None):
+ """Expect the most common value to be equal to `value`
+
+ Args:
+ column (str): The column name.
+ value (any): The value
+ ties_okay (boolean or None): If True, then the expectation will succeed if other values are as common (but not more common) than the selected value
+
+ Returns:
+ dict:
+ {
+ "success": (bool) True if the column passed the expectation,
+ "true_value": (float) the proportion of unique values
+ }
+ """
+ raise NotImplementedError
+
+ def expect_column_most_common_value_to_be_in_set(self, column, value_set, output_format=None, include_config=False, catch_exceptions=None):
+ """Expect the most common value to be within the designated value set
+
+ Args:
+ column (str): The column name.
+ value_set (list): The lis of designated values
+
+ Returns:
+ dict:
+ {
+ "success": (bool) True if the column passed the expectation,
+ "true_value": (float) the proportion of unique values
+ }
+ """
+ raise NotImplementedError
+
+
+ ### Distributional expectations
def expect_column_chisquare_test_p_value_greater_than(self, column, partition_object=None, p=0.05, output_format=None, include_config=False, catch_exceptions=None):
"""
Expect the values in this column to match the distribution of the specified categorical vals and their expected_frequencies. \
diff --git a/great_expectations/dataset/pandas_dataset.py b/great_expectations/dataset/pandas_dataset.py
index <HASH>..<HASH> 100644
--- a/great_expectations/dataset/pandas_dataset.py
+++ b/great_expectations/dataset/pandas_dataset.py
@@ -594,6 +594,44 @@ class PandasDataSet(MetaPandasDataSet, pd.DataFrame):
@DocInherit
@MetaPandasDataSet.column_aggregate_expectation
+ def expect_column_most_common_value_to_be(self, column, value, ties_okay=None, output_format=None, include_config=False, catch_exceptions=None):
+
+ mode_list = list(column.mode().values)
+
+ if ties_okay:
+ success = value in mode_list
+ else:
+ if len(mode_list) > 1:
+ success = False
+ else:
+ success = value == mode_list[0]
+
+ return {
+ "success" : success,
+ "true_value": mode_list,
+ "summary_obj": {},
+ }
+
+ @DocInherit
+ @MetaPandasDataSet.column_aggregate_expectation
+ def expect_column_most_common_value_to_be_in_set(self, column, value_set, output_format=None, include_config=False, catch_exceptions=None):
+
+ if min_value is None and max_value is None:
+ raise ValueError("min_value and max_value cannot both be None")
+
+ unique_value_count = column.value_counts().shape[0]
+
+ return {
+ "success" : (
+ ((min_value is None) or (min_value <= unique_value_count)) and
+ ((max_value is None) or (unique_value_count <= max_value))
+ ),
+ "true_value": unique_value_count,
+ "summary_obj": {}
+ }
+
+ @DocInherit
+ @MetaPandasDataSet.column_aggregate_expectation
def expect_column_proportion_of_unique_values_to_be_between(self, column, min_value=0, max_value=1, output_format=None, include_config=False, catch_exceptions=None):
unique_value_count = column.value_counts().shape[0]
total_value_count = int(len(column))#.notnull().sum() | Implement expect_column_most_common_value_to_be
Add stubs for expect_column_most_common_value_to_be and expect_column_most_common_value_to_be_in_set in base.py | great-expectations_great_expectations | train |
b101eafa29ccf586809f8c2c723c5f36b53bdcb1 | diff --git a/docs/source/adapter_class.rst b/docs/source/adapter_class.rst
index <HASH>..<HASH> 100644
--- a/docs/source/adapter_class.rst
+++ b/docs/source/adapter_class.rst
@@ -104,4 +104,4 @@ Given an exception, should returne if the authentication is expired. If so, tapi
.. method:: refresh_authentication(self, api_params, *args, **kwargs):
-Should run refresh authentication logic.
\ No newline at end of file
+Should run refresh authentication logic. Make sure you update `api_params` dictionary with the new token.
diff --git a/tests/client.py b/tests/client.py
index <HASH>..<HASH> 100644
--- a/tests/client.py
+++ b/tests/client.py
@@ -61,7 +61,7 @@ class TokenRefreshClientAdapter(TesterClientAdapter):
return exception.status_code == 401
def refresh_authentication(self, api_params, *args, **kwargs):
- pass
+ api_params['token'] = 'new_token'
TokenRefreshClient = generate_wrapper_from_adapter(TokenRefreshClientAdapter)
diff --git a/tests/test_tapioca.py b/tests/test_tapioca.py
index <HASH>..<HASH> 100755
--- a/tests/test_tapioca.py
+++ b/tests/test_tapioca.py
@@ -450,7 +450,7 @@ class TestIteratorFeatures(unittest.TestCase):
class TestTokenRefreshing(unittest.TestCase):
def setUp(self):
- self.wrapper = TokenRefreshClient()
+ self.wrapper = TokenRefreshClient(token='token')
@responses.activate
def test_not_token_refresh_ready_client_call_raises_not_implemented(self):
@@ -474,21 +474,25 @@ class TestTokenRefreshing(unittest.TestCase):
with self.assertRaises(ClientError) as context:
response = self.wrapper.test().post()
- def request_callback(self, request):
- if self.first_call:
- self.first_call = False
- return (401, {'content_type':'application/json'}, json.dumps('{"error": "Token expired"}'))
- else:
- self.first_call = None
- return (201, {'content_type':'application/json'}, json.dumps('{"error": "Token expired"}'))
-
@responses.activate
def test_token_expired_with_active_refresh_flag(self):
self.first_call = True
+
+ def request_callback(request):
+ if self.first_call:
+ self.first_call = False
+ return (401, {'content_type':'application/json'}, json.dumps('{"error": "Token expired"}'))
+ else:
+ self.first_call = None
+ return (201, {'content_type':'application/json'}, '')
+
responses.add_callback(
responses.POST, self.wrapper.test().data,
- callback=self.request_callback,
+ callback=request_callback,
content_type='application/json',
)
response = self.wrapper.test().post(refresh_auth=True)
+
+ # refresh_authentication method should be able to update api_params
+ self.assertEqual(response._api_params['token'], 'new_token') | testing refresh_authentication method is able to update api_params | vintasoftware_tapioca-wrapper | train |
a3ff4545507fba66456106f663ae9362c2de10ff | diff --git a/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/AbstractRetryTest.java b/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/AbstractRetryTest.java
index <HASH>..<HASH> 100644
--- a/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/AbstractRetryTest.java
+++ b/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/AbstractRetryTest.java
@@ -86,6 +86,7 @@ public abstract class AbstractRetryTest extends HitsAwareCacheManagersTest {
Properties clientConfig = new Properties();
clientConfig.put("infinispan.client.hotrod.server_list", "localhost:" + hotRodServer2.getPort());
clientConfig.put("infinispan.client.hotrod.force_return_values", "true");
+ clientConfig.put("infinispan.client.hotrod.connect_timeout", "5");
clientConfig.put("maxActive",1); //this ensures that only one server is active at a time
remoteCacheManager = new RemoteCacheManager(clientConfig);
diff --git a/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ReplicationRetryTest.java b/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ReplicationRetryTest.java
index <HASH>..<HASH> 100644
--- a/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ReplicationRetryTest.java
+++ b/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ReplicationRetryTest.java
@@ -25,10 +25,12 @@ package org.infinispan.client.hotrod.retry;
import static org.testng.Assert.assertEquals;
import java.net.SocketAddress;
+import java.util.Iterator;
import java.util.Map;
import org.infinispan.client.hotrod.VersionedValue;
import org.infinispan.config.Configuration;
+import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.testng.annotations.Test;
@@ -48,13 +50,12 @@ public class ReplicationRetryTest extends AbstractRetryTest {
}
}
- @Test(enabled = false, description = "See ISPN-2111")
public void testPut() {
validateSequenceAndStopServer();
resetStats();
- assert "v".equals(remoteCache.put("k", "v0"));
+ assertEquals(remoteCache.put("k", "v0"), "v");
for (int i = 1; i < 100; i++) {
assertEquals("v" + (i-1), remoteCache.put("k", "v"+i));
}
@@ -141,13 +142,17 @@ public class ReplicationRetryTest extends AbstractRetryTest {
resetStats();
expectedServer = strategy.getServers()[strategy.getNextPosition()];
- remoteCache.put("k","v");
+ assertEquals("v", remoteCache.put("k","v"));
assertOnlyServerHit(expectedServer);
//this would be the next server to be shutdown
expectedServer = strategy.getServers()[strategy.getNextPosition()];
HotRodServer toStop = addr2hrServer.get(expectedServer);
toStop.stop();
+ for (Iterator<EmbeddedCacheManager> ecmIt = cacheManagers.iterator(); ecmIt.hasNext();) {
+ if (ecmIt.next().getAddress().equals(expectedServer)) ecmIt.remove();
+ }
+ waitForClusterToForm();
}
@Override | ISPN-<I> ReplicationRetryTest.testPut randomly failing
- I couldn't replicate the failure but fixed a potential race condition and also enhanced the speed of the test by making the connection timeout smaller | infinispan_infinispan | train |
80aaf1e254a4c117b4fc29801423811d1d9c0bd4 | diff --git a/tests/aws/requests/elb/helper.rb b/tests/aws/requests/elb/helper.rb
index <HASH>..<HASH> 100644
--- a/tests/aws/requests/elb/helper.rb
+++ b/tests/aws/requests/elb/helper.rb
@@ -8,6 +8,7 @@ class AWS
LOAD_BALANCER = {
"AvailabilityZones" => Array,
+ "BackendServerDescriptions" => Array,
"CanonicalHostedZoneName" => String,
"CanonicalHostedZoneNameID" => String,
"CreatedTime" => Time,
@@ -25,7 +26,7 @@ class AWS
}
}],
"LoadBalancerName" => String,
- "Policies" => {"LBCookieStickinessPolicies" => Array, "AppCookieStickinessPolicies" => Array},
+ "Policies" => {"LBCookieStickinessPolicies" => Array, "AppCookieStickinessPolicies" => Array, "OtherPolicies" => Array},
"Scheme" => String,
"SecurityGroups" => [Fog::Nullable::String],
"SourceSecurityGroup" => {"GroupName" => String, "OwnerAlias" => String}, | [AWS|ELB] update helper to include BackendServerDescriptions and OtherPolicies | fog_fog | train |
720b6805305a23b73211f7043ec05f3e54a50b18 | diff --git a/src/api/v1/CreateSubscriptionHandler.php b/src/api/v1/CreateSubscriptionHandler.php
index <HASH>..<HASH> 100644
--- a/src/api/v1/CreateSubscriptionHandler.php
+++ b/src/api/v1/CreateSubscriptionHandler.php
@@ -92,7 +92,11 @@ class CreateSubscriptionHandler extends ApiHandler implements IdempotentHandlerI
$type,
DateTime::from(strtotime($params['start_time']))
);
- $this->subscriptionMetaRepository->setMeta($subscription, 'idempotent_key', $this->idempotentKey());
+
+ if ($this->idempotentKey()) {
+ $this->subscriptionMetaRepository->setMeta($subscription, 'idempotent_key', $this->idempotentKey());
+ }
+
$this->emitter->emit(new NewSubscriptionEvent($subscription));
$this->hermesEmitter->emit(new HermesMessage('new-subscription', [
'subscription_id' => $subscription->id,
diff --git a/src/models/Repository/SubscriptionMetaRepository.php b/src/models/Repository/SubscriptionMetaRepository.php
index <HASH>..<HASH> 100644
--- a/src/models/Repository/SubscriptionMetaRepository.php
+++ b/src/models/Repository/SubscriptionMetaRepository.php
@@ -4,6 +4,7 @@ namespace Crm\SubscriptionsModule\Repository;
use Crm\ApplicationModule\Repository;
use Nette\Database\Table\IRow;
+use Nette\Database\Table\Selection;
use Nette\Utils\DateTime;
class SubscriptionMetaRepository extends Repository
@@ -22,6 +23,11 @@ class SubscriptionMetaRepository extends Repository
]);
}
+ public function getMeta(IRow $subscription, string $key): Selection
+ {
+ return $this->getTable()->where(['subscription_id' => $subscription->id, 'key' => $key]);
+ }
+
public function subscriptionMeta(IRow $subscription): array
{
return $this->getTable()->where([
@@ -31,20 +37,20 @@ class SubscriptionMetaRepository extends Repository
public function exists(IRow $subscription, string $key): bool
{
- return $this->getTable()->where(['subscription_id' => $subscription->id, 'key' => $key])->count('*') > 0;
+ return $this->getMeta($subscription, $key)->count('*') > 0;
}
public function setMeta(IRow $subscription, string $key, $value): IRow
{
- if ($this->exists($subscription, $key)) {
- $this->getTable()->where(['subscription_id' => $subscription->id, 'key' => $key])->update(['value' => $value]);
- return $this->getTable()->where(['subscription_id' => $subscription->id, 'key' => $key])->limit(1)->fetch();
+ if ($meta = $this->getMeta($subscription, $key)->fetch()) {
+ $this->update($meta, ['value' => $value]);
+ return $meta;
} else {
return $this->add($subscription, $key, $value);
}
}
- public function getMeta(IRow $subscription, string $key): string
+ public function getMetaValue(IRow $subscription, string $key): string
{
return $this->getTable()->where(['subscription_id' => $subscription->id, 'key' => $key])->fetchField('value');
}
diff --git a/src/models/Repository/SubscriptionTypesMetaRepository.php b/src/models/Repository/SubscriptionTypesMetaRepository.php
index <HASH>..<HASH> 100644
--- a/src/models/Repository/SubscriptionTypesMetaRepository.php
+++ b/src/models/Repository/SubscriptionTypesMetaRepository.php
@@ -4,6 +4,7 @@ namespace Crm\SubscriptionsModule\Repository;
use Crm\ApplicationModule\Repository;
use Nette\Database\Table\IRow;
+use Nette\Database\Table\Selection;
use Nette\Utils\DateTime;
class SubscriptionTypesMetaRepository extends Repository
@@ -22,6 +23,11 @@ class SubscriptionTypesMetaRepository extends Repository
]);
}
+ public function getMeta(IRow $subscriptionType, string $key): Selection
+ {
+ return $this->getTable()->where(['subscription_type_id' => $subscriptionType->id, 'key' => $key]);
+ }
+
public function subscriptionTypeMeta(IRow $subscriptionType): array
{
return $this->getTable()->where([
@@ -31,21 +37,21 @@ class SubscriptionTypesMetaRepository extends Repository
public function exists(IRow $subscriptionType, string $key): bool
{
- return $this->getTable()->where(['subscription_type_id' => $subscriptionType->id, 'key' => $key])->count('*') > 0;
+ return $this->getMeta($subscriptionType, $key)->count('*') > 0;
}
public function setMeta(IRow $subscriptionType, string $key, $value): IRow
{
- if ($this->exists($subscriptionType, $key)) {
- $this->getTable()->where(['subscription_type_id' => $subscriptionType->id, 'key' => $key])->update(['value' => $value]);
- return $this->getTable()->where(['subscription_type_id' => $subscriptionType->id, 'key' => $key])->limit(1)->fetch();
+ if ($meta = $this->getMeta($subscriptionType, $key)->fetch()) {
+ $this->update($meta, ['value' => $value]);
+ return $meta;
} else {
return $this->add($subscriptionType, $key, $value);
}
}
- public function getMeta(IRow $subscriptionType, string $key): string
+ public function getMetaValue(IRow $subscriptionType, string $key): string
{
- return $this->getTable()->where(['subscription_type_id' => $subscriptionType->id, 'key' => $key])->fetchField('value');
+ return $this->getMeta($subscriptionType, $key)->fetchField('value');
}
} | Storing subscription idempotency key only when available, refactoring
remp/crm#<I> | remp2020_crm-subscriptions-module | train |
3ec110604956128d3311cb25ee313d527890c2ef | diff --git a/lib/zold/commands/push.rb b/lib/zold/commands/push.rb
index <HASH>..<HASH> 100644
--- a/lib/zold/commands/push.rb
+++ b/lib/zold/commands/push.rb
@@ -77,9 +77,8 @@ Available options:"
return 0
end
start = Time.now
- response = r.http(
- "/wallet/#{wallet.id}#{opts['sync'] ? '?sync=true' : ''}"
- ).put(File.read(wallet.path))
+ content = File.read(wallet.path)
+ response = r.http("/wallet/#{wallet.id}#{opts['sync'] ? '?sync=true' : ''}").put(content)
if response.code == '304'
@log.info("#{r}: same version of #{wallet.id} there")
return 0
@@ -89,7 +88,8 @@ Available options:"
score = Score.parse_json(json)
r.assert_valid_score(score)
raise "Score is too weak #{score}" if score.strength < Score::STRENGTH
- @log.info("#{r} accepted #{wallet.id} in #{(Time.now - start).round(2)}s: #{Rainbow(score.value).green}")
+ @log.info("#{r} accepted #{wallet.id}/#{content.length}b \
+in #{(Time.now - start).round(2)}s: #{Rainbow(score.value).green} (#{json['version']})")
score.value
end
end | #<I> better log in command line | zold-io_zold | train |
e3f4fb70e3dca09e7e7f32a1c60b1cf12067239f | diff --git a/openquake/commonlib/source.py b/openquake/commonlib/source.py
index <HASH>..<HASH> 100644
--- a/openquake/commonlib/source.py
+++ b/openquake/commonlib/source.py
@@ -23,7 +23,6 @@ from xml.etree import ElementTree as etree
import numpy
from openquake.baselib.general import AccumDict, groupby, block_splitter
-from openquake.hazardlib.const import TRT
from openquake.commonlib.node import read_nodes
from openquake.commonlib import logictree, sourceconverter, parallel, valid
from openquake.commonlib.nrml import nodefactory, PARSE_NS_MAP
@@ -515,7 +514,7 @@ def get_trts(smodel):
:param smodel: a :class:`openquake.commonlib.source.SourceModel` tuple
:returns: a comma separated string of uppercase tectonic region types
"""
- return ','.join(TRT[capitalize(tmodel.trt)]
+ return ','.join(capitalize(tmodel.trt)
for tmodel in smodel.trt_models) | Removed dependence from cost.TRT | gem_oq-engine | train |
09e9f1857bf60fe1e69648cb9de53f88d3682f65 | diff --git a/siphon/http_util.py b/siphon/http_util.py
index <HASH>..<HASH> 100644
--- a/siphon/http_util.py
+++ b/siphon/http_util.py
@@ -163,7 +163,7 @@ class DataQuery(object):
self.extra_params.update(kwargs)
return self
- def lonlat_box(self, north, south, east, west):
+ def lonlat_box(self, west, east, south, north):
r'''Add a latitude/longitude bounding box to the query.
This adds a request for a spatial bounding box, bounded by (`south`, `north`)
@@ -175,14 +175,14 @@ class DataQuery(object):
Parameters
----------
- north : float
- The bounding latitude to the north, in degrees north of the equator
- south : float
- The bounding latitude to the south, in degrees north of the equator
- east : float
- The bounding longitude to the east, in degrees east of the prime meridian
west: float
The bounding longitude to the west, in degrees east of the prime meridian
+ east : float
+ The bounding longitude to the east, in degrees east of the prime meridian
+ south : float
+ The bounding latitude to the south, in degrees north of the equator
+ north : float
+ The bounding latitude to the north, in degrees north of the equator
Returns
-------
@@ -190,8 +190,7 @@ class DataQuery(object):
Returns self for chaining calls
'''
- self._set_query(self.spatial_query, north=north, south=south,
- east=east, west=west)
+ self._set_query(self.spatial_query, west=west, east=east, south=south, north=north)
return self
def lonlat_point(self, lon, lat): | changed lonlat_box param order
fixed issue #<I> | Unidata_siphon | train |
ac75334ccb8d5b95569ccc991ae8e3ed26ebabe0 | diff --git a/config/dpkg/changelog b/config/dpkg/changelog
index <HASH>..<HASH> 100644
--- a/config/dpkg/changelog
+++ b/config/dpkg/changelog
@@ -1,5 +1,5 @@
-plaso (20170518-1) unstable; urgency=low
+plaso (20170519-1) unstable; urgency=low
* Auto-generated
- -- Log2Timeline <[email protected]> Thu, 18 May 2017 21:19:49 +0200
\ No newline at end of file
+ -- Log2Timeline <[email protected]> Fri, 19 May 2017 12:54:56 +0200
\ No newline at end of file
diff --git a/plaso/__init__.py b/plaso/__init__.py
index <HASH>..<HASH> 100644
--- a/plaso/__init__.py
+++ b/plaso/__init__.py
@@ -6,4 +6,4 @@ on a typical computer system(s) and aggregate them. Plaso is the Python rewrite
of log2timeline.
"""
-__version__ = '20170518'
+__version__ = '20170519'
diff --git a/plaso/containers/errors.py b/plaso/containers/errors.py
index <HASH>..<HASH> 100644
--- a/plaso/containers/errors.py
+++ b/plaso/containers/errors.py
@@ -9,7 +9,7 @@ from plaso.containers import manager
class ExtractionError(interface.AttributeContainer):
- """Class to represent an extraction error attribute container.
+ """Extraction error attribute container.
Attributes:
message (str): error message.
diff --git a/plaso/engine/processing_status.py b/plaso/engine/processing_status.py
index <HASH>..<HASH> 100644
--- a/plaso/engine/processing_status.py
+++ b/plaso/engine/processing_status.py
@@ -309,8 +309,8 @@ class ProcessingStatus(object):
Attributes:
aborted (bool): True if processing was aborted.
- error_path_specs (list[str]): path specification strings that caused
- critical errors during processing.
+ error_path_specs (list[dfvfs.PathSpec]): path specifications that
+ caused critical errors during processing.
foreman_status (ProcessingStatus): foreman processing status.
"""
diff --git a/plaso/multi_processing/task_engine.py b/plaso/multi_processing/task_engine.py
index <HASH>..<HASH> 100644
--- a/plaso/multi_processing/task_engine.py
+++ b/plaso/multi_processing/task_engine.py
@@ -11,6 +11,7 @@ from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.resolver import context
from plaso.containers import event_sources
+from plaso.containers import errors as error_containers
from plaso.engine import extractors
from plaso.engine import plaso_queue
from plaso.engine import profiler
@@ -170,7 +171,7 @@ class TaskMultiProcessEngine(engine.MultiProcessEngine):
if not self._storage_merge_reader_on_hold:
task = self._task_manager.GetTaskPendingMerge(self._merge_task)
- # Limit the number of attributes containers from a single task-based
+ # Limit the number of attribute containers from a single task-based
# storage file that are merged per loop to keep tasks flowing.
if task or self._storage_merge_reader:
self._status = definitions.PROCESSING_STATUS_MERGING
@@ -413,6 +414,10 @@ class TaskMultiProcessEngine(engine.MultiProcessEngine):
self._status_update_callback(self._processing_status)
for task in self._task_manager.GetAbandonedTasks():
+ error = error_containers.ExtractionError(
+ message=u'Worker failed to process pathspec',
+ path_spec=task.path_spec)
+ self._storage_writer.AddError(error)
self._processing_status.error_path_specs.append(task.path_spec)
self._status = definitions.PROCESSING_STATUS_IDLE
diff --git a/tools/pinfo.py b/tools/pinfo.py
index <HASH>..<HASH> 100755
--- a/tools/pinfo.py
+++ b/tools/pinfo.py
@@ -194,11 +194,12 @@ class PinfoTool(analysis_tool.AnalysisTool):
table_view.AddRow([u'Message', error.message])
table_view.AddRow([u'Parser chain', error.parser_chain])
- for index, line in enumerate(error.path_spec.comparable.split(u'\n')):
+ for pathspec_index, line in enumerate(
+ error.path_spec.comparable.split(u'\n')):
if not line:
continue
- if index == 0:
+ if pathspec_index == 0:
table_view.AddRow([u'Path specification', line])
else:
table_view.AddRow([u'', line]) | Code review: <I>: Add processing errors to storage. | log2timeline_plaso | train |
d71caefb8dca883e49a0aa3611e9115beeec9542 | diff --git a/lib/Proem/Controller/ControllerBase.php b/lib/Proem/Controller/ControllerBase.php
index <HASH>..<HASH> 100644
--- a/lib/Proem/Controller/ControllerBase.php
+++ b/lib/Proem/Controller/ControllerBase.php
@@ -49,8 +49,20 @@ class ControllerBase
*
* @param Proem\Http\Request
*/
- public function __construct(Request $request)
+ final function __construct(Request $request)
{
$this->request = $request;
+ $this->init();
+ }
+
+ /**
+ * Method called on object instantiation.
+ *
+ * Extend and use this method to pass dependencies into the
+ * controller, or setup whatever you need.
+ */
+ public function init()
+ {
+
}
} | Small improvements to the controller.
Lock down the __construct but allow an *init* method to be overwritten
to be able to pull in object wide dependencies. | proem_proem | train |
a9dab0fef35eee54ca822af944723d5ef9e37338 | diff --git a/src/DOM.js b/src/DOM.js
index <HASH>..<HASH> 100644
--- a/src/DOM.js
+++ b/src/DOM.js
@@ -1704,9 +1704,9 @@ class HTMLScriptElement extends HTMLLoadableElement {
return Promise.reject(new Error('script src got invalid status code: ' + res.status + ' : ' + url));
}
})
- .then(s => {
- utils._runJavascript(s, this.ownerDocument.defaultView, url); // XXX vm
-
+ .then(s => this.ownerDocument.defaultView.runAsync(s))
+ // utils._runJavascript(s, this.ownerDocument.defaultView, url); // XXX inject url into the call
+ .then(() => {
this.readyState = 'complete';
this.dispatchEvent(new Event('load', {target: this}));
@@ -1733,13 +1733,26 @@ class HTMLScriptElement extends HTMLLoadableElement {
const window = this.ownerDocument.defaultView;
return this.ownerDocument.resources.addResource((onprogress, cb) => {
- utils._runJavascript(innerHTML, window, window.location.href, this.location && this.location.line !== null ? this.location.line - 1 : 0, this.location && this.location.col !== null ? this.location.col - 1 : 0); // XXX vm
+ window.runAsync(innerHTML)
+ .then(() => {
+ // utils._runJavascript(innerHTML, window, window.location.href, this.location && this.location.line !== null ? this.location.line - 1 : 0, this.location && this.location.col !== null ? this.location.col - 1 : 0); // XXX inject url into the call
- this.readyState = 'complete';
-
- this.dispatchEvent(new Event('load', {target: this}));
+ this.readyState = 'complete';
+
+ this.dispatchEvent(new Event('load', {target: this}));
- cb();
+ cb();
+ })
+ .catch(err => {
+ this.readyState = 'complete';
+
+ const e = new ErrorEvent('error', {target: this});
+ e.message = err.message;
+ e.stack = err.stack;
+ this.dispatchEvent(e);
+
+ cb(err);
+ });
});
} | Clean up DOM.js run js calls | exokitxr_exokit | train |
b19fc03366002d7f7fec6b4bbc4924382c69eff3 | diff --git a/src/controls/VolumeControl.js b/src/controls/VolumeControl.js
index <HASH>..<HASH> 100644
--- a/src/controls/VolumeControl.js
+++ b/src/controls/VolumeControl.js
@@ -194,31 +194,30 @@ class VolumeControl extends PureComponent {
)}
/>
</button>
- {volumeBarPosition && (
- <div
- ref={this.setVolumeBarContainerRef}
+ <div
+ hidden={!volumeBarPosition}
+ ref={this.setVolumeBarContainerRef}
+ className={classNames(
+ 'rrap__volume_control__volume_bar_container',
+ volumeBarPosition
+ )}
+ >
+ <ProgressBar
className={classNames(
- 'rrap__volume_control__volume_bar_container',
+ 'rrap__volume_control__volume_bar',
volumeBarPosition
)}
- >
- <ProgressBar
- className={classNames(
- 'rrap__volume_control__volume_bar',
- volumeBarPosition
- )}
- progressClassName="volume"
- progress={muted ? 0 : volume}
- progressDirection={getVolumeBarDirectionFromPosition(
- volumeBarPosition
- )}
- handle={this.renderHandle()}
- adjusting={setVolumeInProgress}
- onAdjustProgress={onSetVolume}
- onAdjustComplete={onSetVolumeComplete}
- />
- </div>
- )}
+ progressClassName="volume"
+ progress={muted ? 0 : volume}
+ progressDirection={getVolumeBarDirectionFromPosition(
+ volumeBarPosition
+ )}
+ handle={this.renderHandle()}
+ adjusting={setVolumeInProgress}
+ onAdjustProgress={onSetVolume}
+ onAdjustComplete={onSetVolumeComplete}
+ />
+ </div>
</ButtonWrapper>
);
} | Volume bar stays in the DOM when hidden. | benwiley4000_cassette | train |
6e6489a40847de16eceed718152427d3239d135b | diff --git a/browser-providers.conf.js b/browser-providers.conf.js
index <HASH>..<HASH> 100644
--- a/browser-providers.conf.js
+++ b/browser-providers.conf.js
@@ -46,7 +46,7 @@ var customLaunchers = {
'SL_CHROME': {base: 'SauceLabs', browserName: 'chrome', version: '67'},
'SL_CHROMEBETA': {base: 'SauceLabs', browserName: 'chrome', version: 'beta'},
'SL_CHROMEDEV': {base: 'SauceLabs', browserName: 'chrome', version: 'dev'},
- 'SL_FIREFOX': {base: 'SauceLabs', browserName: 'firefox', version: '54'},
+ 'SL_FIREFOX': {base: 'SauceLabs', browserName: 'firefox', version: '61'},
'SL_FIREFOXBETA':
{base: 'SauceLabs', platform: 'Windows 10', browserName: 'firefox', version: 'beta'},
'SL_FIREFOXDEV': | ci: update firefox version to <I> (#<I>)
PR Close #<I> | angular_angular | train |
0a87da951031349d125dd8dab1000799f8f9f342 | diff --git a/lib/feedcellar/groonga_database.rb b/lib/feedcellar/groonga_database.rb
index <HASH>..<HASH> 100644
--- a/lib/feedcellar/groonga_database.rb
+++ b/lib/feedcellar/groonga_database.rb
@@ -30,9 +30,9 @@ module Feedcellar
feeds.add(key, attributes)
end
- def add(resource, title, link, description, date)
+ def add(resource_key, title, link, description, date)
feeds = Groonga["Feeds"]
- feeds.add(link, :resource => resource,
+ feeds.add(link, :resource => resources[resource_key],
:title => title,
:link => link,
:description => description,
@@ -93,7 +93,7 @@ module Feedcellar
end
schema.create_table("Feeds", :type => :hash) do |table|
- table.short_text("resource")
+ table.reference("resource", "Resources")
table.short_text("title")
table.short_text("link")
table.text("description") | Use "reference" for type of resource column of Feeds | feedcellar_feedcellar | train |
ed61ab8cc46b4447bf40cbab71a88365ecc092b1 | diff --git a/Task/ReportPluginData.php b/Task/ReportPluginData.php
index <HASH>..<HASH> 100644
--- a/Task/ReportPluginData.php
+++ b/Task/ReportPluginData.php
@@ -136,7 +136,11 @@ class ReportPluginData extends ReportHookDataFolder implements OptionsProviderIn
];
foreach ($data as $plugin_type_name => $plugin_type_info) {
- $mapping[$plugin_type_name] = $types[$plugin_type_info['discovery']];
+ // Quick hack: default to 'yaml' variant, as so far there's only
+ // migrations that we don't handle, which are YAML.
+ // TODO: when this is done in analysis, types we don't support should be
+ // filtered out.
+ $mapping[$plugin_type_name] = $types[$plugin_type_info['discovery']] ?? 'yaml';
}
return $mapping; | Fixed plugin types with discovery type not represented by a variant. | drupal-code-builder_drupal-code-builder | train |
ae0bd1e33bd3bc1e76e884ecc3d0924d6fc81b15 | diff --git a/Controller/AdministrationHomeTabController.php b/Controller/AdministrationHomeTabController.php
index <HASH>..<HASH> 100644
--- a/Controller/AdministrationHomeTabController.php
+++ b/Controller/AdministrationHomeTabController.php
@@ -134,7 +134,7 @@ class AdministrationHomeTabController extends Controller
$homeTabConfig->setHomeTab($homeTab);
$homeTabConfig->setType('admin_desktop');
$homeTabConfig->setLocked(false);
- $homeTabConfig->setVisible(false);
+ $homeTabConfig->setVisible(true);
$lastOrder = $this->homeTabManager
->getOrderOfLastAdminDesktopHomeTabConfig();
@@ -209,7 +209,7 @@ class AdministrationHomeTabController extends Controller
$homeTabConfig->setHomeTab($homeTab);
$homeTabConfig->setType('admin_workspace');
$homeTabConfig->setLocked(false);
- $homeTabConfig->setVisible(false);
+ $homeTabConfig->setVisible(true);
$lastOrder = $this->homeTabManager
->getOrderOfLastAdminWorkspaceHomeTabConfig();
@@ -580,7 +580,7 @@ class AdministrationHomeTabController extends Controller
$widgetHomeTabConfig = new WidgetHomeTabConfig();
$widgetHomeTabConfig->setHomeTab($homeTab);
$widgetHomeTabConfig->setWidget($widget);
- $widgetHomeTabConfig->setVisible(false);
+ $widgetHomeTabConfig->setVisible(true);
$widgetHomeTabConfig->setLocked(false);
$widgetHomeTabConfig->setType('admin');
diff --git a/Controller/Tool/HomeController.php b/Controller/Tool/HomeController.php
index <HASH>..<HASH> 100644
--- a/Controller/Tool/HomeController.php
+++ b/Controller/Tool/HomeController.php
@@ -410,7 +410,7 @@ class HomeController extends Controller
$homeTabConfig->setType('desktop');
$homeTabConfig->setUser($user);
$homeTabConfig->setLocked(false);
- $homeTabConfig->setVisible(false);
+ $homeTabConfig->setVisible(true);
$lastOrder = $this->homeTabManager->getOrderOfLastDesktopHomeTabConfigByUser($user);
@@ -692,7 +692,7 @@ class HomeController extends Controller
$homeTabConfig->setType('workspace');
$homeTabConfig->setWorkspace($workspace);
$homeTabConfig->setLocked(false);
- $homeTabConfig->setVisible(false);
+ $homeTabConfig->setVisible(true);
$lastOrder = $this->homeTabManager->getOrderOfLastWorkspaceHomeTabConfigByWorkspace($workspace);
@@ -1222,7 +1222,7 @@ class HomeController extends Controller
$widgetHomeTabConfig->setHomeTab($homeTab);
$widgetHomeTabConfig->setWidget($widget);
$widgetHomeTabConfig->setUser($user);
- $widgetHomeTabConfig->setVisible(false);
+ $widgetHomeTabConfig->setVisible(true);
$widgetHomeTabConfig->setLocked(false);
$widgetHomeTabConfig->setType('desktop');
@@ -1280,7 +1280,7 @@ class HomeController extends Controller
$widgetHomeTabConfig->setHomeTab($homeTab);
$widgetHomeTabConfig->setWidget($widget);
$widgetHomeTabConfig->setWorkspace($workspace);
- $widgetHomeTabConfig->setVisible(false);
+ $widgetHomeTabConfig->setVisible(true);
$widgetHomeTabConfig->setLocked(false);
$widgetHomeTabConfig->setType('workspace'); | [CoreBundle] Set default vivibility of hometab and their widgets to true | claroline_Distribution | train |
dfd1ef11af2385cde84f981bc9ae66c1c07bc6aa | diff --git a/lib/rules/indent.js b/lib/rules/indent.js
index <HASH>..<HASH> 100644
--- a/lib/rules/indent.js
+++ b/lib/rules/indent.js
@@ -623,6 +623,8 @@ module.exports = function(context) {
}
},
+ "ClassBody": blockIndentationCheck,
+
"BlockStatement": blockIndentationCheck,
"WhileStatement": blockLessNodes,
diff --git a/tests/lib/rules/indent.js b/tests/lib/rules/indent.js
index <HASH>..<HASH> 100644
--- a/tests/lib/rules/indent.js
+++ b/tests/lib/rules/indent.js
@@ -960,6 +960,50 @@ ruleTester.run("indent", rule, {
" 'y'\n" +
"]);\n",
options: [2]
+ },
+ {
+ code:
+ "var a = 1,\n" +
+ " B = class {\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ " };",
+ options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}],
+ ecmaFeatures: {classes: true}
+ },
+ {
+ code:
+ "var a = 1,\n" +
+ " B = \n" +
+ " class {\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ " },\n" +
+ " c = 3;",
+ options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}],
+ ecmaFeatures: {classes: true}
+ },
+ {
+ code:
+ "class A{\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ "}",
+ options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}],
+ ecmaFeatures: {classes: true}
+ },
+ {
+ code:
+ "var A = class {\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ "}",
+ options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}],
+ ecmaFeatures: {classes: true}
}
],
invalid: [
@@ -1757,6 +1801,59 @@ ruleTester.run("indent", rule, {
errors: expectedErrors([
[3, 3, 0, "VariableDeclaration"]
])
+ },
+ {
+ code:
+ "class A{\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ "}",
+ output:
+ "class A{\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ "}",
+ options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}],
+ ecmaFeatures: {classes: true},
+ errors: expectedErrors([[2, 4, 2, "MethodDefinition"]])
+ },
+ {
+ code:
+ "var A = class {\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ "};",
+ output:
+ "var A = class {\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ "};",
+ options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}],
+ ecmaFeatures: {classes: true},
+ errors: expectedErrors([[2, 4, 2, "MethodDefinition"], [4, 4, 2, "MethodDefinition"]])
+ },
+ {
+ code:
+ "var a = 1,\n" +
+ " B = class {\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ " };",
+ output:
+ "var a = 1,\n" +
+ " B = class {\n" +
+ " constructor(){}\n" +
+ " a(){}\n" +
+ " get b(){}\n" +
+ " };",
+ options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}],
+ ecmaFeatures: {classes: true},
+ errors: expectedErrors([[3, 6, 4, "MethodDefinition"]])
}
]
}); | Update: Add class body support to `indent` rule (fixes #<I>) | eslint_eslint | train |
0849e0c08da7f6529d85ca8086749c5e84c96b3f | diff --git a/tests/etl/test_buildbot.py b/tests/etl/test_buildbot.py
index <HASH>..<HASH> 100644
--- a/tests/etl/test_buildbot.py
+++ b/tests/etl/test_buildbot.py
@@ -1606,6 +1606,16 @@ buildernames = [
'platform': {'arch': 'x86_64',
'os': 'win',
'os_platform': 'windows8-64'}}),
+ ('Rev7 MacOSX Yosemite 10.10.5 try debug test mochitest-gpu-e10s',
+ {'build_type': 'debug',
+ 'job_type': 'unittest',
+ 'name': {'group_name': 'Mochitest e10s',
+ 'group_symbol': 'M-e10s',
+ 'name': 'Mochitest e10s GPU',
+ 'job_symbol': 'gpu'},
+ 'platform': {'arch': 'x86_64',
+ 'os': 'mac',
+ 'os_platform': 'osx-10-10'}}),
]
diff --git a/treeherder/etl/buildbot.py b/treeherder/etl/buildbot.py
index <HASH>..<HASH> 100644
--- a/treeherder/etl/buildbot.py
+++ b/treeherder/etl/buildbot.py
@@ -511,6 +511,8 @@ JOB_NAME_BUILDERNAME = [
{"regex": re.compile(r'mochitest-push'), "name": "Mochitest Push"},
{"regex": re.compile(r'mochitest-media-e10s'), "name": "Mochitest e10s Media"},
{"regex": re.compile(r'mochitest-media'), "name": "Mochitest Media"},
+ {"regex": re.compile(r'mochitest-gpu-e10s'), "name": "Mochitest e10s GPU"},
+ {"regex": re.compile(r'mochitest-gpu'), "name": "Mochitest GPU"},
{"regex": re.compile(r'mochitest'), "name": "Mochitest"},
{"regex": re.compile(r'webapprt-chrome$'), "name": "Webapprt Chrome"},
{"regex": re.compile(r'webapprt-content$'), "name": "Webapprt Content"},
@@ -711,6 +713,7 @@ GROUP_NAMES = {
"Mochitest": "Mochitest",
"Mochitest Push": "Mochitest",
"Mochitest Media": "Mochitest",
+ "Mochitest GPU": "Mochitest",
"Mochitest Browser Chrome": "Mochitest",
"Mochitest Browser Screenshots": "Mochitest",
"Mochitest Chrome": "Mochitest",
@@ -728,6 +731,7 @@ GROUP_NAMES = {
"Mochitest e10s DevTools Browser Chrome": "Mochitest e10s",
"Mochitest e10s Other": "Mochitest e10s",
"Mochitest e10s Push": "Mochitest e10s",
+ "Mochitest e10s GPU": "Mochitest e10s",
"Mochitest e10s Media": "Mochitest e10s",
"Mochitest e10s WebGL": "Mochitest e10s",
"Mochitest csb": "Mochitest csb",
@@ -924,6 +928,7 @@ SYMBOLS = {
"Mochitest": "M",
"Mochitest Push": "p",
"Mochitest Media": "mda",
+ "Mochitest GPU": "gpu",
"Mochitest Browser Chrome": "bc",
"Mochitest Browser Screenshots": "ss",
"Mochitest Chrome": "c",
@@ -939,6 +944,7 @@ SYMBOLS = {
"Mochitest e10s Other": "oth",
"Mochitest e10s Push": "p",
"Mochitest e10s Media": "mda",
+ "Mochitest e10s GPU": "gpu",
"Mochitest e10s WebGL": "gl",
"Mochitest csb": "M-csb",
"Mochitest OOP": "M-oop", | Bug <I> - Add support for Mochitest-gpu jobs | mozilla_treeherder | train |
c8f1b31714c4e7e68bd93dc5afb8efe361bba148 | diff --git a/utility.go b/utility.go
index <HASH>..<HASH> 100644
--- a/utility.go
+++ b/utility.go
@@ -36,3 +36,10 @@ func UTF16PtrToString(p *uint16) string {
}
return string(utf16.Decode(a[:i]))
}
+
+func convertHresultToError(hr uintptr, r2 uintptr, ignore error) (err error) {
+ if hr != 0 {
+ err = NewError(hr)
+ }
+ return
+} | Add utility function for converting hr to error. | go-ole_go-ole | train |
1e9f6f176c8086e9c40375ffba9b17a63b50d841 | diff --git a/src/main/java/org/komamitsu/fluency/Fluency.java b/src/main/java/org/komamitsu/fluency/Fluency.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/komamitsu/fluency/Fluency.java
+++ b/src/main/java/org/komamitsu/fluency/Fluency.java
@@ -188,7 +188,7 @@ public class Fluency
return flusher.isTerminated();
}
- public boolean waitUntilFlushingAllBuffer(int maxWaitSeconds)
+ public boolean waitUntilAllBufferFlushed(int maxWaitSeconds)
throws InterruptedException
{
int intervalMilli = 500;
diff --git a/src/test/java/org/komamitsu/fluency/FluencyTest.java b/src/test/java/org/komamitsu/fluency/FluencyTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/komamitsu/fluency/FluencyTest.java
+++ b/src/test/java/org/komamitsu/fluency/FluencyTest.java
@@ -30,7 +30,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
-import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
@@ -381,7 +380,7 @@ public class FluencyTest
try {
fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
fluency.emit("foo.bar", new HashMap<String, Object>());
- assertThat(fluency.waitUntilFlushingAllBuffer(2), is(true));
+ assertThat(fluency.waitUntilAllBufferFlushed(2), is(true));
}
finally {
if (fluency != null) {
@@ -398,7 +397,7 @@ public class FluencyTest
try {
fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build();
fluency.emit("foo.bar", new HashMap<String, Object>());
- assertThat(fluency.waitUntilFlushingAllBuffer(1), is(false));
+ assertThat(fluency.waitUntilAllBufferFlushed(1), is(false));
}
finally {
if (fluency != null) {
@@ -708,7 +707,7 @@ public class FluencyTest
else {
fluency.get().flush();
}
- fluency.get().waitUntilFlushingAllBuffer(10);
+ fluency.get().waitUntilAllBufferFlushed(10);
fluentd.stop();
secondaryFluentd.stop();
@@ -1019,7 +1018,7 @@ public class FluencyTest
for (Future<Void> future : futures) {
future.get(60, TimeUnit.SECONDS);
}
- fluency.waitUntilFlushingAllBuffer(60);
+ fluency.waitUntilAllBufferFlushed(60);
}
finally {
fluency.close();
@@ -1055,7 +1054,7 @@ public class FluencyTest
for (Future<Void> future : futures) {
future.get(60, TimeUnit.SECONDS);
}
- fluency.waitUntilFlushingAllBuffer(60);
+ fluency.waitUntilAllBufferFlushed(60);
}
finally {
fluency.close();
@@ -1084,7 +1083,7 @@ public class FluencyTest
for (Future<Void> future : futures) {
future.get(60, TimeUnit.SECONDS);
}
- fluency.waitUntilFlushingAllBuffer(60);
+ fluency.waitUntilAllBufferFlushed(60);
}
finally {
fluency.close(); | Rename Fluency#waitUntilFlushingAllBuffer to waitUntilAllBufferFlushed | komamitsu_fluency | train |
bbd2c9c607ec11bde7b714042459c2217636ec26 | diff --git a/src/share/classes/com/sun/tools/javac/comp/Check.java b/src/share/classes/com/sun/tools/javac/comp/Check.java
index <HASH>..<HASH> 100644
--- a/src/share/classes/com/sun/tools/javac/comp/Check.java
+++ b/src/share/classes/com/sun/tools/javac/comp/Check.java
@@ -2977,6 +2977,7 @@ public class Check {
boolean annotationApplicable(JCAnnotation a, Symbol s) {
Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
Name[] targets;
+
if (arr == null) {
targets = defaultTargetMetaInfo(a, s);
} else {
@@ -2993,7 +2994,7 @@ public class Check {
}
for (Name target : targets) {
if (target == names.TYPE)
- { if (s.kind == TYP && !s.isAnonymous()) return true; }
+ { if (s.kind == TYP) return true; }
else if (target == names.FIELD)
{ if (s.kind == VAR && s.owner.kind != MTH) return true; }
else if (target == names.METHOD) | Undo ChangeSet <I>cd9f<I> from work on bug <I>. | wmdietl_jsr308-langtools | train |
875e7c4db3b38e10b554390e3116c5f05d51ec9a | diff --git a/client.go b/client.go
index <HASH>..<HASH> 100644
--- a/client.go
+++ b/client.go
@@ -3,7 +3,9 @@ package groveclient
import (
"bytes"
"encoding/json"
+ "fmt"
"strings"
+ "time"
pc "github.com/t11e/go-pebbleclient"
)
@@ -13,7 +15,21 @@ import (
type Client interface {
Get(uid string, options GetOptions) (*PostItem, error)
GetMany(uids []string, options GetManyOptions) (*GetManyOutput, error)
- Update(postItem *PostItem) (*PostItem, error)
+ Update(uid string, pu PostUpdate, options UpdateOptions) (*PostItem, error)
+}
+
+type PostUpdate struct {
+ CreatedAt *time.Time `json:"created_at,omitempty"`
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+ Document json.RawMessage `json:"document,omitempty"`
+ ExternalDocument json.RawMessage `json:"external_document,omitempty"`
+ Sensitive json.RawMessage `json:"sensitive,omitempty"`
+ Protected json.RawMessage `json:"protected,omitempty"`
+ Tags *[]string `json:"tags,omitempty",`
+ Deleted *bool `json:"deleted,omitempty"`
+ Published *bool `json:"published,omitempty"`
+ ExternalId string `json:"external_id,omitempty"`
+ Version int `json:"version,omitempty"`
}
type client struct {
@@ -29,6 +45,11 @@ type GetManyOptions struct {
Raw *bool
}
+type UpdateOptions struct {
+ Merge *bool `json:"merge,omitempty"`
+ ExternalID *string `json:"external_id,omitempty"`
+}
+
type GetManyOutput struct {
Posts []PostItem `json:"posts"`
}
@@ -87,20 +108,39 @@ func (c *client) GetMany(uids []string, options GetManyOptions) (*GetManyOutput,
return &out, err
}
-func (c *client) Update(postItem *PostItem) (*PostItem, error) {
+func (c *client) Update(uid string, pu PostUpdate, options UpdateOptions) (*PostItem, error) {
params := pc.Params{
- "uid": postItem.Post.Uid,
+ "uid": uid,
+ }
+ if options.Merge != nil {
+ params["merge"] = *options.Merge
}
- payload, err := json.Marshal(postItem)
+ if options.ExternalID != nil {
+ params["external_id"] = *options.ExternalID
+ }
+ payload, err := json.Marshal(&struct {
+ Post PostUpdate `json:"post"`
+ }{pu})
if err != nil {
return nil, err
}
- var out PostItem
+ result := PostItem{}
err = c.c.Put("/posts/:uid", &pc.RequestOptions{
Params: params,
- }, bytes.NewReader(payload), &out)
- if err != nil {
- return nil, err
+ }, bytes.NewReader(payload), &result)
+ if err == nil {
+ return &result, nil
}
- return &out, err
+ if reqErr, ok := err.(*pc.RequestError); ok && reqErr.Resp.StatusCode == 409 {
+ return &result, ConflictError{uid}
+ }
+ return &result, err
+}
+
+type ConflictError struct {
+ uid string
+}
+
+func (e ConflictError) Error() string {
+ return fmt.Sprintf("grove post failed to update due to version conflict: %s", e.uid)
} | Improves Client.Update() to take a different struct so it can better
handle the optional field overrides that grove supports. Productizes a
simple ConflictError. | t11e_go-groveclient | train |
cfc7b6d2e27e34625ce3eceaa3d7aa3cd663e201 | diff --git a/src/catgen/in/javasrc/Catalog.java b/src/catgen/in/javasrc/Catalog.java
index <HASH>..<HASH> 100644
--- a/src/catgen/in/javasrc/Catalog.java
+++ b/src/catgen/in/javasrc/Catalog.java
@@ -36,7 +36,6 @@ public class Catalog extends CatalogType {
// package private version number
int m_currentCatalogVersion = 1;
- int m_changesMadePerUpdateCount = 0;
/**
* Create a new Catalog hierarchy.
@@ -55,7 +54,7 @@ public class Catalog extends CatalogType {
* newlines
*/
public void execute(final String commands) {
- m_changesMadePerUpdateCount = 0;
+ m_currentCatalogVersion++;
int ctr = 0;
for (String line : commands.split("\n")) {
@@ -71,9 +70,6 @@ public class Catalog extends CatalogType {
}
ctr++;
}
-
- if (m_changesMadePerUpdateCount > 0)
- m_currentCatalogVersion++;
}
void executeOne(String stmt) {
diff --git a/src/catgen/in/javasrc/CatalogMap.java b/src/catgen/in/javasrc/CatalogMap.java
index <HASH>..<HASH> 100644
--- a/src/catgen/in/javasrc/CatalogMap.java
+++ b/src/catgen/in/javasrc/CatalogMap.java
@@ -122,7 +122,6 @@ public final class CatalogMap<T extends CatalogType> implements Iterable<T> {
// update versioning if needed
updateVersioning();
- m_catalog.m_changesMadePerUpdateCount++;
// assign a relative index to every child item
int index = 1;
@@ -149,7 +148,6 @@ public final class CatalogMap<T extends CatalogType> implements Iterable<T> {
// update versioning if needed
updateVersioning();
- m_catalog.m_changesMadePerUpdateCount++;
// assign a relative index to every child item
int index = 1;
diff --git a/src/catgen/in/javasrc/CatalogType.java b/src/catgen/in/javasrc/CatalogType.java
index <HASH>..<HASH> 100644
--- a/src/catgen/in/javasrc/CatalogType.java
+++ b/src/catgen/in/javasrc/CatalogType.java
@@ -236,7 +236,6 @@ public abstract class CatalogType implements Comparable<CatalogType> {
}
void updateVersioning() {
- m_catalog.m_changesMadePerUpdateCount++;
if (m_nodeVersion != m_catalog.m_currentCatalogVersion) {
m_nodeVersion = m_catalog.m_currentCatalogVersion;
updateSubTreeVersion();
diff --git a/src/frontend/org/voltdb/CatalogContext.java b/src/frontend/org/voltdb/CatalogContext.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/CatalogContext.java
+++ b/src/frontend/org/voltdb/CatalogContext.java
@@ -90,10 +90,6 @@ public class CatalogContext {
catalogVersion = version;
}
- public CatalogContext deepCopy() {
- return new CatalogContext(catalog.deepCopy(), m_path, catalogVersion + 1);
- }
-
public CatalogContext update(String pathToNewJar, String diffCommands) {
Catalog newCatalog = catalog.deepCopy();
newCatalog.execute(diffCommands); | ENG-<I> Correct catalog sub-tree versioning implementation.
Code existed, in the direction of, a correct implementation for
catching out-of-date catalog updates. However, the subtree
versioning was not quite correct. | VoltDB_voltdb | train |
1483e981adf4ecc96c5abd01b9ea8dd1d5ced52d | diff --git a/src/Sly/NotificationPusher/Adapter/Apns.php b/src/Sly/NotificationPusher/Adapter/Apns.php
index <HASH>..<HASH> 100644
--- a/src/Sly/NotificationPusher/Adapter/Apns.php
+++ b/src/Sly/NotificationPusher/Adapter/Apns.php
@@ -36,6 +36,11 @@ use ZendService\Apple\Apns\Client\Feedback as ServiceFeedbackClient;
class Apns extends BaseAdapter
{
/**
+ * @var ServiceClient
+ */
+ private $openedClient;
+
+ /**
* {@inheritdoc}
*
* @throws \Sly\NotificationPusher\Exception\AdapterException
@@ -58,7 +63,7 @@ class Apns extends BaseAdapter
*/
public function push(PushInterface $push)
{
- $client = $this->getOpenedClient(new ServiceClient());
+ $client = $this->getOpenedClient();
$pushedDevices = new DeviceCollection();
@@ -103,19 +108,21 @@ class Apns extends BaseAdapter
/**
* Get opened client.
*
- * @param \ZendService\Apple\Apns\Client\AbstractClient $client Client
- *
* @return \ZendService\Apple\Apns\Client\AbstractClient
*/
- public function getOpenedClient(ServiceAbstractClient $client)
+ public function getOpenedClient()
{
- $client->open(
- $this->isProductionEnvironment() ? ServiceClient::PRODUCTION_URI : ServiceClient::SANDBOX_URI,
- $this->getParameter('certificate'),
- $this->getParameter('passPhrase')
- );
+ if (!isset($this->openedClient)) {
+ $this->openedClient = new ServiceClient();
+
+ $this->openedClient->open(
+ $this->isProductionEnvironment() ? ServiceClient::PRODUCTION_URI : ServiceClient::SANDBOX_URI,
+ $this->getParameter('certificate'),
+ $this->getParameter('passPhrase')
+ );
+ }
- return $client;
+ return $this->openedClient;
}
/**
diff --git a/src/Sly/NotificationPusher/Adapter/Gcm.php b/src/Sly/NotificationPusher/Adapter/Gcm.php
index <HASH>..<HASH> 100644
--- a/src/Sly/NotificationPusher/Adapter/Gcm.php
+++ b/src/Sly/NotificationPusher/Adapter/Gcm.php
@@ -40,6 +40,11 @@ class Gcm extends BaseAdapter
private $httpClient;
/**
+ * @var ServiceClient
+ */
+ private $openedClient;
+
+ /**
* {@inheritdoc}
*/
public function supports($token)
@@ -54,7 +59,7 @@ class Gcm extends BaseAdapter
*/
public function push(PushInterface $push)
{
- $client = $this->getOpenedClient(new ServiceClient());
+ $client = $this->getOpenedClient();
$pushedDevices = new DeviceCollection();
$tokens = array_chunk($push->getDevices()->getTokens(), 100);
@@ -80,22 +85,25 @@ class Gcm extends BaseAdapter
/**
* Get opened client.
*
- * @param \ZendService\Google\Gcm\Client $client Client
- *
* @return \ZendService\Google\Gcm\Client
*/
- public function getOpenedClient(ServiceClient $client)
+ public function getOpenedClient()
{
- $client->setApiKey($this->getParameter('apiKey'));
-
- $newClient = new \Zend\Http\Client(null, array(
- 'adapter' => 'Zend\Http\Client\Adapter\Socket',
- 'sslverifypeer' => false
- ));
-
- $client->setHttpClient($newClient);
+ if (!isset($this->openedClient)) {
+ $this->openedClient = new ServiceClient();
+ $this->openedClient->setApiKey($this->getParameter('apiKey'));
+
+ $newClient = new \Zend\Http\Client(
+ null, array(
+ 'adapter' => 'Zend\Http\Client\Adapter\Socket',
+ 'sslverifypeer' => false
+ )
+ );
+
+ $this->openedClient->setHttpClient($newClient);
+ }
- return $client;
+ return $this->openedClient;
}
/** | Setup the Gcm and Apns adapters to reuse their ServiceClient if one has been opened | Ph3nol_NotificationPusher | train |
82a5a2a1445b6bf7fe9cefed3f0bda636ad7b8b5 | diff --git a/lib/Doctrine/Common/ClassLoader.php b/lib/Doctrine/Common/ClassLoader.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Common/ClassLoader.php
+++ b/lib/Doctrine/Common/ClassLoader.php
@@ -184,7 +184,7 @@ class ClassLoader
return file_exists($this->includePath . DIRECTORY_SEPARATOR . $file);
}
- return self::fileExistsInIncludePath($file);
+ return (false !== stream_resolve_include_path($file));//self::fileExistsInIncludePath($file);
}
/**
@@ -264,13 +264,8 @@ class ClassLoader
* @param string $file The file relative path.
* @return boolean Whether file exists in include_path.
*/
- public static function fileExistsInIncludePath($file)
+ /*public static function fileExistsInIncludePath($file)
{
- foreach (explode(PATH_SEPARATOR, get_include_path()) as $dir) {
- if (file_exists($dir . DIRECTORY_SEPARATOR . $file)) {
- return true;
- }
- }
- return false;
- }
+ return (false !== stream_resolve_include_path($file));
+ }*/
} | [DCOM-<I>][PR-<I>] Changed obsolete function ClassLoader::fileExistsInIncludePath() to native PHP implementation stream_resolve_include_path(). | doctrine_common | train |
c0ab433186e60a54deeae59bd2e295dde524f559 | diff --git a/fuse/readonly/ipfs_test.go b/fuse/readonly/ipfs_test.go
index <HASH>..<HASH> 100644
--- a/fuse/readonly/ipfs_test.go
+++ b/fuse/readonly/ipfs_test.go
@@ -4,13 +4,14 @@ package readonly
import (
"bytes"
- "errors"
+ "context"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path"
- "sync"
+ "strconv"
+ "strings"
"testing"
core "github.com/ipfs/go-ipfs/core"
@@ -162,49 +163,45 @@ func TestIpfsStressRead(t *testing.T) {
paths = append(paths, npaths...)
}
- // Now read a bunch, concurrently
- wg := sync.WaitGroup{}
- errs := make(chan error)
+ t.Parallel()
for s := 0; s < 4; s++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
-
+ t.Run(strconv.Itoa(s), func(t *testing.T) {
for i := 0; i < 2000; i++ {
- item, _ := iface.ParsePath(paths[rand.Intn(len(paths))])
- fname := path.Join(mnt.Dir, item.String())
+ item, err := iface.ParsePath(paths[rand.Intn(len(paths))])
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ relpath := strings.Replace(item.String(), "/ipfs/", "/", 1)
+ fname := path.Join(mnt.Dir, relpath)
+
rbuf, err := ioutil.ReadFile(fname)
if err != nil {
- errs <- err
+ t.Fatal(err)
}
- read, err := api.Unixfs().Get(nd.Context(), item)
+ //nd.Context() is never closed which leads to
+ //hitting 8128 goroutine limit in go test -race mode
+ ctx, cancelFunc := context.WithCancel(context.Background())
+
+ read, err := api.Unixfs().Get(ctx, item)
if err != nil {
- errs <- err
+ t.Fatal(err)
}
data, err := ioutil.ReadAll(read.(files.File))
if err != nil {
- errs <- err
+ t.Fatal(err)
}
+ cancelFunc()
+
if !bytes.Equal(rbuf, data) {
- errs <- errors.New("incorrect read")
+ t.Fatal("incorrect read")
}
}
- }()
- }
-
- go func() {
- wg.Wait()
- close(errs)
- }()
-
- for err := range errs {
- if err != nil {
- t.Fatal(err)
- }
+ })
}
} | Fixed and cleaned up TestIpfsStressRead
License: MIT | ipfs_go-ipfs | train |
ebb0b3e3c5bc6096098d26632ad3725b183145fa | diff --git a/src/history.js b/src/history.js
index <HASH>..<HASH> 100644
--- a/src/history.js
+++ b/src/history.js
@@ -27,7 +27,7 @@ class Branch {
this.eventCount = eventCount
}
- // : (EditorState, bool) → ?{transform: Transform, selection: Selection | null, remaining: Branch | null}
+ // : (EditorState, bool) → ?{transform: Transform, selection: ?SelectionBookmark, remaining: Branch}
// Pop the latest event off the branch's history and apply it
// to a document transform.
popEvent(state, preserveItems) {
@@ -83,7 +83,7 @@ class Branch {
return {remaining, transform, selection}
}
- // : (Transform, Selection, Object)
+ // : (Transform, ?SelectionBookmark, Object) → Branch
// Create a new branch with the given transform added.
addTransform(transform, selection, histOptions, preserveItems) {
let newItems = [], eventCount = this.eventCount | Fix some type comments
Closes prosemirror/prosemirror#<I> | ProseMirror_prosemirror-history | train |
21b93a6bf2d60879cfd3e1ae4e533373ca9e530b | diff --git a/lib/modules/apostrophe-assets/public/js/always.js b/lib/modules/apostrophe-assets/public/js/always.js
index <HASH>..<HASH> 100644
--- a/lib/modules/apostrophe-assets/public/js/always.js
+++ b/lib/modules/apostrophe-assets/public/js/always.js
@@ -95,12 +95,6 @@ _.extend(apos, {
apos.ui.globalBusy(false);
// Make sure we run scripts in the returned HTML
$('[data-apos-refreshable]').html($.parseHTML(data, document, true));
- $(function() {
- setImmediate(function() {
- apos.emit('ready');
- apos.emit('enhance', $('[data-apos-refreshable]'));
- });
- });
}).fail(function() {
apos.ui.globalBusy(false);
});
@@ -116,13 +110,32 @@ _.extend(apos, {
mirror: apos.synth.mirror,
- pageReady: function() {
+ // The page is ready for the addition of event handlers and
+ // progressive enhancement of controls.
+ //
+ // Either the entire page is new, or the main content div,
+ // [data-apos-refreshable], has been refreshed.
+ //
+ // $el will be either $('body') or $('[data-apos-refreshable]'),
+ // as appropriate.
+ //
+ // This is not invoked until after DOM Ready and "next tick."
+
+ pageReady: function($el) {
+ apos.emit("ready");
+ apos.emit("enhance", $el);
+ },
+
+ // Wrapper that invokes pageReady after both DOM Ready and
+ // "next tick" so that code in pushed javascript files has had
+ // ample opportunity to run first. See pageReady
+
+ pageReadyWhenCalm: function($el) {
$(function() {
setImmediate(function() {
- apos.emit("ready");
- apos.emit("enhance", $('body'));
+ apos.pageReady($el);
});
- })
+ });
},
// Angular-compatible. Send the csrftoken cookie as the X-CSRFToken header.
diff --git a/lib/modules/apostrophe-templates/index.js b/lib/modules/apostrophe-templates/index.js
index <HASH>..<HASH> 100644
--- a/lib/modules/apostrophe-templates/index.js
+++ b/lib/modules/apostrophe-templates/index.js
@@ -579,7 +579,21 @@ module.exports = {
// Waits for DOMready to give other
// things maximum opportunity to happen.
- req.browserCall('apos.pageReady();');
+ var decorate = !(req.query.apos_refresh || req.query.xhr || req.xhr || (req.decorate === false));
+
+ if (req.query.apos_refresh) {
+ // Trigger the apos.ready and apos.enhance events after the
+ // DOM settles and pushed javascript has had a chance to run;
+ // do it just in the context of the refreshed main content div
+ req.browserCall('apos.pageReadyWhenCalm($("[data-apos-refreshable]"))');
+ } else if (decorate) {
+ // Trigger the apos.ready and apos.enhance events after the
+ // DOM settles and pushed javascript has had a chance to run
+ req.browserCall('apos.pageReadyWhenCalm($("body"));');
+ } else {
+ // If we're ajaxing something other than data-apos-refreshable,
+ // responsibility for progressive enhancement falls on the developer
+ }
// JavaScript may want to know who the user is. Provide
// just a conservative set of basics for security. Devs
@@ -593,8 +607,6 @@ module.exports = {
var reqCalls = req.getBrowserCalls();
- var decorate = !(req.query.apos_refresh || req.query.xhr || req.xhr || (req.decorate === false));
-
var args = {
outerLayout: decorate ? 'apostrophe-templates:outerLayout.html' : 'apostrophe-templates:refreshLayout.html',
permissions: (req.user && req.user._permissions) || {},
diff --git a/lib/modules/apostrophe-templates/views/refreshLayout.html b/lib/modules/apostrophe-templates/views/refreshLayout.html
index <HASH>..<HASH> 100644
--- a/lib/modules/apostrophe-templates/views/refreshLayout.html
+++ b/lib/modules/apostrophe-templates/views/refreshLayout.html
@@ -1,3 +1,8 @@
{% block beforeMain %}{% endblock %}
{% block main %}{% endblock %}
{% block afterMain %}{% endblock %}
+<script type="text/javascript">
+ {# globalCalls already will have happened at initial page load, but we should #}
+ {# make the request-specific calls #}
+ {{ data.js.reqCalls }}
+</script> | browser-side js calls made with req.browserCall should work when refreshing apos-refreshable due to a change event. The apos.change method should rely on this mechanism invoking apos.pageReady rather than duplicating that logic. pageReady should be invoked via a wrapper that handles domready/next tick chores so it is easier to read. | apostrophecms_apostrophe | train |
3f0c79f7f935f83601445f62249ee7ac28be67c6 | diff --git a/cake/libs/model/datasources/dbo/dbo_postgres.php b/cake/libs/model/datasources/dbo/dbo_postgres.php
index <HASH>..<HASH> 100644
--- a/cake/libs/model/datasources/dbo/dbo_postgres.php
+++ b/cake/libs/model/datasources/dbo/dbo_postgres.php
@@ -117,9 +117,6 @@ class DboPostgres extends DboSource {
$flags = array(
PDO::ATTR_PERSISTENT => $config['persistent']
);
- if (!empty($config['encoding'])) {
- $flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET search_path TO ' . $config['schema'];
- }
$this->_connection = new PDO(
"pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}",
$config['login'],
@@ -127,11 +124,13 @@ class DboPostgres extends DboSource {
$flags
);
+ $this->connected = true;
if (!empty($config['encoding'])) {
$this->setEncoding($config['encoding']);
}
-
- $this->connected = true;
+ if (!empty($config['schema'])) {
+ $this->_execute('SET search_path TO ' . $config['schema']);
+ }
} catch (PDOException $e) {
$this->errors[] = $e->getMessage();
} | Fixing some problems in in DboPostgres::connect() | cakephp_cakephp | train |
254bed8dabc24af1104b1f642adcfe4046611d4e | diff --git a/src/Sculpin/Bundle/SculpinBundle/Console/Application.php b/src/Sculpin/Bundle/SculpinBundle/Console/Application.php
index <HASH>..<HASH> 100644
--- a/src/Sculpin/Bundle/SculpinBundle/Console/Application.php
+++ b/src/Sculpin/Bundle/SculpinBundle/Console/Application.php
@@ -25,7 +25,7 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\HttpKernel\Bundle\BundleInterface;
+use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\KernelInterface;
@@ -154,7 +154,7 @@ class Application extends BaseApplication implements EmbeddedComposerAwareInterf
$this->kernel->boot();
foreach ($this->kernel->getBundles() as $bundle) {
- if ($bundle instanceof BundleInterface) {
+ if ($bundle instanceof Bundle) {
$bundle->registerCommands($this);
}
} | registerCommands moethod is not part of BundleInterface. | sculpin_sculpin | train |
30466c06cdc829dec9b974ab72a9787be5903138 | diff --git a/lib/rom/relation.rb b/lib/rom/relation.rb
index <HASH>..<HASH> 100644
--- a/lib/rom/relation.rb
+++ b/lib/rom/relation.rb
@@ -8,10 +8,13 @@ module ROM
undef_method :select
attr_reader :header
+ attr_reader :adapter_inclusions, :adapter_extensions
def initialize(dataset, header = dataset.header)
super
@header = header.dup.freeze
+ @adapter_inclusions = []
+ @adapter_extensions = []
end
def each(&block) | Add adapter inclusions/extensions to relation | rom-rb_rom | train |
ba1466f187a4568e7b9abd9c6c86031e5d0d9c12 | diff --git a/drivers/python/rethinkdb/_import.py b/drivers/python/rethinkdb/_import.py
index <HASH>..<HASH> 100755
--- a/drivers/python/rethinkdb/_import.py
+++ b/drivers/python/rethinkdb/_import.py
@@ -210,7 +210,7 @@ class SourceFile(object):
elif primaryKey != self.primary_key:
raise RuntimeError("Error: table %s.%s primary key was `%s` rather than the expected: %s" % (self.db, table.table, primaryKey, self.primary_key))
- def restore_indexes(self):
+ def restore_indexes(self, warning_queue):
# recreate secondary indexes - dropping existing on the assumption they are wrong
if self.indexes:
existing_indexes = self.query_runner("indexes from: %s.%s" % (self.db, self.table), query.db(self.db).table(self.table).index_list())
@@ -303,7 +303,7 @@ class SourceFile(object):
# - rebuild indexes
if self.indexes:
- self.restore_indexes()
+ self.restore_indexes(warning_queue)
# -
raise e | passing warning_queue where needed
over-the-virtual-shoulder by @danielmewes | rethinkdb_rethinkdb | train |
06d1d945c1b586c0026e203e2e3abb7ee6c20c45 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -9,7 +9,7 @@ from setuptools import setup
setup(
name='Flask-S3',
- version='0.1',
+ version='0.1.1',
url='http://github.com/e-dard/flask-s3',
license='WTFPL',
author='Edward Robinson', | bumped version for re-submission to Pypi | e-dard_flask-s3 | train |
d9037140e31c147bf8133d08be24e3731fc1ec6e | diff --git a/luigi/interface.py b/luigi/interface.py
index <HASH>..<HASH> 100644
--- a/luigi/interface.py
+++ b/luigi/interface.py
@@ -27,7 +27,7 @@ import re
import argparse
import sys
import os
-
+from importlib import import_module
from task import Register
@@ -58,6 +58,12 @@ def get_config():
return configuration.get_config()
+def init_task(module, task, str_params, global_str_params):
+ Task = getattr(import_module(module), task)
+
+ return Task.from_str_params(str_params, global_str_params)
+
+
class EnvironmentParamsContainer(task.Task):
''' Keeps track of a bunch of environment params.
diff --git a/luigi/worker.py b/luigi/worker.py
index <HASH>..<HASH> 100644
--- a/luigi/worker.py
+++ b/luigi/worker.py
@@ -31,7 +31,7 @@ import Queue
import luigi.interface
import sys
import types
-from importlib import import_module
+import interface
from target import Target
from task import Task, flatten, id_to_parsable
from event import Event
@@ -69,6 +69,7 @@ class TaskProcess(multiprocessing.Process):
status = FAILED
error_message = ''
missing = []
+ new_deps = []
try:
# Verify that all the tasks are fulfilled!
missing = [dep.task_id for dep in self.task.deps() if not dep.complete()]
@@ -85,10 +86,12 @@ class TaskProcess(multiprocessing.Process):
new_req = flatten(requires)
status = (RUNNING if all(t.complete() for t in new_req)
else SUSPENDED)
- new_deps = [t.task_id for t in new_req]
- self.result_queue.put(
- (self.task.task_id, status, '', missing, new_deps))
+ new_deps = [(t.task_family, t.to_str_params())
+ for t in new_req]
if status == RUNNING:
+ self.result_queue.put(
+ (self.task.task_id, status, '', missing,
+ new_deps))
continue
logger.info(
'[pid %s] Worker %s new requirements %s',
@@ -115,7 +118,7 @@ class TaskProcess(multiprocessing.Process):
notifications.send_error_email(subject, error_message)
finally:
self.result_queue.put(
- (self.task.task_id, status, error_message, missing, []))
+ (self.task.task_id, status, error_message, missing, new_deps))
class Worker(object):
@@ -394,7 +397,7 @@ class Worker(object):
self._task_result_queue.put(
(task_id, FAILED, error_msg, [], []))
- def _get_subtask(self, parent_task, task_id):
+ def _get_subtask(self, parent_task, task_name, params):
""" Imports task and uses ArgParseInterface to initialize it
"""
# How the module is represented depends on if Luigi was started from
@@ -403,15 +406,10 @@ class Worker(object):
if '__main__' == module.__name__:
parent_module_path = module.__file__
ending = parent_module_path.rfind('.py')
- import_path = parent_module_path[:ending].replace('/', '.')
+ actual_module = parent_module_path[:ending].replace('/', '.')
else:
- import_path = module.__name__
-
- task_name, parameters = id_to_parsable(task_id)
- Task = getattr(import_module(import_path), task_name)
-
- interface = luigi.interface.ArgParseInterface()
- return interface.parse(parameters, Task)[0]
+ actual_module = module.__name__
+ return interface.init_task(actual_module, task_name, params, {})
def _handle_next_task(self):
''' We have to catch three ways a task can be "done"
@@ -425,7 +423,7 @@ class Worker(object):
self._purge_children() # Deal with subprocess failures
try:
- task_id, status, error_message, missing, new_deps = (
+ task_id, status, error_message, missing, new_requirements = (
self._task_result_queue.get(
timeout=float(self.__wait_interval)))
except Queue.Empty:
@@ -433,15 +431,16 @@ class Worker(object):
task = self._scheduled_tasks[task_id]
if not task:
- conti
+ continue
# Not a scheduled task. Probably already removed.
# Maybe it yielded something?
- if new_deps:
-
- new_req = [self._get_subtask(task, new_task_id)
- for new_task_id in new_deps]
+ new_deps = []
+ if new_requirements:
+ new_req = [self._get_subtask(task, name, params)
+ for name, params in new_requirements]
for t in new_req:
self.add(t)
+ new_deps = [t.task_id for t in new_req]
self._scheduler.add_task(self._id,
task_id,
status=status,
@@ -484,7 +483,7 @@ class Worker(object):
"""Returns True if all scheduled tasks were executed successfully"""
logger.info('Running Worker with %d processes', self.worker_processes)
- sleeper = self._sleeper()
+ sleeper = self._sleeper()
self.run_succeeded = True
self._add_worker() | Change init proceduce for dynamic requirements
It used to be initialized using task_id now it's done using
task_family + str_params. | spotify_luigi | train |
145fef0e3e7bc18b7347d3b168db565480579d5c | diff --git a/lib/rules/lint-simple-unless.js b/lib/rules/lint-simple-unless.js
index <HASH>..<HASH> 100644
--- a/lib/rules/lint-simple-unless.js
+++ b/lib/rules/lint-simple-unless.js
@@ -28,7 +28,7 @@ module.exports = class LintSimpleUnless extends Rule {
} else {
this._followingElseBlock(node);
}
- } else if (nodePathOriginal === 'if') {
+ } else if (nodePathOriginal === 'if' && nodeInverse.body[0]) {
if (nodeInverse.body[0].path && nodeInverse.body[0].path.original === 'unless') {
this._asElseUnlessBlock(node);
}
diff --git a/test/unit/rules/lint-simple-unless-test.js b/test/unit/rules/lint-simple-unless-test.js
index <HASH>..<HASH> 100644
--- a/test/unit/rules/lint-simple-unless-test.js
+++ b/test/unit/rules/lint-simple-unless-test.js
@@ -12,6 +12,7 @@ generateRuleTests({
'<div class="{{unless foo \'no-foo\'}}"></div>',
'<div class="{{if foo \'foo\'}}"></div>',
'{{unrelated-mustache-without-params}}',
+ '{{#if foo}}{{else}}{{/if}}',
[
'{{#unless hamburger}}',
' HOT DOG!', | rule lint-simple-unless throws an error when template contains an empty inverse block
/template.hbs
-:- error Cannot read property 'path' of undefined undefined | ember-template-lint_ember-template-lint | train |
27dcc187f6f4eacfefee4fad908212d31c75153b | diff --git a/vendors.php b/vendors.php
index <HASH>..<HASH> 100755
--- a/vendors.php
+++ b/vendors.php
@@ -28,7 +28,7 @@ $deps = array(
array('doctrine-dbal', 'http://github.com/doctrine/dbal.git', 'origin/2.1.x'),
array('doctrine-common', 'http://github.com/doctrine/common.git', 'origin/2.1.x'),
array('monolog', 'http://github.com/Seldaek/monolog.git', '1.0.1'),
- array('swiftmailer', 'http://github.com/swiftmailer/swiftmailer.git', 'v4.1.1'),
+ array('swiftmailer', 'http://github.com/swiftmailer/swiftmailer.git', 'v4.1.2'),
array('twig', 'http://github.com/fabpot/Twig.git', 'v1.1.2'),
); | bumped versions of Swiftmailer | symfony_symfony | train |
3e5e0cfe1abf4993a22b4ce016dc666226c8e73c | diff --git a/ctx.go b/ctx.go
index <HASH>..<HASH> 100644
--- a/ctx.go
+++ b/ctx.go
@@ -22,14 +22,14 @@ func (f BindFunc) Bind(d Doner) { f(d) }
// Doner can block until something is done
type Doner interface {
- Done() C
+ Done() <-chan struct{}
}
// C is a basic implementation of Doner
type C <-chan struct{}
// Done returns a channel that receives when an action is complete
-func (dc C) Done() C { return dc }
+func (dc C) Done() <-chan struct{} { return dc }
// AsContext creates a context that fires when the Doner fires
func AsContext(d Doner) context.Context { | Revert back to original Doner definition, which Context satisfies | SentimensRG_ctx | train |
ad7a336c7e1c345d6bfd43f534444773e2151f0c | diff --git a/src/main/java/com/codeborne/selenide/commands/Commands.java b/src/main/java/com/codeborne/selenide/commands/Commands.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/codeborne/selenide/commands/Commands.java
+++ b/src/main/java/com/codeborne/selenide/commands/Commands.java
@@ -9,15 +9,19 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Commands {
- public static Commands collection = new Commands();
+ private static Commands collection;
private final Map<String, Command> commands = new ConcurrentHashMap<>(128);
- public Commands() {
- resetDefaults();
+ public static synchronized Commands getInstance() {
+ if (collection == null) {
+ collection = new Commands();
+ collection.resetDefaults();
+ }
+ return collection;
}
- public synchronized final void resetDefaults() {
+ public final synchronized void resetDefaults() {
commands.clear();
addFindCommands();
addClickCommands();
@@ -125,7 +129,8 @@ public class Commands {
}
@SuppressWarnings("unchecked")
- public <T> T execute(Object proxy, WebElementSource webElementSource, String methodName, Object[] args) throws IOException {
+ public synchronized <T> T execute(Object proxy, WebElementSource webElementSource, String methodName, Object[] args)
+ throws IOException {
Command command = commands.get(methodName);
if (command == null) {
throw new IllegalArgumentException("Unknown Selenide method: " + methodName);
diff --git a/src/main/java/com/codeborne/selenide/impl/SelenideElementProxy.java b/src/main/java/com/codeborne/selenide/impl/SelenideElementProxy.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/codeborne/selenide/impl/SelenideElementProxy.java
+++ b/src/main/java/com/codeborne/selenide/impl/SelenideElementProxy.java
@@ -9,6 +9,7 @@ import com.codeborne.selenide.logevents.SelenideLogger;
import org.openqa.selenium.InvalidElementStateException;
import org.openqa.selenium.WebDriverException;
+import java.io.FileNotFoundException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -50,7 +51,7 @@ class SelenideElementProxy implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object... args) throws Throwable {
if (methodsToSkipLogging.contains(method.getName()))
- return Commands.collection.execute(proxy, webElementSource, method.getName(), args);
+ return Commands.getInstance().execute(proxy, webElementSource, method.getName(), args);
validateAssertionMode();
@@ -82,7 +83,7 @@ class SelenideElementProxy implements InvocationHandler {
do {
try {
if (SelenideElement.class.isAssignableFrom(method.getDeclaringClass())) {
- return Commands.collection.execute(proxy, webElementSource, method.getName(), args);
+ return Commands.getInstance().execute(proxy, webElementSource, method.getName(), args);
}
return method.invoke(webElementSource.getWebElement(), args);
diff --git a/src/test/java/integration/OverrideCommandsTest.java b/src/test/java/integration/OverrideCommandsTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/integration/OverrideCommandsTest.java
+++ b/src/test/java/integration/OverrideCommandsTest.java
@@ -23,12 +23,12 @@ public class OverrideCommandsTest extends IntegrationTest {
@After
public void tearDown() {
- Commands.collection.resetDefaults();
+ Commands.getInstance().resetDefaults();
}
@Test
public void userCanOverrideAnyCommand() {
- Commands.collection.add("click", new MyClick());
+ Commands.getInstance().add("click", new MyClick());
$("#valid-image").click();
$("#invalid-image").click();
assertEquals(2, clickCounter.get());
diff --git a/src/test/java/integration/customcommands/CustomCommandsTest.java b/src/test/java/integration/customcommands/CustomCommandsTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/integration/customcommands/CustomCommandsTest.java
+++ b/src/test/java/integration/customcommands/CustomCommandsTest.java
@@ -8,7 +8,8 @@ import org.junit.Test;
import static com.codeborne.selenide.Condition.visible;
import static integration.customcommands.MyFramework.*;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
public class CustomCommandsTest extends IntegrationTest {
@Before
@@ -37,6 +38,6 @@ public class CustomCommandsTest extends IntegrationTest {
@After
public void resetSelenideDefaultCommands() {
- Commands.collection.resetDefaults();
+ Commands.getInstance().resetDefaults();
}
}
diff --git a/src/test/java/integration/customcommands/MyFramework.java b/src/test/java/integration/customcommands/MyFramework.java
index <HASH>..<HASH> 100644
--- a/src/test/java/integration/customcommands/MyFramework.java
+++ b/src/test/java/integration/customcommands/MyFramework.java
@@ -11,8 +11,8 @@ public class MyFramework {
static AtomicInteger quadrupleClickCounter = new AtomicInteger();
public static void setUp() {
- Commands.collection.add("tripleClick", new TripleClick());
- Commands.collection.add("quadrupleClick", new QuadrupleClick());
+ Commands.getInstance().add("tripleClick", new TripleClick());
+ Commands.getInstance().add("quadrupleClick", new QuadrupleClick());
}
/** | #<I> Do not create Commands instance, but on first usage | selenide_selenide | train |
30cc5261ac5369d1873d943d88718e563e08db57 | diff --git a/lib/Scaffolding.js b/lib/Scaffolding.js
index <HASH>..<HASH> 100644
--- a/lib/Scaffolding.js
+++ b/lib/Scaffolding.js
@@ -44,7 +44,7 @@ function (helpers, Write, result, assert, assertType, Env,
Scaffolding.prototype = {
constructor: Scaffolding,
type: "Scaffolding",
- tools: helpers.tools,
+ helpers: helpers.pub,
write: write.func,
_written: false,
status: undefined,
@@ -60,14 +60,13 @@ function (helpers, Write, result, assert, assertType, Env,
_assertType: assertType.assertType,
fetch: {
json: (function () {
-
- var Promise = (Promise) ? Promise : helpers.tools.fetch.Promise;
+ var lPromise = (Promise) ? Promise : helpers.pub.fetch.Promise;
function status(response) {
if (response.status >= 200 && response.status < 300) {
- return Promise.resolve(response);
+ return lPromise.resolve(response);
} else {
- return Promise.reject(response);
+ return lPromise.reject(response);
}
}
@@ -77,7 +76,7 @@ function (helpers, Write, result, assert, assertType, Env,
return function (url, postData) {
if ((typeof postData === 'string') && (postData === 'delete')) {
- return helpers.tools.fetch(url, {
+ return helpers.pub.fetch(url, {
method: 'delete',
headers: {
'Accept': 'application/json'
@@ -86,7 +85,7 @@ function (helpers, Write, result, assert, assertType, Env,
.then(status)
.then(json);
} else if (typeof postData === 'object') {
- return helpers.tools.fetch(url, {
+ return helpers.pub.fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json',
@@ -98,7 +97,7 @@ function (helpers, Write, result, assert, assertType, Env,
.then(json);
} else {
- return helpers.tools.fetch(url)
+ return helpers.pub.fetch(url)
.then(status)
.then(json);
}
diff --git a/lib/Suite.js b/lib/Suite.js
index <HASH>..<HASH> 100644
--- a/lib/Suite.js
+++ b/lib/Suite.js
@@ -16,7 +16,7 @@ function (helpers, Write, undefined) {
type: "Suite",
name: "",
desc: "",
- tools: helpers.tools,
+ helpers: helpers.pub,
write: write.func,
setup: undefined,
takedown: undefined,
diff --git a/lib/Test.js b/lib/Test.js
index <HASH>..<HASH> 100644
--- a/lib/Test.js
+++ b/lib/Test.js
@@ -19,7 +19,7 @@ function (helpers, Write, undefined) {
type: "Test",
name: "",
desc: "",
- tools: helpers.tools,
+ helpers: helpers.pub,
write: write.func,
setup: undefined,
takedown: undefined,
diff --git a/lib/helpers.js b/lib/helpers.js
index <HASH>..<HASH> 100644
--- a/lib/helpers.js
+++ b/lib/helpers.js
@@ -2,7 +2,7 @@ if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
-var _fetch, _bluebird;
+var _fetch = 'fetch', _bluebird;
if (typeof window === 'undefined') {
_fetch = 'node-fetch';
@@ -17,12 +17,12 @@ define([ _bluebird, _fetch ], function (bluebird, fetch, undefined) {
fetch = window.fetch;
}
- var tools = {
+ var pub = {
fetch: fetch
};
if (typeof Promise === 'undefined') {
- tools.fetch.Promise = bluebird;
+ pub.fetch.Promise = bluebird;
}
var runFunc = function () { this.result(true); };
@@ -35,7 +35,7 @@ define([ _bluebird, _fetch ], function (bluebird, fetch, undefined) {
};
return {
- tools: tools,
+ pub: pub,
runFunc: runFunc,
runFail: runFail
}; | renamed tools to helpers | silverbucket_jaribu | train |
1004542e17a5567b3d095c5f6415350ab62f0440 | diff --git a/ella/newman/media/js/newman.js b/ella/newman/media/js/newman.js
index <HASH>..<HASH> 100644
--- a/ella/newman/media/js/newman.js
+++ b/ella/newman/media/js/newman.js
@@ -148,8 +148,10 @@ var ContentByHashLib = {};
dec_loading();
// Restore the hash so it doesn't look like the request succeeded.
- url_target_id = ((info.target_id == 'content') ? '' : info.target_id+'::');
- adr(url_target_id + (LOADED_URLS[info.target_id] ? LOADED_URLS[info.target_id] : ''));
+ if (!DEBUG) { //FIXME: figure out what to do on request failure
+ url_target_id = ((info.target_id == 'content') ? '' : info.target_id+'::');
+ adr(url_target_id + (LOADED_URLS[info.target_id] ? LOADED_URLS[info.target_id] : ''));
+ }
carp('Failed to load '+info.address+' into '+info.target_id);
} | URLs are no longer restored after a failed request if DEBUG is on. | ella_ella | train |
f7a114f2b2efe3d1ba2e0a11ac5ee738164b16ce | diff --git a/lib/session/session.rb b/lib/session/session.rb
index <HASH>..<HASH> 100644
--- a/lib/session/session.rb
+++ b/lib/session/session.rb
@@ -81,36 +81,6 @@ module Session
self
end
- # Insert or update using the shift operator
- #
- # @see #persist
- #
- # @param [Object] object
- # the object to be persisted
- #
- # @example
- # # acts as update
- # person = session.first(Person)
- # person.firstname = 'John'
- # session << person
- #
- # @example
- # # acts as insert
- # person = Person.new('John', 'Doe')
- # session << person
- #
- # @api public
- #
- # @return [self]
- #
- # FIXME:
- # Use inheritable alias again when
- # Veritas::Aliasable is packaged as gem
- #
- def <<(object)
- persist(object)
- end
-
# Returns whether an domain object is tracked in this session
#
# @example
diff --git a/spec/unit/session/session/persist_spec.rb b/spec/unit/session/session/persist_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/session/session/persist_spec.rb
+++ b/spec/unit/session/session/persist_spec.rb
@@ -1,14 +1,13 @@
require 'spec_helper'
describe Session::Session, '#persist(object)' do
+ subject { object.persist(domain_object) }
+
let(:mapper) { registry.resolve_model(DomainObject) }
let(:registry) { DummyRegistry.new }
let(:domain_object) { DomainObject.new }
let(:object) { described_class.new(registry) }
- subject { object.persist(domain_object) }
-
-
context 'with untracked domain object' do
it 'should insert update' do
subject | Drop shift operator for persisting objects
The shift operator does not really make sense here. It was introduced
when there was a clear distinction between insert and update. But as
these both actions where merged into #persist I do not see the need for
the shift operator aynmore. | rom-rb_rom | train |
2323e00c5f911426f403fe367e74b39e9777af50 | diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/user_test.rb
+++ b/test/unit/user_test.rb
@@ -67,7 +67,8 @@ class UserTest < ActiveSupport::TestCase
end
def test_should_authenticate_user
- assert_equal @user, User.authenticate(@user.login, @user.password)
+ user = User.make(:login => "foo", :password => "bar")
+ assert_equal user, User.authenticate(user.login, user.password)
end
def test_should_set_remember_token | try to fix broken test on ci server | Graylog2_graylog2-server | train |
b53976d844b5f0b515dfe5a6272d7931952d4041 | diff --git a/grip/browser.py b/grip/browser.py
index <HASH>..<HASH> 100644
--- a/grip/browser.py
+++ b/grip/browser.py
@@ -3,16 +3,36 @@ import webbrowser
def is_server_running(host, port):
+ """
+ Checks whether a server is currently listening on the specified
+ host and port.
+ """
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return not sock.connect_ex((host, port)) == 0
-def start_browser(host, port):
- # Waiting for server to start
+def wait_for_server(host, port):
+ """
+ Blocks until a local server is listening on the specified
+ host and port.
+
+ This is intended to be used in conjunction with running
+ the Flask server.
+ """
while not is_server_running(host, port):
pass
+
+
+def start_browser(url):
+ """
+ Opens the specified URL in a new browser window.
+ """
try:
- browser_url = "http://{0}:{1}".format(host, port)
- webbrowser.open(browser_url)
+ webbrowser.open(url)
except:
pass
+
+
+def wait_and_start_browser(host, port):
+ wait_for_server(host, port)
+ start_browser('http://{0}:{1}/'.format(host, port))
diff --git a/grip/server.py b/grip/server.py
index <HASH>..<HASH> 100644
--- a/grip/server.py
+++ b/grip/server.py
@@ -19,7 +19,7 @@ from flask import (
from . import __version__
from .constants import default_filenames
from .renderer import render_content
-from .browser import start_browser
+from .browser import wait_and_start_browser
try:
from urlparse import urlparse, urljoin
@@ -184,7 +184,7 @@ def serve(path=None, host=None, port=None, gfm=False, context=None,
# Opening browser
if browser:
browser_thread = threading.Thread(
- target=start_browser,
+ target=wait_and_start_browser,
args=(app.config['HOST'], app.config['PORT']))
browser_thread.start() | Add 'wait' to the 'start_browser' name for clear intentions, break up function, and add comments. | joeyespo_grip | train |
e51a012cd58986b404acfbae909eec65eb98d4fa | diff --git a/Datagram/Socket.php b/Datagram/Socket.php
index <HASH>..<HASH> 100644
--- a/Datagram/Socket.php
+++ b/Datagram/Socket.php
@@ -20,7 +20,6 @@ class Socket extends EventEmitter
public function getAddress()
{
- // TODO: doc comment suggests IPv6 address is not enclosed in square brackets?
return $this->address;
}
diff --git a/Datagram/SocketReadable.php b/Datagram/SocketReadable.php
index <HASH>..<HASH> 100644
--- a/Datagram/SocketReadable.php
+++ b/Datagram/SocketReadable.php
@@ -34,7 +34,7 @@ class SocketReadable extends Socket
}
// create remote socket that does NOT have a dedicated readable method (see thie main DatagramSocket instead)
- $remote = new Socket($this->loop, $this->socket, $peer);
+ $remote = new Socket($this->loop, $this->socket, $this->sanitizeAddress($peer));
$this->emit('message', array($data, $remote));
}
@@ -45,4 +45,20 @@ class SocketReadable extends Socket
fclose($this->socket);
$this->socket = false;
}
+
+ private function sanitizeAddress($address)
+ {
+ // doc comment suggests IPv6 address is not enclosed in square brackets?
+
+ $pos = strrpos(':', $address);
+ // this is an IPv6 address which includes colons but no square brackets
+ if ($pos !== false && substr($address, 0, 1) !== '[') {
+ if (strpos(':', $address) < $pos) {
+ $port = substr($address, $pos + 1);
+ $address = '[' . substr($address, 0, $pos) . ']:' . $port;
+ }
+
+ }
+ return $address;
+ }
} | Always sanitize IPv6 addresses | reactphp_datagram | train |
f251d67b674e85b38aca0dc75d05634cfbd5c742 | diff --git a/spec/lyber_core/robots/robot_spec.rb b/spec/lyber_core/robots/robot_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lyber_core/robots/robot_spec.rb
+++ b/spec/lyber_core/robots/robot_spec.rb
@@ -41,6 +41,12 @@ describe LyberCore::Robots::Robot do
robot.workflow_step.should eql(wf_step)
robot.collection_name.should eql(collection)
end
+
+ it "can tell us what environment it's running in" do
+ pending
+ robot = TestRobot.new(wf_name, wf_step, :collection_name => collection)
+ robot.env.should eql("test")
+ end
# it "has a workflow after it has started" do
# ROBOT_ROOT = File.expand_path(File.dirname(__FILE__) + "/..") | Added a pending test for SDRTWO-<I> but I don't think we're ready to change the way we're setting environment yet | sul-dlss_lyber-core | train |
fcda578dec5d98ad9309d74beb57e3babddc011b | diff --git a/tests/copulas/bivariate/test_base.py b/tests/copulas/bivariate/test_base.py
index <HASH>..<HASH> 100644
--- a/tests/copulas/bivariate/test_base.py
+++ b/tests/copulas/bivariate/test_base.py
@@ -128,3 +128,28 @@ class TestBivariate(TestCase):
# Check
assert name == expected
+
+ @mock.patch('copulas.bivariate.clayton.Clayton.partial_derivative')
+ def test_partial_derivative_scalar(self, derivative_mock):
+ """partial_derivative_scalar calls partial_derivative with its arguments in an array."""
+ # Setup
+
+ U = 0.5
+ V = 0.1
+
+ expected_args = ((np.array([[0.5, 0.1]]), 0), {})
+ instance = Bivariate(CopulaTypes.CLAYTON)
+
+ instance.fit(self.X)
+
+ # Run
+ result = instance.partial_derivative_scalar(U, V)
+
+ # Check
+ assert result == derivative_mock.return_value
+ derivative_mock.assert_called_once
+
+ assert len(expected_args) == len(derivative_mock.call_args)
+ assert (derivative_mock.call_args[0][0] == expected_args[0][0]).all()
+ assert derivative_mock.call_args[0][1] == expected_args[0][1]
+ assert derivative_mock.call_args[1] == expected_args[1] | Add test for Bivariate.partial_derivative_scalar | DAI-Lab_Copulas | train |
1ec03ffb76315bc6536fa01d3272281bad194ff1 | diff --git a/src/template-result.js b/src/template-result.js
index <HASH>..<HASH> 100644
--- a/src/template-result.js
+++ b/src/template-result.js
@@ -1,11 +1,21 @@
+import { isAsyncIterator, isPromise } from './is.js';
import { AttributePart } from './parts.js';
import { emptyStringBuffer } from './string.js';
-import { isPromise } from './is.js';
const pool = [];
let id = 0;
/**
+ * Determine whether "result" is a TemplateResult
+ *
+ * @param { TemplateResult } result
+ * @returns { boolean }
+ */
+export function isTemplateResult(result) {
+ return result instanceof TemplateResult;
+}
+
+/**
* Retrieve TemplateResult instance.
* Uses an object pool to recycle instances.
*
@@ -27,16 +37,6 @@ export function templateResult(template, values) {
}
/**
- * Determine whether "result" is a TemplateResult
- *
- * @param { TemplateResult } result
- * @returns { boolean }
- */
-export function isTemplateResult(result) {
- return result instanceof TemplateResult;
-}
-
-/**
* A class for consuming the combined static and dynamic parts of a lit-html Template.
* TemplateResults
*/
@@ -176,7 +176,7 @@ function reduce(buffer, chunks, chunk, deep = false) {
}
} else if (Array.isArray(chunk)) {
return chunk.reduce((buffer, chunk) => reduce(buffer, chunks, chunk), buffer);
- } else if (isPromise(chunk)) {
+ } else if (isPromise(chunk) || isAsyncIterator(chunk)) {
chunks.push(buffer, chunk);
return emptyStringBuffer;
} | handle AsyncIterator when reducing | popeindustries_lit-html-server | train |
bf578d102459b80bc8e2c95a3d2ee877735a6982 | diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/Call/Method/ExistingAtomicMethodCallAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/Call/Method/ExistingAtomicMethodCallAnalyzer.php
index <HASH>..<HASH> 100644
--- a/src/Psalm/Internal/Analyzer/Statements/Expression/Call/Method/ExistingAtomicMethodCallAnalyzer.php
+++ b/src/Psalm/Internal/Analyzer/Statements/Expression/Call/Method/ExistingAtomicMethodCallAnalyzer.php
@@ -423,7 +423,7 @@ class ExistingAtomicMethodCallAnalyzer extends CallAnalyzer
$codebase = $statements_analyzer->getCodebase();
- $first_arg_value = $stmt->args[0]->value;
+ $first_arg_value = $stmt->args[0]->value ?? null;
if (!$first_arg_value instanceof PhpParser\Node\Scalar\String_) {
return null;
}
@@ -461,7 +461,9 @@ class ExistingAtomicMethodCallAnalyzer extends CallAnalyzer
// If a `@property` annotation is set, the type of the value passed to the
// magic setter must match the annotation.
- $second_arg_type = $statements_analyzer->node_data->getType($stmt->args[1]->value);
+ $second_arg_type = isset($stmt->args[1])
+ ? $statements_analyzer->node_data->getType($stmt->args[1]->value)
+ : null;
if (isset($class_storage->pseudo_property_set_types['$' . $prop_name]) && $second_arg_type) {
$pseudo_set_type = \Psalm\Internal\Type\TypeExpander::expandUnion(
diff --git a/tests/PropertyTypeTest.php b/tests/PropertyTypeTest.php
index <HASH>..<HASH> 100644
--- a/tests/PropertyTypeTest.php
+++ b/tests/PropertyTypeTest.php
@@ -3646,6 +3646,24 @@ class PropertyTypeTest extends TestCase
}',
'error_message' => 'PossiblyNullPropertyFetch',
],
+ 'noCrashWhenCallingMagicSet' => [
+ '<?php
+ class A {
+ public function __set(string $s, mixed $value) : void {}
+ }
+
+ (new A)->__set("foo");',
+ 'error_message' => 'TooFewArguments',
+ ],
+ 'noCrashWhenCallingMagicGet' => [
+ '<?php
+ class A {
+ public function __get(string $s) : mixed {}
+ }
+
+ (new A)->__get();',
+ 'error_message' => 'TooFewArguments',
+ ],
];
}
} | Fix potential crash when calling magic setter | vimeo_psalm | train |
babb028b86df3501cbc90cd08079febe7a2edb57 | diff --git a/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/SubProcessNodeInstance.java b/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/SubProcessNodeInstance.java
index <HASH>..<HASH> 100644
--- a/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/SubProcessNodeInstance.java
+++ b/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/SubProcessNodeInstance.java
@@ -23,6 +23,7 @@ import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
+import org.drools.core.common.InternalKnowledgeRuntime;
import org.drools.core.util.MVELSafeHelper;
import org.jbpm.process.core.Context;
import org.jbpm.process.core.ContextContainer;
@@ -184,9 +185,17 @@ public class SubProcessNodeInstance extends StateBasedNodeInstance implements Ev
public void cancel() {
super.cancel();
if (getSubProcessNode() == null || !getSubProcessNode().isIndependent()) {
- ProcessInstance processInstance = (ProcessInstance)
- ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime()
- .getProcessInstance(processInstanceId);
+ ProcessInstance processInstance = null;
+ InternalKnowledgeRuntime kruntime = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime();
+ RuntimeManager manager = (RuntimeManager) kruntime.getEnvironment().get("RuntimeManager");
+ if (manager != null) {
+ RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
+ KnowledgeRuntime managedkruntime = (KnowledgeRuntime) runtime.getKieSession();
+ processInstance = (ProcessInstance) managedkruntime.getProcessInstance(processInstanceId);
+ } else {
+ processInstance = (ProcessInstance) kruntime.getProcessInstance(processInstanceId);
+ }
+
if (processInstance != null) {
processInstance.setState(ProcessInstance.STATE_ABORTED);
} | JBPM-<I> - PerProcessInstanceRuntimeManager fails with dependent subprocess abort | kiegroup_jbpm | train |
802fec9bfd12afc3a3ef2ecad2120303e858eed6 | diff --git a/guacamole-common-js/src/main/webapp/modules/Keyboard.js b/guacamole-common-js/src/main/webapp/modules/Keyboard.js
index <HASH>..<HASH> 100644
--- a/guacamole-common-js/src/main/webapp/modules/Keyboard.js
+++ b/guacamole-common-js/src/main/webapp/modules/Keyboard.js
@@ -1293,7 +1293,7 @@ Guacamole.Keyboard = function Keyboard(element) {
// Type all content written
if (e.data && !e.isComposing) {
- element.removeEventListener("compositionend", handleComposition, true);
+ element.removeEventListener("compositionend", handleComposition, false);
guac_keyboard.type(e.data);
}
@@ -1319,15 +1319,15 @@ Guacamole.Keyboard = function Keyboard(element) {
// Type all content written
if (e.data) {
- element.removeEventListener("input", handleInput, true);
+ element.removeEventListener("input", handleInput, false);
guac_keyboard.type(e.data);
}
};
// Automatically type text entered into the wrapped field
- element.addEventListener("input", handleInput, true);
- element.addEventListener("compositionend", handleComposition, true);
+ element.addEventListener("input", handleInput, false);
+ element.addEventListener("compositionend", handleComposition, false);
}; | GUACAMOLE-<I>: Handle input/composition events while bubbling. | glyptodon_guacamole-client | train |
373b844cb284417520d250811928d8bce778e8c4 | diff --git a/projects/samskivert/src/java/com/samskivert/util/SystemInfo.java b/projects/samskivert/src/java/com/samskivert/util/SystemInfo.java
index <HASH>..<HASH> 100644
--- a/projects/samskivert/src/java/com/samskivert/util/SystemInfo.java
+++ b/projects/samskivert/src/java/com/samskivert/util/SystemInfo.java
@@ -1,5 +1,5 @@
//
-// $Id: SystemInfo.java,v 1.2 2003/01/14 22:31:27 shaper Exp $
+// $Id: SystemInfo.java,v 1.3 2003/01/15 01:27:44 shaper Exp $
//
// samskivert library - useful routines for java programs
// Copyright (C) 2003 Walter Korman
@@ -59,6 +59,10 @@ public class SystemInfo
/** The maximum amount of memory available in kilobytes. */
public long maxMemory;
+ /** Whether the video display is headless or video information is
+ * unavailable. */
+ public boolean isHeadless;
+
/** The video display bit depth; see {@link DisplayMode}. */
public int bitDepth;
@@ -104,15 +108,23 @@ public class SystemInfo
maxMemory = rtime.maxMemory() / 1024;
// determine video display information
- GraphicsEnvironment env =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
- GraphicsDevice gd = env.getDefaultScreenDevice();
- DisplayMode mode = gd.getDisplayMode();
- bitDepth = mode.getBitDepth();
- refreshRate = mode.getRefreshRate() / 1024;
- isFullScreen = (gd.getFullScreenWindow() != null);
- displayWidth = mode.getWidth();
- displayHeight = mode.getHeight();
+ isHeadless = GraphicsEnvironment.isHeadless();
+ if (!isHeadless) {
+ try {
+ GraphicsEnvironment env =
+ GraphicsEnvironment.getLocalGraphicsEnvironment();
+ GraphicsDevice gd = env.getDefaultScreenDevice();
+ DisplayMode mode = gd.getDisplayMode();
+ bitDepth = mode.getBitDepth();
+ refreshRate = mode.getRefreshRate() / 1024;
+ isFullScreen = (gd.getFullScreenWindow() != null);
+ displayWidth = mode.getWidth();
+ displayHeight = mode.getHeight();
+
+ } catch (Throwable t) {
+ isHeadless = true;
+ }
+ }
}
/**
@@ -148,6 +160,10 @@ public class SystemInfo
*/
public String videoToString ()
{
+ if (isHeadless) {
+ return "headless or unavailable";
+ }
+
String sdepth = (bitDepth == -1) ? "unknown bit depth" :
bitDepth + "-bit";
String srate = (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) ? | Deal gracefully with systems running with a headless AWT toolkit, or
general failure to obtain the graphics environment or other video
information.
git-svn-id: <URL> | samskivert_samskivert | train |
e2b3b0b2683f710dc50652292d2a8e25202e0941 | diff --git a/src/com/opencms/flex/CmsJspLoader.java b/src/com/opencms/flex/CmsJspLoader.java
index <HASH>..<HASH> 100644
--- a/src/com/opencms/flex/CmsJspLoader.java
+++ b/src/com/opencms/flex/CmsJspLoader.java
@@ -1,7 +1,7 @@
/*
* File : $Source: /alkacon/cvs/opencms/src/com/opencms/flex/Attic/CmsJspLoader.java,v $
-* Date : $Date: 2002/10/31 11:40:39 $
-* Version: $Revision: 1.9 $
+* Date : $Date: 2002/11/17 13:58:41 $
+* Version: $Revision: 1.10 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
@@ -46,7 +46,6 @@ import com.opencms.util.Encoder;
import com.opencms.util.Utils;
import com.opencms.flex.cache.*;
import com.opencms.flex.jsp.*;
-import com.opencms.flex.util.CmsPropertyLookup;
/**
* The JSP loader which enables the execution of JSP in OpenCms.<p>
@@ -57,7 +56,7 @@ import com.opencms.flex.util.CmsPropertyLookup;
*
* @author Alexander Kandzior ([email protected])
*
- * @version $Revision: 1.9 $
+ * @version $Revision: 1.10 $
* @since FLEX alpha 1
*
* @see I_CmsResourceLoader
@@ -174,24 +173,25 @@ public class CmsJspLoader implements I_CmsLauncher, I_CmsResourceLoader {
/*
// This works :-)
try {
- // TODO: Build the exportUrl automatically from the server settings
+ // TODO: static export of JSP pages
+ // 1: Build the exportUrl automatically from the server settings
// [ok] Maybe have some setting in opencms.properties
// Default settings could be used in servlet to calculate server / webapp / context
- // TODO: Check possibility to not make http request in case element is
+ // 2: Check possibility to not make http request in case element is
// [ok] already cached in FlexCache
// However, FlexCache shoule be empty anyway since publish
// had occured, so element will never be found in cache.
- // TODO: Add parameters to the exportUrl (don't forget to encode)
+ // 3: Add parameters to the exportUrl (don't forget to encode)
// [ok]
- // TODO: Must make a check / setting so that the http request is
+ // 4: Must make a check / setting so that the http request is
// recognized as export request, prop. "_flex=export"
// Set "mode" of CmsObject to "export" using cms.setMode(int)
// Put the collected links from the vector
// cms.getRequestContext().getLinkVector() back through the request,
// probably as a header in the http response (?)
- // TODO: Add handling of included JSP sub-elements
+ // 5: Add handling of included JSP sub-elements
// Maybe have some new parameter _flex=export
// It is important to ensure the URI/pathInfo is in sync for exported/not exported elements
// In export with request like below, URI will be URI of sub-element
@@ -208,7 +208,7 @@ public class CmsJspLoader implements I_CmsLauncher, I_CmsResourceLoader {
String values[] = (String[])context.getRequest().getParameterValues(key);
for (int i=0; i<values.length; i++) {
exportUrl += key + "=";
- exportUrl += Encoder.encode(values[i], "'UTF-8", true);
+ exportUrl += Encoder.encode(values[i], "UTF-8", true);
if ((i+1)<values.length) exportUrl+="&";
}
if (params.hasMoreElements()) exportUrl+="&";
@@ -585,7 +585,7 @@ public class CmsJspLoader implements I_CmsLauncher, I_CmsResourceLoader {
contents = req.getCmsObject().readFile(file.getAbsolutePath()).getContents();
// Encoding project:
// Check the JSP "content-encoding" property
- jspEncoding = CmsPropertyLookup.lookupProperty(cms, file.getAbsolutePath(), I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, false);
+ jspEncoding = cms.readProperty(file.getAbsolutePath(), I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, false);
if (jspEncoding == null) jspEncoding = C_DEFAULT_JSP_ENCODING;
jspEncoding = jspEncoding.trim().toLowerCase();
} catch (CmsException e) { | Moved propertyLookup() into CmsObject | alkacon_opencms-core | train |
4952a80200cf916636b1e0ca11985bbd09f42a80 | diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index <HASH>..<HASH> 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -9,26 +9,45 @@ class CacheKeyTest < ActiveSupport::TestCase
end
def test_expand_cache_key_with_rails_cache_id
- ENV['RAILS_APP_VERSION'] = nil
- ENV['RAILS_CACHE_ID'] = 'c99'
- assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo)
- assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key([:foo])
- assert_equal 'c99/c99/foo/c99/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar])
- assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key(:foo, :nm)
- assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key([:foo], :nm)
- assert_equal 'nm/c99/c99/foo/c99/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm)
+ begin
+ ENV['RAILS_CACHE_ID'] = 'c99'
+ assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo)
+ assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key([:foo])
+ assert_equal 'c99/c99/foo/c99/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar])
+ assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key(:foo, :nm)
+ assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key([:foo], :nm)
+ assert_equal 'nm/c99/c99/foo/c99/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm)
+ ensure
+ ENV['RAILS_CACHE_ID'] = nil
+ end
end
def test_expand_cache_key_with_rails_app_version
- ENV['RAILS_CACHE_ID'] = nil
- ENV['RAILS_APP_VERSION'] = 'rails3'
- assert_equal 'rails3/foo', ActiveSupport::Cache.expand_cache_key(:foo)
+ begin
+ ENV['RAILS_APP_VERSION'] = 'rails3'
+ assert_equal 'rails3/foo', ActiveSupport::Cache.expand_cache_key(:foo)
+ ensure
+ ENV['RAILS_APP_VERSION'] = nil
+ end
end
def test_expand_cache_key_rails_cache_id_should_win_over_rails_app_version
- ENV['RAILS_CACHE_ID'] = 'c99'
- ENV['RAILS_APP_VERSION'] = 'rails3'
- assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo)
+ begin
+ ENV['RAILS_CACHE_ID'] = 'c99'
+ ENV['RAILS_APP_VERSION'] = 'rails3'
+ assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo)
+ ensure
+ ENV['RAILS_CACHE_ID'] = nil
+ ENV['RAILS_APP_VERSION'] = nil
+ end
+ end
+
+ def test_respond_to_cache_key
+ key = 'foo'
+ def key.cache_key
+ :foo_key
+ end
+ assert_equal 'foo_key', ActiveSupport::Cache.expand_cache_key(key)
end
end | adding test for respond_to cache_key and cleaning up the ENV settings | rails_rails | train |
24148f8c8b197ad2114c80795f9fd24f601bd84a | diff --git a/chance.js b/chance.js
index <HASH>..<HASH> 100644
--- a/chance.js
+++ b/chance.js
@@ -63,6 +63,15 @@
}
}
+ function gen_random(num){
+ var ranNum = Math.round(Math.random()*num);
+ return ranNum;
+ }
+
+ function mod(dividen,divisor) {
+ return Math.round(dividen - (Math.floor(dividen/divisor)*divisor));
+ }
+
// -- Basics --
Chance.prototype.bool = function (options) {
@@ -511,6 +520,33 @@
return ssn;
};
+ // CPF; ID to identify taxpayers in Brazil
+ Chance.prototype.cpf = function (){
+ var n = 9;
+ var n1 = gen_random(n);
+ var n2 = gen_random(n);
+ var n3 = gen_random(n);
+ var n4 = gen_random(n);
+ var n5 = gen_random(n);
+ var n6 = gen_random(n);
+ var n7 = gen_random(n);
+ var n8 = gen_random(n);
+ var n9 = gen_random(n);
+ var d1 = n9*2+n8*3+n7*4+n6*5+n5*6+n4*7+n3*8+n2*9+n1*10;
+ d1 = 11 - ( mod(d1,11) );
+ if (d1>=10){
+ d1 = 0;
+ }
+ var d2 = d1*2+n9*3+n8*4+n7*5+n6*6+n5*7+n4*8+n3*9+n2*10+n1*11;
+ d2 = 11 - ( mod(d2,11) );
+ if (d2>=10){
+ d2 = 0;
+ }
+ result = '';
+ result = ''+n1+n2+n3+'.'+n4+n5+n6+'.'+n7+n8+n9+'-'+d1+d2;
+ return result;
+ }
+
// -- End Person --
// -- Web --
diff --git a/test/test.person.js b/test/test.person.js
index <HASH>..<HASH> 100644
--- a/test/test.person.js
+++ b/test/test.person.js
@@ -155,5 +155,16 @@ define(['Chance', 'mocha', 'chai', 'underscore'], function (Chance, mocha, chai,
});
});
});
+
+ describe("cpf()", function () {
+ it("returns a random valid taxpayer number for Brazil citizens (CPF)", function () {
+ _(1000).times(function () {
+ cpf = chance.cpf();
+ expect(cpf).to.be.a('string');
+ expect(cpf).to.match(/^\d{3}.\d{3}.\d{3}-\d{2}$/m);
+ expect(cpf).to.have.length(14);
+ });
+ });
+ });
});
}); | Added CPF generator for getting a taxpayer id for Brazil citizens. Basic test included. | chancejs_chancejs | train |
fb147693839fe994c89a60d2780f8484b0edc100 | diff --git a/pkg/macaron/binding/binding.go b/pkg/macaron/binding/binding.go
index <HASH>..<HASH> 100644
--- a/pkg/macaron/binding/binding.go
+++ b/pkg/macaron/binding/binding.go
@@ -419,6 +419,10 @@ func validateField(errors Errors, zero interface{}, field reflect.StructField, f
sliceVal = sliceVal.Elem()
}
+ if sliceVal.Kind() == reflect.Invalid {
+ continue
+ }
+
sliceValue := sliceVal.Interface()
zero := reflect.Zero(sliceVal.Type()).Interface()
if sliceVal.Kind() == reflect.Struct || | Macaron: Continue on invalid slice type to avoid panic (#<I>)
Makes the panic go away.
Otherwise I get a reflect: call of reflect.Value.Interface on zero Value | grafana_grafana | train |
e8601da16ae01945bea2a21560dad6d0e11762ef | diff --git a/shellish/command/supplement.py b/shellish/command/supplement.py
index <HASH>..<HASH> 100644
--- a/shellish/command/supplement.py
+++ b/shellish/command/supplement.py
@@ -142,8 +142,78 @@ class VTMLHelpFormatter(argparse.HelpFormatter):
else:
default = action.default
prefix = '[<b>%s</b>] %s ' % (default, prefix)
- vhelp = rendering.vtmlrender('%s<blue>%s</blue>' % (prefix, help))
- return str(vhelp.plain() if not sys.stdout.isatty() else vhelp)
+ return prefix, help
+
+ def _format_usage(self, *args, **kwargs):
+ usage = '\n%s' % super()._format_usage(*args, **kwargs)
+ return '\n'.join(str(rendering.vtmlrender('<red>%s</red>' % x))
+ for x in usage.split('\n'))
+
+ def _format_action(self, action):
+ # determine the required width and the entry label
+ help_position = min(self._action_max_length + 2,
+ self._max_help_position)
+ help_width = max(self._width - help_position, 11)
+ action_width = help_position - self._current_indent - 2
+ action_header = self._format_action_invocation(action)
+
+ # no help; start on same line and add a final newline
+ if not action.help:
+ tup = self._current_indent, '', action_header
+ action_header = '%*s%s\n' % tup
+
+ # short action name; start on the same line and pad two spaces
+ elif len(action_header) <= action_width:
+ tup = self._current_indent, '', action_width, action_header
+ action_header = '%*s%-*s ' % tup
+ indent_first = 0
+
+ # long action name; start on the next line
+ else:
+ tup = self._current_indent, '', action_header
+ action_header = '%*s%s\n' % tup
+ indent_first = help_position
+
+ # collect the pieces of the action help
+ parts = [action_header]
+
+ # if there was help for the action, add lines of help text
+ if action.help:
+ help_prefix, help_text = self._expand_help(action)
+ help_lines = []
+ for x in self._split_lines(help_text, help_width):
+ line = rendering.vtmlrender('<blue>%s</blue>' % x)
+ line = str(line.plain() if not sys.stdout.isatty() else line)
+ help_lines.append(line)
+ if help_lines:
+ parts.append('%*s%s\n' % (indent_first, help_prefix, help_lines[0]))
+ for line in help_lines[1:]:
+ parts.append('%*s%s\n' % (help_position, '', line))
+
+ # or add a newline if the description doesn't end with one
+ elif not action_header.endswith('\n'):
+ parts.append('\n')
+
+ # if there are any sub-actions, add their help as well
+ for subaction in self._iter_indented_subactions(action):
+ parts.append(self._format_action(subaction))
+
+ # return a single string
+ return self._join_parts(parts)
+
+ def _expand_help(self, action):
+ params = dict(vars(action), prog=self._prog)
+ for name in list(params):
+ if params[name] is argparse.SUPPRESS:
+ del params[name]
+ for name in list(params):
+ if hasattr(params[name], '__name__'):
+ params[name] = params[name].__name__
+ if params.get('choices') is not None:
+ choices_str = ', '.join([str(c) for c in params['choices']])
+ params['choices'] = choices_str
+ prefix, text = self._get_help_string(action)
+ return prefix, (text % params)
class SafeFileContext(object): | Help colorization fixes
Had to copy/pasta more argparse. :( | mayfield_shellish | train |
7fa0c2e910c34617e98acfcb683242610bdbd08d | diff --git a/doc/tasks/psalm.md b/doc/tasks/psalm.md
index <HASH>..<HASH> 100644
--- a/doc/tasks/psalm.md
+++ b/doc/tasks/psalm.md
@@ -8,6 +8,11 @@ It lives under the `psalm` namespace and has following configurable parameters:
composer require --dev vimeo/psalm
```
+If you'd like to use the Phar version
+```bash
+composer require --dev psalm/phar
+```
+
## Config
```yaml
# grumphp.yml
diff --git a/spec/Locator/ExternalCommandSpec.php b/spec/Locator/ExternalCommandSpec.php
index <HASH>..<HASH> 100644
--- a/spec/Locator/ExternalCommandSpec.php
+++ b/spec/Locator/ExternalCommandSpec.php
@@ -4,7 +4,6 @@ namespace spec\GrumPHP\Locator;
use GrumPHP\Exception\RuntimeException;
use GrumPHP\Locator\ExternalCommand;
-use GrumPHP\Util\Filesystem;
use PhpSpec\ObjectBehavior;
use Symfony\Component\Process\ExecutableFinder;
@@ -23,6 +22,7 @@ class ExternalCommandSpec extends ObjectBehavior
function it_throws_exception_when_external_command_is_not_found(ExecutableFinder $executableFinder)
{
$executableFinder->find('test', null, ['bin'])->willReturn(false);
+ $executableFinder->find('test.phar', null, ['bin'])->willReturn(false);
$this->shouldThrow(RuntimeException::class)->duringLocate('test');
}
@@ -31,4 +31,17 @@ class ExternalCommandSpec extends ObjectBehavior
$executableFinder->find('test', null, ['bin'])->willReturn('bin/test');
$this->locate('test')->shouldEqual('bin/test');
}
+
+ function it_locates_external_commands_with_a_suffix(ExecutableFinder $executableFinder)
+ {
+ $executableFinder->find('test', null, ['bin'])->willReturn(false);
+ $executableFinder->find('test.phar', null, ['bin'])->willReturn('bin/test.phar');
+ $this->locate('test')->shouldEqual('bin/test.phar');
+ }
+
+ function it_locates_external_commands_without_suffix_first(ExecutableFinder $executableFinder) {
+ $executableFinder->find('test', null, ['bin'])->willReturn('bin/test');
+ $executableFinder->find('test.phar', null, ['bin'])->willReturn('bin/test.phar');
+ $this->locate('test')->shouldEqual('bin/test');
+ }
}
diff --git a/src/Locator/ExternalCommand.php b/src/Locator/ExternalCommand.php
index <HASH>..<HASH> 100644
--- a/src/Locator/ExternalCommand.php
+++ b/src/Locator/ExternalCommand.php
@@ -10,6 +10,8 @@ use Symfony\Component\Process\ExecutableFinder;
class ExternalCommand
{
+ private $suffixes = ['', '.phar'];
+
/**
* @var string
*/
@@ -36,8 +38,17 @@ class ExternalCommand
public function locate(string $command): string
{
- // Search executable:
- $executable = $this->executableFinder->find($command, null, [$this->binDir]);
+ $executable = false;
+ foreach ($this->suffixes as $suffix) {
+ $cmdName = $command . $suffix;
+ // Search executable:
+ $executable = $this->executableFinder->find($cmdName, null, [$this->binDir]);
+
+ if ($executable) {
+ break;
+ }
+ }
+
if (!$executable) {
throw new RuntimeException(
sprintf('The executable for "%s" could not be found.', $command) | Add support for phar executables on non-windows environments | phpro_grumphp | train |
8803304f4c79f7ec9049d83d767189c9e91f1705 | diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobCache.java b/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobCache.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobCache.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobCache.java
@@ -57,7 +57,7 @@ public final class BlobCache implements BlobService {
LOG.info("Created BLOB cache storage directory " + storageDir);
// Add shutdown hook to delete storage directory
- BlobUtils.addDeleteDirectoryShutdownHook(storageDir);
+ BlobUtils.addDeleteDirectoryShutdownHook(storageDir, LOG);
}
/**
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobServer.java b/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobServer.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobServer.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobServer.java
@@ -115,7 +115,7 @@ public final class BlobServer extends Thread implements BlobService{
LOG.info("Created BLOB server storage directory " + storageDir);
// Add shutdown hook to delete storage directory
- BlobUtils.addDeleteDirectoryShutdownHook(storageDir);
+ BlobUtils.addDeleteDirectoryShutdownHook(storageDir, LOG);
}
catch (IOException e) {
throw new IOException("Could not create BlobServer with random port.", e);
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobUtils.java b/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobUtils.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobUtils.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobUtils.java
@@ -23,6 +23,7 @@ import org.apache.commons.io.FileUtils;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.runtime.jobgraph.JobID;
+import org.slf4j.Logger;
import java.io.File;
import java.io.IOException;
@@ -34,6 +35,7 @@ import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
public class BlobUtils {
+
/**
* Algorithm to be used for calculating the BLOB keys.
*/
@@ -197,7 +199,7 @@ public class BlobUtils {
/**
* Adds a shutdown hook to the JVM to delete the given directory.
*/
- static void addDeleteDirectoryShutdownHook(final File dir) {
+ static void addDeleteDirectoryShutdownHook(final File dir, final Logger errorLogger) {
checkNotNull(dir);
// Add shutdown hook to delete directory
@@ -207,8 +209,8 @@ public class BlobUtils {
try {
FileUtils.deleteDirectory(dir);
}
- catch (IOException e) {
- throw new RuntimeException("Error deleting directory " + dir + " during JVM shutdown: " + e.getMessage(), e);
+ catch (Throwable t) {
+ errorLogger.error("Error deleting directory " + dir + " during JVM shutdown: " + t.getMessage(), t);
}
}
})); | [FLINK-<I>] Log error instead of rethrowing it during shutdown hook | apache_flink | train |
94cef268570879e018adc3795938fb6e054ce443 | diff --git a/plugin/postgres/plugin.go b/plugin/postgres/plugin.go
index <HASH>..<HASH> 100644
--- a/plugin/postgres/plugin.go
+++ b/plugin/postgres/plugin.go
@@ -137,10 +137,7 @@ func pgConnectionInfo(endpoint ShieldEndpoint) (*PostgresConnectionInfo, error)
}
DEBUG("PGPORT: '%s'", port)
- bin, err := endpoint.StringValue("pg_bindir")
- if err != nil {
- return nil, err
- }
+ bin := "/var/vcap/packages/postgres-9.4/bin"
DEBUG("PGBINDIR: '%s'", bin)
return &PostgresConnectionInfo{ | Force postgres plugin to use the psql provided by shield-boshrelease
Fixes #<I> | starkandwayne_shield | train |
7432508986e1a5f9ac242ea99a79d30fe3d99dd4 | diff --git a/lib/processImage.js b/lib/processImage.js
index <HASH>..<HASH> 100644
--- a/lib/processImage.js
+++ b/lib/processImage.js
@@ -234,6 +234,7 @@ module.exports = (options) => {
maxInputPixels: options.maxInputPixels,
maxOutputPixels: options.maxOutputPixels,
sharpCache: options.sharpCache,
+ sharpFailOnError: options.sharpFailOnError,
svgAssetPath: options.root
? Path.resolve(options.root, req.url.substr(1))
: null, | Added support for configuring 'failOnError' for Sharp engine via 'impro' | papandreou_express-processimage | train |
7b16eeac20478130bfdd3d6952c2643f124f9620 | diff --git a/kernel/classes/ezcontentobject.php b/kernel/classes/ezcontentobject.php
index <HASH>..<HASH> 100644
--- a/kernel/classes/ezcontentobject.php
+++ b/kernel/classes/ezcontentobject.php
@@ -1392,7 +1392,7 @@ class eZContentObject extends eZPersistentObject
{
$versionlimit = eZContentClass::versionHistoryLimit( $this->attribute( 'contentclass_id' ) );
$versionCount = $this->getVersionCount();
- if ( $versionCount >= $versionlimit )
+ if ( $versionCount > $versionlimit )
{
// Remove oldest archived version
$params = array( 'conditions'=> array( 'status' => eZContentObjectVersion::STATUS_ARCHIVED ) ); | Fix EZP-<I>: Number of history items regression
After fixing EZP-<I> the number of maximum items was not respected. It was missing one item because we are doing the check after the creation instead of before. | ezsystems_ezpublish-legacy | train |
bf943e6206d01c8c9cad144f0c02dd1e40868791 | diff --git a/python/dllib/src/bigdl/dllib/utils/file_utils.py b/python/dllib/src/bigdl/dllib/utils/file_utils.py
index <HASH>..<HASH> 100644
--- a/python/dllib/src/bigdl/dllib/utils/file_utils.py
+++ b/python/dllib/src/bigdl/dllib/utils/file_utils.py
@@ -17,6 +17,11 @@ from bigdl.util.common import Sample as BSample, JTensor as BJTensor,\
JavaCreator, _get_gateway, _java2py, _py2java
import numpy as np
import os
+import tempfile
+import uuid
+import shutil
+
+from urllib.parse import urlparse
def convert_to_safe_path(input_path, follow_symlinks=True):
@@ -47,6 +52,60 @@ def to_list_of_numpy(elements):
return results
+def is_local_path(path):
+ parse_result = urlparse(path)
+ return len(parse_result.scheme.lower()) == 0 or parse_result.scheme.lower() == "file"
+
+
+def append_suffix(prefix, path):
+ # append suffix
+ splits = path.split(".")
+ if len(splits) > 0:
+ file_name = prefix + "." + splits[-1]
+ else:
+ file_name = prefix
+
+ return file_name
+
+
+def save_file(save_func, path):
+
+ if is_local_path(path):
+ save_func(path)
+ else:
+ file_name = str(uuid.uuid1())
+ file_name = append_suffix(file_name, path)
+ temp_path = os.path.join(tempfile.gettempdir(), file_name)
+
+ try:
+ save_func(temp_path)
+ put_local_file_to_remote(temp_path, path)
+ finally:
+ os.remove(temp_path)
+
+
+def load_from_file(load_func, path):
+ if is_local_path(path):
+ return load_func(path)
+ else:
+ file_name = str(uuid.uuid1())
+ file_name = append_suffix(file_name, path)
+ temp_path = os.path.join(tempfile.gettempdir(), file_name)
+ get_remote_file_to_local(path, temp_path)
+ try:
+ return load_func(temp_path)
+ finally:
+ os.remove(temp_path)
+
+
+def get_remote_file_to_local(remote_path, local_path, over_write=False):
+ callZooFunc("float", "getRemoteFileToLocal", remote_path, local_path, over_write)
+
+
+def put_local_file_to_remote(local_path, remote_path, over_write=False):
+ callZooFunc("float", "putLocalFileToRemote", local_path, remote_path, over_write)
+
+
def set_core_number(num):
callZooFunc("float", "setCoreNumber", num)
@@ -65,7 +124,8 @@ def callZooFunc(bigdl_type, name, *args):
result = _java2py(gateway, java_result)
except Exception as e:
error = e
- if "does not exist" not in str(e):
+ if not ("does not exist" in str(e)
+ and "Method {}".format(name) in str(e)):
raise e
else:
return result | [Issue #<I>] KerasModel support saving and loading from HDFS (#<I>)
* add scala implementation
* KerasModel support saving and loading from HDFS
* fix
* first decide if path is local, if not forward to scala | intel-analytics_BigDL | train |
866026149af8a2ccd2e2ec9d1774bcac2b39212e | diff --git a/prow/plank/controller.go b/prow/plank/controller.go
index <HASH>..<HASH> 100644
--- a/prow/plank/controller.go
+++ b/prow/plank/controller.go
@@ -492,7 +492,7 @@ func (c *Controller) syncPendingJob(pj prowapi.ProwJob, pm map[string]corev1.Pod
if !pj.Complete() && pod.DeletionTimestamp != nil {
pj.SetComplete()
pj.Status.State = prowapi.ErrorState
- pj.Status.Description = "Pod got deleteted unexpectedly"
+ pj.Status.Description = "Pod got deleted unexpectedly"
}
var err error
diff --git a/prow/plank/reconciler.go b/prow/plank/reconciler.go
index <HASH>..<HASH> 100644
--- a/prow/plank/reconciler.go
+++ b/prow/plank/reconciler.go
@@ -441,7 +441,7 @@ func (r *reconciler) syncPendingJob(pj *prowv1.ProwJob) error {
if !pj.Complete() && pod != nil && pod.DeletionTimestamp != nil {
pj.SetComplete()
pj.Status.State = prowv1.ErrorState
- pj.Status.Description = "Pod got deleteted unexpectedly"
+ pj.Status.Description = "Pod got deleted unexpectedly"
}
pj.Status.URL, err = pjutil.JobURL(r.config().Plank, *pj, r.log) | fix typo -- s/deleteted/deleted/ | kubernetes_test-infra | train |
4171c15fab02605659fd175579e39b207a7e74cf | diff --git a/features/04_aruba_api/core/expand_path.feature b/features/04_aruba_api/core/expand_path.feature
index <HASH>..<HASH> 100644
--- a/features/04_aruba_api/core/expand_path.feature
+++ b/features/04_aruba_api/core/expand_path.feature
@@ -52,7 +52,7 @@ Feature: Expand paths with aruba
When I run `rspec`
Then the specs should all pass
- Scenario: Warn when using absolute path
+ Scenario: Raise error when using absolute path
Given a file named "spec/expand_path_spec.rb" with:
"""ruby
require 'spec_helper'
@@ -63,15 +63,15 @@ Feature: Expand paths with aruba
end
"""
When I run `rspec`
- Then the specs should all pass
+ Then the specs should not all pass
And the output should contain:
"""
Aruba's `expand_path` method was called with an absolute path
"""
- Scenario: Silence warning about using absolute path
+ Scenario: Silence error about using absolute path
- You can use config.allow_absolute_paths to silence the warning about the
+ You can use config.allow_absolute_paths to silence the error about the
use of absolute paths.
Given a file named "spec/expand_path_spec.rb" with:
diff --git a/lib/aruba/api/core.rb b/lib/aruba/api/core.rb
index <HASH>..<HASH> 100644
--- a/lib/aruba/api/core.rb
+++ b/lib/aruba/api/core.rb
@@ -117,28 +117,29 @@ module Aruba
#
# @example Single file name
#
- # # => <path>/tmp/aruba/file
# expand_path('file')
+ # # => <path>/tmp/aruba/file
#
# @example Single Dot
#
- # # => <path>/tmp/aruba
# expand_path('.')
+ # # => <path>/tmp/aruba
#
# @example using home directory
#
- # # => <path>/home/<name>/file
# expand_path('~/file')
+ # # => <path>/home/<name>/file
#
# @example using fixtures directory
#
- # # => <path>/test/fixtures/file
# expand_path('%/file')
+ # # => <path>/test/fixtures/file
#
- # @example Absolute directory
+ # @example Absolute directory (requires aruba.config.allow_absolute_paths
+ # to be set)
#
- # # => /foo/bar
# expand_path('/foo/bar')
+ # # => /foo/bar
#
def expand_path(file_name, dir_string = nil)
unless file_name.is_a?(String) && !file_name.empty?
@@ -157,7 +158,7 @@ module Aruba
prefix = file_name[0]
- if aruba.config.fixtures_path_prefix == prefix
+ if prefix == aruba.config.fixtures_path_prefix
rest = file_name[2..-1]
path = File.join(*[aruba.fixtures_directory, rest].compact)
unless Aruba.platform.exist? path
@@ -189,11 +190,13 @@ module Aruba
unless aruba.config.allow_absolute_paths
caller_location = caller_locations(1, 1).first
caller_file_line = "#{caller_location.path}:#{caller_location.lineno}"
- aruba.logger.warn \
+ message =
"Aruba's `expand_path` method was called with an absolute path" \
" at #{caller_file_line}, which is not recommended." \
+ " The path passed was '#{file_name}'." \
" Change the call to pass a relative path or set "\
"`config.allow_absolute_paths = true` to silence this warning"
+ raise UserError, message
end
file_name
else
diff --git a/spec/aruba/api/core_spec.rb b/spec/aruba/api/core_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/aruba/api/core_spec.rb
+++ b/spec/aruba/api/core_spec.rb
@@ -82,21 +82,16 @@ RSpec.describe Aruba::Api::Core do
let(:logger) { @aruba.aruba.logger }
before do
- allow(@aruba.aruba.logger).to receive :warn
+ allow(logger).to receive :warn
end
- it { expect(@aruba.expand_path(@file_path)).to eq @file_path }
-
- it "warns about it" do
- @aruba.expand_path(@file_path)
- expect(logger).to have_received(:warn)
- .with(/Aruba's `expand_path` method was called with an absolute path/)
+ it "raises a UserError" do
+ expect { @aruba.expand_path(@file_path) }.to raise_error Aruba::UserError
end
- it "does not warn about it if told not to" do
+ it "does not raise an error if told not to" do
@aruba.aruba.config.allow_absolute_paths = true
- @aruba.expand_path(@file_path)
- expect(logger).not_to have_received(:warn)
+ expect { @aruba.expand_path(@file_path) }.not_to raise_error
end
end | Raise an error when an absolute path is passed to expand_path | cucumber_aruba | train |
ed26229a19359b356f3a401698488c1707d4c029 | diff --git a/tests/lib/rules/no-extra-parens.js b/tests/lib/rules/no-extra-parens.js
index <HASH>..<HASH> 100644
--- a/tests/lib/rules/no-extra-parens.js
+++ b/tests/lib/rules/no-extra-parens.js
@@ -2334,13 +2334,8 @@ ruleTester.run("no-extra-parens", rule, {
invalid("[...(a.b)] = []", "[...a.b] = []", "MemberExpression"),
invalid("({ a: (b) } = {})", "({ a: b } = {})", "Identifier"),
invalid("({ a: (b.c) } = {})", "({ a: b.c } = {})", "MemberExpression"),
-
- /*
- * TODO: Add these tests for RestElement's parenthesized arguments in object patterns when that becomes supported by Espree.
- *
- * invalid("({ ...(a) } = {})", "({ ...a } = {})", "Identifier"),
- * invalid("({ ...(a.b) } = {})", "({ ...a.b } = {})", "MemberExpression")
- */
+ invalid("({ ...(a) } = {})", "({ ...a } = {})", "Identifier"),
+ invalid("({ ...(a.b) } = {})", "({ ...a.b } = {})", "MemberExpression"),
// https://github.com/eslint/eslint/issues/11706 (also in valid[])
{ | test: add no-extra-parens tests with rest properties (#<I>) | eslint_eslint | train |
10f3ca14f60314b822eccb67163d544c861d04b1 | diff --git a/lib/tempoiq.js b/lib/tempoiq.js
index <HASH>..<HASH> 100644
--- a/lib/tempoiq.js
+++ b/lib/tempoiq.js
@@ -226,10 +226,11 @@ TempoIQ.Client = function(key, secret, host, opts) {
// @param {function(err, multiStatus)} callback Returns a WriteStatus with the results of the write
base.writeBulk = function(write, callback) {
base._session.post("/v2/write", JSON.stringify(write), {}, callback, function(result) {
+ var body = result.body || "{}";
if (result.code == HttpResult.OK) {
- return { error: null, payload: new WriteStatus(JSON.parse(result.body)) };
+ return { error: null, payload: new WriteStatus(JSON.parse(body)) };
} else if (result.code == HttpResult.MULTI) {
- return { error: null, payload: new WriteStatus(JSON.parse(result.body)) };
+ return { error: null, payload: new WriteStatus(JSON.parse(body)) };
}
});
}; | Handle empty bodies for older server versions | TempoIQ_tempoiq-node-js | train |
b7e22aea99695835905df686aeb2a6ce4ff8f95c | diff --git a/user_agents/parsers.py b/user_agents/parsers.py
index <HASH>..<HASH> 100644
--- a/user_agents/parsers.py
+++ b/user_agents/parsers.py
@@ -33,6 +33,9 @@ MOBILE_BROWSER_FAMILIES = (
'IE Mobile',
'Opera Mobile',
'Opera Mini',
+ 'Chrome Mobile',
+ 'Chrome Mobile WebView',
+ 'Chrome Mobile iOS',
)
TABLET_DEVICE_FAMILIES = ( | add browser family chrome mobile (#<I>) | selwin_python-user-agents | train |
d58b3d30b7611b482753fc7c2648099abff75f0a | diff --git a/lib/support/cli.js b/lib/support/cli.js
index <HASH>..<HASH> 100644
--- a/lib/support/cli.js
+++ b/lib/support/cli.js
@@ -586,7 +586,8 @@ module.exports.parseCommandLine = function parseCommandLine() {
})
.option('videoParams.thumbsize', {
default: 400,
- describe: 'The maximum size of the thumbnail',
+ describe:
+ 'The maximum size of the thumbnail in the filmstrip. Default is 400 pixels in either direction. If videoParams.filmstripFullSize is used that setting overrides this.',
group: 'video'
})
.option('videoParams.filmstripFullSize', { | cli: better cli help for thumbsize | sitespeedio_browsertime | train |
0d2a6cd35cc286e90fda6903114f1b14fc8727c0 | diff --git a/lib/origen/core_ext/string.rb b/lib/origen/core_ext/string.rb
index <HASH>..<HASH> 100644
--- a/lib/origen/core_ext/string.rb
+++ b/lib/origen/core_ext/string.rb
@@ -154,6 +154,15 @@ class String
audit_verilog_value(value_bit_string, verilog_hash[:radix], verilog_hash[:size], verilog_hash[:signed])
end
+ def is_verilog_number?
+ case self
+ when /^[0,1]+$/, /^[b,o,d,h]\S+$/, /^\d+\'[b,o,d,h]\S+$/, /^\d+\'s[b,o,d,h]\S+$/
+ true
+ else
+ false
+ end
+ end
+
private
def parse_verilog_number
@@ -171,7 +180,7 @@ class String
end
str.downcase!
case str
- when /^\d+$/ # Just a value
+ when /^[0,1]+$/ # Just a value
verilog_hash[:size], verilog_hash[:radix], verilog_hash[:value] = 32, 'b', self
when /^[b,o,d,h]\S+$/ # A value and a radix
_m, verilog_hash[:radix], verilog_hash[:value] = /^([b,o,d,h])(\S+)$/.match(str).to_a
diff --git a/spec/string_spec.rb b/spec/string_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/string_spec.rb
+++ b/spec/string_spec.rb
@@ -79,4 +79,18 @@ describe String do
"8'shA6".verilog_to_i.should == -166
"9'shA6".verilog_to_i.should == 166
end
+
+ specify 'can correctly identify a verilog number' do
+ "10100110".is_verilog_number?.should == true
+ "b10100110".is_verilog_number?.should == true
+ "o246".is_verilog_number?.should == true
+ "d166".is_verilog_number?.should == true
+ "hA6".is_verilog_number?.should == true
+ "8'b10100110".is_verilog_number?.should == true
+ "8'o246".is_verilog_number?.should == true
+ "8'd166".is_verilog_number?.should == true
+ "8'hA6".is_verilog_number?.should == true
+ "0x1234".is_verilog_number?.should == false
+ "12".is_verilog_number?.should == false
+ end
end | Added in String core_ext method 'is_verilog_number?' | Origen-SDK_origen | train |
acd9907ef7f027de2f68d3f3e40941acb93ea02a | diff --git a/src/main/java/com/treasure_data/logger/sender/HttpSender.java b/src/main/java/com/treasure_data/logger/sender/HttpSender.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/treasure_data/logger/sender/HttpSender.java
+++ b/src/main/java/com/treasure_data/logger/sender/HttpSender.java
@@ -39,6 +39,53 @@ public class HttpSender implements Sender {
private static Pattern columnPat = Pattern.compile("^([a-z0-9_]+)$");
+ public static boolean validateDatabaseName(String name) {
+ if (name == null || name.equals("")) {
+ LOG.info(String.format("Empty name is not allowed: %s",
+ new Object[] { name }));
+ return false;
+ }
+ int len = name.length();
+ if (len < 3 || 32 < len) {
+ LOG.info(String.format("Name must be 3 to 32 characters, got %d characters.",
+ new Object[] { len }));
+ return false;
+ }
+
+ if (!databasePat.matcher(name).matches()) {
+ LOG.info("Name must consist only of alphabets, numbers, '_'.");
+ return false;
+ }
+
+ return true;
+ }
+
+ public static boolean validateTableName(String name) {
+ return validateDatabaseName(name);
+ }
+
+ public static boolean validateColumnName(String name) {
+ if (name == null || name.equals("")) {
+ LOG.info(String.format("Empty column name is not allowed: %s",
+ new Object[] { name }));
+ return false;
+ }
+
+ int len = name.length();
+ if (32 < len) {
+ LOG.info(String.format("Column name must be to 32 characters, got %d characters.",
+ new Object[] { len }));
+ return false;
+ }
+
+ if (!columnPat.matcher(name).matches()) {
+ LOG.info("Column name must consist only of alphabets, numbers, '_'.");
+ return false;
+ }
+
+ return true;
+ }
+
private MessagePack msgpack;
private Map<String, ExtendedPacker> chunks;
@@ -51,6 +98,8 @@ public class HttpSender implements Sender {
private HttpSenderThread senderThread;
+ private String name;
+
public HttpSender(final String host, final int port, final String apiKey) {
if (apiKey == null) {
throw new IllegalArgumentException("APIKey is required");
@@ -62,6 +111,7 @@ public class HttpSender implements Sender {
TreasureDataClient client = new TreasureDataClient(new TreasureDataCredentials(apiKey), props);
senderThread = new HttpSenderThread(queue, client);
new Thread(senderThread).start();
+ name = String.format("%s_%d", host, port);
}
public boolean emit(String tag, Map<String, Object> record) {
@@ -187,50 +237,14 @@ public class HttpSender implements Sender {
}
}
- public static boolean validateDatabaseName(String name) {
- if (name == null || name.equals("")) {
- LOG.info(String.format("Empty name is not allowed: %s",
- new Object[] { name }));
- return false;
- }
- int len = name.length();
- if (len < 3 || 32 < len) {
- LOG.info(String.format("Name must be 3 to 32 characters, got %d characters.",
- new Object[] { len }));
- return false;
- }
-
- if (!databasePat.matcher(name).matches()) {
- LOG.info("Name must consist only of alphabets, numbers, '_'.");
- return false;
- }
-
- return true;
+ @Override
+ public String getName() {
+ return name;
}
- public static boolean validateTableName(String name) {
- return validateDatabaseName(name);
+ @Override
+ public String toString() {
+ return getName();
}
- public boolean validateColumnName(String name) {
- if (name == null || name.equals("")) {
- LOG.info(String.format("Empty column name is not allowed: %s",
- new Object[] { name }));
- return false;
- }
-
- int len = name.length();
- if (32 < len) {
- LOG.info(String.format("Column name must be to 32 characters, got %d characters.",
- new Object[] { len }));
- return false;
- }
-
- if (!columnPat.matcher(name).matches()) {
- LOG.info("Column name must consist only of alphabets, numbers, '_'.");
- return false;
- }
-
- return true;
- }
} | defined an unimplemented method within HttpSender class | treasure-data_td-logger-java | train |
1ffd931672977946ba214dd5e3d2169f5c4d8d33 | diff --git a/library/Search/Algolia.php b/library/Search/Algolia.php
index <HASH>..<HASH> 100644
--- a/library/Search/Algolia.php
+++ b/library/Search/Algolia.php
@@ -100,18 +100,6 @@ class Algolia
//Get post type object
if (isset($post->post_type)) {
- //Default to index pages (discard other stuff below)
- $defaultIndexableTypes = apply_filters('algolia_indexable_post_types', array(
- 'page'
- ));
- if (in_array($post->post_type, $defaultIndexableTypes)) {
- return true;
- }
- }
-
- //Get post type object
- if (isset($post->post_type)) {
-
//Get post object details
$postTypeObject = get_post_type_object($post->post_type); | Fix issue where trashed posts would not be removed from index. | helsingborg-stad_Municipio | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.