hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
6a71d414d19068a6e4dd42d903c0276faf32b4d4
|
diff --git a/libpebble2/protocol/base/types.py b/libpebble2/protocol/base/types.py
index <HASH>..<HASH> 100644
--- a/libpebble2/protocol/base/types.py
+++ b/libpebble2/protocol/base/types.py
@@ -262,7 +262,11 @@ class Embed(Field):
def value_to_bytes(self, obj, value, default_endianness=DEFAULT_ENDIANNESS):
v = value.serialise(default_endianness=default_endianness)
- if self.length is not None and len(v) > self.length:
+ if isinstance(self.length, Field):
+ max_len = getattr(obj, self.length._name)
+ else:
+ max_len = self.length
+ if max_len is not None and len(v) > max_len:
raise PacketEncodeError("Embedded field with max length {} is actually {} bytes long."
.format(self.length, len(v)))
return v
diff --git a/tests/test_protocol.py b/tests/test_protocol.py
index <HASH>..<HASH> 100644
--- a/tests/test_protocol.py
+++ b/tests/test_protocol.py
@@ -8,7 +8,7 @@ import pytest
from enum import IntEnum, Enum
import uuid
-from libpebble2.exceptions import PacketDecodeError
+from libpebble2.exceptions import PacketDecodeError, PacketEncodeError
from libpebble2.protocol.base import PebblePacket
from libpebble2.protocol.base.types import *
@@ -698,3 +698,13 @@ def test_embedded_fixedlist():
thing.serialise()
assert thing.length == 3
assert thing.list_of_foo.length == 2
+
+def test_embed_length_too_short():
+ class Embedded(PebblePacket):
+ foo = Padding(10)
+
+ class Embedder(PebblePacket):
+ embedded = Embed(Embedded, length=5)
+
+ with pytest.raises(PacketEncodeError):
+ Embedder(embedded=Embedded()).serialise()
|
Fix bug and py3 tests.
|
pebble_libpebble2
|
train
|
b2a838bf15ba45c3e9b89c0f583b90b98cdfb18b
|
diff --git a/src/Util/Guid.php b/src/Util/Guid.php
index <HASH>..<HASH> 100644
--- a/src/Util/Guid.php
+++ b/src/Util/Guid.php
@@ -33,7 +33,9 @@ class Guid
public static function generateAsHex(): string
{
- return self::generate()->getHex();
+ // string cast is a BC layer for ramsey/uuid v3
+ // to be refactor when dropping retrocompatibility
+ return (string) self::generate()->getHex();
}
public static function fromString(string $uuid): UuidInterface
|
Make Guid class compatible with gedmo uuid 4 (#<I>)
Problem: the composer.json was updated so it's possible to have
gedmo/uuid 4, besides the project is not compatible with it.
Solution: update Guid class.
|
prooph_event-store
|
train
|
968dd537b7ab3201b5026650bc99428da8fb4af3
|
diff --git a/lib/SQL/Relation.php b/lib/SQL/Relation.php
index <HASH>..<HASH> 100644
--- a/lib/SQL/Relation.php
+++ b/lib/SQL/Relation.php
@@ -46,6 +46,12 @@ class SQL_Relation extends AbstractModel
return $f;
}
+ public function addExpression($n, $expression = null)
+ {
+ $f = $this->owner->addExpression($n, $expression)->from($this);
+
+ return $f;
+ }
public function join($foreign_table, $master_field = null, $join_kind = null, $_foreign_alias = null)
{
return $this->owner->join($foreign_table, $master_field, $join_kind, $_foreign_alias, $this);
|
proxy addExpression method too for consistancy
|
atk4_atk4
|
train
|
7a5694c50387180acfbe7807a2e2599126433223
|
diff --git a/integration-tests/src/test/java/tachyon/worker/DataServerIntegrationTest.java b/integration-tests/src/test/java/tachyon/worker/DataServerIntegrationTest.java
index <HASH>..<HASH> 100644
--- a/integration-tests/src/test/java/tachyon/worker/DataServerIntegrationTest.java
+++ b/integration-tests/src/test/java/tachyon/worker/DataServerIntegrationTest.java
@@ -106,10 +106,11 @@ public class DataServerIntegrationTest {
@Before
public final void before() throws IOException {
- System.setProperty(Constants.WORKER_DATA_SERVER, mDataServerClass);
- mLocalTachyonCluster = new LocalTachyonCluster(WORKER_CAPACITY_BYTES, USER_QUOTA_UNIT_BYTES,
- Constants.GB);
- mLocalTachyonCluster.start();
+ TachyonConf tachyonConf = new TachyonConf();
+ tachyonConf.set(Constants.WORKER_DATA_SERVER, mDataServerClass);
+ mLocalTachyonCluster =
+ new LocalTachyonCluster(WORKER_CAPACITY_BYTES, USER_QUOTA_UNIT_BYTES, Constants.GB);
+ mLocalTachyonCluster.start(tachyonConf);
mWorkerTachyonConf = mLocalTachyonCluster.getWorkerTachyonConf();
mTFS = mLocalTachyonCluster.getClient();
}
|
Update and clean up DataServer integration test.
|
Alluxio_alluxio
|
train
|
1413605a358ad1dc171a4a81ebf836d701dab07c
|
diff --git a/src/Format/Xml.php b/src/Format/Xml.php
index <HASH>..<HASH> 100644
--- a/src/Format/Xml.php
+++ b/src/Format/Xml.php
@@ -35,40 +35,38 @@ final class Xml extends Format
$output = $this->elementNode($node);
break;
}
-
return $output;
}
private function elementNode($node)
{
- $output = $this->addChildNodes($this->childNode($node));
+ $output = $this->childNode($node);
+ $output = $this->addChildNodes($output);
return $this->attributes($node, $output);
}
- private function childNode($node)
+ private function childNode($node, $output = [])
{
- foreach($node->childNodes as $child) {
+ foreach ($node->childNodes as $child) {
$children = $this->convert($child);
- if(isset($child->tagName)) {
+ if (isset($child->tagName)) {
$tagName = $child->tagName;
$output[$tagName] = isset($output[$tagName])
? $output[$tagName]
: [];
-
$output[$tagName][] = $children;
- } elseif($children !== '') {
+ } elseif ($children !== '') {
$output = $children;
}
}
-
return $output;
}
private function loopAttributes($attributes, $array = [])
{
// Loop through the attributes and collect them.
- foreach($attributes as $key => $node) {
+ foreach ($attributes as $key => $node) {
$array[$key] = (string) $node->value;
}
@@ -78,28 +76,24 @@ final class Xml extends Format
private function attributes($node, $output)
{
// If there are attributes.
- if($node->attributes->length) {
+ if ($node->attributes->length) {
$output = is_array($output) ? $output : ['@value' => $output];
$output['@attributes'] = $this->loopAttributes($node->attributes);
}
-
return $output;
}
- private function addChildNodes ($output)
+ private function addChildNodes($output)
{
- if(is_array($output)) {
+ if (is_array($output)) {
foreach ($output as $key => $value) {
$output[$key] = is_array($value) && count($value) === 1
? $value[0]
: $value;
}
-
- $output = empty($output) ? '' : $output;
+ $output = !isset($output) || empty($output) ? '' : $output;
}
return $output;
}
-
-
}
|
XML tidy up, still needs refactoring, it is not pretty
|
nark3d_PhalueObjects
|
train
|
605c9eac8e638bc32b5dfb4a6f894c7188e4d7a5
|
diff --git a/cognito/__init__.py b/cognito/__init__.py
index <HASH>..<HASH> 100644
--- a/cognito/__init__.py
+++ b/cognito/__init__.py
@@ -3,6 +3,7 @@ import boto3
import ast
import json
import base64
+import jwt
def attribute_dict(attributes):
@@ -12,19 +13,6 @@ def attribute_dict(attributes):
"""
return [{'Name': key, 'Value': value} for key, value in attributes.items()]
-def decode_jwt(token):
- """Decode base64, padding being optional.
-
- :param data: Base64 data as an ASCII byte string
- :returns: The decoded byte string.
-
- """
- header,payload,signature = token.split('.')
- missing_padding = len(payload) % 4
- if missing_padding != 0:
- payload += b'='* (4 - missing_padding)
- return json.loads(base64.decodestring(payload))
-
class UserObj(object):
@@ -108,7 +96,7 @@ class Cognito(object):
if not self.access_token:
raise AttributeError('Access Token Required to Check Token')
now = datetime.datetime.now()
- dec_access_token = decode_jwt(self.access_token)
+ dec_access_token = jwt.decode(self.access_token,verify=False)
if now > datetime.datetime.fromtimestamp(dec_access_token['exp']):
self.renew_access_token()
diff --git a/cognito/django/views.py b/cognito/django/views.py
index <HASH>..<HASH> 100644
--- a/cognito/django/views.py
+++ b/cognito/django/views.py
@@ -1,12 +1,9 @@
-from django.conf import settings
from django.urls import reverse_lazy
from django.views.generic import FormView, TemplateView
from django.contrib import messages
from braces.views._access import AccessMixin,LoginRequiredMixin
-from cognito import Cognito
-from cognito.django.utils import get_cognito,user_obj_to_django
-
+from .utils import get_cognito
from .forms import ProfileForm
|
removed unused imports in django.views and removed homegrown decode_jwt in favor of jwt.decode verify false
|
capless_warrant
|
train
|
6698955d1bf9c325da05abde3a0f44c838e4b8b2
|
diff --git a/agent/tcs/client/client.go b/agent/tcs/client/client.go
index <HASH>..<HASH> 100644
--- a/agent/tcs/client/client.go
+++ b/agent/tcs/client/client.go
@@ -190,7 +190,7 @@ func (cs *clientServer) metricsToPublishMetricRequests() ([]*ecstcs.PublishMetri
requestMetadata := fromMetricsMetadata(metadata, fin)
if (i+1)%tasksInMessage == 0 {
// Construct payload with tasksInMessage number of task metrics and send to backend.
- requests = append(requests, ecstcs.NewPublishMetricsRequest(requestMetadata, messageTaskMetrics))
+ requests = append(requests, ecstcs.NewPublishMetricsRequest(requestMetadata, copyTaskMetrics(messageTaskMetrics)))
messageTaskMetrics = messageTaskMetrics[:0]
}
}
@@ -221,3 +221,11 @@ func fromMetricsMetadata(metadata *ecstcs.MetricsMetadata, fin bool) *ecstcs.Met
Fin: &fin,
}
}
+
+// copyTaskMetrics copies a slice of TaskMetric objects to another slice. This is needed as we
+// reset the source slice after creating a new PublishMetricsRequest object.
+func copyTaskMetrics(from []*ecstcs.TaskMetric) []*ecstcs.TaskMetric {
+ to := make([]*ecstcs.TaskMetric, len(from))
+ copy(to, from)
+ return to
+}
diff --git a/agent/tcs/client/client_test.go b/agent/tcs/client/client_test.go
index <HASH>..<HASH> 100644
--- a/agent/tcs/client/client_test.go
+++ b/agent/tcs/client/client_test.go
@@ -22,6 +22,7 @@ package tcsclient
import (
"errors"
"fmt"
+ "strconv"
"testing"
"time"
@@ -107,8 +108,10 @@ func (engine *nonIdleStatsEngine) GetInstanceMetrics() (*ecstcs.MetricsMetadata,
MessageId: &messageId,
}
var taskMetrics []*ecstcs.TaskMetric
- for i := 0; i < engine.numTasks; i++ {
- taskMetrics = append(taskMetrics, &ecstcs.TaskMetric{})
+ var i int64
+ for i = 0; int(i) < engine.numTasks; i++ {
+ taskArn := "task/" + strconv.FormatInt(i, 10)
+ taskMetrics = append(taskMetrics, &ecstcs.TaskMetric{TaskArn: &taskArn})
}
return metadata, taskMetrics, nil
}
@@ -184,6 +187,16 @@ func TestPublishOnceNonIdleStatsEngine(t *testing.T) {
if err != nil {
t.Fatal("Error creating publishmetricrequests: ", err)
}
+ taskArns := make(map[string]bool)
+ for _, request := range requests {
+ for _, taskMetric := range request.TaskMetrics {
+ _, exists := taskArns[*taskMetric.TaskArn]
+ if exists {
+ t.Fatal("Duplicate task arn in requests: ", *taskMetric.TaskArn)
+ }
+ taskArns[*taskMetric.TaskArn] = true
+ }
+ }
if len(requests) != expectedRequests {
t.Errorf("Expected %d requests, got %d", expectedRequests, len(requests))
}
|
Fix generating duplicate arns in PublishMetricsRequest due to incorrect slice copy
|
aws_amazon-ecs-agent
|
train
|
661f38b355b21a574a3501399cf9d5bdcc2aa5ae
|
diff --git a/Menu/MenuBuilder.php b/Menu/MenuBuilder.php
index <HASH>..<HASH> 100644
--- a/Menu/MenuBuilder.php
+++ b/Menu/MenuBuilder.php
@@ -179,6 +179,22 @@ class MenuBuilder implements MenuBuilderInterface
)
{
$options = $this->getMenuOptions($name);
+
+ return $this->createMenuFromOptions($options, $defaultRouteParams, $extra);
+ }
+
+ /**
+ * {@inheritDoc}
+ * @see Millwright\MenuBundle\Menu.MenuBuilderInterface::createMenuFromOptions()
+ */
+ public function createMenuFromOptions(
+ array $options,
+ array $defaultRouteParams = array(),
+ array $extra = array()
+ )
+ {
+ $routeParams = array();
+
$factory = $this->createFactory($defaultRouteParams, $routeParams, $extra);
return $factory->createFromArray($options);
diff --git a/Menu/MenuBuilderInterface.php b/Menu/MenuBuilderInterface.php
index <HASH>..<HASH> 100644
--- a/Menu/MenuBuilderInterface.php
+++ b/Menu/MenuBuilderInterface.php
@@ -37,6 +37,22 @@ interface MenuBuilderInterface
);
/**
+ * Create menu from options
+ *
+ * @param array $options menu container options
+ * @param array $defaultRouteParams default route params for options
+ * @param array $extra
+ *
+ * @return MenuItemInterface
+ */
+ public function createMenuFromOptions(
+ array $options,
+ array $defaultRouteParams = array(),
+ array $extra = array()
+ );
+
+
+ /**
* Create single item without children (for menu link)
*
* @param string $name name of menu item
diff --git a/Resources/config/services.xml b/Resources/config/services.xml
index <HASH>..<HASH> 100644
--- a/Resources/config/services.xml
+++ b/Resources/config/services.xml
@@ -49,7 +49,7 @@
<service id="millwright_menu.factory" class="%millwright_menu.factory.class%">
<argument type="service" id="router" />
<argument type="service" id="security.context" />
- <argument type="service" id="security.acl.provider" />
+ <argument type="service" id="security.acl.provider" on-invalid="null" />
</service>
<service id="millwright_menu.merger" class="%millwright_menu.merger.class%">
|
added create menu from options method into builder
|
zerkalica_MillwrightMenuBundle
|
train
|
2152023f390a7dc45cf16cd5cc283d0cfa93b8ee
|
diff --git a/manticore/native/cpu/x86.py b/manticore/native/cpu/x86.py
index <HASH>..<HASH> 100644
--- a/manticore/native/cpu/x86.py
+++ b/manticore/native/cpu/x86.py
@@ -961,6 +961,10 @@ class X86Cpu(Cpu):
0x0: (0x00000000, 0x00000000, 0x00000000, 0x00000000),
0x1: (0x00000000, 0x00000000, 0x00000000, 0x00000000),
},
+ # CPUID with EAX=80000000h returns the highest supported extended function
+ # query in EAX. We don't currently support any other than 80000000h itself,
+ # so just return it back.
+ 0x80000000: (0x80000000, 0x00000000, 0x00000000, 0x00000000),
}
if cpu.EAX not in conf:
|
native/cpu/x<I>: Add support for CPUID EAX=<I>h (#<I>)
|
trailofbits_manticore
|
train
|
64b8ffa8b91d2a01c3cafaf20f1559cfb3bd796d
|
diff --git a/bulbs/indexable/tests.py b/bulbs/indexable/tests.py
index <HASH>..<HASH> 100644
--- a/bulbs/indexable/tests.py
+++ b/bulbs/indexable/tests.py
@@ -24,16 +24,31 @@ class IndexableTestCase(TestCase):
ParentIndexable.search.refresh()
SeparateIndexable.search.refresh()
-
def test_index_names(self):
self.assertEqual(ParentIndexable.get_index_name(), 'testindexable_parentindexable')
self.assertEqual(ChildIndexable.get_index_name(), 'testindexable_parentindexable')
self.assertEqual(GrandchildIndexable.get_index_name(), 'testindexable_parentindexable')
-
self.assertEqual(SeparateIndexable.get_index_name(), 'testindexable_separateindexable')
- def test_search(self):
+ def test_mapping_type_names(self):
+ self.assertEqual(ParentIndexable.get_mapping_type_name(), 'testindexable_parentindexable')
+ self.assertEqual(ChildIndexable.get_mapping_type_name(), 'testindexable_childindexable')
+ self.assertEqual(GrandchildIndexable.get_mapping_type_name(), 'testindexable_grandchildindexable')
+ self.assertEqual(SeparateIndexable.get_mapping_type_name(), 'testindexable_separateindexable')
+ self.assertEqual(
+ ParentIndexable.get_mapping_type_names(), [
+ ParentIndexable.get_mapping_type_name(),
+ ChildIndexable.get_mapping_type_name(),
+ GrandchildIndexable.get_mapping_type_name(),
+ ]
+ )
+ self.assertEqual(
+ SeparateIndexable.get_mapping_type_names(), [
+ SeparateIndexable.get_mapping_type_name(),
+ ]
+ )
+ def test_search(self):
self.assertEqual(ParentIndexable.search.s().count(), 3)
self.assertEqual(ParentIndexable.search.query(bar=69).count(), 2)
self.assertEqual(ParentIndexable.search.query(foo__match="Fighters").count(), 3)
@@ -50,7 +65,7 @@ class IndexableTestCase(TestCase):
self.assertEqual(ParentIndexable.search.s().instanceof(ChildIndexable).count(), 2)
self.assertEqual(ParentIndexable.search.s().instanceof(GrandchildIndexable).count(), 1)
- def test_model_Results(self):
+ def test_model_results(self):
qs = ParentIndexable.search.s().full()
for obj in qs:
self.assertTrue(obj.__class__ in [ParentIndexable, ChildIndexable, GrandchildIndexable])
|
Added tests for indexable mapping type names
|
theonion_django-bulbs
|
train
|
af1139d911a4e0a043a081fac7e1d09873ef8b0a
|
diff --git a/dist/tagify.js b/dist/tagify.js
index <HASH>..<HASH> 100644
--- a/dist/tagify.js
+++ b/dist/tagify.js
@@ -2152,7 +2152,7 @@ Tagify.prototype = {
// 2. dropdown is disabled
// 3. loader is showing (controlled outside of this code)
- if (noWhitelist && !allowNewTags || _s.dropdown.enable === false || this.state.isLoading) return;
+ if (noWhitelist && !allowNewTags && !_s.templates.dropdownItemNoMatch || _s.dropdown.enable === false || this.state.isLoading) return;
clearTimeout(this.dropdownHide__bindEventsTimeout); // if no value was supplied, show all the "whitelist" items in the dropdown
// @type [Array] listItems
// TODO: add a Setting to control items' sort order for "listItems"
diff --git a/dist/tagify.min.js b/dist/tagify.min.js
index <HASH>..<HASH> 100644
--- a/dist/tagify.min.js
+++ b/dist/tagify.min.js
@@ -2158,7 +2158,7 @@ Tagify.prototype = {
// 2. dropdown is disabled
// 3. loader is showing (controlled outside of this code)
- if (noWhitelist && !allowNewTags || _s.dropdown.enable === false || this.state.isLoading) return;
+ if (noWhitelist && !allowNewTags && !_s.templates.dropdownItemNoMatch || _s.dropdown.enable === false || this.state.isLoading) return;
clearTimeout(this.dropdownHide__bindEventsTimeout); // if no value was supplied, show all the "whitelist" items in the dropdown
// @type [Array] listItems
// TODO: add a Setting to control items' sort order for "listItems"
diff --git a/src/tagify.js b/src/tagify.js
index <HASH>..<HASH> 100644
--- a/src/tagify.js
+++ b/src/tagify.js
@@ -2252,7 +2252,7 @@ Tagify.prototype = {
// 1. there's no whitelist (can happen while async loading) AND new tags arn't allowed
// 2. dropdown is disabled
// 3. loader is showing (controlled outside of this code)
- if( (noWhitelist && !allowNewTags) || _s.dropdown.enable === false || this.state.isLoading ) return;
+ if( (noWhitelist && !allowNewTags && !_s.templates.dropdownItemNoMatch) || _s.dropdown.enable === false || this.state.isLoading ) return;
clearTimeout(this.dropdownHide__bindEventsTimeout)
|
fixes #<I> - allowNewTags in "show" should include "dropdownItemNoMatch" template check
|
yairEO_tagify
|
train
|
f204540da359cb05ebc27577c76e673b16582021
|
diff --git a/tasks/compile-example.js b/tasks/compile-example.js
index <HASH>..<HASH> 100644
--- a/tasks/compile-example.js
+++ b/tasks/compile-example.js
@@ -447,7 +447,10 @@ module.exports = function(config, indexPath, updateTimestamp) {
if (!document.isAmpStory) {
return string;
}
- return string.replace(/<script\s+async\s+custom-element="amp-story"\s+src="https:\/\/cdn\.ampproject\.org\/v0\/amp-story-0\.1\.js">\s*<\/script>/, "");
+ string = string.replace(/<script\s+async\s+custom-element="amp-story"\s+src="https:\/\/cdn\.ampproject\.org\/v0\/amp-story-0\.1\.js">\s*<\/script>/, "");
+ string = string.replace(/<script\s+async\s+custom-element="amp-story-auto-ads"\s+src="https:\/\/cdn\.ampproject\.org\/v0\/amp-story-auto-ads-0\.1\.js">\s*<\/script>/, "");
+ return string;
+ amp-story-auto-ads
}
function replaceAmpAdRuntime(document, string) {
|
filter amp-story-auto-ads extension (#<I>)
|
ampproject_amp-by-example
|
train
|
d5ea4795301074fc2deb6f32edff615fe916eb16
|
diff --git a/packages/plugin-team/test/unit/spec/team.js b/packages/plugin-team/test/unit/spec/team.js
index <HASH>..<HASH> 100644
--- a/packages/plugin-team/test/unit/spec/team.js
+++ b/packages/plugin-team/test/unit/spec/team.js
@@ -5,8 +5,10 @@
*/
import {assert} from '@ciscospark/test-helper-chai';
-import Team from '../..';
import MockSpark from '@ciscospark/test-helper-mock-spark';
+import sinon from '@ciscospark/test-helper-sinon';
+import Team from '../..';
+import User from '@ciscospark/plugin-user';
describe(`plugin-team`, () => {
describe(`Team`, () => {
@@ -15,9 +17,12 @@ describe(`plugin-team`, () => {
beforeEach(() => {
spark = new MockSpark({
children: {
- team: Team
+ team: Team,
+ user: User
}
});
+
+ spark.user.recordUUID = sinon.spy();
});
describe(`#create()`, () => {
@@ -33,5 +38,17 @@ describe(`plugin-team`, () => {
it(`requires a team object with a general conversation`, () => assert.isRejected(spark.team.createConversation({}, {displayName: `test`}), /\`team.generalConversationUuid\` must be present/));
});
+
+ describe(`#prepareTeamConversation()`, () => {
+ it(`requires a KRO`, () => assert.isRejected(spark.team._prepareTeamConversation({}), /Error: Team general conversation must have a KRO/));
+ });
+
+ describe(`#recordUUIDs`, () => {
+ it(`resolves if there are no teamMembers`, () => spark.team._recordUUIDs({})
+ .then(() => assert.equal(spark.user.recordUUID.callCount, 0)));
+
+ it(`resolves if there isn't teamMembers.items`, () => spark.team._recordUUIDs({teamMembers: {}})
+ .then(() => assert.equal(spark.user.recordUUID.callCount, 0)));
+ });
});
});
|
test(plugin-team): Add unit test coverage for teams.js
|
webex_spark-js-sdk
|
train
|
f254c963fa13de52be7e57d590a4be70bd305f9e
|
diff --git a/flask_security/datastore.py b/flask_security/datastore.py
index <HASH>..<HASH> 100644
--- a/flask_security/datastore.py
+++ b/flask_security/datastore.py
@@ -234,18 +234,17 @@ class SQLAlchemyUserDatastore(SQLAlchemyDatastore, UserDatastore):
def get_user(self, identifier):
from sqlalchemy import func as alchemyFn
- from sqlalchemy.orm import joinedload
+ user_model_query = self.user_model.query
+ if hasattr(self.user_model, 'roles'):
+ from sqlalchemy.orm import joinedload
+ user_model_query = user_model_query.options(joinedload('roles'))
+
if self._is_numeric(identifier):
- return self.user_model.query\
- .options(joinedload('roles'))\
- .get(identifier)
+ return user_model_query.get(identifier)
for attr in get_identity_attributes():
query = alchemyFn.lower(getattr(self.user_model, attr)) \
== alchemyFn.lower(identifier)
- rv = self.user_model.query\
- .options(joinedload('roles'))\
- .filter(query)\
- .first()
+ rv = user_model_query.filter(query).first()
if rv is not None:
return rv
@@ -257,11 +256,12 @@ class SQLAlchemyUserDatastore(SQLAlchemyDatastore, UserDatastore):
return True
def find_user(self, **kwargs):
- from sqlalchemy.orm import joinedload
- return self.user_model.query\
- .options(joinedload('roles'))\
- .filter_by(**kwargs)\
- .first()
+ query = self.user_model.query
+ if hasattr(self.user_model, 'roles'):
+ from sqlalchemy.orm import joinedload
+ query = query.options(joinedload('roles'))
+
+ return query.filter_by(**kwargs).first()
def find_role(self, role):
return self.role_model.query.filter_by(name=role).first()
|
Make `roles` in user model query optimization "optional".
|
mattupstate_flask-security
|
train
|
a420b6982ba66c125853d438ecea61073b752ea5
|
diff --git a/satpy/tests/__init__.py b/satpy/tests/__init__.py
index <HASH>..<HASH> 100644
--- a/satpy/tests/__init__.py
+++ b/satpy/tests/__init__.py
@@ -23,6 +23,11 @@
"""The tests package.
"""
+import sys
+if sys.version_info < (2, 7):
+ import unittest2 as unittest
+else:
+ import unittest
from satpy.tests import (#test_satin_helpers,
#test_pp_core, # crash
#test_channel,
@@ -40,7 +45,6 @@ from satpy.tests import (#test_satin_helpers,
#test_visir,
)
-import unittest
def suite():
"""The global test suite.
diff --git a/satpy/tests/test_projectable.py b/satpy/tests/test_projectable.py
index <HASH>..<HASH> 100644
--- a/satpy/tests/test_projectable.py
+++ b/satpy/tests/test_projectable.py
@@ -358,7 +358,7 @@ class TestProjectable(unittest.TestCase):
p = projectable.Projectable(data=tuple())
p_str = str(p)
- @mock.patch('satpy.projectable.resample')
+ @mock.patch('satpy.resample.resample')
def test_resample_2D(self, mock_resampler):
data = np.arange(25).reshape((5, 5))
mock_resampler.return_value = data
@@ -379,7 +379,7 @@ class TestProjectable(unittest.TestCase):
self.assertTrue(isinstance(res, projectable.Projectable))
np.testing.assert_array_equal(res.data, mock_resampler.return_value)
- @mock.patch('satpy.projectable.resample')
+ @mock.patch('satpy.resample.resample')
def test_resample_3D(self, mock_resampler):
data = np.arange(75).reshape((3, 5, 5))
mock_resampler.return_value = np.rollaxis(data, 0, 3)
diff --git a/satpy/tests/test_scene.py b/satpy/tests/test_scene.py
index <HASH>..<HASH> 100644
--- a/satpy/tests/test_scene.py
+++ b/satpy/tests/test_scene.py
@@ -24,7 +24,11 @@
"""
import os
-import unittest
+import sys
+if sys.version_info < (2, 7):
+ import unittest2 as unittest
+else:
+ import unittest
import mock
# clear the config dir environment variable so it doesn't interfere
|
Fix resample test from moved resample import
The 'resample' method imported at the top of projectable.py was moved to inside the resample method to avoid circular imports. The resample tests were still patching the global import. Now they modify the original function. I also imported unittest2 in a few modules to be more consistent.
|
pytroll_satpy
|
train
|
9a33c99dfb2cc00238c9ebb46afa4ac1741989e4
|
diff --git a/lib/requester/request-wrapper.js b/lib/requester/request-wrapper.js
index <HASH>..<HASH> 100644
--- a/lib/requester/request-wrapper.js
+++ b/lib/requester/request-wrapper.js
@@ -25,6 +25,7 @@ var _ = require('lodash'),
* Gets the certificate from the options.certificate
* And appends it with the options provided
*
+ * @param request
* @param options
* @param cb
*/
@@ -62,6 +63,8 @@ module.exports = function (request, options, callback) {
setCertificate(request, options, next);
}
], function (err, options) {
+ if (err) { return callback(err); }
+
var request = requests(options, callback);
// todo: this is a hack to ensure that we can abort requests from the app before they're complete.
|
FIx lint issues in `request-wrapper.js`
|
postmanlabs_postman-runtime
|
train
|
26530244097796ae0766c63215f871cd7665aefc
|
diff --git a/_pytest/junitxml.py b/_pytest/junitxml.py
index <HASH>..<HASH> 100644
--- a/_pytest/junitxml.py
+++ b/_pytest/junitxml.py
@@ -206,7 +206,7 @@ class LogXML(object):
def pytest_sessionfinish(self):
dirname = os.path.dirname(os.path.abspath(self.logfile))
- if not os.path.exists(dirname):
+ if not os.path.isdir(dirname):
os.makedirs(dirname)
logfile = open(self.logfile, 'w', encoding='utf-8')
suite_stop_time = time.time()
diff --git a/_pytest/resultlog.py b/_pytest/resultlog.py
index <HASH>..<HASH> 100644
--- a/_pytest/resultlog.py
+++ b/_pytest/resultlog.py
@@ -16,7 +16,7 @@ def pytest_configure(config):
# prevent opening resultlog on slave nodes (xdist)
if resultlog and not hasattr(config, 'slaveinput'):
dirname = os.path.dirname(os.path.abspath(resultlog))
- if not os.path.exists(dirname):
+ if not os.path.isdir(dirname):
os.makedirs(dirname)
logfile = open(resultlog, 'w', 1) # line buffered
config._resultlog = ResultLog(config, logfile)
|
Use os.path.isdir instead of os.path.exists
As suggested during review
|
pytest-dev_pytest
|
train
|
11d4f7f59660300ae92859789a1c71929a26a7d3
|
diff --git a/lib/achoo.rb b/lib/achoo.rb
index <HASH>..<HASH> 100644
--- a/lib/achoo.rb
+++ b/lib/achoo.rb
@@ -82,7 +82,6 @@ class Achoo
form.remark = get_remark(date)
form.hours = hours_chooser(date)
-
form.print_values
if confirm
puts "Submitting ..."
@@ -94,7 +93,7 @@ class Achoo
def phase_chooser(form)
- phases = form.phases_for_project
+ phases = form.phases_for_selected_project
puts "Phases"
Term.menu(phases.collect {|p| "#{p[1]} (#{p[0]})"})
if phases.length == 1
diff --git a/lib/achoo/hour_registration_form.rb b/lib/achoo/hour_registration_form.rb
index <HASH>..<HASH> 100644
--- a/lib/achoo/hour_registration_form.rb
+++ b/lib/achoo/hour_registration_form.rb
@@ -33,9 +33,7 @@ class Achoo::HourRegistrationForm < Achoo::Form
@form.phaseid = "phase.id='#{phaseid}'"
end
-
-
- def phases_for_project
+ def phases_for_selected_project
old = {
:atkaction => @form.atkaction,
:action => @form.action,
|
Refactoring. Renamed a method
|
kjellm_achoo
|
train
|
1a781fe2cf943c1a70ca73c4b4b860f4cebc25f3
|
diff --git a/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java b/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java
index <HASH>..<HASH> 100644
--- a/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java
+++ b/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java
@@ -888,7 +888,7 @@ public class IconicsDrawable extends Drawable {
@Override
protected boolean onStateChange(int[] stateSet) {
boolean ret = false;
- if (mIconColor != null) {
+ if (mIconColor != null && mIconColor.isStateful()) {
updateIconColor();
ret = true;
}
|
* fix issue with wrong opacity of icons displayed in drawer
|
mikepenz_Android-Iconics
|
train
|
dafa017d9ebeede370d97525f2f99c6958eb40e3
|
diff --git a/lib/functions/packLocal.js b/lib/functions/packLocal.js
index <HASH>..<HASH> 100755
--- a/lib/functions/packLocal.js
+++ b/lib/functions/packLocal.js
@@ -61,7 +61,7 @@ function packLocal() {
// If extension is correct and file does not start with a dot
if ((extension === '.js' || extension === '.html') && (file[0] !== '.')) {
const filename = path.join(folder, nameWithoutExtension).replace(`\\`, `/`);
- promises.push(getFileJSON(file, path.join(folder, nameWithoutExtension), extension));
+ promises.push(getFileJSON(file, filename, extension));
}
}
|
small fix to only have forward slashes in google drive
|
MaartenDesnouck_google-apps-script
|
train
|
440cc83c839111e6b33d7b0986f4f46775664033
|
diff --git a/src/game/structures.js b/src/game/structures.js
index <HASH>..<HASH> 100644
--- a/src/game/structures.js
+++ b/src/game/structures.js
@@ -297,7 +297,7 @@ exports.make = function(_runtimeData, _intents, _register, _globals) {
return C.ERR_NOT_ENOUGH_RESOURCES;
}
if(this.safeModeCooldown || this.upgradeBlocked > 0 ||
- this.ticksToDowngrade < C.CONTROLLER_DOWNGRADE[this.level] - C.CONTROLLER_DOWNGRADE_SAFEMODE_THRESHOLD) {
+ this.ticksToDowngrade < C.CONTROLLER_DOWNGRADE[this.level]/2 - C.CONTROLLER_DOWNGRADE_SAFEMODE_THRESHOLD) {
return C.ERR_TIRED;
}
if(_.any(register.structures, i => i.structureType == 'controller' && i.my && i.safeMode)) {
diff --git a/src/processor/intents/controllers/activateSafeMode.js b/src/processor/intents/controllers/activateSafeMode.js
index <HASH>..<HASH> 100644
--- a/src/processor/intents/controllers/activateSafeMode.js
+++ b/src/processor/intents/controllers/activateSafeMode.js
@@ -17,7 +17,7 @@ module.exports = function(object, intent, {bulk, gameTime, roomInfo}) {
if(object.upgradeBlocked > gameTime) {
return;
}
- if(object.downgradeTime < gameTime + C.CONTROLLER_DOWNGRADE[object.level] - C.CONTROLLER_DOWNGRADE_SAFEMODE_THRESHOLD) {
+ if(object.downgradeTime < gameTime + C.CONTROLLER_DOWNGRADE[object.level]/2 - C.CONTROLLER_DOWNGRADE_SAFEMODE_THRESHOLD) {
return;
}
diff --git a/src/processor/intents/controllers/tick.js b/src/processor/intents/controllers/tick.js
index <HASH>..<HASH> 100644
--- a/src/processor/intents/controllers/tick.js
+++ b/src/processor/intents/controllers/tick.js
@@ -38,9 +38,7 @@ module.exports = function(object, {bulk, bulkUsers, gameTime, roomInfo, users})
driver.sendNotification(object.user, `Attention! Your Controller in room ${object.room} will be downgraded to level ${object.level-1} in 3000 ticks (~2 hours)! Upgrade it to prevent losing of this room. <a href='http://support.screeps.com/hc/en-us/articles/203086021-Territory-control'>Learn more</a>`);
}
-
- if(gameTime >= object.downgradeTime-1) {
-
+ while(gameTime >= object.downgradeTime-1) {
object.level--;
driver.sendNotification(object.user, `Your Controller in room ${object.room} has been downgraded to level ${object.level} due to absence of upgrading activity!`);
if(object.level == 0) {
@@ -55,7 +53,7 @@ module.exports = function(object, {bulk, bulkUsers, gameTime, roomInfo, users})
object.safeModeCooldown = roomInfo.novice > Date.now() ? null : gameTime + C.SAFE_MODE_COOLDOWN
}
else {
- object.downgradeTime = gameTime + C.CONTROLLER_DOWNGRADE[object.level] + 1;
+ object.downgradeTime += C.CONTROLLER_DOWNGRADE[object.level]/2 + 1;
object.progress += Math.round(C.CONTROLLER_LEVELS[object.level] * 0.9);
object.safeModeAvailable = 0;
object.safeModeCooldown = roomInfo.novice > Date.now() ? null : gameTime + C.SAFE_MODE_COOLDOWN
@@ -74,4 +72,4 @@ module.exports = function(object, {bulk, bulkUsers, gameTime, roomInfo, users})
}
-};
\ No newline at end of file
+};
diff --git a/src/processor/intents/creeps/upgradeController.js b/src/processor/intents/creeps/upgradeController.js
index <HASH>..<HASH> 100644
--- a/src/processor/intents/creeps/upgradeController.js
+++ b/src/processor/intents/creeps/upgradeController.js
@@ -63,7 +63,7 @@ module.exports = function(object, intent, {roomObjects, bulk, bulkUsers, stats,
target.progress = target.progress + boostedEffect - nextLevelProgress;
target.level++;
- target.downgradeTime = gameTime + C.CONTROLLER_DOWNGRADE[target.level];
+ target.downgradeTime = gameTime + C.CONTROLLER_DOWNGRADE[target.level]/2;
driver.sendNotification(target.user, `Your Controller in room ${target.room} has been upgraded to level ${target.level}.`);
if(target.level == 8) {
target.progress = 0;
@@ -100,4 +100,4 @@ module.exports = function(object, intent, {roomObjects, bulk, bulkUsers, stats,
amount: boostedEffect, energySpent: buildEffect
}});
-};
\ No newline at end of file
+};
|
feat: made downgrade timer half-empty on level upgrades/downgrades, made attackController downgrade damage overflow on level downgrade
DEV-<I>
|
screeps_engine
|
train
|
377b5e21732bcbc6227406559267b922bf847b71
|
diff --git a/datapackage/resource.py b/datapackage/resource.py
index <HASH>..<HASH> 100644
--- a/datapackage/resource.py
+++ b/datapackage/resource.py
@@ -18,6 +18,7 @@ if sys.version_info[0] < 3:
from . import sources
from . import licenses
from .util import is_local, is_url, is_mimetype
+from .util import get_size_from_url
name_regex = re.compile(r"^[0-9A-Za-z-_\.]+$")
@@ -242,9 +243,7 @@ class Resource(object):
if self.is_local:
size = os.path.getsize(self.fullpath)
else:
- site = urllib.urlopen(self.fullpath)
- meta = site.info()
- size = int(meta.getheaders("Content-Length")[0])
+ size = get_size_from_url(self.fullpath)
return size
@@ -252,10 +251,7 @@ class Resource(object):
"""Compute the size of the file specified by the url"""
if not self.url:
raise ValueError("url to file is not specified")
- site = urllib.urlopen(self.url)
- meta = site.info()
- size = int(meta.getheaders("Content-Length")[0])
- return size
+ return get_size_from_url(self.url)
def update_bytes(self, verify=True):
"""Re-compute the size of the resource, using either the inline data,
diff --git a/datapackage/util.py b/datapackage/util.py
index <HASH>..<HASH> 100644
--- a/datapackage/util.py
+++ b/datapackage/util.py
@@ -165,3 +165,10 @@ def is_mimetype(val):
"""
return bool(re.match(r"[^/]+/[^/]+", val))
+
+
+def get_size_from_url(url):
+ site = urllib.urlopen(url)
+ meta = site.info()
+ size = int(meta.getheaders("Content-Length")[0])
+ return size
|
Return helper function for getting the file size from a url
|
frictionlessdata_datapackage-py
|
train
|
1f7d0cac33a134676c4b595c1328d203f5dfea2b
|
diff --git a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilder.java b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilder.java
index <HASH>..<HASH> 100644
--- a/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilder.java
+++ b/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilder.java
@@ -18,6 +18,7 @@ package io.micrometer.statsd.internal;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Statistic;
+import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.lang.Nullable;
import org.pcollections.HashTreePMap;
@@ -57,7 +58,7 @@ public class DatadogStatsdLineBuilder extends FlavorStatsdLineBuilder {
this.tags = HashTreePMap.empty();
this.conventionTags = id.getTagsAsIterable().iterator().hasNext() ?
id.getConventionTags(next).stream()
- .map(t -> sanitizeName(t.getKey()) + ":" + sanitizeTagValue(t.getValue()))
+ .map(t -> formatTag(t))
.collect(Collectors.joining(","))
: null;
}
@@ -67,6 +68,14 @@ public class DatadogStatsdLineBuilder extends FlavorStatsdLineBuilder {
}
}
+ private String formatTag(Tag t) {
+ String sanitizedTag = sanitizeName(t.getKey());
+ if (!t.getValue().isEmpty()) {
+ sanitizedTag += ":" + sanitizeTagValue(t.getValue());
+ }
+ return sanitizedTag;
+ }
+
private String sanitizeName(String value) {
if (!Character.isLetter(value.charAt(0))) {
value = "m." + value;
diff --git a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilderTest.java b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilderTest.java
index <HASH>..<HASH> 100644
--- a/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilderTest.java
+++ b/implementations/micrometer-registry-statsd/src/test/java/io/micrometer/statsd/internal/DatadogStatsdLineBuilderTest.java
@@ -50,6 +50,15 @@ class DatadogStatsdLineBuilderTest {
assertThat(lb.line("1", Statistic.COUNT, "c")).isEqualTo("my_counter:1|c|#statistic:count,my_tag:my_value");
}
+ @Test
+ void interpretEmptyTagValuesAsValuelessTags() {
+ Counter c = registry.counter("my:counter", "my:tag", "");
+ DatadogStatsdLineBuilder lb = new DatadogStatsdLineBuilder(c.getId(), registry.config());
+
+ registry.config().namingConvention(NamingConvention.dot);
+ assertThat(lb.line("1", Statistic.COUNT, "c")).isEqualTo("my_counter:1|c|#statistic:count,my_tag");
+ }
+
@Issue("#1998")
@Test
void allowColonsInTagValues() {
|
Prevent StringIndexOutOfBoundsException in Datadog statsD on empty tag value (#<I>)
Interpret an empty tag value as valueless tag for DogstatsD, since an empty-value tag is not allowed.
|
micrometer-metrics_micrometer
|
train
|
88e464f32100878ac60383c22baf89043036dd02
|
diff --git a/adapters/src/main/java/org/jboss/jca/adapters/jdbc/BaseWrapperManagedConnectionFactory.java b/adapters/src/main/java/org/jboss/jca/adapters/jdbc/BaseWrapperManagedConnectionFactory.java
index <HASH>..<HASH> 100644
--- a/adapters/src/main/java/org/jboss/jca/adapters/jdbc/BaseWrapperManagedConnectionFactory.java
+++ b/adapters/src/main/java/org/jboss/jca/adapters/jdbc/BaseWrapperManagedConnectionFactory.java
@@ -998,7 +998,7 @@ public abstract class BaseWrapperManagedConnectionFactory
* @return The properties
* @exception ResourceException Thrown if an error occurs
*/
- protected Properties getConnectionProperties(Subject subject, ConnectionRequestInfo cri)
+ protected synchronized Properties getConnectionProperties(Subject subject, ConnectionRequestInfo cri)
throws ResourceException
{
if (cri != null && cri.getClass() != WrappedConnectionRequestInfo.class)
|
Add synchronized to getConnectionProperties
|
ironjacamar_ironjacamar
|
train
|
f8470e0b3b25d7d4d4b30e711a0730f086174969
|
diff --git a/resource_aws_eip.go b/resource_aws_eip.go
index <HASH>..<HASH> 100644
--- a/resource_aws_eip.go
+++ b/resource_aws_eip.go
@@ -97,7 +97,7 @@ func resourceAwsEipUpdate(d *schema.ResourceData, meta interface{}) error {
domain := resourceAwsEipDomain(d)
// Only register with an instance if we have one
- if v := d.Get("instance"); v != nil {
+ if v, ok := d.GetOk("instance"); ok {
instanceId := v.(string)
assocOpts := ec2.AssociateAddress{
|
providers/aws: check if instance is set on eip
|
terraform-providers_terraform-provider-aws
|
train
|
3ded14df6ab4cf153ca9463e2bea8f84ae321e11
|
diff --git a/parseany.go b/parseany.go
index <HASH>..<HASH> 100644
--- a/parseany.go
+++ b/parseany.go
@@ -280,18 +280,33 @@ iterRunes:
// Mon, 02 Jan 2006 15:04:05 MST
// Mon, 02 Jan 2006 15:04:05 -0700
// Monday, 02-Jan-06 15:04:05 MST
+ // Monday, 02 Jan 2006 15:04:05 -0700
switch {
case r == '-':
state = ST_ALPHACOMMADASH
}
-
+ if t, err := time.Parse("Mon, 02 Jan 2006 15:04:05 MST", datestr); err == nil {
+ return t, nil
+ }
+ if t, err := time.Parse("Monday, 02 Jan 2006 15:04:05 MST", datestr); err == nil {
+ return t, nil
+ }
case ST_ALPHACOMMADASH: // Starts alpha then comma and one dash
// Mon, 02 Jan 2006 15:04:05 -0700
+ // Monday, 02 Jan 2006 15:04:05 -0700
// Monday, 02-Jan-06 15:04:05 MST
switch {
case r == '-':
state = ST_ALPHACOMMADASHDASH
}
+ t, err := time.Parse("Mon, 02 Jan 2006 15:04:05 -0700", datestr)
+ if err == nil {
+ return t, nil
+ }
+ if t, err := time.Parse("Monday, 02 Jan 2006 15:04:05 -0700", datestr); err == nil {
+ return t, nil
+ }
+
case ST_ALPHAWSCOMMA: // Starts Alpha, whitespace, digit, comma
// May 8, 2009 5:57:51 PM
if t, err := time.Parse("Jan 2, 2006 3:04:05 PM", datestr); err == nil {
diff --git a/parseany_test.go b/parseany_test.go
index <HASH>..<HASH> 100644
--- a/parseany_test.go
+++ b/parseany_test.go
@@ -106,6 +106,16 @@ func TestParse(t *testing.T) {
//u.Debug(fmt.Sprintf("%v", ts.In(time.UTC)), " ---- ", ts.In(time.UTC))
assert.T(t, "2015-07-03 17:04:07 +0000 UTC" == fmt.Sprintf("%v", ts.In(time.UTC)))
+ ts, err = ParseAny("Mon, 02 Jan 2006 15:04:05 MST")
+ assert.Tf(t, err == nil, "%v", err)
+ //u.Debug(ts.In(time.UTC).Unix(), ts.In(time.UTC))
+ assert.T(t, "2006-01-02 15:04:05 +0000 UTC" == fmt.Sprintf("%v", ts.In(time.UTC)))
+
+ ts, err = ParseAny("Mon, 02 Jan 2006 15:04:05 -0700")
+ assert.Tf(t, err == nil, "%v", err)
+ //u.Debug(ts.In(time.UTC).Unix(), ts.In(time.UTC))
+ assert.T(t, "2006-01-02 22:04:05 +0000 UTC" == fmt.Sprintf("%v", ts.In(time.UTC)))
+
// Golang Native Format
ts, err = ParseAny("2015-02-18 00:12:00 +0000 UTC")
assert.Tf(t, err == nil, "%v", err)
|
Support timestamps with leading day of week
|
araddon_dateparse
|
train
|
7fdd2909885f37863d466328ff8bd8c4fd3ec644
|
diff --git a/src/de/lmu/ifi/dbs/elki/visualization/svg/MinimalMarkers.java b/src/de/lmu/ifi/dbs/elki/visualization/svg/MinimalMarkers.java
index <HASH>..<HASH> 100755
--- a/src/de/lmu/ifi/dbs/elki/visualization/svg/MinimalMarkers.java
+++ b/src/de/lmu/ifi/dbs/elki/visualization/svg/MinimalMarkers.java
@@ -1,5 +1,6 @@
package de.lmu.ifi.dbs.elki.visualization.svg;
+import org.apache.batik.util.SVGConstants;
import org.w3c.dom.Element;
import de.lmu.ifi.dbs.elki.visualization.colors.ColorLibrary;
@@ -37,7 +38,7 @@ public class MinimalMarkers implements MarkerLibrary {
*/
public Element useMarker(SVGPlot plot, Element parent, double x, double y, int style, double size) {
Element marker = plot.svgRect(x - size / 2, y - size / 2, size, size);
- SVGUtil.setStyle(marker, "fill:" + colors.getColor(style));
+ SVGUtil.setStyle(marker, SVGConstants.CSS_FILL_PROPERTY+":" + colors.getColor(style));
parent.appendChild(marker);
return marker;
}
diff --git a/src/de/lmu/ifi/dbs/elki/visualization/svg/PrettyMarkers.java b/src/de/lmu/ifi/dbs/elki/visualization/svg/PrettyMarkers.java
index <HASH>..<HASH> 100755
--- a/src/de/lmu/ifi/dbs/elki/visualization/svg/PrettyMarkers.java
+++ b/src/de/lmu/ifi/dbs/elki/visualization/svg/PrettyMarkers.java
@@ -40,7 +40,8 @@ public class PrettyMarkers implements MarkerLibrary {
}
/**
- * Constructor without prefix argument, will use {@link #DEFAULT_PREFIX} as prefix.
+ * Constructor without prefix argument, will use {@link #DEFAULT_PREFIX} as
+ * prefix.
*
* @param colors color library to use
*/
@@ -82,7 +83,7 @@ public class PrettyMarkers implements MarkerLibrary {
assert (parent != null);
// TODO: add more styles.
String colorstr = colors.getColor(style);
- String strokestyle = "stroke:" + colorstr + ";stroke-width:" + SVGUtil.fmt(size / 6);
+ String strokestyle = SVGConstants.CSS_STROKE_PROPERTY + ":" + colorstr + ";" + SVGConstants.CSS_STROKE_WIDTH_PROPERTY + ":" + SVGUtil.fmt(size / 6);
switch(style % 8){
case 0: {
@@ -107,8 +108,8 @@ public class PrettyMarkers implements MarkerLibrary {
}
case 2: {
// O filled circle
- Element circ = plot.svgCircle( x, y, size / 2);
- SVGUtil.setStyle(circ, "fill:" + colorstr);
+ Element circ = plot.svgCircle(x, y, size / 2);
+ SVGUtil.setStyle(circ, SVGConstants.CSS_FILL_PROPERTY + ":" + colorstr);
parent.appendChild(circ);
break;
}
@@ -154,22 +155,19 @@ public class PrettyMarkers implements MarkerLibrary {
@Override
public Element useMarker(SVGPlot plot, Element parent, double x, double y, int style, double size) {
- String id = prefix + style;
+ String id = prefix + style + "_" + size;
Element existing = plot.getIdElement(id);
if(existing == null) {
Element symbol = plot.svgElement(SVGConstants.SVG_SYMBOL_TAG);
SVGUtil.setAtt(symbol, SVGConstants.SVG_ID_ATTRIBUTE, id);
- SVGUtil.setAtt(symbol, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE, "-1 -1 2 2");
- plotMarker(plot, symbol, 0, 0, style, 2);
+ plotMarker(plot, symbol, 2*size, 2*size, style, 2*size);
plot.getDefs().appendChild(symbol);
plot.putIdElement(id, symbol);
}
Element use = plot.svgElement(SVGConstants.SVG_USE_TAG);
use.setAttributeNS(SVGConstants.XLINK_NAMESPACE_URI, SVGConstants.XLINK_HREF_QNAME, "#" + id);
- SVGUtil.setAtt(use, SVGConstants.SVG_X_ATTRIBUTE, x - size);
- SVGUtil.setAtt(use, SVGConstants.SVG_Y_ATTRIBUTE, y - size);
- SVGUtil.setAtt(use, SVGConstants.SVG_WIDTH_ATTRIBUTE, size * 2);
- SVGUtil.setAtt(use, SVGConstants.SVG_HEIGHT_ATTRIBUTE, size * 2);
+ SVGUtil.setAtt(use, SVGConstants.SVG_X_ATTRIBUTE, x - 2*size);
+ SVGUtil.setAtt(use, SVGConstants.SVG_Y_ATTRIBUTE, y - 2*size);
if(parent != null) {
parent.appendChild(use);
}
|
Don't use viewbox and such for markers. This avoids problems with exporting to PDF from latest inkscape.
|
elki-project_elki
|
train
|
c4d02d804baa46f8c48d4bdf732d0405f21f99f4
|
diff --git a/ouimeaux/server/__init__.py b/ouimeaux/server/__init__.py
index <HASH>..<HASH> 100644
--- a/ouimeaux/server/__init__.py
+++ b/ouimeaux/server/__init__.py
@@ -74,8 +74,8 @@ class DeviceResource(Resource):
dev = get_device(name)
if not isinstance(dev, Switch):
abort(405, error='Only switches can have their state changed')
- action = request.json.get('state', request.values.get(
- 'state', 'toggle'))
+ action = (request.json or {}).get('state', (
+ request.values or {}).get('state', 'toggle'))
if action not in ('on', 'off', 'toggle'):
abort(400, error='{} is not a valid state'.format(action))
getattr(dev, action)()
|
Fix a bug with query params on devices.
|
iancmcc_ouimeaux
|
train
|
28615098bb6dfd780afa27ae124fc8292cb6bf33
|
diff --git a/plugin.php b/plugin.php
index <HASH>..<HASH> 100644
--- a/plugin.php
+++ b/plugin.php
@@ -208,7 +208,7 @@ register_deactivation_hook( __FILE__, 'json_api_deactivation' );
function json_register_scripts() {
wp_register_script( 'wp-api', 'http://wp-api.github.io/client-js/build/js/wp-api.js', array( 'jquery', 'backbone', 'underscore' ), '1.1', true );
- $settings = array( 'root' => esc_url_raw( home_url( 'wp-json' ) ) );
+ $settings = array( 'root' => esc_url_raw( home_url( 'wp-json' ) ), 'nonce' => wp_create_nonce( 'wp_json' ) );
wp_localize_script( 'wp-api', 'WP_API_Settings', $settings );
}
add_action( 'wp_enqueue_scripts', 'json_register_scripts', -100 );
|
Re-localize nonce for JS
|
WP-API_WP-API
|
train
|
7f04fbb0785a3da094f954ccdd8d016eea4d52cd
|
diff --git a/src/Symfony/Component/Security/Guard/Token/GuardTokenInterface.php b/src/Symfony/Component/Security/Guard/Token/GuardTokenInterface.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Security/Guard/Token/GuardTokenInterface.php
+++ b/src/Symfony/Component/Security/Guard/Token/GuardTokenInterface.php
@@ -11,6 +11,8 @@
namespace Symfony\Component\Security\Guard\Token;
+use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
+
/**
* A marker interface that both guard tokens implement.
*
@@ -20,6 +22,6 @@ namespace Symfony\Component\Security\Guard\Token;
*
* @author Ryan Weaver <ryan@knpuniversity.com>
*/
-interface GuardTokenInterface
+interface GuardTokenInterface extends TokenInterface
{
}
|
Making GuardTokenInterface extend TokenInterface
This makes some of our type-hints more honest: i.e. where we look for a GuardTokenInterface,
but really also expect it to implement TokenInterface.
|
symfony_symfony
|
train
|
9ba5d9884eb4decc479a3abfbfff990c7f8d1079
|
diff --git a/nanoservice/service.py b/nanoservice/service.py
index <HASH>..<HASH> 100644
--- a/nanoservice/service.py
+++ b/nanoservice/service.py
@@ -113,4 +113,13 @@ class SubService(Service):
def process(self):
msg = self.sock.recv()
fun, data = self.get_fun_and_data(msg)
- return fun(data) # Also return to allow testing
+
+ result = None
+ try:
+ result = fun(data)
+ except Exception as e:
+ logging.error(e, exc_info=1)
+
+ # Return result to check successful execution
+ # of `fun` when testing
+ return result
|
Catch expections when executing subscriber fun
|
walkr_nanoservice
|
train
|
407e25b006e0c7a985ef0495764c538e33bbb8bc
|
diff --git a/synapse/lib/types.py b/synapse/lib/types.py
index <HASH>..<HASH> 100644
--- a/synapse/lib/types.py
+++ b/synapse/lib/types.py
@@ -790,6 +790,7 @@ class Loc(Type):
def postTypeInit(self):
self.setNormFunc(str, self._normPyStr)
+ self.indxcmpr['^='] = self.indxByPref
def _normPyStr(self, valu):
@@ -817,6 +818,17 @@ class Loc(Type):
('pref', indx),
)
+ def indxByPref(self, valu):
+ norm, info = self.norm(valu)
+ indx = self.indx(norm)
+
+ if indx is None:
+ raise s_exc.NoSuchIndx(name=self.name)
+
+ return (
+ ('pref', indx),
+ )
+
@s_cache.memoize()
def stems(self, valu):
norm, info = self.norm(valu)
@@ -840,7 +852,6 @@ class Loc(Type):
return cmpr
-
class Ndef(Type):
def postTypeInit(self):
diff --git a/synapse/tests/test_lib_types.py b/synapse/tests/test_lib_types.py
index <HASH>..<HASH> 100644
--- a/synapse/tests/test_lib_types.py
+++ b/synapse/tests/test_lib_types.py
@@ -309,25 +309,39 @@ class TypesTest(s_t_utils.SynTest):
await self.agenlen(1, core.eval('[testint=1 :loc=us.va.syria]'))
await self.agenlen(1, core.eval('[testint=2 :loc=us.va.sydney]'))
await self.agenlen(1, core.eval('[testint=3 :loc=""]'))
+ await self.agenlen(1, core.eval('[testint=4 :loc=us.va.fairfax.reston]'))
+ await self.agenlen(1, core.eval('[testint=5 :loc=us.va.fairfax.herndon]'))
+ await self.agenlen(1, core.eval('[testint=6 :loc=us.ca.sandiego]'))
+ await self.agenlen(1, core.eval('[testint=7 :loc=us.ओं]'))
await self.agenlen(1, core.eval('testint:loc=us.va.syria'))
await self.agenlen(1, core.eval('testint:loc=us.va.sydney'))
await self.agenlen(0, core.eval('testint:loc=us.va.sy'))
- await self.agenlen(2, core.eval('testint:loc=us.va'))
+ await self.agenlen(4, core.eval('testint:loc=us.va'))
await self.agenlen(0, core.eval('testint:loc=us.v'))
- await self.agenlen(2, core.eval('testint:loc=us'))
+ await self.agenlen(6, core.eval('testint:loc=us'))
await self.agenlen(0, core.eval('testint:loc=u'))
await self.agenlen(1, core.eval('testint:loc=""'))
await self.agenlen(1, core.eval('testint +:loc="us.va. syria"'))
await self.agenlen(1, core.eval('testint +:loc=us.va.sydney'))
await self.agenlen(0, core.eval('testint +:loc=us.va.sy'))
- await self.agenlen(2, core.eval('testint +:loc=us.va'))
+ await self.agenlen(4, core.eval('testint +:loc=us.va'))
await self.agenlen(0, core.eval('testint +:loc=us.v'))
- await self.agenlen(2, core.eval('testint +:loc=us'))
+ await self.agenlen(6, core.eval('testint +:loc=us'))
await self.agenlen(0, core.eval('testint +:loc=u'))
await self.agenlen(1, core.eval('testint +:loc=""'))
+ await self.agenlen(6, core.eval('testint:loc^=us'))
+ await self.agenlen(4, core.eval('testint:loc^=us.va'))
+ await self.agenlen(2, core.eval('testint:loc^=us.va.fairfax'))
+ await self.agenlen(1, core.eval('testint:loc^=us.va.fairfax.reston'))
+ await self.agenlen(0, core.eval('testint:loc^=us.va.fairfax.chantilly'))
+ await self.agenlen(0, core.eval('testint:loc^=u'))
+ await self.agenlen(0, core.eval('testint:loc^=us.ओं.'))
+ await self.agenlen(1, core.eval('testint:loc^=""'))
+ await self.agenlen(0, core.eval('testint:loc^=23'))
+
def test_ndef(self):
self.skip('Implement base ndef test')
|
add missing prefix indx comp for Loc type and associated tests
|
vertexproject_synapse
|
train
|
19e71b2ad86fad4cf4995b9e4dc6cf5ee2f966f0
|
diff --git a/lib/Thelia/Core/Thelia.php b/lib/Thelia/Core/Thelia.php
index <HASH>..<HASH> 100755
--- a/lib/Thelia/Core/Thelia.php
+++ b/lib/Thelia/Core/Thelia.php
@@ -69,29 +69,22 @@ class Thelia extends Kernel
protected function initPropel()
{
- if (defined('THELIA_INSTALL_MODE') === true) {
- $serviceContainer = Propel::getServiceContainer();
- $serviceContainer->setAdapterClass('thelia', 'sqlite');
- $manager = new ConnectionManagerSingle();
- $manager->setConfiguration(array(
- "classname" => "\Propel\Runtime\Connection\PropelPDO",
- "dsn" => "sqlite:".THELIA_ROOT . "/install/thelia.sqlite"
- ));
- $serviceContainer->setConnectionManager('thelia', $manager);
- } else {
- $definePropel = new DefinePropel(new DatabaseConfiguration(),
- Yaml::parse(THELIA_ROOT . '/local/config/database.yml'));
- $serviceContainer = Propel::getServiceContainer();
- $serviceContainer->setAdapterClass('thelia', 'mysql');
- $manager = new ConnectionManagerSingle();
- $manager->setConfiguration($definePropel->getConfig());
- $serviceContainer->setConnectionManager('thelia', $manager);
- $con = Propel::getConnection(\Thelia\Model\Map\ProductTableMap::DATABASE_NAME);
- $con->setAttribute(ConnectionWrapper::PROPEL_ATTR_CACHE_PREPARES, true);
- if ($this->isDebug()) {
- $serviceContainer->setLogger('defaultLogger', \Thelia\Log\Tlog::getInstance());
- $con->useDebug(true);
- }
+ if (file_exists(THELIA_ROOT . '/local/config/database.yml') === false) {
+ return ;
+ }
+
+ $definePropel = new DefinePropel(new DatabaseConfiguration(),
+ Yaml::parse(THELIA_ROOT . '/local/config/database.yml'));
+ $serviceContainer = Propel::getServiceContainer();
+ $serviceContainer->setAdapterClass('thelia', 'mysql');
+ $manager = new ConnectionManagerSingle();
+ $manager->setConfiguration($definePropel->getConfig());
+ $serviceContainer->setConnectionManager('thelia', $manager);
+ $con = Propel::getConnection(\Thelia\Model\Map\ProductTableMap::DATABASE_NAME);
+ $con->setAttribute(ConnectionWrapper::PROPEL_ATTR_CACHE_PREPARES, true);
+ if ($this->isDebug()) {
+ $serviceContainer->setLogger('defaultLogger', \Thelia\Log\Tlog::getInstance());
+ $con->useDebug(true);
}
diff --git a/lib/Thelia/Install/Database.php b/lib/Thelia/Install/Database.php
index <HASH>..<HASH> 100644
--- a/lib/Thelia/Install/Database.php
+++ b/lib/Thelia/Install/Database.php
@@ -93,7 +93,7 @@ class Database
*/
public function createDatabase($dbName)
{
- $this->connection->query(
+ $this->connection->exec(
sprintf(
"CREATE DATABASE IF NOT EXISTS %s CHARACTER SET utf8",
$dbName
diff --git a/lib/Thelia/Model/Admin.php b/lib/Thelia/Model/Admin.php
index <HASH>..<HASH> 100755
--- a/lib/Thelia/Model/Admin.php
+++ b/lib/Thelia/Model/Admin.php
@@ -34,8 +34,6 @@ class Admin extends BaseAdmin implements UserInterface
public function setPassword($password)
{
- \Thelia\Log\Tlog::getInstance()->debug($password);
-
if ($this->isNew() && ($password === null || trim($password) == "")) {
throw new \InvalidArgumentException("customer password is mandatory on creation");
}
|
nstall step Please enter the commit message for your changes. Lines starting
|
thelia_core
|
train
|
4ba9f3eb1e18e213579cfdcd26d8fdcfd49568b9
|
diff --git a/doc/types/export-output.md b/doc/types/export-output.md
index <HASH>..<HASH> 100644
--- a/doc/types/export-output.md
+++ b/doc/types/export-output.md
@@ -9,8 +9,16 @@ addition to [steal-tools.transform.options].
with their dependencies.
-@option {Array<moduleName|comparitor>|Boolean} [eachModule] Builds each module in the list
-with its dependendencies individually.
+@option {Array<moduleName|comparitor>} [eachModule] Builds each module in the list with its dependendencies individually. Use this if you want to create separate builds for more than one module in your graph:
+
+```js
+stealTools.export({
+ system: {
+ config: __dirname + "/package.json!npm"
+ }
+
+});
+```
@option {Array<moduleName|comparitor>} [graphs] Builds each item in the graph on its own. Each dependency is
built individually.
@@ -94,16 +102,28 @@ will also be included.
Each module specified by `eachModule` will be exported, including its dependencies individually. For example:
-```
-{
- eachModule: ["foo","bar"],
- format: "global"
-}
-```
+**eachModule** is useful when you want to take a dependency graph and split it into separate builds that will be combined around certain modules within that graph.
-This will build a "foo" export and a "bar" export. If "foo" and "bar" both depend on "zed", "zed" will
-be included in both exports.
+For example:
+
+```js
+stealTools.export({
+ system: {
+ config: __dirname + "/package.json!npm"
+ },
+ options: {},
+ outputs: {
+ "+standalone": {
+ eachModule: [
+ "app/a",
+ "app/b"
+ ]
+ }
+ }
+});
+```
+This will build out `dist/global/app/a.js` and `dist/global/app/b.js`, both as standalone builds.
## graphs
diff --git a/lib/build/helpers/global.js b/lib/build/helpers/global.js
index <HASH>..<HASH> 100644
--- a/lib/build/helpers/global.js
+++ b/lib/build/helpers/global.js
@@ -57,6 +57,10 @@ var make = function(buildType){
dest: function(loc){
return function(moduleName, moduleData, load, System){
if(loc) {
+ if(typeof loc === "function") {
+ return loc(moduleName, moduleData, load, System);
+ }
+
return loc;
} else {
var baseRoot = baseHelper.removeFileProtocol(System.baseURL);
diff --git a/test/export_standalone_test.js b/test/export_standalone_test.js
index <HASH>..<HASH> 100644
--- a/test/export_standalone_test.js
+++ b/test/export_standalone_test.js
@@ -33,6 +33,33 @@ describe("+standalone", function(){
}, close);
}, done);
}, done);
+ });
+
+ it("Works when using dest as a function", function(done){
+ this.timeout(10000);
+ stealExport({
+ system: {
+ config: __dirname + "/exports_basics/package.json!npm"
+ },
+ options: { quiet: true },
+ outputs: {
+ "+standalone": {
+ exports: { "foo": "FOO.foo" },
+ dest: function(){
+ return __dirname + "/exports_basics/out.js"
+ }
+ }
+ }
+ })
+ .then(function(){
+ open("test/exports_basics/global.html",
+ function(browser, close) {
+ find(browser,"FOO", function(foo){
+ assert.equal(foo.foo.bar.name, "bar", "it worked");
+ close();
+ }, close);
+ }, done);
+ });
});
});
|
export `dest` when used with global-js/standalone
This fixes the global-js helper to work properly with `dest` when dest is a function. Also better documents `eachModule` slightly.
Closes #<I>
|
stealjs_steal-tools
|
train
|
8ddac4bf81ca1abcb7aa5b3ce0a5d35b0e2cfe2e
|
diff --git a/lib/grasshopper.js b/lib/grasshopper.js
index <HASH>..<HASH> 100644
--- a/lib/grasshopper.js
+++ b/lib/grasshopper.js
@@ -71,8 +71,10 @@ q.longStackSupport = true;
module.exports = grasshopper;
-process.on('SIGINT', function() {
- //Issue system/shutdown on SIGINT
+process.on('SIGINT', shutdown);
+process.on('SIGUSR2', shutdown);
+
+function shutdown(){ //Issue system/shutdown on SIGINT & SIGUSR2
var coordinator = require('./runners/coordinator'),
middleware = require('./middleware');
@@ -82,4 +84,4 @@ process.on('SIGINT', function() {
]);
coordinator.handle('system.shutdown', [], grasshopper);
-});
+}
|
Added another way to add a hook when someone shuts down the service
|
grasshopper-cms_grasshopper-core-nodejs
|
train
|
bb8be50049fdfdad3a3881b4417d51e83d1ea11a
|
diff --git a/funkyyak/core.py b/funkyyak/core.py
index <HASH>..<HASH> 100644
--- a/funkyyak/core.py
+++ b/funkyyak/core.py
@@ -1,18 +1,18 @@
import operator as op
import numpy as np
from functools import partial
+from operator import attrgetter
# ----- Autodiff logic -----
def grad(fun, argnum=0):
def gradfun(*args):
- args = list(args)
tape = CalculationTape(highest_tape(args))
start_node = new_node(args[argnum], tape)
+ args = list(args)
args[argnum] = start_node
ans = fun(*args)
- if not isnode(ans): return 0.0
- ans.outgrad = 1.0
+ if isnode(ans): ans.outgrad = 1.0
for step_back in tape[::-1]:
step_back()
return start_node.outgrad
@@ -21,20 +21,18 @@ def grad(fun, argnum=0):
def kyapply(fun, *args, **kwargs):
tape = highest_tape(args)
- if tape is not None:
+ if tape is None:
+ return fun(*args, **kwargs)
+ else:
is_parent = lambda x : isnode(x) and x.tape is tape
arg_vals = [arg.value if is_parent(arg) else arg for arg in args]
- node = new_node(kyapply(fun, *arg_vals, **kwargs), tape)
+ cur_node = new_node(kyapply(fun, *arg_vals, **kwargs), tape)
+ def send_grad_back(gradfun, parent):
+ parent.add_outgrad(gradfun(cur_node.outgrad, *arg_vals, **kwargs))
for i, arg in enumerate(args):
if not is_parent(arg): continue
- tape.append(partial(send_grad_back, node, gradfuns[fun][i],
- arg, arg_vals, kwargs))
- return node
- else:
- return fun(*args, **kwargs)
-
-def send_grad_back(node, gradfun, parent, args, kwargs):
- parent.outgrad += gradfun(node.outgrad, *args, **kwargs)
+ tape.append(partial(send_grad_back, gradfuns[fun][i], arg))
+ return cur_node
class CalculationTape(list):
def __init__(self, prev_tape):
@@ -43,15 +41,14 @@ class CalculationTape(list):
def highest_tape(args):
tapes = [node.tape for node in filter(isnode, args)]
- return max(tapes, key=lambda x : x.priority) if tapes else None
-
-isnode = lambda x : isinstance(x, Node)
-getval = lambda x : getval(x.value) if isnode(x) else x
+ return max(tapes, key=attrgetter('priority')) if tapes else None
# ----- Nodes and subclasses for operator overloading -----
k = kyapply
-isarrayish = lambda x : isinstance(x, (np.ndarray, numpyNode))
+getval = lambda x : getval(x.value) if isnode(x) else x
+isnode = lambda x : isinstance(x, Node)
+isarrayish = lambda x : isinstance(getval(x), np.ndarray)
def new_node(value, tape):
if isarrayish(value):
@@ -66,6 +63,10 @@ class Node(object):
self.value = value
self.outgrad = 0.0
+ def add_outgrad(self, new):
+ new = np.sum(new) if isarrayish(new) else new
+ self.outgrad += new
+
# Ensure precedence of Node's __rmul__ over numpy's __mul__
__array_priority__ = 100.0
@@ -96,6 +97,16 @@ class numpyNode(Node):
def __init__(self, *args):
super(numpyNode, self).__init__(*args)
+ def add_outgrad(self, new):
+ # Handle broadcasting
+ while new.ndim > self.ndim:
+ new = k(np.sum, new, 0)
+ for axis, size in enumerate(self.shape):
+ if size is 1:
+ new = k(np.sum, new, axis, keepdims=True)
+
+ self.outgrad += new
+
@property
def T(self): return k(np.transpose, self)
@property
@@ -159,27 +170,5 @@ def grad_np_dot_B(g, A, B):
return g * A
gradfuns[np.dot] = [grad_np_dot_A, grad_np_dot_B]
-# ----- Process gradients -----
-
-def make_unbroadcasting(fun, i):
- def unbroadcasting_fun(g, *args):
- new_x = fun(g, *args)
- old_x = args[i]
- if isarrayish(new_x) and isarrayish(old_x):
- while new_x.ndim > old_x.ndim:
- new_x = k(np.sum, new_x, 0)
- for axis, size in enumerate(old_x.shape):
- if size is 1:
- new_x = k(np.sum, new_x, axis, keepdims=True)
- elif isarrayish(new_x):
- new_x = k(np.sum, new_x)
- return new_x
-
- return unbroadcasting_fun
-
gradfuns = {k : v if isinstance(v, list) else [v]
for k, v in gradfuns.iteritems()}
-
-for fun in [op.add, op.mul, op.sub, op.div, op.pow]:
- for i, gradfun in enumerate(gradfuns[fun]):
- gradfuns[fun][i] = make_unbroadcasting(gradfun, i)
|
Moved unbroadcasting sums into type-specific add_outgrad methods
|
HIPS_autograd
|
train
|
bf4f77a780863d9edb003fa082830dd76347958b
|
diff --git a/cmd/minikube/cmd/delete.go b/cmd/minikube/cmd/delete.go
index <HASH>..<HASH> 100644
--- a/cmd/minikube/cmd/delete.go
+++ b/cmd/minikube/cmd/delete.go
@@ -17,11 +17,11 @@ limitations under the License.
package cmd
import (
+ "github.com/docker/machine/libmachine/mcnerror"
+ "github.com/pkg/errors"
"os"
"github.com/docker/machine/libmachine"
- "github.com/docker/machine/libmachine/mcnerror"
- "github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config"
@@ -69,7 +69,7 @@ func runDelete(cmd *cobra.Command, args []string) {
if err = cluster.DeleteHost(api); err != nil {
switch err := errors.Cause(err).(type) {
case mcnerror.ErrHostDoesNotExist:
- out.T(out.Meh, `"{{.name}}" cluster does not exist`, out.V{"name": profile})
+ out.T(out.Meh, `"{{.name}}" cluster does not exist. Proceeding ahead with cleanup.`, out.V{"name": err.Name})
default:
exit.WithError("Failed to delete cluster", err)
}
diff --git a/pkg/minikube/cluster/cluster.go b/pkg/minikube/cluster/cluster.go
index <HASH>..<HASH> 100644
--- a/pkg/minikube/cluster/cluster.go
+++ b/pkg/minikube/cluster/cluster.go
@@ -275,6 +275,16 @@ func DeleteHost(api libmachine.API) error {
if err != nil {
return errors.Wrap(err, "load")
}
+
+ // Get the status of the host. Ensure that it exists before proceeding ahead.
+ status, err := GetHostStatus(api)
+ if err != nil {
+ exit.WithCodeT(exit.Failure,"Unable to get the status of the cluster.")
+ }
+ if status == state.None.String() {
+ return mcnerror.ErrHostDoesNotExist{Name:host.Name}
+ }
+
// This is slow if SSH is not responding, but HyperV hangs otherwise, See issue #2914
if host.Driver.DriverName() == constants.DriverHyperv {
if err := trySSHPowerOff(host); err != nil {
|
Fix crash when the cluster doesn't exist
|
kubernetes_minikube
|
train
|
1418dd4d22214c02b0ae7213901995cfdc01ce7c
|
diff --git a/lib/webmake.js b/lib/webmake.js
index <HASH>..<HASH> 100755
--- a/lib/webmake.js
+++ b/lib/webmake.js
@@ -33,6 +33,7 @@ filesAtPath = function (path) {
};
module.exports = function (input, options, cb) {
+ var promise;
if (isFunction(options)) {
cb = options;
options = {};
@@ -40,7 +41,7 @@ module.exports = function (input, options, cb) {
options = Object(options);
}
var parser = createParser();
- return parser.readInput(input)(function (path) {
+ promise = parser.readInput(input)(function (path) {
return deferred.map([].concat(options.include || []), function (path) {
path = resolve(String(path));
return filesAtPath(path).invoke('filter', function (filename) {
@@ -58,4 +59,6 @@ module.exports = function (input, options, cb) {
writeFile(resolve(String(options.output)), src)(parser) : src;
});
}).cb(cb);
+ promise.parser = parser;
+ return promise;
};
|
Expose parser on a promise
|
medikoo_modules-webmake
|
train
|
bfbcb38e5f692edcf75b1426f5fe0c84a77a2948
|
diff --git a/lib/Property.js b/lib/Property.js
index <HASH>..<HASH> 100644
--- a/lib/Property.js
+++ b/lib/Property.js
@@ -48,6 +48,61 @@ Property.prototype.runTest = function(testCase) {
return result;
};
+// Returns an iterator (compliant with the ES6 iterator protocol) over
+// shrunk versions of the failing `testCase`. This should be a test
+// case returned by `.genTest` and which has resulted in a `{success:
+// false}` return value from `.runTest`.
+//
+// Concretely, calling `.next()` on the returned iterator causes a
+// shrunk test case to be executed, if any remain to be tried. The
+// iterator will return something like:
+//
+// {
+// done: false,
+// value: {
+// testArgs: [the arguments tested],
+// result: [same as return value of .runTest()]
+// }
+// }
+//
+// When the iterator finishes by returning `{done: true}`, the last
+// value it produced where `result.success === false` (or the original
+// `testCase`, if no such value was produced) should be considered the
+// minimum failing test case.
+//
+Property.prototype.shrinkFailingTest = function(testCase) {
+ // Implementation note: This would be clearer with coroutines (aka ES6
+ // "generators" — unfortunate clash of terminology there). This function
+ // basically fakes a coroutine, which requires explicitly keeping track
+ // of the state between return values, namely:
+ var node = testCase; // The node whose children we are exploring.
+ var childIndex = 0; // The index of the child to explore next.
+ var prop = this; // (constant) Reference to `this`.
+
+ return {next: function() {
+ if (childIndex >= node.children().length) {
+ return {done: true};
+ }
+
+ var child = node.children()[childIndex];
+ var result = prop.runTest(child);
+ if (!result.success) {
+ node = child;
+ childIndex = 0;
+ } else {
+ childIndex++;
+ }
+
+ return {
+ done: false,
+ value: {
+ testArgs: child.root,
+ result: result
+ }
+ };
+ }};
+};
+
// Implement the forAll(args, name, func) sugar, returning a Property.
Property.forAll = function(args, name, func) {
// `args` may be an array of generators (positional arguments to `func`),
diff --git a/lib/Runner.js b/lib/Runner.js
index <HASH>..<HASH> 100644
--- a/lib/Runner.js
+++ b/lib/Runner.js
@@ -55,6 +55,7 @@ Runner.prototype.run = function(options) {
var success = true;
var error;
var failingTestCase;
+ var shrunkFailArgs;
for (var k = 1; k <= numTests; k++) {
write('\r' + k + '/' + numTests + ' ' + prop.name);
@@ -70,12 +71,39 @@ Runner.prototype.run = function(options) {
}
}
+ if (!success) {
+ var iter = prop.shrinkFailingTest(failingTestCase);
+ var numAttempts = 0;
+ var numShrinks = 0;
+
+ // FIXME: Having some vars be rose trees and some be plain values
+ // is confusing, and converting one to the other by directly looking
+ // at ".root" violates abstraction. Ideally the Runner shouldn't
+ // know about rose trees at all.
+ //
+ // Also, "shrunkFailArgs" is incorrectly named in the case where we
+ // use this default, un-shrunk value.
+ shrunkFailArgs = failingTestCase.root;
+
+ var ret;
+ while (!((ret = iter.next()).done)) {
+ var value = ret.value;
+ numAttempts++;
+ if (!value.result.success) {
+ numShrinks++;
+ shrunkFailArgs = value.testArgs;
+ }
+ write('\r' + k + '/' + numTests + ' ' + prop.name +
+ ', shrinking ' + numShrinks + '/' + numAttempts);
+ }
+ }
+
write('\r' + (success ? '✓' : '✘') + ' ' + prop.name);
if (success) {
write(', passed ' + numTests + ' tests\n');
} else {
write(', counterexample found:\n');
- write(failingTestCase.root.toString() + '\n');
+ write(shrunkFailArgs.toString() + '\n');
if (error) {
write('exception raised: ' + (error.name || '(no name)') + '\n');
write(error.stack + '\n');
|
Shrink reported failure cases in the test runner
Closes #8
|
graue_gentest
|
train
|
aa5eca350f06d3774b51bb8e230194f56b5c95f1
|
diff --git a/spikeextractors/extractors/axonaunitrecordingextractor/axonaunitrecordingextractor.py b/spikeextractors/extractors/axonaunitrecordingextractor/axonaunitrecordingextractor.py
index <HASH>..<HASH> 100644
--- a/spikeextractors/extractors/axonaunitrecordingextractor/axonaunitrecordingextractor.py
+++ b/spikeextractors/extractors/axonaunitrecordingextractor/axonaunitrecordingextractor.py
@@ -45,6 +45,10 @@ class AxonaUnitRecordingExtractor(NeoBaseRecordingExtractor):
for i, ind in enumerate(self.get_channel_ids()):
self.set_channel_property(channel_id=ind, property_name='name', value=names[i])
+ # Set channel gains for int8 .X Unit data
+ gains = self.neo_reader._get_channel_gain(bytes_per_sample=1)[0:len(self.get_channel_ids())]
+ self.set_channel_gains(self, gains, channel_ids=None)
+
@check_get_traces_args
def get_traces(self, channel_ids=None, start_frame=None, end_frame=None, return_scaled=True):
|
set channel gains on init for int8 rather than int<I>
|
SpikeInterface_spikeextractors
|
train
|
1758ea5581db6b8d5793ae3a9db358cdfa0c0fdb
|
diff --git a/src/Offer/Commands/OfferCommandFactoryInterface.php b/src/Offer/Commands/OfferCommandFactoryInterface.php
index <HASH>..<HASH> 100644
--- a/src/Offer/Commands/OfferCommandFactoryInterface.php
+++ b/src/Offer/Commands/OfferCommandFactoryInterface.php
@@ -11,12 +11,12 @@ interface OfferCommandFactoryInterface
* @param Label $label
* @return AbstractAddLabel
*/
- public static function createAddLabelCommand($id, Label $label);
+ public function createAddLabelCommand($id, Label $label);
/**
* @param $id
* @param Label $label
* @return AbstractDeleteLabel
*/
- public static function createDeleteLabelCommand($id, Label $label);
+ public function createDeleteLabelCommand($id, Label $label);
}
diff --git a/src/Place/Commands/PlaceCommandFactory.php b/src/Place/Commands/PlaceCommandFactory.php
index <HASH>..<HASH> 100644
--- a/src/Place/Commands/PlaceCommandFactory.php
+++ b/src/Place/Commands/PlaceCommandFactory.php
@@ -12,7 +12,7 @@ class PlaceCommandFactory implements OfferCommandFactoryInterface
* @param Label $label
* @return AddLabel
*/
- public static function createAddLabelCommand($id, Label $label)
+ public function createAddLabelCommand($id, Label $label)
{
return new AddLabel($id, $label);
}
@@ -22,7 +22,7 @@ class PlaceCommandFactory implements OfferCommandFactoryInterface
* @param Label $label
* @return DeleteLabel
*/
- public static function createDeleteLabelCommand($id, Label $label)
+ public function createDeleteLabelCommand($id, Label $label)
{
return new DeleteLabel($id, $label);
}
|
III-<I>: Make methods of factory non-static
|
cultuurnet_udb3-php
|
train
|
84491f509888324efd30a29555dcd82618b1c146
|
diff --git a/js/config/wordBoundaries.js b/js/config/wordBoundaries.js
index <HASH>..<HASH> 100644
--- a/js/config/wordBoundaries.js
+++ b/js/config/wordBoundaries.js
@@ -1,3 +1,10 @@
module.exports = function() {
- return [ " ", "\\n", "\\r", "\\t", ".", ",", "'", "(", ")", "\"", "+", "-", ";", "!", "?", ":", "/", "»", "«", "‹", "›", "<", ">" ];
+ return [
+ // Whitespace is always a word boundary.
+ " ", "\\n", "\\r", "\\t",
+ // NO-BREAK SPACE.
+ "\u00a0",
+ " ",
+
+ ".", ",", "'", "(", ")", "\"", "+", "-", ";", "!", "?", ":", "/", "»", "«", "‹", "›", "<", ">" ];
};
diff --git a/spec/researches/transitionWordsSpec.js b/spec/researches/transitionWordsSpec.js
index <HASH>..<HASH> 100644
--- a/spec/researches/transitionWordsSpec.js
+++ b/spec/researches/transitionWordsSpec.js
@@ -157,4 +157,20 @@ describe("a test for finding transition words from a string", function() {
transitionWordSentences: 1
} );
});
+
+ it( "works with the no-break space character", function() {
+ mockPaper = new Paper( "and\u00a0then" );
+ var expected = {
+ totalSentences: 1,
+ sentenceResults: [{
+ sentence: "and\u00a0then",
+ transitionWords: [ "then" ]
+ }],
+ transitionWordSentences: 1
+ };
+
+ var result = transitionWordsResearch( mockPaper );
+
+ expect( result ).toEqual( expected );
+ });
} );
|
Add the no-break space character to the word boundaries
|
Yoast_YoastSEO.js
|
train
|
1aeaac449c635e286f0e5af7d5ef7e2e3d0dd2b4
|
diff --git a/lib/puppet/pops/types/types.rb b/lib/puppet/pops/types/types.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/pops/types/types.rb
+++ b/lib/puppet/pops/types/types.rb
@@ -1311,6 +1311,8 @@ class PStructType < PAnyType
if required_elements_assignable
size_o = o.size_type || PCollectionType::DEFAULT_SIZE
PIntegerType.new(required, elements.size).assignable?(size_o, guard)
+ else
+ false
end
else
false
diff --git a/spec/unit/pops/types/type_calculator_spec.rb b/spec/unit/pops/types/type_calculator_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/pops/types/type_calculator_spec.rb
+++ b/spec/unit/pops/types/type_calculator_spec.rb
@@ -894,6 +894,12 @@ describe 'The type calculator' do
t2 = struct_t({not_undef_t('other_member') => string_t})
expect(t2).not_to be_assignable_to(t1)
end
+
+ it 'A hash of string is not assignable to struct with integer value' do
+ t1 = struct_t({'foo' => integer_t, 'bar' => string_t})
+ t2 = hash_t(string_t, string_t, range_t(2, 2))
+ expect(t1.assignable?(t2)).to eql(false)
+ end
end
context 'for Callable, such that' do
|
(PUP-<I>) Fix bug causing Struct assignable? to return nil
The `PStructType#assignable?` method would return `nil` instead of
`false` when compared to a PHashType. This commit fixes that.
|
puppetlabs_puppet
|
train
|
31550144739f0fddc69e7f70bdbf56fc3adf7436
|
diff --git a/devices.js b/devices.js
index <HASH>..<HASH> 100644
--- a/devices.js
+++ b/devices.js
@@ -1678,6 +1678,13 @@ const devices = [
description: 'LIGHTIFY LED gardenspot mini RGB',
extend: generic.light_onoff_brightness_colorxy,
},
+ {
+ zigbeeModel: ['PAR38 W 10 year'],
+ model: '74580',
+ vendor: 'Sylvania',
+ description: 'Smart Home soft white PAR38 outdoor bulb',
+ extend: generic.light_onoff_brightness,
+ },
// GE
{
|
Add support for Sylvania soft white PAR<I> outdoor bulb (#<I>)
* Add support for Sylvania soft white PAR<I> outdoor bulb
* Update devices.js
|
Koenkk_zigbee-shepherd-converters
|
train
|
d26ffa2e93f59b6a467c151f69a0142222e46b18
|
diff --git a/lib/rspec_command.rb b/lib/rspec_command.rb
index <HASH>..<HASH> 100644
--- a/lib/rspec_command.rb
+++ b/lib/rspec_command.rb
@@ -66,6 +66,12 @@ module RSpecCommand
# Matcher to compare files or folders from the temporary directory to a
# fixture.
+ #
+ # @example
+ # describe 'myapp' do
+ # command 'myapp write'
+ # it { is_expected.to match_fixture('write_data') }
+ # end
def match_fixture(fixture_path, local_path=nil)
MatchFixture.new(find_fixture(self.class.file_path), temp_path, fixture_path, local_path || fixture_path)
end
|
Yard docs for match_fixture.
|
coderanger_rspec-command
|
train
|
8d0f8018baacaa5dc94996a4a285867d682623c8
|
diff --git a/salt/payload.py b/salt/payload.py
index <HASH>..<HASH> 100644
--- a/salt/payload.py
+++ b/salt/payload.py
@@ -14,7 +14,6 @@ import datetime
# Import salt libs
import salt.log
-import salt.crypt
import salt.transport.frame
from salt.exceptions import SaltReqTimeoutError
from salt.utils import immutabletypes
|
removing salt.crypt from payload.py which is not used and causing salt-key to break.
|
saltstack_salt
|
train
|
74d882c9d57dd4246f768be843b26863119ddf9a
|
diff --git a/src/domnodes.js b/src/domnodes.js
index <HASH>..<HASH> 100644
--- a/src/domnodes.js
+++ b/src/domnodes.js
@@ -45,7 +45,11 @@ function allChildren({props = {}}) {
return [];
}
let children = ensureToBeArray(props.children);
- return [...children, ...children.map(allChildren).reduce(flatten)];
+ let all = [];
+ for (let i=0, l=children.length; i<l; i++) {
+ all = [...all, children[i], ...ensureToBeArray(children[i]).map(allChildren).reduce(flatten)];
+ }
+ return all;
}
function allNodes(tree) {
diff --git a/test/find-dom-nodes-spec.js b/test/find-dom-nodes-spec.js
index <HASH>..<HASH> 100644
--- a/test/find-dom-nodes-spec.js
+++ b/test/find-dom-nodes-spec.js
@@ -56,26 +56,31 @@ describe('find dom nodes', function() {
it('second node is the 1st node on the first level', () => { assert.equal(domNodes[1].type, 'b'); });
it('third node is the 2nd node on the first level', () => { assert.equal(domNodes[2].type, 'span'); });
});
- describe('many DOM nodes, various nestings', function() {
+ describe.only('many DOM nodes, various nestings', function() {
let domNodes;
beforeEach(function() {
- let renderedTree = <div>
+ let renderedTree = (
<div>
- <span></span><span></span>
+ <p>
+ <a/><b/>
+ </p>
+ <span></span>
+ <blockquote><form><button/></form></blockquote>
</div>
- <span></span>
- <span><b><a></a></b></span>
- </div>;
+ );
domNodes = domNodesFromComponent(renderedTree);
});
- it('the count is correct', () => { assert.equal(domNodes.length, 8); });
- it('first node is the outer node', () => { assert.equal(domNodes[0].type, 'div'); });
- it('2nd node is `div`', () => { assert.equal(domNodes[1].type, 'div'); });
- it('3rd node is `span`', () => { assert.equal(domNodes[2].type, 'span'); });
- it('4th node is `span`', () => { assert.equal(domNodes[3].type, 'span'); });
- it('5th node is `span`', () => { assert.equal(domNodes[4].type, 'span'); });
- it('6th node is `span`', () => { assert.equal(domNodes[5].type, 'span'); });
- it('7th node is `b`', () => { assert.equal(domNodes[6].type, 'b'); });
+ describe('the order should be depth first', function() {
+ it('the count is correct', () => { assert.equal(domNodes.length, 8); });
+ it('first node is the outer node', () => { assert.equal(domNodes[0].type, 'div'); });
+ it('2nd node is `p`', () => { assert.equal(domNodes[1].type, 'p'); });
+ it('3rd node is `a`', () => { assert.equal(domNodes[2].type, 'a'); });
+ it('4th node is `b`', () => { assert.equal(domNodes[3].type, 'b'); });
+ it('5th node is `span`', () => { assert.equal(domNodes[4].type, 'span'); });
+ it('6th node is `blockquote`', () => { assert.equal(domNodes[5].type, 'blockquote'); });
+ it('7th node is `form`', () => { assert.equal(domNodes[6].type, 'form'); });
+ it('8th node is `button`', () => { assert.equal(domNodes[7].type, 'button'); });
+ });
});
});
});
|
Fix the order to be depth first.
|
uxebu_react-components-asserts
|
train
|
97f96cbea674faedfc1a3e7041ecbeda1ee5fd63
|
diff --git a/lib/GameWindow.js b/lib/GameWindow.js
index <HASH>..<HASH> 100644
--- a/lib/GameWindow.js
+++ b/lib/GameWindow.js
@@ -898,7 +898,7 @@
oldPos = this.headerPosition;
- // Store the new position in a reference variable
+ // Store the new position in a reference variable
// **before** adaptFrame2HeaderPosition is called
this.headerPosition = pos;
@@ -1344,6 +1344,8 @@
*
* Warning: Security policies may block this method if the content is
* coming from another domain.
+ * Notice: If called multiple times within the same stage/step, it will
+ * the `VisualTimer` widget to reload the timer.
*
* @param {string} uri The uri to load
* @param {function} func Optional. The function to call once the DOM is
@@ -1770,7 +1772,7 @@
W.removeClass(W.frameElement, 'ng_mainframe-header-[a-z-]*');
switch(position) {
- case 'right':
+ case 'right':
W.addClass(W.frameElement, 'ng_mainframe-header-vertical-r');
break;
case 'left':
|
Added notice to GameWindow.loadFrame about resetting of VisualTimer
|
nodeGame_nodegame-window
|
train
|
ef3f48c5bc9ecc7ca1987467f382cbb1f8948054
|
diff --git a/lib/rspec-puppet/coverage.rb b/lib/rspec-puppet/coverage.rb
index <HASH>..<HASH> 100644
--- a/lib/rspec-puppet/coverage.rb
+++ b/lib/rspec-puppet/coverage.rb
@@ -159,7 +159,13 @@ module RSpec::Puppet
end
coverage_test.run(RSpec.configuration.reporter)
- if coverage_results.execution_result[:status] == :failed
+ status = if coverage_results.execution_result.respond_to?(:status)
+ coverage_results.execution_result.status
+ else
+ coverage_results.execution_result[:status]
+ end
+
+ if status == :failed
RSpec.world.non_example_failure = true
RSpec.world.wants_to_quit = true
end
|
Fix deprecation warning from <I> with latest rspec
|
rodjek_rspec-puppet
|
train
|
b528cd05ddc095cc9141050b9a905cff81ef0d41
|
diff --git a/src/frontend/org/voltdb/dbmonitor/js/voltdb.core.js b/src/frontend/org/voltdb/dbmonitor/js/voltdb.core.js
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/dbmonitor/js/voltdb.core.js
+++ b/src/frontend/org/voltdb/dbmonitor/js/voltdb.core.js
@@ -196,14 +196,14 @@
}
};
- var callbackWrapper = function (userCallback) {
+ var callbackWrapper = function (userCallback, isHighTimeout) {
var criticalErrorResponse = { "status": -1, "statusstring": "Query timeout.", "results": [] };
var UserCallback = userCallback;
var timeoutOccurred = 0;
var timeout = setTimeout(function () {
timeoutOccurred = 1;
UserCallback(criticalErrorResponse);
- }, 20000);
+ }, !isHighTimeout ? 20000 : 6000000);
this.Callback = function (response, headerInfo) {
clearTimeout(timeout);
if (timeoutOccurred == 0) UserCallback(response, headerInfo);
@@ -211,8 +211,10 @@
return this;
};
- this.BeginExecute = function(procedure, parameters, callback, shortApiCallDetails) {
- this.CallExecute(procedure, parameters, (new callbackWrapper(callback)).Callback, shortApiCallDetails);
+ this.BeginExecute = function (procedure, parameters, callback, shortApiCallDetails) {
+ var isHighTimeout = procedure == "@SnapshotRestore";
+ console.log("procedure: " + procedure);
+ this.CallExecute(procedure, parameters, (new callbackWrapper(callback, isHighTimeout)).Callback, shortApiCallDetails);
};
var iQueue = function (connection) {
@@ -242,6 +244,7 @@
if (stack.length > 0 && (success || continueOnFailure)) {
var item = stack[0];
var shortApiCallDetails = item[3];
+ var isHighTimeout = item[0] == "@SnapshotRestore";
var callback =
(new callbackWrapper(
(function(queue, item) {
@@ -263,7 +266,7 @@
queue.EndExecute();
}
};
- })(this, item))).Callback;
+ })(this, item), isHighTimeout)).Callback;
if (shortApiCallDetails != null && shortApiCallDetails.isShortApiCall && shortApiCallDetails.isUpdateConfiguration)
Connection.CallExecuteUpdate(item[0], item[1], callback, item[3]);
@@ -625,7 +628,7 @@ jQuery.extend({
jQuery.extend({
getJSON: function (url, formData, callback, authorization) {
- formData += '&User=admin&Hashedpassword=20e3aae7fc23385295505a6b703fd1fba66760d5';
+
if (VoltDBCore.hostIP == "") {
jQuery.ajax({
type: 'GET',
|
VMC-<I> Perform Restore snapshot functionality
|
VoltDB_voltdb
|
train
|
c1a767f14dbb685e01b1ae4e0d8316a6ced4ed0b
|
diff --git a/javamelody-core/src/main/java/net/bull/javamelody/MonitoredSpringAsyncAndScheduledPointcut.java b/javamelody-core/src/main/java/net/bull/javamelody/MonitoredSpringAsyncAndScheduledPointcut.java
index <HASH>..<HASH> 100644
--- a/javamelody-core/src/main/java/net/bull/javamelody/MonitoredSpringAsyncAndScheduledPointcut.java
+++ b/javamelody-core/src/main/java/net/bull/javamelody/MonitoredSpringAsyncAndScheduledPointcut.java
@@ -72,13 +72,11 @@ public class MonitoredSpringAsyncAndScheduledPointcut implements Pointcut {
/** {@inheritDoc} */
@Override
- @SuppressWarnings("rawtypes")
- public boolean matches(Method method, Class targetClass) {
+ public boolean matches(Method method, Class<?> targetClass) {
return matchesAsync(method, targetClass) || matchesScheduled(method);
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private boolean matchesAsync(Method method, Class targetClass) {
+ private boolean matchesAsync(Method method, Class<?> targetClass) {
return ASYNC_CLASS != null && (targetClass.isAnnotationPresent(ASYNC_CLASS)
|| method.getDeclaringClass().isAnnotationPresent(ASYNC_CLASS)
|| method.isAnnotationPresent(ASYNC_CLASS));
diff --git a/javamelody-core/src/main/java/net/bull/javamelody/MonitoredWithAnnotationPointcut.java b/javamelody-core/src/main/java/net/bull/javamelody/MonitoredWithAnnotationPointcut.java
index <HASH>..<HASH> 100644
--- a/javamelody-core/src/main/java/net/bull/javamelody/MonitoredWithAnnotationPointcut.java
+++ b/javamelody-core/src/main/java/net/bull/javamelody/MonitoredWithAnnotationPointcut.java
@@ -52,8 +52,7 @@ public class MonitoredWithAnnotationPointcut implements Pointcut {
/** {@inheritDoc} */
@Override
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public boolean matches(Method method, Class targetClass) {
+ public boolean matches(Method method, Class<?> targetClass) {
return targetClass.isAnnotationPresent(MonitoredWithSpring.class)
|| method.getDeclaringClass().isAnnotationPresent(MonitoredWithSpring.class)
|| method.isAnnotationPresent(MonitoredWithSpring.class);
diff --git a/javamelody-core/src/main/java/net/bull/javamelody/MonitoredWithInterfacePointcut.java b/javamelody-core/src/main/java/net/bull/javamelody/MonitoredWithInterfacePointcut.java
index <HASH>..<HASH> 100644
--- a/javamelody-core/src/main/java/net/bull/javamelody/MonitoredWithInterfacePointcut.java
+++ b/javamelody-core/src/main/java/net/bull/javamelody/MonitoredWithInterfacePointcut.java
@@ -31,8 +31,7 @@ public class MonitoredWithInterfacePointcut implements Pointcut {
private final ClassFilter classFilter = new ClassFilter() {
/** {@inheritDoc} */
@Override
- @SuppressWarnings("rawtypes")
- public boolean matches(Class clazz) {
+ public boolean matches(Class<?> clazz) {
return interfaceClass.isAssignableFrom(clazz);
}
};
|
follow-up to upgrade of some optional dependencies
|
javamelody_javamelody
|
train
|
67e18a0d02a3d83a97facc0705ab6f8ef1d79a20
|
diff --git a/morango/models.py b/morango/models.py
index <HASH>..<HASH> 100644
--- a/morango/models.py
+++ b/morango/models.py
@@ -8,6 +8,8 @@ import sys
import uuid
from django.conf import settings
+from django.core import exceptions
+from django.core.cache import cache
from django.db.models import signals
from django.core import exceptions
from django.db import connection, models, transaction
@@ -508,6 +510,42 @@ class SyncableModel(UUIDModelMixin):
obj._update_hard_deleted_models()
return collector.delete()
+ def clean_fields(self, exclude=None):
+ """
+ Cleans all fields and raises a ValidationError containing a dict
+ of all validation errors if any occur.
+ """
+ if exclude is None:
+ exclude = []
+
+ errors = {}
+ for f in self._meta.fields:
+ if f.name in exclude:
+ continue
+ # Skip validation for empty fields with blank=True. The developer
+ # is responsible for making sure they have a valid value.
+ raw_value = getattr(self, f.attname)
+ if f.blank and raw_value in f.empty_values:
+ continue
+ try:
+ if isinstance(f, models.ForeignKey):
+ key = 'morango_{id}_{db_table}_foreignkey'.format(db_table=f.related_model._meta.db_table, id=raw_value)
+ cached_value = cache.get(key)
+ if cached_value:
+ setattr(self, f.attname, cached_value)
+ else:
+ cleaned_value = f.clean(raw_value, self)
+ cache.set(key, cleaned_value, 60 * 10)
+ setattr(self, f.attname, cleaned_value)
+ else:
+ setattr(self, f.attname, f.clean(raw_value, self))
+
+ except exceptions.ValidationError as e:
+ errors[f.name] = e.error_list
+
+ if errors:
+ raise exceptions.ValidationError(errors)
+
def serialize(self):
"""All concrete fields of the ``SyncableModel`` subclass, except for those specifically blacklisted, are returned in a dict."""
# NOTE: code adapted from https://github.com/django/django/blob/master/django/forms/models.py#L75
|
Cache foreign key lookups across models
|
learningequality_morango
|
train
|
a0afca71cc0105d913d8164a7d2e9747cf8e1ca6
|
diff --git a/CHANGES.txt b/CHANGES.txt
index <HASH>..<HASH> 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,3 +1,8 @@
+0.5.9
+------
+
+- fixed bug where text wouldn't write unless xpath specified
+
0.5.8
------
diff --git a/scrape/__init__.py b/scrape/__init__.py
index <HASH>..<HASH> 100644
--- a/scrape/__init__.py
+++ b/scrape/__init__.py
@@ -1 +1 @@
-__version__ = '0.5.8'
+__version__ = '0.5.9'
diff --git a/scrape/utils.py b/scrape/utils.py
index <HASH>..<HASH> 100644
--- a/scrape/utils.py
+++ b/scrape/utils.py
@@ -140,14 +140,16 @@ def parse_text(in_file, xpath=None, filter_words=None, attributes=None):
in_file = parse_html(in_file, xpath)
if isinstance(in_file, list):
- if isinstance(in_file[0], str):
- text = [line + '\n' for line in in_file]
- else:
+ if isinstance(in_file[0], lh.HtmlElement):
in_files = list(in_file)
- elif isinstance(in_file, str):
- text = [in_file]
- else:
+ else:
+ text = [line + '\n' for line in in_file]
+ elif isinstance(in_file, lh.HtmlElement):
in_files = [in_file]
+ else:
+ text = [in_file]
+ else:
+ in_files = [in_file]
if attributes is not None:
attributes = [clean_attr(x) for x in attributes]
|
fixed bug where text wouldn't write without xpath
|
huntrar_scrape
|
train
|
54d73e15c165ae7e5c640efaa4a6180d969f89e0
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -15,7 +15,9 @@ type PluginOptions = {
aliases?: {
[key: string]: string|Template;
};
- strip?: boolean|string|{[key: string]: boolean};
+ strip?: boolean | {
+ [key: string]: boolean | { [key: string]: boolean }
+ };
};
type LogFunction = (message: Message, metadata: Metadata) => Node;
@@ -245,28 +247,32 @@ function collectMetadata (path: NodePath, opts: PluginOptions): Metadata {
* Determine whether the given logging statement should be stripped.
*/
function shouldStrip (name: string, metadata: Metadata, { strip }: PluginOptions): boolean {
- if (
- strip && (
- strip === true ||
- strip === process.env.NODE_ENV ||
- strip[process.env.NODE_ENV]
- )
- ) {
- if (PRESERVE_CONTEXTS.length) {
- const context = metadata.context.toLowerCase();
- if (PRESERVE_CONTEXTS.some(pc => context.includes(pc))) return false;
- }
- if (PRESERVE_FILES.length) {
- const filename = metadata.filename.toLowerCase();
- if (PRESERVE_FILES.some(pf => filename.includes(pf))) return false;
- }
- if (PRESERVE_LEVELS.length) {
- const level = name.toLowerCase();
- if (PRESERVE_LEVELS.some(pl => level === pl)) return false;
- }
- return true;
+ switch (typeof strip) {
+ case 'boolean':
+ if (!strip) return false;
+ // strip === true
+ break;
+ case 'object':
+ const se = strip[name];
+ if (!se || (typeof se === 'object' && !se[process.env.NODE_ENV])) return false;
+ // strip[name] === true || strip[name][env] === true
+ break;
+ default:
+ return false;
+ }
+ if (PRESERVE_CONTEXTS.length) {
+ const context = metadata.context.toLowerCase();
+ if (PRESERVE_CONTEXTS.some(pc => context.includes(pc))) return false;
+ }
+ if (PRESERVE_FILES.length) {
+ const filename = metadata.filename.toLowerCase();
+ if (PRESERVE_FILES.some(pf => filename.includes(pf))) return false;
+ }
+ if (PRESERVE_LEVELS.length) {
+ const level = name.toLowerCase();
+ if (PRESERVE_LEVELS.some(pl => level === pl)) return false;
}
- return false;
+ return true;
}
export function handleLabeledStatement (babel: PluginParams, path: NodePath, opts: PluginOptions): void {
|
Breaking change: Refactor "strip" option shape to support strip[env][name] control
|
codemix_babel-plugin-trace
|
train
|
438b3cb694ea8360540192b990f2eb4f520f4c12
|
diff --git a/client_test.go b/client_test.go
index <HASH>..<HASH> 100644
--- a/client_test.go
+++ b/client_test.go
@@ -201,7 +201,7 @@ func TestImagePullAllPlatforms(t *testing.T) {
defer cancel()
cs := client.ContentStore()
- img, err := client.Fetch(ctx, testImage)
+ img, err := client.Fetch(ctx, "docker.io/library/busybox:latest")
if err != nil {
t.Fatal(err)
}
@@ -249,7 +249,7 @@ func TestImagePullSomePlatforms(t *testing.T) {
opts = append(opts, WithPlatform(platform))
}
- img, err := client.Fetch(ctx, "docker.io/library/busybox:latest", opts...)
+ img, err := client.Fetch(ctx, "k8s.gcr.io/pause:3.1", opts...)
if err != nil {
t.Fatal(err)
}
diff --git a/image_test.go b/image_test.go
index <HASH>..<HASH> 100644
--- a/image_test.go
+++ b/image_test.go
@@ -45,7 +45,7 @@ func TestImageIsUnpacked(t *testing.T) {
}
// By default pull does not unpack an image
- image, err := client.Pull(ctx, imageName)
+ image, err := client.Pull(ctx, imageName, WithPlatform("linux/amd64"))
if err != nil {
t.Fatal(err)
}
|
Update multi-arch image tests
Ensure the test pull for all platforms uses a multi-arch image
Use the pause container for testing specific platforms
Update the image unpack test to be explicit about the platform to unpack
|
containerd_containerd
|
train
|
dd53f25a4aa4b7f48f56fa90c700db58a4933bb2
|
diff --git a/test/model.save.js b/test/model.save.js
index <HASH>..<HASH> 100644
--- a/test/model.save.js
+++ b/test/model.save.js
@@ -1,10 +1,12 @@
+var couchbase = require('couchbase');
var expect = require('chai').expect;
+
var lounge = require('../lib');
var Schema = lounge.Schema;
-var couchbase = require('couchbase');
-var cluster, bucket;
-describe('Model save tests', function () {
+var bucket;
+
+describe.only('Model save tests', function () {
beforeEach(function (done) {
lounge = new lounge.Lounge(); // recreate it
@@ -16,7 +18,7 @@ describe('Model save tests', function () {
});
});
- it.only('should save a simple document', function (done) {
+ it('should save a simple document', function (done) {
var userSchema = lounge.schema({
firstName: String,
lastName: String,
@@ -71,4 +73,122 @@ describe('Model save tests', function () {
});
});
});
+
+ it('should save a simple document with data passed in to save()', function (done) {
+ var userSchema = lounge.schema({
+ firstName: String,
+ lastName: String,
+ email: String,
+ dateOfBirth: Date
+ });
+
+ var User = lounge.model('User', userSchema);
+
+ var dob = new Date('March 3, 1989 03:30:00');
+
+ var user = new User();
+
+ var data = {
+ firstName: 'Joe2',
+ lastName: 'Smith2',
+ email: 'joe2@gmail.com',
+ dateOfBirth: dob
+ };
+
+ user.save(data, function (err, savedDoc) {
+ expect(err).to.not.be.ok;
+
+ expect(savedDoc).to.be.ok;
+ expect(savedDoc).to.be.an('object');
+ expect(savedDoc.id).to.be.ok;
+ expect(savedDoc.id).to.be.a('string');
+
+ expect(savedDoc.firstName).to.be.equal('Joe2');
+ expect(savedDoc.lastName).to.be.equal('Smith2');
+ expect(savedDoc.email).to.be.equal('joe2@gmail.com');
+ expect(savedDoc.dateOfBirth).to.be.ok;
+ expect(savedDoc.dateOfBirth).to.be.an.instanceof(Date);
+ expect(savedDoc.dateOfBirth.toString()).to.be.equal((new Date(1989, 2, 3, 3, 30, 0)).toString());
+
+ bucket.get(savedDoc.getDocumentKeyValue(true), function (err, dbDoc) {
+ expect(err).to.not.be.ok;
+
+ expect(dbDoc).to.be.ok;
+ expect(dbDoc.value).to.be.ok;
+ expect(dbDoc.value).to.be.an('object');
+
+ var expected = {
+ firstName: 'Joe2',
+ lastName: 'Smith2',
+ email: 'joe2@gmail.com',
+ dateOfBirth: dob.toISOString()
+ };
+
+ expected.id = savedDoc.getDocumentKeyValue(true);
+
+ expect(dbDoc.value).to.deep.equal(expected);
+ done();
+ });
+ });
+ });
+
+ it('should save a simple document with some data passed in to save()', function (done) {
+ var userSchema = lounge.schema({
+ firstName: String,
+ lastName: String,
+ email: String,
+ dateOfBirth: Date
+ });
+
+ var User = lounge.model('User', userSchema);
+
+ var dob = new Date('March 3, 1989 03:30:00');
+
+ var user = new User({
+ firstName: 'Joe',
+ email: 'joe2@gmail.com'
+ });
+
+ var data = {
+ firstName: 'Joe2',
+ lastName: 'Smith2',
+ dateOfBirth: dob
+ };
+
+ user.save(data, function (err, savedDoc) {
+ expect(err).to.not.be.ok;
+
+ expect(savedDoc).to.be.ok;
+ expect(savedDoc).to.be.an('object');
+ expect(savedDoc.id).to.be.ok;
+ expect(savedDoc.id).to.be.a('string');
+
+ expect(savedDoc.firstName).to.be.equal('Joe2');
+ expect(savedDoc.lastName).to.be.equal('Smith2');
+ expect(savedDoc.email).to.be.equal('joe2@gmail.com');
+ expect(savedDoc.dateOfBirth).to.be.ok;
+ expect(savedDoc.dateOfBirth).to.be.an.instanceof(Date);
+ expect(savedDoc.dateOfBirth.toString()).to.be.equal((new Date(1989, 2, 3, 3, 30, 0)).toString());
+
+ bucket.get(savedDoc.getDocumentKeyValue(true), function (err, dbDoc) {
+ expect(err).to.not.be.ok;
+
+ expect(dbDoc).to.be.ok;
+ expect(dbDoc.value).to.be.ok;
+ expect(dbDoc.value).to.be.an('object');
+
+ var expected = {
+ firstName: 'Joe2',
+ lastName: 'Smith2',
+ email: 'joe2@gmail.com',
+ dateOfBirth: dob.toISOString()
+ };
+
+ expected.id = savedDoc.getDocumentKeyValue(true);
+
+ expect(dbDoc.value).to.deep.equal(expected);
+ done();
+ });
+ });
+ });
});
\ No newline at end of file
|
more model.save() tests
|
bojand_lounge
|
train
|
c0d96a7e84775f092689c9ee976084a27eff2643
|
diff --git a/airflow/models.py b/airflow/models.py
index <HASH>..<HASH> 100644
--- a/airflow/models.py
+++ b/airflow/models.py
@@ -572,6 +572,8 @@ class TaskInstance(Base):
return False
elif self.task.end_date and self.execution_date > self.task.end_date:
return False
+ elif self.state == State.SKIPPED:
+ return False
elif (
self.state in State.runnable() and
self.are_dependencies_met(
|
Making sure that SKIPPED task state don't run
|
apache_airflow
|
train
|
3921fbf23a2baed67358644cb75086ce166e2a80
|
diff --git a/lib/utils.js b/lib/utils.js
index <HASH>..<HASH> 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -20,6 +20,8 @@ const XCTEST_LOG_FILES_PATTERNS = [
/^Session-WebDriverAgentRunner.*\.log$/i,
/^StandardOutputAndStandardError\.txt$/i,
];
+const XCTEST_LOGS_CACHE_FOLDER_PREFIX = 'com.apple.dt.XCTest';
+
async function detectUdid () {
log.debug('Auto-detecting real device udid...');
@@ -135,31 +137,39 @@ async function clearSystemFiles (wda) {
derivedDataCleanupMarkers.set(logsRoot, 0);
// Cleaning up big temporary files created by XCTest: https://github.com/appium/appium/issues/9410
- const tmpDir = os.tmpdir();
- let cleanedFilesCount = 0;
- // perform the cleanup asynchronously
- B.resolve(fs.walkDir(tmpDir, true, (itemPath, isDir) => {
- if (isDir) {
- return;
- }
- const fileName = path.basename(itemPath);
- if (!XCTEST_LOG_FILES_PATTERNS.some((p) => p.test(fileName))) {
- return;
+ const globPattern = `${os.tmpdir()}/${XCTEST_LOGS_CACHE_FOLDER_PREFIX}*/`;
+ const dstFolders = await fs.glob(globPattern);
+ if (_.isEmpty(dstFolders)) {
+ log.debug(`Did not find the temporary XCTest logs root at '${globPattern}'`);
+ } else {
+ // perform the cleanup asynchronously
+ for (const dstFolder of dstFolders) {
+ let scheduledFilesCount = 0;
+ B.resolve(fs.walkDir(dstFolder, true, (itemPath, isDir) => {
+ if (isDir) {
+ return;
+ }
+ const fileName = path.basename(itemPath);
+ if (!XCTEST_LOG_FILES_PATTERNS.some((p) => p.test(fileName))) {
+ return;
+ }
+
+ // delete the file asynchronously
+ fs.unlink(itemPath).catch((e) => {
+ log.info(e.message);
+ });
+ scheduledFilesCount++;
+ })).finally(() => {
+ if (scheduledFilesCount > 0) {
+ log.info(`Scheduled ${scheduledFilesCount} temporary XCTest log ` +
+ `file${scheduledFilesCount === 1 ? '' : 's'} for cleanup in '${dstFolder}'`);
+ }
+ }).catch((e) => {
+ log.info(e.message);
+ });
}
-
- // delete the file asynchronously
- fs.unlink(itemPath)
- // eslint-disable-next-line promise/prefer-await-to-then
- .then(() => {
- cleanedFilesCount++;
- }).catch(() => {});
- })).finally(() => {
- if (cleanedFilesCount > 0) {
- log.info(`Successfully cleaned up ${cleanedFilesCount} ` +
- `temporary XCTest log file${cleanedFilesCount === 1 ? '' : 's'}`);
- }
- }).catch(() => {});
- log.debug(`Started background XCTest logs cleanup in '${tmpDir}'`);
+ log.debug(`Started background XCTest logs cleanup in '${dstFolders}'`);
+ }
if (await fs.exists(logsRoot)) {
log.info(`Cleaning test logs in '${logsRoot}' folder`);
diff --git a/test/unit/utils-specs.js b/test/unit/utils-specs.js
index <HASH>..<HASH> 100644
--- a/test/unit/utils-specs.js
+++ b/test/unit/utils-specs.js
@@ -24,12 +24,14 @@ describe('utils', function () {
return DERIVED_DATA_ROOT;
}
};
+ mocks.fs.expects('glob')
+ .once()
+ .returns([]);
mocks.fs.expects('walkDir')
.once()
.returns();
mocks.fs.expects('exists')
- .once()
- .withExactArgs(`${DERIVED_DATA_ROOT}/Logs`)
+ .atLeast(1)
.returns(true);
mocks.iosUtils.expects('clearLogs')
.once()
@@ -44,11 +46,14 @@ describe('utils', function () {
return DERIVED_DATA_ROOT;
}
};
+ mocks.fs.expects('glob')
+ .once()
+ .returns([]);
mocks.fs.expects('walkDir')
.once()
.returns();
mocks.fs.expects('exists')
- .withExactArgs(`${DERIVED_DATA_ROOT}/Logs`)
+ .atLeast(1)
.returns(true);
mocks.iosUtils.expects('clearLogs')
.once()
|
fix: Look for temporary logs in the specific root folder instead of the whole tempdir (#<I>)
|
appium_appium-xcuitest-driver
|
train
|
df99099a3d6271119900a42bf5b4e42df4f9e042
|
diff --git a/src/horizon_api.ts b/src/horizon_api.ts
index <HASH>..<HASH> 100644
--- a/src/horizon_api.ts
+++ b/src/horizon_api.ts
@@ -30,7 +30,6 @@ export namespace Horizon {
> {
created_at: string;
fee_meta_xdr: string;
- fee_paid: number;
fee_charged: number;
max_fee: number;
id: string;
diff --git a/test/unit/server/join_test.js b/test/unit/server/join_test.js
index <HASH>..<HASH> 100644
--- a/test/unit/server/join_test.js
+++ b/test/unit/server/join_test.js
@@ -56,7 +56,6 @@ describe("Server - CallBuilder#join", function() {
source_account:
"GBIABVWR2LOKFDMAI6QA2NGT4G54O3BC577GAWDQ6QMOUP5E3ULBBGYX",
source_account_sequence: "2954696981479425",
- fee_paid: 3600,
fee_charged: 3600,
max_fee: 3600,
operation_count: 6,
diff --git a/test/unit/server_test.js b/test/unit/server_test.js
index <HASH>..<HASH> 100644
--- a/test/unit/server_test.js
+++ b/test/unit/server_test.js
@@ -646,7 +646,8 @@ describe('server.js non-transaction tests', function() {
source_account:
'GBURK32BMC7XORYES62HDKY7VTA5MO7JYBDH7KTML4EPN4BV2MIRQOVR',
source_account_sequence: '25631492944168311',
- fee_paid: 400,
+ fee_charged: 3600,
+ max_fee: 3600,
operation_count: 4,
envelope_xdr:
'AAAAAGkVb0Fgv3dHBJe0casfrMHWO+nARn+qbF8I9vA10xEYAAABkABbD7UAAAV3AAAAAAAAAAAAAAAEAAAAAAAAAAMAAAABRlVOVAAAAABpigEf7e9h5IpePeEXCoPJPqY8IRt8hpneL5+OXfZ45QAAAAAAAAAABfXhAEeeSWkAKXANAAAAAAAAB74AAAABAAAAAGkVb0Fgv3dHBJe0casfrMHWO+nARn+qbF8I9vA10xEYAAAAAwAAAAAAAAABRlVOVAAAAABpigEf7e9h5IpePeEXCoPJPqY8IRt8hpneL5+OXfZ45QAAAApNO6TmAEeYrnXHsdUAAAAAAAAHvwAAAAEAAAAAaRVvQWC/d0cEl7Rxqx+swdY76cBGf6psXwj28DXTERgAAAADAAAAAAAAAAFVU0QAAAAAAGmKAR/t72Hkil494RcKg8k+pjwhG3yGmd4vn45d9njlAAAACVAvkAAACRT4DX+q6QAAAAAAAAfCAAAAAQAAAABpFW9BYL93RwSXtHGrH6zB1jvpwEZ/qmxfCPbwNdMRGAAAAAMAAAABVVNEAAAAAABpigEf7e9h5IpePeEXCoPJPqY8IRt8hpneL5+OXfZ45QAAAAAAAAAABkQTwCl6AxMAGo+PAAAAAAAAB8MAAAAAAAAAATXTERgAAABApox1kE2/f2oYQw/PdJZHUk74JVWRHDPwcqzGP+lSJljl6ABBRPqXewP1jAzpgY+vicDeLR/35/HyDyeAG7H0Aw==',
|
Remove fee_paid field from transaction response. (#<I>)
* Remove fee_paid field from transaction response.
* Update test.
|
stellar_js-stellar-sdk
|
train
|
511f81ec6746fe04503bf1ab627fb20e56f78179
|
diff --git a/test/package.test.js b/test/package.test.js
index <HASH>..<HASH> 100644
--- a/test/package.test.js
+++ b/test/package.test.js
@@ -11,7 +11,6 @@ var Package = require('../lib/index').Package;
// --- Globals
var UFDS_URL = 'ldaps://' + (process.env.UFDS_IP || '10.99.99.13');
-
var pack;
var entry = {
@@ -158,8 +157,6 @@ exports.test_urn_must_be_unique = function (t) {
pack.add(changes, function (err, pkg) {
t.ok(err);
t.ok(/already exists/.test(err.message));
- t.ok(/urn/.test(err.message));
- t.ok(/unique/.test(err.message));
t.done();
});
};
|
Fixed little test breakage due to latest upgrade.
|
joyent_node-sdc-clients
|
train
|
dd709283d57a9f3d78669dcdbbfef8bf7e2a0c9c
|
diff --git a/cli/src/main/java/org/jboss/as/cli/operation/impl/DefaultOperationCandidatesProvider.java b/cli/src/main/java/org/jboss/as/cli/operation/impl/DefaultOperationCandidatesProvider.java
index <HASH>..<HASH> 100644
--- a/cli/src/main/java/org/jboss/as/cli/operation/impl/DefaultOperationCandidatesProvider.java
+++ b/cli/src/main/java/org/jboss/as/cli/operation/impl/DefaultOperationCandidatesProvider.java
@@ -231,29 +231,34 @@ public class DefaultOperationCandidatesProvider implements OperationCandidatesPr
result = new ArrayList<CommandArgument>(propList.size());
for(final Property prop : propList) {
final CommandLineCompleterFactory factory = globalOpProps == null ? null : globalOpProps.get(prop.getName());
- final CommandLineCompleter completer;
+ CommandLineCompleter propCompleter = null;
if(factory != null) {
- completer = factory.createCompleter(address);
+ propCompleter = factory.createCompleter(address);
} else {
final ModelNode typeNode = prop.getValue().get(Util.TYPE);
if(typeNode.isDefined() && typeNode.asType().equals(ModelType.BOOLEAN)) {
- completer = SimpleTabCompleter.BOOLEAN;
- } else if(prop.getValue().has(Util.ALLOWED)) {
- final ModelNode allowedNode = prop.getValue().get(Util.ALLOWED);
- if(allowedNode.isDefined()) {
- final List<ModelNode> nodeList = allowedNode.asList();
- final String[] values = new String[nodeList.size()];
- for(int i = 0; i < values.length; ++i) {
- values[i] = nodeList.get(i).asString();
+ propCompleter = SimpleTabCompleter.BOOLEAN;
+ } else {
+ if(prop.getValue().has(Util.VALUE_TYPE)) {
+ final ModelNode valueTypeNode = prop.getValue().get(Util.VALUE_TYPE);
+ try {
+ // the logic is: if value-type is set to a specific type
+ // (i.e. doesn't describe a custom structure)
+ // then if allowed is specified, use it.
+ // it might be broken but so far this is not looking clear to me
+ valueTypeNode.asType();
+ if(prop.getValue().has(Util.ALLOWED)) {
+ propCompleter = getAllowedCompleter(prop);
+ }
+ } catch(IllegalArgumentException e) {
+ // TODO this means value-type describes a custom structure
}
- completer = new SimpleTabCompleter(values);
- } else {
- completer = null;
+ } else if(prop.getValue().has(Util.ALLOWED)) {
+ propCompleter = getAllowedCompleter(prop);
}
- } else {
- completer = null;
}
}
+ final CommandLineCompleter completer = propCompleter;
result.add(new CommandArgument(){
final String argName = prop.getName();
@Override
@@ -322,6 +327,19 @@ public class DefaultOperationCandidatesProvider implements OperationCandidatesPr
return result;
}
+ private CommandLineCompleter getAllowedCompleter(final Property prop) {
+ final ModelNode allowedNode = prop.getValue().get(Util.ALLOWED);
+ if(allowedNode.isDefined()) {
+ final List<ModelNode> nodeList = allowedNode.asList();
+ final String[] values = new String[nodeList.size()];
+ for(int i = 0; i < values.length; ++i) {
+ values[i] = nodeList.get(i).asString();
+ }
+ return new SimpleTabCompleter(values);
+ }
+ return null;
+ }
+
@Override
public Map<String, OperationRequestHeader> getHeaders(CommandContext ctx) {
return HEADERS;
diff --git a/cli/src/main/java/org/jboss/as/cli/parsing/arguments/ArgumentValueCallbackHandler.java b/cli/src/main/java/org/jboss/as/cli/parsing/arguments/ArgumentValueCallbackHandler.java
index <HASH>..<HASH> 100644
--- a/cli/src/main/java/org/jboss/as/cli/parsing/arguments/ArgumentValueCallbackHandler.java
+++ b/cli/src/main/java/org/jboss/as/cli/parsing/arguments/ArgumentValueCallbackHandler.java
@@ -139,6 +139,7 @@ public class ArgumentValueCallbackHandler implements ParsingStateCallbackHandler
}
class DefaultValueState implements ValueState {
+
private ModelNode wrapper;
private boolean list;
@@ -196,7 +197,11 @@ public class ArgumentValueCallbackHandler implements ParsingStateCallbackHandler
if(wrapper != null) {
if(name == null) {
if(buf != null && buf.length() > 0) {
- wrapper.add(getStringValue());
+ if(list || wrapper.getType().equals(ModelType.LIST)) {
+ wrapper.add(getStringValue());
+ } else {
+ wrapper.set(getStringValue());
+ }
}
} else {
addChild(wrapper, name, getStringValue());
@@ -310,17 +315,4 @@ public class ArgumentValueCallbackHandler implements ParsingStateCallbackHandler
return true;
}
}
-
- public static void main(String[] args) throws Exception {
-
- ModelNode one = new ModelNode();
- one.get("prop1").set("value1");
- one.get("prop2").set("value2");
- System.out.println(one);
-
- ModelNode two = new ModelNode();
- two.add("prop1", "value1");
- two.add("prop2", "value2");
- System.out.println(two);
- }
}
|
cli: initial steps to custom dmr value-type structure tab-completion
|
wildfly_wildfly
|
train
|
83dd853d0eff6dbc1f7834098e7619281e9ce287
|
diff --git a/lib/Doctrine/ODM/CouchDB/DocumentRepository.php b/lib/Doctrine/ODM/CouchDB/DocumentRepository.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ODM/CouchDB/DocumentRepository.php
+++ b/lib/Doctrine/ODM/CouchDB/DocumentRepository.php
@@ -132,20 +132,15 @@ class DocumentRepository implements ObjectRepository
foreach ($criteria AS $field => $value) {
$query = $this->dm->createQuery('doctrine_repositories', 'equal_constraint')
->setKey(array($this->documentType, $field, $value))
- ->setIncludeDocs(true);
+ ->setIncludeDocs(true)
+ ->toArray(true);
if ($limit) {
$query->setLimit($limit);
}
if ($offset) {
$query->setSkip($offset);
}
- $result = $query->execute();
-
- $docs = array();
- foreach ($result AS $doc) {
- $docs[] = $doc['doc'];
- }
- return $docs;
+ return $query->execute();
}
} else {
$ids = array();
diff --git a/lib/Doctrine/ODM/CouchDB/View/ODMQuery.php b/lib/Doctrine/ODM/CouchDB/View/ODMQuery.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ODM/CouchDB/View/ODMQuery.php
+++ b/lib/Doctrine/ODM/CouchDB/View/ODMQuery.php
@@ -35,14 +35,19 @@ class ODMQuery extends Query
*/
private $onlyDocs = false;
+ private $toArray = false;
+
public function execute()
{
$response = $this->doExecute();
+ $data = array();
if ($this->dm && $this->getParameter('include_docs') === true) {
$uow = $this->dm->getUnitOfWork();
foreach ($response->body['rows'] AS $k => $v) {
$doc = $uow->createDocument(null, $v['doc']);
- if ($this->onlyDocs) {
+ if ($this->toArray) {
+ $data[] = $doc;
+ } else if ($this->onlyDocs) {
$response->body['rows'][$k] = $doc;
} else {
$response->body['rows'][$k]['doc'] = $doc;
@@ -50,7 +55,7 @@ class ODMQuery extends Query
}
}
- return $this->createResult($response);
+ return ($this->toArray) ? $data : $this->createResult($response);
}
@@ -72,4 +77,10 @@ class ODMQuery extends Query
$this->onlyDocs = $flag;
return $this;
}
+
+ public function toArray($flag)
+ {
+ $this->toArray = $flag;
+ return $this;
+ }
}
\ No newline at end of file
|
Add toArray() hydration to simplify repository code.
|
doctrine_couchdb-odm
|
train
|
95ec92a92340ab083cdaa3b7f048c45e8e506e26
|
diff --git a/cmd/main.js b/cmd/main.js
index <HASH>..<HASH> 100755
--- a/cmd/main.js
+++ b/cmd/main.js
@@ -88,6 +88,7 @@ if( cli.build ) {
console.log("Testing...");
var workspace = new Workspace();
+ var env = cli['--environment'] || workspace.getEnvironment();
var initStream;
if (cli['--skip-build']) {
@@ -104,5 +105,12 @@ if( cli.build ) {
}).pipe(workspace.getBuildDest());
}
- initStream.pipe(pipelines.TestPipeline());
+ if (!(env in rc.data.environments)) {
+ console.error("Environment not defined: " + env);
+
+ } else {
+ initStream.pipe(pipelines.TestPipeline({
+ web3: rc.data.environments[env].ethereum || 'internal'
+ }));
+ }
}
diff --git a/lib/pipelines.js b/lib/pipelines.js
index <HASH>..<HASH> 100644
--- a/lib/pipelines.js
+++ b/lib/pipelines.js
@@ -23,7 +23,8 @@ var _fillOptionDefaults = function(opts) {
logger: console,
packageRoot: process.cwd(),
preprocessorVars: {},
- sourceRoot: process.cwd()
+ sourceRoot: process.cwd(),
+ web3: 'internal'
};
return _.assign(defaults, opts);
@@ -90,6 +91,10 @@ var BuildPipeline = function (opts) {
// Builds JS-specific output.
var JSBuildPipeline = function (opts) {
+
+ // Defaults
+ opts = _fillOptionDefaults(opts);
+
if (opts.environment && opts.environments
&& !(opts.environment in opts.environments))
{
@@ -108,9 +113,13 @@ var BuiltClassesPipeline = function (buildDir) {
// Takes built contracts and deploys and runs any test
// contracts among them, emitting the results to the CLI
// and passing them downstream as File objects.
-var TestPipeline = function () {
+var TestPipeline = function (opts) {
+
+ // Defaults
+ opts = _fillOptionDefaults(opts);
+
return Combine(
- streams.test(), streams.cli_out(),
+ streams.test(opts), streams.cli_out(),
streams.test_summarizer(), streams.cli_out());
};
diff --git a/lib/streams/test.js b/lib/streams/test.js
index <HASH>..<HASH> 100644
--- a/lib/streams/test.js
+++ b/lib/streams/test.js
@@ -16,7 +16,7 @@ var Web3Factory = require("../web3Factory");
// of running each `Test` contract. A special, non-standard `error` flag is set
// on File objects representing failed tests. This allows the `cli_out` stream
// to push the content of those files to `stderr` instead of `stdout`.
-module.exports = function () {
+module.exports = function (opts) {
return through.obj(function (file, enc, cb) {
var that = this;
var classes = JSON.parse(String(file.contents));
@@ -35,9 +35,24 @@ module.exports = function () {
return cb(err);
}
+ var web3;
+ if (opts.web3 == 'internal') {
+ web3 = Web3Factory.EVM();
+ } else {
+ try {
+ web3 = Web3Factory.JSONRPC(opts.web3);
+ } catch (e) {
+ this.push(new File({
+ path: "JSON-RPC Connection/Can't connect.stderr",
+ contents: new Buffer(String(e))
+ }));
+ cb();
+ return;
+ }
+ }
+
// **TODO**: Run all tests in chain forks at the same height.
var remaining = -1;
- var web3 = Web3Factory.EVM();
var logTranslator = new LogTranslator(contract.abi);
var vmtest = new VMTest(web3, contract, logTranslator);
var testCount = vmtest.testCount();
diff --git a/lib/web3Factory.js b/lib/web3Factory.js
index <HASH>..<HASH> 100644
--- a/lib/web3Factory.js
+++ b/lib/web3Factory.js
@@ -7,18 +7,41 @@ var Web3 = require('web3');
const DEFAULT_GAS = 900000000;
module.exports = {
- JSONRPC: function (connection_string, cb) {
- if (typeof(connection_string) == 'function' && typeof(cb) == 'undefined') {
- cb = connection_string;
- connection_string = "http://localhost:8544";
+ JSONRPC: function (opts, cb) {
+ var connection_string = "http://localhost:8545";
+
+ if (typeof(opts) == 'function' && typeof(cb) == 'undefined') {
+ cb = opts;
+ }
+
+ if (typeof(opts) == "object" && "web3" in opts) {
+ if ("connection_string" in opts.web3) {
+ connection_string = opts.web3.connection_string;
+ } else {
+ var host = opts.web3.host;
+ if (!/^https?:\/\//.test(host.toLowerCase())) {
+ host = "http://" + host;
+ }
+ connection_string = host + ":" + opts.web3.port;
+ }
}
+
+ if (typeof(opts) == "string") {
+ connection_string = opts;
+ }
+
cb = utils.optionalCallback(cb);
var web3 = new Web3(new Web3.providers.HttpProvider(connection_string));
- if( web3.eth.coinbase === undefined ) {
+ try {
+ if( web3.eth.coinbase === undefined ) {
+ return cb(new Error("Couldn't connect to test web3 provider,"
+ + " or it set no coinbase"));
+ }
+ } catch (e) {
return cb(new Error(
- "Couldn't connect to test web3 provider, or it set no coinbase"));
+ "Couldn't connect to Ethereum client at " + connection_string));
}
web3.eth.defaultAccount = web3.eth.accounts[0];
|
Use .dapplerc environment settings when running tests.
|
dapphub_dapple
|
train
|
c2ffbf4797c0a1a42014993d7b147e77ed387fb1
|
diff --git a/php-typography/class-settings.php b/php-typography/class-settings.php
index <HASH>..<HASH> 100644
--- a/php-typography/class-settings.php
+++ b/php-typography/class-settings.php
@@ -848,7 +848,7 @@ class Settings implements \ArrayAccess {
$this->regex['customDiacriticsDoubleQuoteValue'] = '/(?:=>\s*")([^"]+)(?:")/';
$this->regex['customDiacriticsSingleQuoteValue'] = "/(?:=>\s*')([^']+)(?:')/";
- $this->regex['controlCharacters'] = '/\p{C}/Su';
+ $this->regex['controlCharacters'] = '/\p{C}/Su'; // obsolete.
$this->regex['smartQuotesSingleQuotedNumbers'] = "/(?<=\W|\A)'([^\"]*\d+)'(?=\W|\Z)/u";
$this->regex['smartQuotesDoubleQuotedNumbers'] = '/(?<=\W|\A)"([^"]*\d+)"(?=\W|\Z)/u';
|
The controlCharacters regex is only used in by PHP_Typography proper
|
mundschenk-at_php-typography
|
train
|
c702091281369612419a370531e66c6db0a0ae40
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -5,6 +5,7 @@ process.env.ALLOW_COLORS = true;
var async = require('async'),
colors = require('colors/safe'),
+ Overload = require('irrelon-overload'),
padRight,
TB;
@@ -44,53 +45,55 @@ TB.timeRecord = {
TB.timeStepRecord = {};
TB.timeStep = {};
-TB.test = function test (name, codeFunc) {
- TB.tests[name] = function (callback) {
- var start,
- testEnclosure;
+TB.test = new Overload({
+ 'string, function': function test (name, codeFunc) {
+ TB.tests[name] = function (callback) {
+ var start,
+ testEnclosure;
- console.log(colors.green('Test "') + colors.green.bold(name) + colors.green('"'), colors.green('started'));
+ console.log(colors.green('Test "') + colors.green.bold(name) + colors.green('"'), colors.green('started'));
- start = new Date().getTime();
+ start = new Date().getTime();
- testEnclosure = function () {
- return codeFunc(function (err, data) {
- TB.timeRecord[name] = new Date().getTime() - start;
+ testEnclosure = function () {
+ return codeFunc(function (err, data) {
+ TB.timeRecord[name] = new Date().getTime() - start;
- if (!err) {
- console.log(colors.green('Test "') + colors.green.bold(name) + colors.green('"'), colors.green.bold('PASSED'), 'and took', colors.magenta.bold(TB.timeRecord[name] + ' ms'));
- } else {
- console.log(colors.red('Test "') + colors.red.bold(name) + colors.red('"'), colors.red.bold('FAILED!'), 'and took', colors.magenta.bold(TB.timeRecord[name] + ' ms'));
- }
+ if (!err) {
+ console.log(colors.green('Test "') + colors.green.bold(name) + colors.green('"'), colors.green.bold('PASSED'), 'and took', colors.magenta.bold(TB.timeRecord[name] + ' ms'));
+ } else {
+ console.log(colors.red('Test "') + colors.red.bold(name) + colors.red('"'), colors.red.bold('FAILED!'), 'and took', colors.magenta.bold(TB.timeRecord[name] + ' ms'));
+ }
- TB.summary.passed++;
- callback(err, data);
- });
- };
+ TB.summary.passed++;
+ callback(err, data);
+ });
+ };
- TB.summary.run++;
+ TB.summary.run++;
- if (TB.config.noCatch) {
- testEnclosure();
- } else {
- try {
+ if (TB.config.noCatch) {
testEnclosure();
- TB.testResult[name] = true;
- } catch (e) {
- TB.timeRecord[name] = new Date().getTime() - start;
- console.log(colors.red('Test "') + colors.red.bold(name) + colors.red('"'), colors.red.bold('FAILED!'), 'and took', colors.magenta.bold(TB.timeRecord[name] + ' ms'));
- console.log(colors.red.bold('Error:', e));
+ } else {
+ try {
+ testEnclosure();
+ TB.testResult[name] = true;
+ } catch (e) {
+ TB.timeRecord[name] = new Date().getTime() - start;
+ console.log(colors.red('Test "') + colors.red.bold(name) + colors.red('"'), colors.red.bold('FAILED!'), 'and took', colors.magenta.bold(TB.timeRecord[name] + ' ms'));
+ console.log(colors.red.bold('Error:', e));
- TB.testResult[name] = false;
- TB.summary.failed++;
+ TB.testResult[name] = false;
+ TB.summary.failed++;
- setImmediate(function () {
- callback(false);
- });
+ setImmediate(function () {
+ callback(false);
+ });
+ }
}
- }
- };
-};
+ };
+ }
+});
TB.time = function time (name) {
var totalTime = 0;
|
Used overload on test() method, can add more signatures in the future like number of tests to expect etc
|
Irrelon_testbear
|
train
|
6848ee8f4c7d4aacb2818c5e0e8948516056643a
|
diff --git a/src/sap.uxap/test/sap/uxap/qunit/js/ObjectPageAPICreation.qunit.js b/src/sap.uxap/test/sap/uxap/qunit/js/ObjectPageAPICreation.qunit.js
index <HASH>..<HASH> 100644
--- a/src/sap.uxap/test/sap/uxap/qunit/js/ObjectPageAPICreation.qunit.js
+++ b/src/sap.uxap/test/sap/uxap/qunit/js/ObjectPageAPICreation.qunit.js
@@ -324,8 +324,7 @@
oSelectedSection: this.oSecondSection,
sSelectedTitle: this.oSecondSection.getSubSections()[0].getTitle()
},
- done = assert.async(),
- bFirefox = sap.ui.Device.browser.firefox;
+ done = assert.async();
oObjectPage.setUseIconTabBar(false);
oObjectPage.addHeaderContent(oHeaderContent);
@@ -342,7 +341,7 @@
oObjectPage.attachEventOnce("onAfterRenderingDOMReady", function() {
setTimeout(function() {
sectionIsSelected(oObjectPage, assert, oExpected);
- assert.strictEqual(oObjectPage._$opWrapper.scrollTop(), bFirefox ? 0 : oObjectPage.iHeaderContentHeight, "top section is selected");
+ assert.strictEqual(oObjectPage._$opWrapper.scrollTop(), oObjectPage.iHeaderContentHeight, "top section is selected");
assert.strictEqual(oObjectPage._bStickyAnchorBar, true, "anchor bar is snapped");
assert.strictEqual(oObjectPage._bHeaderExpanded, false, "header is snapped");
|
[INTERNAL] uxap.ObjectPage: APICreation qunit fixed to work in Firefox
This reverts commit d8ee<I>f<I>cabc<I>a8c8a2a<I>f5f<I>.
Change-Id: If<I>e5df8a<I>c0e<I>ac9abb<I>eeede<I>f
BCP: <I>
|
SAP_openui5
|
train
|
535c16fcce7b0f19d9221aac795b3008b593bfe2
|
diff --git a/lsh.go b/lsh.go
index <HASH>..<HASH> 100644
--- a/lsh.go
+++ b/lsh.go
@@ -83,9 +83,6 @@ func optimalKL(numHash int, t float64) (optK, optL int, fp, fn float64) {
return
}
-// NewMinhashLSH is the default constructor uses 32 bit hash value
-var NewMinhashLSH = NewMinhashLSH32
-
// entry contains the hash key (from minhash signature) and the indexed key
type entry struct {
hashKey string
@@ -114,11 +111,11 @@ type MinhashLSH struct {
numIndexedKeys int
}
-func newMinhashLSH(threshold float64, numHash, hashValueSize int) *MinhashLSH {
+func newMinhashLSH(threshold float64, numHash, hashValueSize, initSize int) *MinhashLSH {
k, l, _, _ := optimalKL(numHash, threshold)
hashTables := make([]hashTable, l)
for i := range hashTables {
- hashTables[i] = make(hashTable, 0)
+ hashTables[i] = make(hashTable, 0, initSize)
}
return &MinhashLSH{
k: k,
@@ -130,25 +127,29 @@ func newMinhashLSH(threshold float64, numHash, hashValueSize int) *MinhashLSH {
}
}
-// NewMinhashLSH64 uses 64-bit hash values.
-func NewMinhashLSH64(numHash int, threshold float64) *MinhashLSH {
- return newMinhashLSH(threshold, numHash, 8)
+// NewMinhashLSH64 uses 64-bit hash values and pre-allocation of hash tables.
+func NewMinhashLSH64(numHash int, threshold float64, initSize int) *MinhashLSH {
+ return newMinhashLSH(threshold, numHash, 8, initSize)
}
-// NewMinhashLSH32 uses 32-bit hash values.
+// NewMinhashLSH32 uses 32-bit hash values and pre-allocation of hash tables.
// MinHash signatures with 64 bit hash values will have
// their hash values trimed.
-func NewMinhashLSH32(numHash int, threshold float64) *MinhashLSH {
- return newMinhashLSH(threshold, numHash, 4)
+func NewMinhashLSH32(numHash int, threshold float64, initSize int) *MinhashLSH {
+ return newMinhashLSH(threshold, numHash, 4, initSize)
}
-// NewMinhashLSH16 uses 16-bit hash values.
+// NewMinhashLSH16 uses 16-bit hash values and pre-allocation of hash tables.
// MinHash signatures with 64 or 32 bit hash values will have
// their hash values trimed.
-func NewMinhashLSH16(numHash int, threshold float64) *MinhashLSH {
- return newMinhashLSH(threshold, numHash, 2)
+func NewMinhashLSH16(numHash int, threshold float64, initSize int) *MinhashLSH {
+ return newMinhashLSH(threshold, numHash, 2, initSize)
}
+// NewMinhashLSH is the default constructor uses 32 bit hash value
+// with pre-allocation of hash tables.
+var NewMinhashLSH = NewMinhashLSH32
+
// Params returns the LSH parameters k and l
func (f *MinhashLSH) Params() (k, l int) {
return f.k, f.l
diff --git a/lsh_benchmark_test.go b/lsh_benchmark_test.go
index <HASH>..<HASH> 100644
--- a/lsh_benchmark_test.go
+++ b/lsh_benchmark_test.go
@@ -11,7 +11,7 @@ func Benchmark_Insert10000(b *testing.B) {
sigs[i] = randomSignature(64, int64(i))
}
b.ResetTimer()
- f := NewMinhashLSH16(64, 0.5)
+ f := NewMinhashLSH16(64, 0.5, 10000)
for i := range sigs {
f.Add(strconv.Itoa(i), sigs[i])
}
diff --git a/lsh_test.go b/lsh_test.go
index <HASH>..<HASH> 100644
--- a/lsh_test.go
+++ b/lsh_test.go
@@ -33,7 +33,7 @@ func Test_HashKeyFunc64(t *testing.T) {
}
func Test_MinhashLSH(t *testing.T) {
- f := NewMinhashLSH16(256, 0.6)
+ f := NewMinhashLSH16(256, 0.6, 3)
// sig1 is different from sig2 and sig3
// sig2 and sig3 are identical
sig1 := randomSignature(256, 1)
@@ -69,7 +69,7 @@ func Test_MinhashLSH(t *testing.T) {
}
func Test_MinhashLSH2(t *testing.T) {
- minhashLsh := NewMinhashLSH16(256, 0.5)
+ minhashLsh := NewMinhashLSH16(256, 0.5, 1)
seed := int64(1)
numHash := 256
mh := NewMinhash(seed, numHash)
|
memory optimization: preallocation of hash tables
|
ekzhu_minhash-lsh
|
train
|
c0f14aad6f93a57e0cbca587c4e8fccfb7eb3d81
|
diff --git a/optaplanner-core/src/main/java/org/optaplanner/core/api/score/AbstractScore.java b/optaplanner-core/src/main/java/org/optaplanner/core/api/score/AbstractScore.java
index <HASH>..<HASH> 100644
--- a/optaplanner-core/src/main/java/org/optaplanner/core/api/score/AbstractScore.java
+++ b/optaplanner-core/src/main/java/org/optaplanner/core/api/score/AbstractScore.java
@@ -20,7 +20,6 @@ import java.io.Serializable;
import java.math.BigDecimal;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
-import org.optaplanner.core.impl.score.director.ScoreDirector;
/**
* Abstract superclass for {@link Score}.
@@ -182,8 +181,8 @@ public abstract class AbstractScore<S extends Score> implements Score<S>, Serial
if (initScore != 0) {
throw new IllegalStateException("The score (" + this + ")'s initScore (" + initScore
+ ") should be 0.\n"
- + "Maybe the score calculator is calculating the initScore too, although it's the "
- + ScoreDirector.class.getSimpleName() + "'s responsibility.");
+ + "Maybe the score calculator is calculating the initScore too,"
+ + " although it's the score director's responsibility.");
}
}
|
Avoid Scoredirector dependency in AbstractScore to make GWT happy in optaplanner-wb
|
kiegroup_optaplanner
|
train
|
790977b5b95170549826059baece167a881ab4e6
|
diff --git a/runcronjobs.php b/runcronjobs.php
index <HASH>..<HASH> 100755
--- a/runcronjobs.php
+++ b/runcronjobs.php
@@ -305,12 +305,14 @@ if ( $listCronjobs )
$hasScripts = false;
if ( $block === 'CronjobSettings' )
{
- $cli->output( "\n Standard scripts:" );
+ $cli->output( $cli->endLineString() );
+ $cli->output( "Standard scripts:" );
$hasScripts = true;
}
if ( strpos( $block, 'CronjobPart-' ) !== false )
{
- $cli->output( "\n {$block}:" );
+ $cli->output( $cli->endLineString() );
+ $cli->output( "{$block}:" );
$hasScripts = true;
}
if ( $hasScripts )
@@ -324,11 +326,11 @@ if ( $listCronjobs )
if ( file_exists( $filePath ) )
{
$fileExists = true;
- $cli->output( "\t {$filePath}" );
+ $cli->output( "{$cli->goToColumn( 4 )} {$filePath}" );
}
}
if ( !$fileExists )
- $cli->output( "\t Error: No {$fileName} file in any of configured directories!" );
+ $cli->output( "{$cli->goToColumn( 4 )} Error: No {$fileName} file in any of configured directories!" );
}
}
}
|
Implemented #<I>: use endLineString() and goToColumn() in place of '\n' and '\t'
|
ezsystems_ezpublish-legacy
|
train
|
31362bc3318dcf893a944d010f48858b6607e02a
|
diff --git a/sync/task/broker/broker.go b/sync/task/broker/broker.go
index <HASH>..<HASH> 100644
--- a/sync/task/broker/broker.go
+++ b/sync/task/broker/broker.go
@@ -99,14 +99,22 @@ func (t *Task) Run(c task.Command) error {
// subscribe for the pool size
for i := 0; i < t.Options.Pool; i++ {
- // subscribe to work
- subWork, err := t.Broker.Subscribe(topic, workFn, broker.Queue(fmt.Sprintf("work.%d", i)))
+ err := func() error {
+ // subscribe to work
+ subWork, err := t.Broker.Subscribe(topic, workFn, broker.Queue(fmt.Sprintf("work.%d", i)))
+ if err != nil {
+ return err
+ }
+
+ // unsubscribe on completion
+ defer subWork.Unsubscribe()
+
+ return nil
+ }()
+
if err != nil {
return err
}
-
- // unsubscribe on completion
- defer subWork.Unsubscribe()
}
// subscribe to all status messages
|
prevent resource leak (#<I>)
|
micro_go-micro
|
train
|
290e51877cdd61c3e34bb69d669e4da5b7bd1ae0
|
diff --git a/test/RedisCommandsTest.php b/test/RedisCommandsTest.php
index <HASH>..<HASH> 100644
--- a/test/RedisCommandsTest.php
+++ b/test/RedisCommandsTest.php
@@ -1504,6 +1504,21 @@ class RedisCommandTestSuite extends PHPUnit_Framework_TestCase {
$this->assertEquals(array('bar', 'piyo'), $this->redis->hmget('metavars', 'foo', 'hoge'));
}
+ function testHashIncrementBy() {
+ // test subsequent increment commands
+ $this->assertEquals(10, $this->redis->hincrby('hash', 'counter', 10));
+ $this->assertEquals(20, $this->redis->hincrby('hash', 'counter', 10));
+ $this->assertEquals(0, $this->redis->hincrby('hash', 'counter', -20));
+
+ $this->assertTrue($this->redis->hset('hash', 'field', 'stringvalue'));
+ $this->assertEquals(10, $this->redis->hincrby('hash', 'field', 10));
+
+ RC::testForServerException($this, RC::EXCEPTION_WRONG_TYPE, function($test) {
+ $test->redis->set('foo', 'bar');
+ $test->redis->hincrby('foo', 'bar', 1);
+ });
+ }
+
/* multiple databases handling commands */
function testSelectDatabase() {
|
Test suite: added HINCRBY.
|
nrk_predis
|
train
|
33928ccdfff978aefe80af65846c6070030adb91
|
diff --git a/app/scripts/ViewportTracker2D.js b/app/scripts/ViewportTracker2D.js
index <HASH>..<HASH> 100644
--- a/app/scripts/ViewportTracker2D.js
+++ b/app/scripts/ViewportTracker2D.js
@@ -92,7 +92,9 @@ export class ViewportTracker2D extends SVGTrack {
// set the fill and stroke colors
this.gBrush.selectAll('.selection')
.attr('fill', this.options.projectionFillColor)
- .attr('stroke', this.options.projectionStrokeColor);
+ .attr('stroke', this.options.projectionStrokeColor)
+ .attr('fill-opacity', this.options.projectionFillOpacity)
+ .attr('stroke-opacity', this.options.projectionStrokeOpacity);
}
draw() {
diff --git a/app/scripts/config.js b/app/scripts/config.js
index <HASH>..<HASH> 100644
--- a/app/scripts/config.js
+++ b/app/scripts/config.js
@@ -302,7 +302,9 @@ export const tracksInfo = [
availableOptions: ['projectionFillColor', 'projectionStrokeColor'],
defaultOptions: {
projectionFillColor: "#777",
- projectionStrokeColor: "#777"
+ projectionStrokeColor: "#777",
+ projectionFillOpacity: 0.3,
+ projectionStrokeOpacity: 0.3
}
},
{
|
Added fill and stroke opacity options
|
higlass_higlass
|
train
|
aa788b3c42443b345f811aa9d34da6a119b206d9
|
diff --git a/lib/classes/user.php b/lib/classes/user.php
index <HASH>..<HASH> 100644
--- a/lib/classes/user.php
+++ b/lib/classes/user.php
@@ -332,7 +332,7 @@ class core_user {
$fields['country'] = array('type' => PARAM_ALPHA, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->country,
'choices' => array_merge(array('' => ''), get_string_manager()->get_list_of_countries(true, true)));
$fields['lang'] = array('type' => PARAM_LANG, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->lang,
- 'choices' => array_merge(array('' => ''), get_string_manager()->get_list_of_languages()));
+ 'choices' => array_merge(array('' => ''), get_string_manager()->get_list_of_translations(false)));
$fields['calendartype'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->calendartype,
'choices' => array_merge(array('' => ''), \core_calendar\type_factory::get_list_of_calendar_types()));
$fields['theme'] = array('type' => PARAM_THEME, 'null' => NULL_NOT_ALLOWED,
@@ -409,8 +409,7 @@ class core_user {
}
// Check that the value is part of a list of allowed values.
if (!empty(self::$propertiescache[$property]['choices']) &&
- !isset(self::$propertiescache[$property]['choices'][$data->$property]) &&
- !array_key_exists($data->$property, self::$propertiescache[$property]['choices'])) {
+ !isset(self::$propertiescache[$property]['choices'][$value])) {
throw new invalid_parameter_exception($value);
}
} catch (invalid_parameter_exception $e) {
@@ -445,17 +444,7 @@ class core_user {
foreach ($user as $field => $value) {
// Get the property parameter type and do the cleaning.
try {
- if (isset(self::$propertiescache[$field]['choices'])) {
- if (!array_key_exists($value, self::$propertiescache[$field]['choices'])) {
- if (isset(self::$propertiescache[$field]['default'])) {
- $user->$field = self::$propertiescache[$field]['default'];
- } else {
- $user->$field = '';
- }
- }
- } else {
- $user->$field = core_user::clean_field($value, $field);
- }
+ $user->$field = core_user::clean_field($value, $field);
} catch (coding_exception $e) {
debugging("The property '$field' could not be cleaned.", DEBUG_DEVELOPER);
}
@@ -486,6 +475,8 @@ class core_user {
} else {
$data = '';
}
+ } else {
+ return $data;
}
} else {
$data = clean_param($data, $type);
|
MDL-<I> core_user: fix wrong lang check
|
moodle_moodle
|
train
|
25339e3fc3c27b268b930823bf7652dea78eb0d9
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -13,16 +13,12 @@ class ServerlessPlugin {
const filename = path.resolve(__dirname, 'layers.json');
const layers = JSON.parse(fs.readFileSync(filename));
- // Read the region from the `--region` option, or fallback on the `serverless.yml` config
- const region = (typeof options.region !== 'undefined')
- ? options.region
- : serverless.service.provider.region;
-
// Override the variable resolver to declare our own variables
const delegate = serverless.variables
.getValueFromSource.bind(serverless.variables);
serverless.variables.getValueFromSource = (variableString) => {
if (variableString.startsWith('bref:layer.')) {
+ const region = serverless.getProvider('aws').getRegion();
const layerName = variableString.substr('bref:layer.'.length);
if (! (layerName in layers)) {
throw `Unknown Bref layer named "${layerName}"`;
@@ -40,3 +36,4 @@ class ServerlessPlugin {
}
module.exports = ServerlessPlugin;
+
|
Allow region to be a variable
Before, the region would be read from incoming options, sometimes
resulting in an unresolved variable.
This change uses the `getRegion()` method of the AWS provider to make
sure the region is resolved, before using it in layer resolution.
Fixes #<I>
|
mnapoli_bref
|
train
|
d687a7b9a007772df0b4b02a95e041f9f910b0e5
|
diff --git a/firenado/conf/__init__.py b/firenado/conf/__init__.py
index <HASH>..<HASH> 100644
--- a/firenado/conf/__init__.py
+++ b/firenado/conf/__init__.py
@@ -227,12 +227,12 @@ def process_app_config_section(app_config):
if 'port' in app_config:
app['port'] = app_config['port']
if 'type' in app_config:
- app['types'] = app_config['type']
+ app['type'] = app_config['type']
if 'types' in app_config:
for app_type in app_config['types']:
app_type['launcher'] = get_config_from_package(
app_type['launcher'])
- app['types'][type['name']] = app_type
+ app['types'][app_type['name']] = app_type
def process_components_config_section(components_config):
diff --git a/firenado/core/management/tasks.py b/firenado/core/management/tasks.py
index <HASH>..<HASH> 100644
--- a/firenado/core/management/tasks.py
+++ b/firenado/core/management/tasks.py
@@ -102,10 +102,11 @@ class InstallProjectTask(ManagementTask):
class RunApplicationTask(ManagementTask):
- """Runs a Firenado Tornado Application based
+ """ Runs a Firenado Tornado Application based
on the it's project configuration
"""
def run(self, namespace):
+ #TODO throw a custom error when type is not found
app_type = firenado.conf.app['types'][firenado.conf.app['type']]
launcher = firenado.conf.get_class_from_config(app_type['launcher'])()
launcher.launch()
|
Fixed reading of app type configuration.
Fixes: #<I>
|
candango_firenado
|
train
|
f1e033c32871e274867009a4b74d5fa94930ad9c
|
diff --git a/law/config.py b/law/config.py
index <HASH>..<HASH> 100644
--- a/law/config.py
+++ b/law/config.py
@@ -89,11 +89,15 @@ class Config(ConfigParser):
# lsf, glite, arc) by prefixing the option, e.g. "htcondor_job_file_dir"
},
"bash_sandbox": {
+ "uid": None,
+ "gid": None,
"stagein_dir": "stagein",
"stageout_dir": "stageout",
},
"bash_sandbox_env": {},
"docker_sandbox": {
+ "uid": None,
+ "gid": None,
"forward_dir": "/law_forward",
"python_dir": "py",
"bin_dir": "bin",
@@ -103,6 +107,8 @@ class Config(ConfigParser):
"docker_sandbox_env": {},
"docker_sandbox_volumes": {},
"singularity_sandbox": {
+ "uid": None,
+ "gid": None,
"forward_dir": "/law_forward",
"python_dir": "py",
"bin_dir": "bin",
diff --git a/law/sandbox/base.py b/law/sandbox/base.py
index <HASH>..<HASH> 100644
--- a/law/sandbox/base.py
+++ b/law/sandbox/base.py
@@ -440,7 +440,18 @@ class SandboxTask(Task):
return None
def sandbox_user(self):
- return (os.getuid(), os.getgid())
+ uid, gid = os.getuid(), os.getgid()
+
+ # check if there is a config section that defines the user and group ids
+ if self.sandbox_inst:
+ cfg = Config.instance()
+ section = self.sandbox_inst.get_config_section()
+ if not cfg.is_missing_or_none(section, "uid"):
+ uid = cfg.get_expanded(section, "uid", type=int)
+ if not cfg.is_missing_or_none(section, "gid"):
+ gid = cfg.get_expanded(section, "gid", type=int)
+
+ return uid, gid
def sandbox_stagein_mask(self):
# disable stage-in by default
|
Make uid and gid for sandboxing configurable via config.
|
riga_law
|
train
|
8f0fbd2fe81b4af1a394a0109820362df011c0ae
|
diff --git a/commands.go b/commands.go
index <HASH>..<HASH> 100644
--- a/commands.go
+++ b/commands.go
@@ -179,6 +179,7 @@ type Cmdable interface {
LInsertAfter(ctx context.Context, key string, pivot, value interface{}) *IntCmd
LLen(ctx context.Context, key string) *IntCmd
LPop(ctx context.Context, key string) *StringCmd
+ LPopCount(ctx context.Context, key string, count int) *StringSliceCmd
LPos(ctx context.Context, key string, value string, args LPosArgs) *IntCmd
LPosCount(ctx context.Context, key string, value string, count int64, args LPosArgs) *IntSliceCmd
LPush(ctx context.Context, key string, values ...interface{}) *IntCmd
@@ -1314,6 +1315,12 @@ func (c cmdable) LPop(ctx context.Context, key string) *StringCmd {
return cmd
}
+func (c cmdable) LPopCount(ctx context.Context, key string, count int) *StringSliceCmd {
+ cmd := NewStringSliceCmd(ctx, "lpop", key, count)
+ _ = c(ctx, cmd)
+ return cmd
+}
+
type LPosArgs struct {
Rank, MaxLen int64
}
diff --git a/commands_test.go b/commands_test.go
index <HASH>..<HASH> 100644
--- a/commands_test.go
+++ b/commands_test.go
@@ -2050,6 +2050,25 @@ var _ = Describe("Commands", func() {
Expect(lRange.Val()).To(Equal([]string{"two", "three"}))
})
+ It("should LPopCount", func() {
+ rPush := client.RPush(ctx, "list", "one")
+ Expect(rPush.Err()).NotTo(HaveOccurred())
+ rPush = client.RPush(ctx, "list", "two")
+ Expect(rPush.Err()).NotTo(HaveOccurred())
+ rPush = client.RPush(ctx, "list", "three")
+ Expect(rPush.Err()).NotTo(HaveOccurred())
+ rPush = client.RPush(ctx, "list", "four")
+ Expect(rPush.Err()).NotTo(HaveOccurred())
+
+ lPopCount := client.LPopCount(ctx, "list", 2)
+ Expect(lPopCount.Err()).NotTo(HaveOccurred())
+ Expect(lPopCount.Val()).To(Equal([]string{"one", "two"}))
+
+ lRange := client.LRange(ctx, "list", 0, -1)
+ Expect(lRange.Err()).NotTo(HaveOccurred())
+ Expect(lRange.Val()).To(Equal([]string{"three", "four"}))
+ })
+
It("should LPos", func() {
rPush := client.RPush(ctx, "list", "a")
Expect(rPush.Err()).NotTo(HaveOccurred())
|
fix #<I> (#<I>)
|
go-redis_redis
|
train
|
f6add66561c981c44cb18417d95558262240df9b
|
diff --git a/examples/platformer2/js/entities/HUD.js b/examples/platformer2/js/entities/HUD.js
index <HASH>..<HASH> 100644
--- a/examples/platformer2/js/entities/HUD.js
+++ b/examples/platformer2/js/entities/HUD.js
@@ -28,11 +28,13 @@ game.HUD.Container = me.Container.extend({
// add our child score object at position
this.addChild(new game.HUD.ScoreItem(-10, -40));
- // add our fullscreen control object
- this.addChild(new game.HUD.FSControl(10, 10));
-
// add our audio control object
- this.addChild(new game.HUD.AudioControl(10 + 48 + 10, 10));
+ this.addChild(new game.HUD.AudioControl(10, 10));
+
+ if (!me.device.isMobile) {
+ // add our fullscreen control object
+ this.addChild(new game.HUD.FSControl(10 + 48 + 10, 10));
+ }
}
});
|
[#<I>] do not add the fullscreen control on mobile devices
btw, is the `me.device.isMobile` still up-to-date in terms of UA
matching ?
|
melonjs_melonJS
|
train
|
a3aa47c39d1991dcdbf0f41313e7ffd66ae9260e
|
diff --git a/lib/ApiCLI.php b/lib/ApiCLI.php
index <HASH>..<HASH> 100644
--- a/lib/ApiCLI.php
+++ b/lib/ApiCLI.php
@@ -99,8 +99,10 @@ class ApiCLI extends AbstractView {
}
if(file_exists($file)){
include_once $file;
+ // some tricky thing to make config be read in some cases it could not in simple way
+ if(!$config)global $config;
}
-
+
$this->config = array_merge($this->config,$config);
if(isset($this->config['table_prefix'])){
if(!defined('DTP'))define('DTP',$this->config['table_prefix']);
|
Upgrades to the way config being read
|
atk4_atk4
|
train
|
3b108d333dfaebe967c4871b61116660073252a1
|
diff --git a/autopep8.py b/autopep8.py
index <HASH>..<HASH> 100755
--- a/autopep8.py
+++ b/autopep8.py
@@ -1373,7 +1373,7 @@ def _get_as_string(items):
elif item.is_colon:
string += ': '
else:
- item_string = repr(item)
+ item_string = unicode(item)
if (
string and
(last_was_keyword or
@@ -1452,13 +1452,14 @@ class ReflowedLines(object):
):
return
- prev_text = unicode(prev_item)
+ prev_text = unicode(prev_item)[-1]
if (
((prev_item.is_keyword or prev_item.is_string or
prev_item.is_name or prev_item.is_number) and
- curr_text not in '.,}])') or
- (prev_text != '.' and
- (prev_text in ':,}])' or (equal and prev_text == '=')))
+ curr_text[0] not in '([{.,:}])') or
+ (prev_text != '.' and curr_text[0] != ':' and
+ ((prev_text in '}])' and curr_text[0] not in '.,}])') or
+ prev_text in ':,' or (equal and prev_text == '=')))
):
self._lines.append(self._Space())
@@ -1606,7 +1607,7 @@ class Container_(object):
# Prefer to keep empty containers together instead of
# separating them.
unicode(item) == self.open_bracket and
- (not next_elem or repr(next_elem) != self.close_bracket)
+ (not next_elem or unicode(next_elem) != self.close_bracket)
):
reflowed_lines.add_line_break()
reflowed_lines.add_indent(continued_indent)
diff --git a/test/test_autopep8.py b/test/test_autopep8.py
index <HASH>..<HASH> 100755
--- a/test/test_autopep8.py
+++ b/test/test_autopep8.py
@@ -3091,8 +3091,8 @@ bork(111, 111, 111, 111, 222, 222, 222, { 'foo': 222, 'qux': 222 }, ((['hello',
bork(
111, 111, 111, 111, 222, 222, 222, {'foo': 222, 'qux': 222}, (([
'hello', 'world'], ['yo', 'stella', "how's", 'it'], ['going']), {
- str(i): i for i in range(10)}, {'bork': ((x, x ** x) for x in
- range(10))}), 222, 222, 222, 222, 333, 333, 333, 333)
+ str(i): i for i in range(10)}, {'bork': ((x, x ** x) for x in range(
+ 10))}), 222, 222, 222, 222, 333, 333, 333, 333)
"""
with autopep8_context(line, options=['--experimental']) as result:
|
Fix more spacing problems. Also use unicode instead of repr.
|
hhatto_autopep8
|
train
|
d6bf93fdf177280b1bd7e8b94d0aa3cec937ce8d
|
diff --git a/Controller/FavouriteController.php b/Controller/FavouriteController.php
index <HASH>..<HASH> 100644
--- a/Controller/FavouriteController.php
+++ b/Controller/FavouriteController.php
@@ -10,7 +10,6 @@ use Symfony\Component\HttpFoundation\Response;
class FavouriteController extends Controller
{
-
/**
* @EXT\Route(
* "/{isFavourite}/node/{id}",
|
[FavouriteBundle] Suppression of the blank line
|
claroline_Distribution
|
train
|
ad716a203f2204ee3e46b44cb8a7ae75dfe46e6b
|
diff --git a/config/mediable.php b/config/mediable.php
index <HASH>..<HASH> 100644
--- a/config/mediable.php
+++ b/config/mediable.php
@@ -171,6 +171,20 @@ return [
'xlsx',
]
],
+ Plank\Mediable\Media::TYPE_PRESENTATION => [
+ 'mime_types' =>
+ [
+ 'application/vnd.ms-powerpoint',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'
+ ],
+ 'extensions' =>
+ [
+ 'ppt',
+ 'pptx',
+ 'ppsx',
+ ]
+ ],
],
/*
diff --git a/src/Media.php b/src/Media.php
index <HASH>..<HASH> 100644
--- a/src/Media.php
+++ b/src/Media.php
@@ -24,6 +24,7 @@ class Media extends Model
const TYPE_ARCHIVE = 'archive';
const TYPE_DOCUMENT = 'document';
const TYPE_SPREADSHEET = 'spreadsheet';
+ const TYPE_PRESENTATION = 'presentation';
const TYPE_OTHER = 'other';
const TYPE_ALL = 'all';
|
Adding Presentation media type (#<I>)
|
plank_laravel-mediable
|
train
|
0464094c18cf9a8aea6000cde36fb8d027fc33fd
|
diff --git a/src/Versatile/Query/Builder.php b/src/Versatile/Query/Builder.php
index <HASH>..<HASH> 100644
--- a/src/Versatile/Query/Builder.php
+++ b/src/Versatile/Query/Builder.php
@@ -401,7 +401,21 @@ class Builder
return;
}
- $modelTable = $model->getTable();
+ $modelTable = '';
+
+ // If the table has already an alias
+ if (str_contains($name, '.')) {
+ $path = explode('.', $name);
+ array_pop($path);
+ $parentPath = implode('.', $path);
+ if (isset($this->joinAliases[$parentPath])) {
+ $modelTable = $this->joinAliases[$parentPath];
+ }
+ }
+
+ if (!$modelTable) {
+ $modelTable = $belongsTo->getParent()->getTable();
+ }
$related = $belongsTo->getRelated();
$relatedTable = $related->getTable();
$foreignKey = $belongsTo->getForeignKey();
@@ -414,7 +428,7 @@ class Builder
$query->{$joinMethod}("$relatedTable AS $alias", "$modelTable.$foreignKey",'=',"$alias.$otherKey");
$query->distinct();
- $this->addQueryColumn($foreignKey);
+ $this->addQueryColumn("$modelTable.$foreignKey");
$this->joinClasses[$name] = $belongsTo->getRelated();
$this->joinTable[$name] = $relatedTable;
|
Fixed error in nested BelongsToMany
|
mtils_versatile
|
train
|
fb8ce1f5e7bd5dfa05ef72c2fe24c546c45e7283
|
diff --git a/rtllib/multipliers.py b/rtllib/multipliers.py
index <HASH>..<HASH> 100644
--- a/rtllib/multipliers.py
+++ b/rtllib/multipliers.py
@@ -9,7 +9,6 @@ def main():
# test_simple_mult()
# test_wallace_tree()
# test_wallace_timing()
- # test_conditional()
def simple_mult(A, B, start, done):
@@ -46,43 +45,6 @@ def simple_mult(A, B, start, done):
return accum
-def conditional_broken(A, B, C):
-
- # not_zero_vector = Const(2**2, bitwidth=3)
- all_ones = Const(1, bitwidth=3)
- # zero_vector = WireVector(bitwidth=3)
- # output = WireVector(bitwidth=3)
-
- zero_vector = WireVector(bitwidth=3)
- zero_vector <<= 5
-
- zero_vector.name = "it_is_four"
-
- # with ConditionalUpdate(zero_vector[0] == 1):
- zero_vector <<= mux(zero_vector[0] == 1, zero_vector, zero_vector + all_ones)
-
- zero_vector.name = "what is it"
-
- return zero_vector
-
-
-def test_conditional():
- input_length = 4
- a, b, n = [Input(input_length, name) for name in 'ignore ingore2 ignore3'.split()]
-
- modded = Output(input_length*2, "ignore4")
-
- modded <<= conditional_broken(a, b, n)
-
- aval, bval, nval = 1, 2, 3
-
- sim_trace = SimulationTrace()
- sim = Simulation(tracer=sim_trace)
- sim.step({a: aval, b: bval, n: nval})
-
- sim_trace.render_trace()
-
-
def wallace_tree(A, B, adder_func=adders.kogge_stone):
"""Build an unclocked multiplier for inputs A and B using a Wallace Tree.
Delay is order logN, while area is order N^2. It's very important to note that
|
deleted conditional testing from multipliers, it was dysfunctional
|
UCSBarchlab_PyRTL
|
train
|
19869f7c923ad59cfb0771345352b684685e06a9
|
diff --git a/View/Helper/TaskHelper.php b/View/Helper/TaskHelper.php
index <HASH>..<HASH> 100644
--- a/View/Helper/TaskHelper.php
+++ b/View/Helper/TaskHelper.php
@@ -84,7 +84,13 @@ class TaskHelper extends AppHelper {
* @return string
*/
public function id(array $task) {
- return $this->_isCli ? $task['id'] : $this->Html->link($task['id'], array('action' => 'view', $task['id'], 'full_base' => true));
+ return $this->_isCli ? $task['id'] : $this->Html->link($task['id'], array(
+ 'action' => 'view',
+ 'controller' => 'task',
+ 'plugin' => 'task',
+ $task['id'],
+ 'full_base' => true
+ ));
}
/**
|
full links in TaskHelper::id #<I>
|
imsamurai_cakephp-task-plugin
|
train
|
a4c242d5b75f52c465929f11233dc414ce119e1f
|
diff --git a/bounded_context/spec/spec_helper.rb b/bounded_context/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/bounded_context/spec/spec_helper.rb
+++ b/bounded_context/spec/spec_helper.rb
@@ -4,7 +4,7 @@ require 'support/rspec_defaults'
require 'rails'
ENV['RAILS_VERSION'] ||= Rails::VERSION::STRING
-DUMMY_APP_NAME = "dummy_#{ENV['RAILS_VERSION'].gsub(".", "_")}"
+DUMMY_APP_NAME = "dummy_#{ENV['RAILS_VERSION'].split('.').take(2).join('_')}"
TMP_ROOT = File.join(__dir__, 'tmp')
DUMMY_ROOT = File.join(__dir__, DUMMY_APP_NAME)
raise "App #{DUMMY_APP_NAME} doesn't exist" unless File.exists?(DUMMY_ROOT)
|
Change the way to determine dummy apps folder
|
RailsEventStore_rails_event_store
|
train
|
ef95e535d5ef58c19cf088dfe7415011272ea22f
|
diff --git a/lib/fluent/plugin/out_exec_filter.rb b/lib/fluent/plugin/out_exec_filter.rb
index <HASH>..<HASH> 100644
--- a/lib/fluent/plugin/out_exec_filter.rb
+++ b/lib/fluent/plugin/out_exec_filter.rb
@@ -234,23 +234,17 @@ class ExecFilterOutput < BufferedOutput
begin
Process.kill(:TERM, @pid)
rescue Errno::ESRCH
- if $!.message == 'No such process'
- # child process killed by signal chained from fluentd process
- else
- raise
- end
+ # Errno::ESRCH 'No such process', ignore
+ # child process killed by signal chained from fluentd process
end
if @thread.join(60) # TODO wait time
+ # @thread successfully shutdown
return
end
begin
Process.kill(:KILL, @pid)
rescue Errno::ESRCH
- if $!.message == 'No such process'
- # ignore if successfully killed by :TERM
- else
- raise
- end
+ # ignore if successfully killed by :TERM
end
@thread.join
end
|
shrink buggy error message check (on non-LANG=C environment)
|
fluent_fluentd
|
train
|
c71c181693822d56f8ac4227e1113732a61d055a
|
diff --git a/concrete/src/Foundation/Queue/Mutex/MutexGeneratorFactory.php b/concrete/src/Foundation/Queue/Mutex/MutexGeneratorFactory.php
index <HASH>..<HASH> 100644
--- a/concrete/src/Foundation/Queue/Mutex/MutexGeneratorFactory.php
+++ b/concrete/src/Foundation/Queue/Mutex/MutexGeneratorFactory.php
@@ -22,7 +22,7 @@ class MutexGeneratorFactory
$config = $this->app->make('config');
$mutexes = $config->get('app.mutex');
foreach($config->get('app.commands') as $entry) {
- if ($entry[2]) {
+ if ($entry[2] ?? null) {
$mutexes[$keyGenerator->getMutexKey($entry[2])] = true;
}
}
diff --git a/concrete/src/Foundation/Queue/QueueService.php b/concrete/src/Foundation/Queue/QueueService.php
index <HASH>..<HASH> 100644
--- a/concrete/src/Foundation/Queue/QueueService.php
+++ b/concrete/src/Foundation/Queue/QueueService.php
@@ -80,7 +80,7 @@ class QueueService
if (!$queue) {
$queue = [];
foreach($this->config->get('app.commands') as $entry) {
- if ($entry[2]) {
+ if ($entry[2] ?? null) {
$queue[] = $entry[2];
}
}
|
Avoid accessing undefined command bus key
|
concrete5_concrete5
|
train
|
e7fce25f637a22848e63e210f32db69d1340379c
|
diff --git a/integration-faces/src/test/java/org/ocpsoft/rewrite/faces/navigate/NavigateTest.java b/integration-faces/src/test/java/org/ocpsoft/rewrite/faces/navigate/NavigateTest.java
index <HASH>..<HASH> 100644
--- a/integration-faces/src/test/java/org/ocpsoft/rewrite/faces/navigate/NavigateTest.java
+++ b/integration-faces/src/test/java/org/ocpsoft/rewrite/faces/navigate/NavigateTest.java
@@ -17,6 +17,7 @@ package org.ocpsoft.rewrite.faces.navigate;
import static org.junit.Assert.assertEquals;
+import org.junit.Ignore;
import org.junit.Test;
public class NavigateTest
@@ -87,6 +88,8 @@ public class NavigateTest
}
@Test
+ // Navigate class doesn't do encoding any more
+ @Ignore
public void testParameterEncoding()
{
assertEquals("/faces/some-view.xhtml?faces-redirect=true¶m=a+b+%C3%A4",
|
Ignore old encoding test for Navigate class
|
ocpsoft_rewrite
|
train
|
232e94ba9292f9b77b675bfa9934fe391aba1bb7
|
diff --git a/classes/Kohana/Jam/Model.php b/classes/Kohana/Jam/Model.php
index <HASH>..<HASH> 100755
--- a/classes/Kohana/Jam/Model.php
+++ b/classes/Kohana/Jam/Model.php
@@ -417,8 +417,12 @@ abstract class Kohana_Jam_Model extends Jam_Validated {
if ($association instanceof Jam_Association_Collection)
throw new Kohana_Exception(':association_name association must not be a collection on model :model', array(':association_name' => $association_name, ':model' => $this->meta()->model()));
+
+ $item = $association->build($this, $attributes);
+
+ $this->set($association_name, $item);
- return $this->_changed[$association_name] = $association->build($this, $attributes);
+ return $item;
}
/**
|
Fix build to set the item on the model
|
OpenBuildings_jam
|
train
|
a733658094f0ff8b447c4d05f699e8f662e6b384
|
diff --git a/main.go b/main.go
index <HASH>..<HASH> 100644
--- a/main.go
+++ b/main.go
@@ -201,6 +201,10 @@ func debug(format string, args ...interface{}) {
}
}
+func warning(format string, args ...interface{}) {
+ fmt.Fprintf(os.Stderr, "WARNING: "+format+"\n", args...)
+}
+
func formatLinters() string {
w := bytes.NewBuffer(nil)
for name := range lintersFlag {
@@ -520,7 +524,7 @@ func executeLinter(state *linterState) {
case <-done:
case <-state.deadline:
- debug("warning: deadline exceeded by linter %s", state.name)
+ warning("warning: deadline exceeded by linter %s", state.name)
_ = cmd.Process.Kill()
return
}
|
Display deadline exceeded warning to stderr.
|
alecthomas_gometalinter
|
train
|
8c981ef26f30d8dac08a3ad9c7f1328a8ddd0a56
|
diff --git a/tests/test_conf.py b/tests/test_conf.py
index <HASH>..<HASH> 100644
--- a/tests/test_conf.py
+++ b/tests/test_conf.py
@@ -13,7 +13,6 @@ class TestConf(TestCase):
if test_config_d not in sys.path:
sys.path.append(test_config_d)
-
def test_update_config_fail_identifier(self):
"""Fail when naming does not pass correctness"""
bad_dict = {'bad name':'value'}
@@ -69,16 +68,13 @@ class TestConf(TestCase):
def test_update_config_fail_bad_attribute(self):
conf = configuration.initconf()
self.assertRaises(AttributeError, conf.update_with_module, 'bad.attribute')
+
def test_update_config_with_dict(self):
conf = configuration.initconf()
d = {'attr':True}
conf['attr'] = d
self.assertTrue(conf.attr.attr)
- def test_module_ends_in_py(self):
- conf = configuration.initconf()
- conf.update_with_module('config.py')
-
def test_config_dir(self):
conf = configuration.initconf()
@@ -131,4 +127,3 @@ class TestConf(TestCase):
self.assertTrue(configuration.ConfigString.contains_formatting(s))
cs = configuration.ConfigString(s)
self.assertEqual(str(cs), s)
-
|
Removing duplicate test and minor PEP8 fixes
|
pecan_pecan
|
train
|
bb4943fd5104285c67270774a4b37eb6b56ba80e
|
diff --git a/src/MakePotCommand.php b/src/MakePotCommand.php
index <HASH>..<HASH> 100644
--- a/src/MakePotCommand.php
+++ b/src/MakePotCommand.php
@@ -620,8 +620,6 @@ class MakePotCommand extends WP_CLI_Command {
if ( ! $this->skip_blade ) {
$options = [
- // Extract 'Template Name' headers in theme files.
- 'wpExtractTemplates' => isset( $this->main_file_data['Theme Name'] ),
'include' => $this->include,
'exclude' => $this->exclude,
'extensions' => [ 'blade.php' ],
|
Remove `Template Name` extraction from PHP-blade extractor, as it doesn't apply to PHP-blade templates.
|
wp-cli_i18n-command
|
train
|
61cda61b22fa12c130aa094c0f1bf2118b068b19
|
diff --git a/multigtfs/models/route.py b/multigtfs/models/route.py
index <HASH>..<HASH> 100644
--- a/multigtfs/models/route.py
+++ b/multigtfs/models/route.py
@@ -159,7 +159,14 @@ class Route(Base):
"""Update the geometry from the Trips"""
original = self.geometry
trips = self.trip_set.exclude(geometry=None)
- self.geometry = MultiLineString([t.geometry for t in trips])
+ unique_coords = set()
+ unique_geom = list()
+ for t in trips:
+ coords = t.geometry.coords
+ if coords not in unique_coords:
+ unique_coords.add(coords)
+ unique_geom.append(t.geometry)
+ self.geometry = MultiLineString(unique_geom)
if self.geometry != original:
self.save()
diff --git a/multigtfs/tests/route.py b/multigtfs/tests/route.py
index <HASH>..<HASH> 100644
--- a/multigtfs/tests/route.py
+++ b/multigtfs/tests/route.py
@@ -109,6 +109,30 @@ AB,DTA,10,Airport - Bullfrog,Our Airport Route,3,http://example.com,\
route.update_geometry()
self.assertEqual(route.geometry.coords, (((1.0, 2.0), (1.0, 3.0)),))
+ def test_update_geometry_2_trips_different_geometries(self):
+ route = Route.objects.create(feed=self.feed, route_id='RTEST', rtype=3)
+ Trip.objects.create(route=route, geometry='LINESTRING(1 2, 1 3)')
+ Trip.objects.create(route=route, geometry='LINESTRING(1 2, 1 4)')
+ self.assertFalse(route.geometry)
+ route.update_geometry()
+ route_coords = list(route.geometry.coords)
+ route_coords.sort()
+ self.assertEqual(len(route_coords), 2)
+ self.assertEqual(
+ route_coords,
+ [((1., 2.), (1., 3.)), ((1., 2.), (1., 4.))])
+
+ def test_update_geometry_2_trips_same_geometry(self):
+ route = Route.objects.create(feed=self.feed, route_id='RTEST', rtype=3)
+ Trip.objects.create(route=route, geometry='LINESTRING(1 2, 1 3)')
+ Trip.objects.create(route=route, geometry='LINESTRING(1 2, 1 3)')
+ self.assertFalse(route.geometry)
+ route.update_geometry()
+ route_coords = list(route.geometry.coords)
+ route_coords.sort()
+ self.assertEqual(len(route_coords), 1)
+ self.assertEqual(route.geometry.coords, (((1.0, 2.0), (1.0, 3.0)),))
+
def test_update_geometry_no_change(self):
# For code coverage
route = Route.objects.create(
|
Route geometry is unique trip geometries, fixes #<I>
|
tulsawebdevs_django-multi-gtfs
|
train
|
68d7feb85bafe2d3c08f956bdb85706c16b7671e
|
diff --git a/src/storage-preview/azext_storage_preview/azcopy/util.py b/src/storage-preview/azext_storage_preview/azcopy/util.py
index <HASH>..<HASH> 100644
--- a/src/storage-preview/azext_storage_preview/azcopy/util.py
+++ b/src/storage-preview/azext_storage_preview/azcopy/util.py
@@ -102,7 +102,7 @@ def _unserialize_non_msi_token_payload(token_info):
import jwt # pylint: disable=import-error
parsed_authority = urlparse(token_info['_authority'])
- decode = jwt.decode(token_info['accessToken'], verify=False, algorithms=['RS256'])
+ decode = jwt.decode(token_info['accessToken'], algorithms=['RS256'], options={"verify_signature": False})
return {
'access_token': token_info['accessToken'],
'refresh_token': token_info['refreshToken'],
diff --git a/src/storage-preview/azext_storage_preview/azext_metadata.json b/src/storage-preview/azext_storage_preview/azext_metadata.json
index <HASH>..<HASH> 100644
--- a/src/storage-preview/azext_storage_preview/azext_metadata.json
+++ b/src/storage-preview/azext_storage_preview/azext_metadata.json
@@ -1,4 +1,4 @@
{
- "azext.minCliCoreVersion": "2.21.0",
+ "azext.minCliCoreVersion": "2.25.0",
"azext.isPreview": true
}
\ No newline at end of file
diff --git a/src/storage-preview/setup.py b/src/storage-preview/setup.py
index <HASH>..<HASH> 100644
--- a/src/storage-preview/setup.py
+++ b/src/storage-preview/setup.py
@@ -8,7 +8,7 @@
from codecs import open
from setuptools import setup, find_packages
-VERSION = "0.7.3"
+VERSION = "0.7.4"
CLASSIFIERS = [
'Development Status :: 4 - Beta',
|
{storage-preview} Fix issue <I>: Fix jwt issue (#<I>)
|
Azure_azure-cli-extensions
|
train
|
2343de33895fe884e4fe5b72418918517938d631
|
diff --git a/src/Ipunkt/SocialAuth/EventListeners/UpdateProfileEventListener.php b/src/Ipunkt/SocialAuth/EventListeners/UpdateProfileEventListener.php
index <HASH>..<HASH> 100644
--- a/src/Ipunkt/SocialAuth/EventListeners/UpdateProfileEventListener.php
+++ b/src/Ipunkt/SocialAuth/EventListeners/UpdateProfileEventListener.php
@@ -40,8 +40,9 @@ class UpdateProfileEventListener {
$database_profile = $this->socialProfileRepository->findByUserAndProvider($user, 'UserProfile');
if($database_profile === null) {
$database_profile = $this->socialProfileRepository->create();
+ $database_profile->copy($registerInfo->getProfile());
$database_profile->setProvider('UserProfile');
- $database_profile->setIdentifier($user->getAuthIdentifier());
+ $database_profile->setUser($user->getAuthIdentifier());
$this->socialProfileRepository->saveProfile($database_profile);
}
}
diff --git a/src/Ipunkt/SocialAuth/Profile/ProfileSetInterface.php b/src/Ipunkt/SocialAuth/Profile/ProfileSetInterface.php
index <HASH>..<HASH> 100644
--- a/src/Ipunkt/SocialAuth/Profile/ProfileSetInterface.php
+++ b/src/Ipunkt/SocialAuth/Profile/ProfileSetInterface.php
@@ -2,6 +2,7 @@
namespace Ipunkt\SocialAuth\Profile;
+use Illuminate\Auth\UserInterface;
use Ipunkt\SocialAuth\Provider\ProviderInterface;
@@ -13,6 +14,12 @@ use Ipunkt\SocialAuth\Provider\ProviderInterface;
*/
interface ProfileSetInterface {
/**
+ * @param $userid
+ * @return mixed
+ */
+ function setUser($userid);
+
+ /**
* @return ProviderInterface
*/
function setProvider($value);
|
Userid is now correctly set upon creating a db profile while registering
|
ipunkt_social-auth
|
train
|
e6183ec64364e51a374692ac89f2d2585b6c3e59
|
diff --git a/py/nupic/frameworks/prediction/callbacks.py b/py/nupic/frameworks/prediction/callbacks.py
index <HASH>..<HASH> 100644
--- a/py/nupic/frameworks/prediction/callbacks.py
+++ b/py/nupic/frameworks/prediction/callbacks.py
@@ -28,8 +28,9 @@ try:
import matplotlib
matplotlib.use('agg', warn=False)
import pylab
+ pylabAvailable = True
except:
- pass
+ pylabAvailable = False
"""A callback (aka "hook function") for the Prediction Framework is invoked by
the framework as:
@@ -391,16 +392,15 @@ def _initPylab():
Initialize pylab for plotting
"""
global _pylabInitialized
- if _pylabInitialized:
- return
-
- if "pylab" in sys.modules:
- _pylabInitialized = True
+ if pylabAvailable and not _pylabInitialized:
pylab.ion()
pylab.figure(2)
pylab.figure(1)
+ _pylabInitialized = True
+
+
##########################################################
# Callbacks for displaying TP information
|
Slightly more graceful approach to initializing pylab if it's available.
|
numenta_nupic
|
train
|
eb1594f4e6986ec60711875d27629dc34a5d214b
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -148,11 +148,11 @@ def readme():
setup(
name='dustmaps',
- version='1.0.4',
+ version='1.0.5',
description='Uniform interface for multiple dust reddening maps.',
long_description=readme(),
url='https://github.com/gregreen/dustmaps',
- download_url='https://github.com/gregreen/dustmaps/archive/v1.0.4.tar.gz',
+ download_url='https://github.com/gregreen/dustmaps/archive/v1.0.5.tar.gz',
author='Gregory M. Green',
author_email='gregorymgreen@gmail.com',
license='GPLv2',
|
Updated version string in setup.py.
|
gregreen_dustmaps
|
train
|
8ae310edc8455afdcea18df0772f333b65d23dff
|
diff --git a/src/Broadway/CommandHandling/Testing/Scenario.php b/src/Broadway/CommandHandling/Testing/Scenario.php
index <HASH>..<HASH> 100644
--- a/src/Broadway/CommandHandling/Testing/Scenario.php
+++ b/src/Broadway/CommandHandling/Testing/Scenario.php
@@ -33,6 +33,7 @@ class Scenario
private $eventStore;
private $commandHandler;
private $testCase;
+ private $aggregateId;
public function __construct(
PHPUnit_Framework_TestCase $testCase,
@@ -42,6 +43,17 @@ class Scenario
$this->testCase = $testCase;
$this->eventStore = $eventStore;
$this->commandHandler = $commandHandler;
+ $this->aggregateId = 1;
+ }
+
+ /**
+ * @param string $aggregateId
+ */
+ public function withAggregateId($aggregateId)
+ {
+ $this->aggregateId = $aggregateId;
+
+ return $this;
}
/**
@@ -50,24 +62,20 @@ class Scenario
*
* @return Scenario
*/
- public function given(array $events = null, $id = null)
+ public function given(array $events = null)
{
if ($events === null) {
return $this;
}
- if ($id === null) {
- $id = 1;
- }
-
$messages = array();
$playhead = -1;
foreach ($events as $event) {
$playhead++;
- $messages[] = DomainMessage::recordNow($id, $playhead, new Metadata(array()), $event);
+ $messages[] = DomainMessage::recordNow($this->aggregateId, $playhead, new Metadata(array()), $event);
}
- $this->eventStore->append($id, new DomainEventStream($messages));
+ $this->eventStore->append($this->aggregateId, new DomainEventStream($messages));
return $this;
}
|
Add aggreateId as part of the scenario
|
broadway_broadway
|
train
|
fd09dfb1150c781d6e5865b72d9d18c70261b2bf
|
diff --git a/thinc/config.py b/thinc/config.py
index <HASH>..<HASH> 100644
--- a/thinc/config.py
+++ b/thinc/config.py
@@ -492,7 +492,7 @@ class registry(object):
schema: Type[BaseModel] = EmptySchema,
overrides: Dict[str, Any] = {},
validate: bool = True,
- ) -> Tuple[Config, Config]:
+ ) -> Tuple[Dict[str, Any], Config]:
"""Unpack a config dictionary and create two versions of the config:
a resolved version with objects from the registry created recursively,
and a filled version with all references to registry functions left
@@ -532,7 +532,7 @@ class registry(object):
schema: Type[BaseModel] = EmptySchema,
overrides: Dict[str, Any] = {},
validate: bool = True,
- ) -> Config:
+ ) -> Dict[str, Any]:
"""Unpack a config dictionary, creating objects from the registry
recursively. If validate=True, the config will be validated against the
type annotations of the registered functions referenced in the config
@@ -575,7 +575,7 @@ class registry(object):
validate: bool = True,
parent: str = "",
overrides: Dict[str, Dict[str, Any]] = {},
- ) -> Tuple[Config, Config, Config]:
+ ) -> Tuple[Config, Config, Dict[str, Any]]:
"""Build three representations of the config:
1. All promises are preserved (just like config user would provide).
2. Promises are replaced by their return values. This is the validation
@@ -668,7 +668,7 @@ class registry(object):
exclude_validation = set([ARGS_FIELD_ALIAS, *RESERVED_FIELDS.keys()])
validation.update(result.dict(exclude=exclude_validation))
filled, final = cls._update_from_parsed(validation, filled, final)
- return Config(filled), Config(validation), Config(final)
+ return Config(filled), Config(validation), dict(final)
@classmethod
def _update_from_parsed(
|
Make resolved config a dict
No point in making it a Config object because it's not really a valid config – it contains arbitrary Python objects, can't be serialized or interpolated as a config, etc.
|
explosion_thinc
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.