hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
e79516c213fd57adb97d1c48347bdda85a6f7d14
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -9,5 +9,5 @@ setup( author='snjoetw', author_email='[email protected]', description='Python API for August Smart Lock and Doorbell', - requires=['requests', 'vol'] + install_requires=['requests', 'vol'] )
Set install_requires for pip deps
snjoetw_py-august
train
fb1bdc59da28fbea7a036e6c2e2c8df3b64325f8
diff --git a/tests/ServiceProviderTest.php b/tests/ServiceProviderTest.php index <HASH>..<HASH> 100644 --- a/tests/ServiceProviderTest.php +++ b/tests/ServiceProviderTest.php @@ -16,6 +16,7 @@ use GrahamCampbell\Throttle\Factories\CacheFactory; use GrahamCampbell\Throttle\Factories\FactoryInterface; use GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware; use GrahamCampbell\Throttle\Throttle; +use GrahamCampbell\Throttle\Transformers\TransformerFactory; use GrahamCampbell\Throttle\Transformers\TransformerFactoryInterface; /** @@ -35,6 +36,7 @@ class ServiceProviderTest extends AbstractTestCase public function testTransformerFactoryIsInjectable() { + $this->assertIsInjectable(TransformerFactory::class); $this->assertIsInjectable(TransformerFactoryInterface::class); }
Update ServiceProviderTest.php
GrahamCampbell_Laravel-Throttle
train
227f3d40333e9c5f6241fb2436b55373004cebcd
diff --git a/tests/unit/test_static.py b/tests/unit/test_static.py index <HASH>..<HASH> 100644 --- a/tests/unit/test_static.py +++ b/tests/unit/test_static.py @@ -182,8 +182,8 @@ class TestWhitenoiseTween: assert resp.status_code == 200 assert resp.headers["Content-Type"] == "application/json" assert ( - set(i.strip() for i in resp.headers["Cache-Control"].split(",")) - == {"public", "max-age=60"} + set(i.strip() for i in resp.headers["Cache-Control"].split(",")) == + {"public", "max-age=60"} ) assert resp.headers["Vary"] == "Accept-Encoding" diff --git a/warehouse/legacy/api/json.py b/warehouse/legacy/api/json.py index <HASH>..<HASH> 100644 --- a/warehouse/legacy/api/json.py +++ b/warehouse/legacy/api/json.py @@ -43,8 +43,8 @@ def json_project(project, request): request.db.query(Release) .filter(Release.project == project) .order_by( - Release.is_prerelease.nullslast(), - Release._pypi_ordering.desc()) + Release.is_prerelease.nullslast(), + Release._pypi_ordering.desc()) .limit(1) .one() ) diff --git a/warehouse/migrations/versions/99291f0fe9c2_update_release_file_on_insert.py b/warehouse/migrations/versions/99291f0fe9c2_update_release_file_on_insert.py index <HASH>..<HASH> 100644 --- a/warehouse/migrations/versions/99291f0fe9c2_update_release_file_on_insert.py +++ b/warehouse/migrations/versions/99291f0fe9c2_update_release_file_on_insert.py @@ -35,14 +35,14 @@ down_revision = 'e7b09b5c089d' def upgrade(): op.execute( - """ UPDATE release_files - SET requires_python = releases.requires_python - FROM releases - WHERE - release_files.name=releases.name - AND release_files.version=releases.version; - """ - ) + """ UPDATE release_files + SET requires_python = releases.requires_python + FROM releases + WHERE + release_files.name=releases.name + AND release_files.version=releases.version; + """ + ) # Establish a trigger such that on INSERT on release_files. # The requires_python value is no supposed to be set directly here diff --git a/warehouse/packaging/views.py b/warehouse/packaging/views.py index <HASH>..<HASH> 100644 --- a/warehouse/packaging/views.py +++ b/warehouse/packaging/views.py @@ -42,8 +42,8 @@ def project_detail(project, request): request.db.query(Release) .filter(Release.project == project) .order_by( - Release.is_prerelease.nullslast(), - Release._pypi_ordering.desc()) + Release.is_prerelease.nullslast(), + Release._pypi_ordering.desc()) .limit(1) .one() ) @@ -78,9 +78,9 @@ def release_detail(release, request): request.db.query(Release) .filter(Release.project == project) .with_entities( - Release.version, - Release.is_prerelease, - Release.created) + Release.version, + Release.is_prerelease, + Release.created) .order_by(Release._pypi_ordering.desc()) .all() ) diff --git a/warehouse/tasks.py b/warehouse/tasks.py index <HASH>..<HASH> 100644 --- a/warehouse/tasks.py +++ b/warehouse/tasks.py @@ -57,8 +57,8 @@ class WarehouseTask(celery.Task): try: return original_run(*args, **kwargs) except BaseException as exc: - if (isinstance(exc, pyramid_retry.RetryableException) - or pyramid_retry.IRetryableError.providedBy(exc)): + if (isinstance(exc, pyramid_retry.RetryableException) or + pyramid_retry.IRetryableError.providedBy(exc)): raise obj.retry(exc=exc) raise
Fixes for the new flake8. Refs #<I> (#<I>)
pypa_warehouse
train
11b26b52563ef9bfecfcd0839b0f439e7661416f
diff --git a/gson/src/main/java/com/google/gson/Gson.java b/gson/src/main/java/com/google/gson/Gson.java index <HASH>..<HASH> 100644 --- a/gson/src/main/java/com/google/gson/Gson.java +++ b/gson/src/main/java/com/google/gson/Gson.java @@ -30,10 +30,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicLongArray; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.Excluder; @@ -224,6 +222,7 @@ public final class Gson { factories.add(TypeAdapters.ATOMIC_INTEGER_FACTORY); factories.add(TypeAdapters.ATOMIC_BOOLEAN_FACTORY); factories.add(TypeAdapters.newFactory(AtomicLong.class, atomicLongAdapter(longAdapter))); + factories.add(TypeAdapters.newFactory(AtomicLongArray.class, atomicLongArrayAdapter(longAdapter))); factories.add(TypeAdapters.ATOMIC_INTEGER_ARRAY_FACTORY); factories.add(TypeAdapters.CHARACTER_FACTORY); factories.add(TypeAdapters.STRING_BUILDER_FACTORY); @@ -344,6 +343,34 @@ public final class Gson { } }.nullSafe(); } + + private static TypeAdapter<AtomicLongArray> atomicLongArrayAdapter(final TypeAdapter<Number> longAdapter) { + return new TypeAdapter<AtomicLongArray>() { + @Override public void write(JsonWriter out, AtomicLongArray value) throws IOException { + out.beginArray(); + for (int i = 0, length = value.length(); i < length; i++) { + longAdapter.write(out, value.get(i)); + } + out.endArray(); + } + @Override public AtomicLongArray read(JsonReader in) throws IOException { + List<Long> list = new ArrayList<Long>(); + in.beginArray(); + while (in.hasNext()) { + long value = longAdapter.read(in).longValue(); + list.add(value); + } + in.endArray(); + int length = list.size(); + AtomicLongArray array = new AtomicLongArray(length); + for (int i = 0; i < length; ++i) { + array.set(i, list.get(i)); + } + return array; + } + }.nullSafe(); + } + /** * Returns the type adapter for {@code} type. * diff --git a/gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentLocksTest.java b/gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentLocksTest.java index <HASH>..<HASH> 100644 --- a/gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentLocksTest.java +++ b/gson/src/test/java/com/google/gson/functional/JavaUtilConcurrentLocksTest.java @@ -20,8 +20,11 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicLongArray; import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.LongSerializationPolicy; import junit.framework.TestCase; @@ -58,6 +61,16 @@ public class JavaUtilConcurrentLocksTest extends TestCase { assertEquals("10", json); } + public void testAtomicLongWithStringSerializationPolicy() throws Exception { + Gson gson = new GsonBuilder() + .setLongSerializationPolicy(LongSerializationPolicy.STRING) + .create(); + AtomicLongHolder target = gson.fromJson("{'value':'10'}", AtomicLongHolder.class); + assertEquals(10, target.value.get()); + String json = gson.toJson(target); + assertEquals("{\"value\":\"10\"}", json); + } + public void testAtomicIntegerArray() throws Exception { AtomicIntegerArray target = gson.fromJson("[10, 13, 14]", AtomicIntegerArray.class); assertEquals(3, target.length()); @@ -67,4 +80,31 @@ public class JavaUtilConcurrentLocksTest extends TestCase { String json = gson.toJson(target); assertEquals("[10,13,14]", json); } + + public void testAtomicLongArray() throws Exception { + AtomicLongArray target = gson.fromJson("[10, 13, 14]", AtomicLongArray.class); + assertEquals(3, target.length()); + assertEquals(10, target.get(0)); + assertEquals(13, target.get(1)); + assertEquals(14, target.get(2)); + String json = gson.toJson(target); + assertEquals("[10,13,14]", json); + } + + public void testAtomicLongArrayWithStringSerializationPolicy() throws Exception { + Gson gson = new GsonBuilder() + .setLongSerializationPolicy(LongSerializationPolicy.STRING) + .create(); + AtomicLongArray target = gson.fromJson("['10', '13', '14']", AtomicLongArray.class); + assertEquals(3, target.length()); + assertEquals(10, target.get(0)); + assertEquals(13, target.get(1)); + assertEquals(14, target.get(2)); + String json = gson.toJson(target); + assertEquals("[\"10\",\"13\",\"14\"]", json); + } + + private static class AtomicLongHolder { + AtomicLong value; + } }
Added support for AtomicLongArray. Also added tests to ensure LongSerializationPolicy is honored.
google_gson
train
f8acd80573b61dc638c5d1db5ebc10eafe530f54
diff --git a/.travis.yml b/.travis.yml index <HASH>..<HASH> 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,6 +9,7 @@ python: env: - DJANGO="Django==1.8" - DJANGO="Django==1.9" + - DJANGO="Django==1.10" # command to install dependencies, e.g. pip install -r requirements.txt install: diff --git a/example/urls.py b/example/urls.py index <HASH>..<HASH> 100644 --- a/example/urls.py +++ b/example/urls.py @@ -1,13 +1,12 @@ -from django.conf.urls import patterns, include, url +from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView admin.autodiscover() -urlpatterns = patterns( - '', +urlpatterns = [ url(r'^manage/', include(admin.site.urls)), url(r'^current-usersettings/$', TemplateView.as_view(template_name='example/current-usersettings.html'), name='current_usersettings'), -) +] diff --git a/runtests.py b/runtests.py index <HASH>..<HASH> 100644 --- a/runtests.py +++ b/runtests.py @@ -1,7 +1,43 @@ import sys try: - from django.conf import settings + import django + from django.conf import settings, global_settings as default_settings + + if django.VERSION >= (1, 10): + template_settings = dict( + TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': (), + 'OPTIONS': { + 'autoescape': False, + 'loaders': ( + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', + ), + 'context_processors': ( + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + 'usersettings.context_processors.usersettings', + ), + }, + }, + ] + ) + else: + template_settings = dict( + TEMPLATE_LOADERS = ( + 'django.template.loaders.app_directories.Loader', + 'django.template.loaders.filesystem.Loader', + ), + TEMPLATE_CONTEXT_PROCESSORS = list(default_settings.TEMPLATE_CONTEXT_PROCESSORS) + [ + 'django.core.context_processors.request', + 'usersettings.context_processors.usersettings', + ], + ) settings.configure( DEBUG=True, @@ -33,10 +69,7 @@ try: 'django.contrib.messages.middleware.MessageMiddleware', 'usersettings.middleware.CurrentUserSettingsMiddleware', ), - TEMPLATE_CONTEXT_PROCESSORS = ( - 'django.core.context_processors.request', - 'usersettings.context_processors.usersettings', - ) + **template_settings ) try: diff --git a/tests/test_admin.py b/tests/test_admin.py index <HASH>..<HASH> 100644 --- a/tests/test_admin.py +++ b/tests/test_admin.py @@ -98,9 +98,6 @@ class AdminTest(TestCase): 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',), - TEMPLATE_CONTEXT_PROCESSORS = ( - 'django.core.context_processors.request', - ), ) def test_chagelist_view_redirects_to_add_view(self): """ diff --git a/usersettings/admin.py b/usersettings/admin.py index <HASH>..<HASH> 100644 --- a/usersettings/admin.py +++ b/usersettings/admin.py @@ -9,7 +9,6 @@ from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response -from django.template.context import RequestContext from django.utils.encoding import force_text from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ @@ -139,14 +138,12 @@ class SettingsAdmin(admin.ModelAdmin): 'save_on_top': self.save_on_top, }) - context_instance = RequestContext(request, current_app=self.admin_site.name) - return render_to_response(self.select_site_form_template or [ 'admin/%s/%s/select_site_form.html' % (app_label, self.opts.object_name.lower()), 'admin/%s/select_site_form.html' % app_label, 'admin/usersettings/select_site_form.html', # added default here 'admin/select_site_form.html' - ], context, context_instance=context_instance) + ], context) @csrf_protect_m def changelist_view(self, request, extra_context=None):
Django <I> support
mishbahr_django-usersettings2
train
d1103da8197c7acfe450c4791473eae5fcec4f91
diff --git a/dataclass.py b/dataclass.py index <HASH>..<HASH> 100644 --- a/dataclass.py +++ b/dataclass.py @@ -132,8 +132,11 @@ def _init(fields): def _repr(fields): return _create_fn('__repr__', - [f'{_SELF}'], - [f'return {_SELF}.__class__.__name__ + f"(' + ','.join([f"{f.name}={{{_SELF}.{f.name}!r}}" for f in fields]) + ')"'], + [_SELF], + [f'return {_SELF}.__class__.__name__ + f"(' + + ','.join([f"{f.name}={{{_SELF}.{f.name}!r}}" + for f in fields]) + + ')"'], ) @@ -223,14 +226,12 @@ def _process_class(cls, repr, cmp, hash, init, slots, frozen, dynamic): # Find our base classes in reverse MRO order, and exclude # ourselves. In reversed order so that more derived classes # overrides earlier field definitions in base classes. - bases = [b for b in cls.__mro__ if not b is cls] - - for b in bases: + for b in [b for b in cls.__mro__ if not b is cls]: # Only process classes marked with our decorator. if hasattr(b, _MARKER): # This is one of our base classes, where we've already # set _MARKER with a list of fields. Add them to the - # fields we're building up. already processed. + # fields we're building up. for f in getattr(b, _MARKER): fields[f.name] = f @@ -310,7 +311,8 @@ def dataclass(_cls=None, *, repr=True, cmp=True, hash=None, init=True, def make_class(cls_name, fields, *, bases=None, repr=True, cmp=True, - hash=None, init=True, slots=False, frozen=False): + hash=None, init=True, slots=False, frozen=False, + default_type=str): # fields is a list of (name, type, field) if bases is None: bases = (object,) @@ -327,11 +329,11 @@ def make_class(cls_name, fields, *, bases=None, repr=True, cmp=True, annotations = {} # XXX also ordered? for idx, f in enumerate(fields, 1): if isinstance(f, str): - # Only a name specified, assume it's a str. - f = field(f, str) + # Only a name specified, assume it's of type default_type. + f = field(f, default_type) if f.name is None: - raise ValueError(f'name must be specified for field {idx}') + raise ValueError(f'name must be specified for field #{idx}') if f.type is None: raise ValueError(f'type must be specified for field {f.name!r}') diff --git a/tst.py b/tst.py index <HASH>..<HASH> 100755 --- a/tst.py +++ b/tst.py @@ -380,7 +380,7 @@ class TestCase(unittest.TestCase): [field('x', int), field(), ]) - self.assertEqual(str(ex.exception), 'name must be specified for field 2') + self.assertEqual(str(ex.exception), 'name must be specified for field #2') with self.assertRaises(ValueError) as ex: C = make_class('C',
Misc. small code cleanups and line wrapping.
ericvsmith_dataclasses
train
7667fc2eb17a7f05a8a5f655fb8b50d97a236d9c
diff --git a/source/org/jasig/portal/groups/EntityGroupImpl.java b/source/org/jasig/portal/groups/EntityGroupImpl.java index <HASH>..<HASH> 100644 --- a/source/org/jasig/portal/groups/EntityGroupImpl.java +++ b/source/org/jasig/portal/groups/EntityGroupImpl.java @@ -115,6 +115,10 @@ private void checkIfAlreadyMember(IGroupMember gm) throws GroupsException */ private void checkProspectiveMember(IGroupMember gm) throws GroupsException { + if ( gm.equals(this) ) + { + throw new GroupsException("Attempt to add " + gm + " to itself."); + } checkIfAlreadyMember(gm); checkProspectiveMemberEntityType(gm);
Fix bug that allowed a group to be added to itself. git-svn-id: <URL>
Jasig_uPortal
train
8950112c93259e9f0b4ff21a468e8873af388b0e
diff --git a/public/src/Entity/Meta.php b/public/src/Entity/Meta.php index <HASH>..<HASH> 100644 --- a/public/src/Entity/Meta.php +++ b/public/src/Entity/Meta.php @@ -808,8 +808,8 @@ class Meta if ($isImage) { try { $image = WideImage::load(PATH_HOME . $dir . $nameFile); - $image->resize(1500, 500)->crop('center', 'center', 500, 500)->saveToFile(PATH_HOME . $dir . "medium/" . $nameFile); - $image->resize(300, 100)->crop('center', 'center', 100, 100)->saveToFile(PATH_HOME . $dir . "thumb/" . $nameFile); + $image->resize(500)->saveToFile(PATH_HOME . $dir . "medium/" . $nameFile); + $image->resize(100)->saveToFile(PATH_HOME . $dir . "thumb/" . $nameFile); $value[$i]['urls'] = [ 'thumb' => HOME . $dir . "thumb/" . $nameFile,
image medium and thumb only resize
edineibauer_uebEntity
train
a1ce9e662c67b399ae06e5e7fcbe7f1e11b18e5e
diff --git a/cake/libs/controller/components/cookie.php b/cake/libs/controller/components/cookie.php index <HASH>..<HASH> 100644 --- a/cake/libs/controller/components/cookie.php +++ b/cake/libs/controller/components/cookie.php @@ -215,7 +215,7 @@ class CookieComponent extends Object { foreach ($key as $name => $value) { if (strpos($name, '.') === false) { $this->__values[$name] = $value; - $this->__write(".$name", $value); + $this->__write("[$name]", $value); } else { $names = explode('.', $name, 2); @@ -223,7 +223,7 @@ class CookieComponent extends Object { $this->__values[$names[0]] = array(); } $this->__values[$names[0]] = Set::insert($this->__values[$names[0]], $names[1], $value); - $this->__write("." . implode('.', $names), $value); + $this->__write('[' . implode('][', $names) . ']', $value); } } $this->__encrypted = true; @@ -289,12 +289,12 @@ class CookieComponent extends Object { } if (strpos($key, '.') === false) { unset($this->__values[$key]); - $this->__delete(".$key"); + $this->__delete("[$key]"); return; } $names = explode('.', $key, 2); $this->__values[$names[0]] = Set::remove($this->__values[$names[0]], $names[1]); - $this->__delete("." . implode('.', $names)); + $this->__delete('[' . implode('][', $names) . ']'); } /** @@ -315,11 +315,11 @@ class CookieComponent extends Object { if (is_array($value)) { foreach ($value as $key => $val) { unset($this->__values[$name][$key]); - $this->__delete(".$name.$key"); + $this->__delete("[$name][$key]"); } } unset($this->__values[$name]); - $this->__delete(".$name"); + $this->__delete("[$name]"); } } @@ -354,6 +354,11 @@ class CookieComponent extends Object { return $this->__expires; } $this->__reset = $this->__expires; + + if ($expires == 0) { + return $this->__expires = 0; + } + if (is_integer($expires) || is_numeric($expires)) { return $this->__expires = $now + intval($expires); }
Fixing real issue for Ticket #<I> Reverted changes replacing [ and ] with .
cakephp_cakephp
train
7501a99bcced6a44d81efbd78269d08252c299eb
diff --git a/lib/replace-require-and-define.js b/lib/replace-require-and-define.js index <HASH>..<HASH> 100644 --- a/lib/replace-require-and-define.js +++ b/lib/replace-require-and-define.js @@ -20,11 +20,14 @@ const t = require('@babel/types'); const generator = require('@babel/generator').default; // Replace indentifier -const Identifiers = { +const IdentifierMap = { 'require': 'eriuqer', 'define': 'enifed' }; +const Identifiers = Object.keys(IdentifierMap); + + // Use babel to parse/traverse/generate code. // - replace define and require with enifed and eriuqer // - if required, collect the external AMD modules referenced @@ -39,8 +42,7 @@ module.exports = function replaceRequireAndDefine(code, amdPackages, externalAmd // This will take care of the loader.js code where define and require are define globally // The cool thing is that babel will rename all references as well // Rename at the end so we don't overlap with the CallExpression visitor - path.scope.rename('define', Identifiers.define); - path.scope.rename('require', Identifiers.require); + Identifiers.forEach(identifier => path.scope.rename(identifier, IdentifierMap[identifier])); } }, CallExpression(path) { @@ -81,59 +83,32 @@ module.exports = function replaceRequireAndDefine(code, amdPackages, externalAmd }); } - // Rename if it's invoking a global require function - if (t.isIdentifier(node.callee, { - name: 'define' - }) && !path.scope.hasBinding('define')) { - node.callee.name = Identifiers.define; - return; - } - - // Rename if it's invoking a global require function - if (t.isIdentifier(node.callee, { - name: 'require' - }) && !path.scope.hasBinding('require')) { - node.callee.name = Identifiers.require; - return; - } - // auto-import injects eval expression. We need to process them as individual code if (t.isIdentifier(node.callee, { - name: 'eval' - }) && t.isStringLiteral(node.arguments[0])) { + name: 'eval' + }) && t.isStringLiteral(node.arguments[0])) { node.arguments[0].value = replaceRequireAndDefine(node.arguments[0].value, amdPackages, externalAmdModules); } }, - VariableDeclarator(path) { - // This could happened in auto-import eval: var d = define; - if (t.isIdentifier(path.node.init, { - name: 'define' - }) && !path.scope.hasBinding('define')) { - path.node.init.name = Identifiers.define; + Identifier(path) { + // Only interested by our identifiers that have no bindings in the path scope + if (!Identifiers.includes(path.node.name) || path.scope.hasBinding(path.node.name)) { return; } - // This could happened in auto-import eval: var r = require; - if (t.isIdentifier(path.node.init, { - name: 'require' - }) && !path.scope.hasBinding('require')) { - path.node.init.name = Identifiers.require; - } - }, - AssignmentExpression(path) { - // This could happened in auto-import eval: window.d = define; - if (t.isIdentifier(path.node.right, { - name: 'define' - }) && !path.scope.hasBinding('define')) { - path.node.right.name = Identifiers.define; + + // Avoid: foo.define/require + if (t.isMemberExpression(path.container) && path.container.property === path.node) { return; } - // This could happened in auto-import eval: window.r = require; - if (t.isIdentifier(path.node.right, { - name: 'require' - }) && !path.scope.hasBinding('require')) { - path.node.right.name = Identifiers.require; + + // Avoid class properties/methods + if ((t.isClassMethod(path.container) || t.isClassProperty(path.container)) && path.container.key === path.node) { + return; } - }, + + // Rename + path.node.name = IdentifierMap[path.node.name]; + } });
Fixed require/define conversion for tests
Esri_ember-cli-amd
train
f6dc4113c0967e4c11175e0b586153e5a217ba59
diff --git a/js/spec/index-spec.js b/js/spec/index-spec.js index <HASH>..<HASH> 100644 --- a/js/spec/index-spec.js +++ b/js/spec/index-spec.js @@ -422,13 +422,23 @@ describe('Node Sentinel File Watcher', function() { it('does not loop endlessly when watching directories with recursive symlinks', (done) => { fse.mkdirSync(path.join(workDir, 'test')); fse.symlinkSync(path.join(workDir, 'test'), path.join(workDir, 'test', 'link')); + + let watch; + return nsfw( workDir, () => {}, { debounceMS: DEBOUNCE, errorCallback() {} } - ).then((watch) => { - return watch.start(); - }).then(done); + ) + .then(_w => { + watch = _w; + return watch.start(); + }) + .then(() => { + return watch.stop(); + }) + .then(done, () => + watch.stop().then((err) => done.fail(err))); }); });
Close watcher in test and match code style
Axosoft_nsfw
train
f672464faf733b68001d6ced711bb9119c3a6f7d
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -66,10 +66,13 @@ module ActiveSupport alias :assert_not_respond_to :refute_respond_to alias :assert_not_same :refute_same - # Reveals the intention that the block should not raise any exception. + + # Assertion that the block should not raise an exception. + # + # Passes if evaluated code in the yielded block raises no exception. # # assert_nothing_raised do - # ... + # perform_service(param: 'no_exception') # end def assert_nothing_raised(*args) yield
better docs for ActiveSupport::TestCase#assert_nothing_raised
rails_rails
train
58e4a052120dd25de9ddcf096d18ded3b116fe7d
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -27,5 +27,8 @@ "covex-nn/phpcb": "1.0.4.*", "doctrine/cache": "~1.4", "apigen/apigen": "~4.0" + }, + "suggest": { + "ext-intl": "for convenient handling of localizations" } } diff --git a/docroot/index.php b/docroot/index.php index <HASH>..<HASH> 100644 --- a/docroot/index.php +++ b/docroot/index.php @@ -5,11 +5,13 @@ */ namespace Sphere\Core; +use Sphere\Core\Model\Product\Product; use Sphere\Core\Request\Products\ProductsSearchRequest; use Sphere\Core\Response\PagedQueryResponse; require '../vendor/autoload.php'; +\Locale::setDefault('en-US'); $appConfig = parse_ini_file('myapp.ini', true); // create the sphere config object @@ -44,10 +46,13 @@ $products = $client->execute($search); <input type="submit"> </form> <?php - foreach ($products as $product) : ?> - <h1><?= $product['name']['en'] ?></h1> - <img src="<?= $product['masterVariant']['images'][0]['url'] ?>" width="100"> - <p><?= $product['description']['en'] ?></p> + foreach ($products as $data) : ?> + <?php + $product = Product::fromArray($data); + ?> + <h1><?= $product->getName() ?></h1> + <img src="<?= $product->getMasterVariant()['images'][0]['url'] ?>" width="100"> + <p><?= $product->getDescription() ?></p> <?php endforeach; ?> diff --git a/src/Model/Common/JsonObject.php b/src/Model/Common/JsonObject.php index <HASH>..<HASH> 100644 --- a/src/Model/Common/JsonObject.php +++ b/src/Model/Common/JsonObject.php @@ -118,7 +118,7 @@ class JsonObject implements \JsonSerializable, JsonDeserializeInterface /** * @param $field * @param $key - * @return bool + * @return string|false * @internal */ protected function getFieldKey($field, $key) diff --git a/src/Model/Common/LocalizedString.php b/src/Model/Common/LocalizedString.php index <HASH>..<HASH> 100644 --- a/src/Model/Common/LocalizedString.php +++ b/src/Model/Common/LocalizedString.php @@ -16,6 +16,7 @@ use Sphere\Core\Error\InvalidArgumentException; */ class LocalizedString implements \JsonSerializable, JsonDeserializeInterface { + protected static $language; protected $values = []; /** @@ -26,13 +27,26 @@ class LocalizedString implements \JsonSerializable, JsonDeserializeInterface $this->values = $values; } + protected function getDefaultLocale() + { + if (is_null(static::$language)) { + if (\extension_loaded('intl')) { + $locale = \Locale::getDefault(); + static::$language = \Locale::getPrimaryLanguage($locale); + } + } + return static::$language; + } /** * @param $locale * @return string */ - public function get($locale) + public function get($locale = null) { + if (is_null($locale)) { + $locale = $this->getDefaultLocale(); + } if (!isset($this->values[$locale])) { throw new InvalidArgumentException(Message::NO_VALUE_FOR_LOCALE); } @@ -56,6 +70,11 @@ class LocalizedString implements \JsonSerializable, JsonDeserializeInterface $this->values = array_merge($this->values, $localizedString->toArray()); } + public function __toString() + { + return $this->get(); + } + /** * @return array */ diff --git a/src/Model/Common/ReferenceFromArrayTrait.php b/src/Model/Common/ReferenceFromArrayTrait.php index <HASH>..<HASH> 100644 --- a/src/Model/Common/ReferenceFromArrayTrait.php +++ b/src/Model/Common/ReferenceFromArrayTrait.php @@ -7,6 +7,10 @@ namespace Sphere\Core\Model\Common; +/** + * Class ReferenceFromArrayTrait + * @package Sphere\Core\Model\Common + */ trait ReferenceFromArrayTrait { public static function fromArray(array $data)
add default locale handler to localized strings
commercetools_commercetools-php-sdk
train
2264f6090c3366151ebc8a138ce77b82aa30a435
diff --git a/lib/client.js b/lib/client.js index <HASH>..<HASH> 100644 --- a/lib/client.js +++ b/lib/client.js @@ -150,7 +150,7 @@ function onConnected(frame, beforeSendResponse){ } } - self.emit("connect"); + self.emit("connect", {headers: frame.headers}); beforeSendResponse(); });
Pass object with headers property on connect emit
gdaws_node-stomp
train
cd0f7fac44326f9cd417db6d66c2bfdddf071702
diff --git a/spec/lib/eve/api/calls/server_status_spec.rb b/spec/lib/eve/api/calls/server_status_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/eve/api/calls/server_status_spec.rb +++ b/spec/lib/eve/api/calls/server_status_spec.rb @@ -8,15 +8,19 @@ describe Eve::API do it "should respond to current_time" do @result.should respond_to(:current_time) end + it "should respond to api_version" do @result.should respond_to(:api_version) end + it "should respond to server_open" do @result.should respond_to(:server_open) end + it "should respond to online_players" do @result.should respond_to(:online_players) end + it "should respond to cached_until" do @result.should respond_to(:cached_until) end diff --git a/spec/support/mock_api_helpers.rb b/spec/support/mock_api_helpers.rb index <HASH>..<HASH> 100644 --- a/spec/support/mock_api_helpers.rb +++ b/spec/support/mock_api_helpers.rb @@ -30,8 +30,11 @@ module MockAPIHelpers end if options[:service] && eve_api(options).respond_to?(base) eve_api(options).send(base).send(options[:service], *(options[:args] || [])) - elsif options[:service] - raise "Service specified but API doesn't respond to '#{base}'" + # If having trouble with mock services, this may be of some help, but it alters how the API can be + # interacted with (most notably for spec/lib/eve/api/calls/server_status_spec.rb) so it should be + # disabled when no issues are showing up. +# elsif options[:service] +# raise "Service '#{options[:service]}' specified but API doesn't respond to '#{base}'" else eve_api(options) end
Rails 3 / Ruby <I> compatibility: down to only 6 failures. API is working again -- it's just controller and trust issues, now.
sinisterchipmunk_eve
train
77b879d6bb47814b9a0fae71d8288106e2a2f129
diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/VulnerableSoftware.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/VulnerableSoftware.java index <HASH>..<HASH> 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/VulnerableSoftware.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/VulnerableSoftware.java @@ -73,19 +73,19 @@ public class VulnerableSoftware extends IndexEntry implements Serializable, Comp if (cpeName != null && cpeName.length() > 7) { final String[] data = cpeName.substring(7).split(":"); if (data.length >= 1) { - this.setVendor(URLDecoder.decode(data[0].replace("+", "%2B"), "UTF-8")); //.replaceAll("[_-]", " ") - if (data.length >= 2) { - this.setProduct(URLDecoder.decode(data[1].replace("+", "%2B"), "UTF-8")); //.replaceAll("[_-]", " ") - if (data.length >= 3) { - version = URLDecoder.decode(data[2].replace("+", "%2B"), "UTF-8"); - if (data.length >= 4) { - revision = URLDecoder.decode(data[3].replace("+", "%2B"), "UTF-8"); - if (data.length >= 5) { - edition = URLDecoder.decode(data[4].replace("+", "%2B"), "UTF-8"); - } - } - } - } + this.setVendor(URLDecoder.decode(data[0].replace("+", "%2B"), "UTF-8")); + } + if (data.length >= 2) { + this.setProduct(URLDecoder.decode(data[1].replace("+", "%2B"), "UTF-8")); + } + if (data.length >= 3) { + version = URLDecoder.decode(data[2].replace("+", "%2B"), "UTF-8"); + } + if (data.length >= 4) { + revision = URLDecoder.decode(data[3].replace("+", "%2B"), "UTF-8"); + } + if (data.length >= 5) { + edition = URLDecoder.decode(data[4].replace("+", "%2B"), "UTF-8"); } } }
changed nested ifs to avoid checkstyle complaint Former-commit-id: ed<I>c<I>cf<I>a<I>abdb2ca<I>ef6
jeremylong_DependencyCheck
train
69c2d2df8b90fd02a39e657569ac6b03875e43fd
diff --git a/lib/editor.js b/lib/editor.js index <HASH>..<HASH> 100644 --- a/lib/editor.js +++ b/lib/editor.js @@ -557,6 +557,7 @@ module.exports = { var slug = req.body.slug; var content = req.body.content; var options = req.body.options; + // "OMG, what if they cheat and use a type not allowed for this singleton?" // When they refresh the page they will discover they can't see their hack. // aposSingleton only shows the first item of the specified type, regardless diff --git a/public/js/user.js b/public/js/user.js index <HASH>..<HASH> 100644 --- a/public/js/user.js +++ b/public/js/user.js @@ -84,7 +84,7 @@ apos.enableAreas = function() { }, { slug: slug, - options: $singleton.attr('data-options'), + options: JSON.parse($singleton.attr('data-options') || {}), // By now itemData has been updated (we passed it // into the widget and JavaScript passes objects by reference) content: itemData
Singletons should transmit their options as JSON, not as JSON-of-JSON. Fixes bugs in singleton editing
apostrophecms_apostrophe
train
e101f753417e0b0a0ce8a0af8a9a443df5339aff
diff --git a/bind/einhorn.go b/bind/einhorn.go index <HASH>..<HASH> 100644 --- a/bind/einhorn.go +++ b/bind/einhorn.go @@ -1,4 +1,4 @@ -// +build !windows !appengine +// +build !windows,!appengine package bind diff --git a/bind/systemd.go b/bind/systemd.go index <HASH>..<HASH> 100644 --- a/bind/systemd.go +++ b/bind/systemd.go @@ -1,4 +1,4 @@ -// +build !windows !appengine +// +build !windows,!appengine package bind diff --git a/graceful/einhorn.go b/graceful/einhorn.go index <HASH>..<HASH> 100644 --- a/graceful/einhorn.go +++ b/graceful/einhorn.go @@ -1,4 +1,4 @@ -// +build !windows !appengine +// +build !windows,!appengine package graceful
Boolean logic is hard, guys :( The result of this was that builds were broken on windows and app engine. Fixes #<I>.
zenazn_goji
train
c337b8d933de6f5f854545d2a9ebc949eb2e943e
diff --git a/tests/elements_tests.py b/tests/elements_tests.py index <HASH>..<HASH> 100755 --- a/tests/elements_tests.py +++ b/tests/elements_tests.py @@ -75,3 +75,7 @@ def reverse(seq): s11 = s9.transform(reverse) assert s11[0] == p3 + +s12 = HSeq(p2, p4) + +assert s9 + s12 == HSeq(p1, p3, p2, p4)
wrote more tests for coverage including failing test for buggy HSeq.__eq__
jtauber_sebastian
train
3444cf5c9c0160dae1d38f95ad8083f179184535
diff --git a/src/test/java/com/github/mkolisnyk/aerial/document/FeatureSectionTest.java b/src/test/java/com/github/mkolisnyk/aerial/document/FeatureSectionTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/github/mkolisnyk/aerial/document/FeatureSectionTest.java +++ b/src/test/java/com/github/mkolisnyk/aerial/document/FeatureSectionTest.java @@ -58,6 +58,12 @@ public class FeatureSectionTest { section.validate(); } + @Test(expected = AssertionError.class) + public void testValidateShouldFailOnEmptyCaseName() throws Exception { + section.parse(sampleFeatureText.replace("Sample Case 001", "")); + section.validate(); + } + @Test public void testValidateScenariosSectionIsOptional() throws Exception { section.parse(sampleFeatureText);
#6 Small changes to tests to cover validation cases
mkolisnyk_aerial
train
a9b853c8996b50479f4655f9f66cf0e4e93796ec
diff --git a/lib/protocol/READ_WRITE_MULTIPLE_REGISTERS.js b/lib/protocol/READ_WRITE_MULTIPLE_REGISTERS.js index <HASH>..<HASH> 100644 --- a/lib/protocol/READ_WRITE_MULTIPLE_REGISTERS.js +++ b/lib/protocol/READ_WRITE_MULTIPLE_REGISTERS.js @@ -1,7 +1,7 @@ var Helpers = require("../Helpers"); var Buff = require("../Buffer"); -exports.code = 0x10; +exports.code = 0x17; exports.buildRequest = function (read_address, read_quantity, write_address, values) { var buffer = Buff.alloc(9 + (values.length * 2));
fixes function code for read-write-multiple-registers :(
node-modbus_pdu
train
cba710fe308824f39d53cf4d7be432dd2eedd875
diff --git a/test/lib/Elastica/Test/Aggregation/ScriptTest.php b/test/lib/Elastica/Test/Aggregation/ScriptTest.php index <HASH>..<HASH> 100644 --- a/test/lib/Elastica/Test/Aggregation/ScriptTest.php +++ b/test/lib/Elastica/Test/Aggregation/ScriptTest.php @@ -13,29 +13,29 @@ class ScriptTest extends BaseAggregationTest protected function setUp() { parent::setUp(); - $this->_index = $this->_createIndex( 'script' ); + $this->_index = $this->_createIndex('script'); $docs = array( new Document('1', array('price' => 5)), new Document('2', array('price' => 8)), new Document('3', array('price' => 1)), new Document('4', array('price' => 3)), ); - $this->_index->getType( 'test' )->addDocuments( $docs ); + $this->_index->getType('test')->addDocuments($docs); $this->_index->refresh(); } public function testAggregationScript() { - $agg = new Sum( "sum" ); + $agg = new Sum("sum"); // x = (0..1) is groovy-specific syntax, to see if lang is recognized - $script = new Script( "x = (0..1); return doc['price'].value", null, "groovy" ); - $agg->setScript( $script ); + $script = new Script("x = (0..1); return doc['price'].value", null, "groovy"); + $agg->setScript($script); $query = new Query(); - $query->addAggregation( $agg ); - $results = $this->_index->search( $query )->getAggregation( "sum" ); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("sum"); - $this->assertEquals( 5 + 8 + 1 + 3, $results['value'] ); + $this->assertEquals(5 + 8 + 1 + 3, $results['value']); } public function testSetScript() { @@ -47,9 +47,9 @@ class ScriptTest extends BaseAggregationTest ); $lang = "groovy"; - $agg = new Sum( $aggregation ); - $script = new Script( $string, $params, $lang ); - $agg->setScript( $script ); + $agg = new Sum($aggregation); + $script = new Script($string, $params, $lang); + $agg->setScript($script); $array = $agg->toArray();
Get rid of auto-formatted MediaWiki-like coding standards MediaWiki has spaces around parentheses & my IDE auto-formats source like that. Obviously, don't want this here.
ruflin_Elastica
train
b4707b395334b50be6d4635671353f66b7f5f40c
diff --git a/smr/ec2.py b/smr/ec2.py index <HASH>..<HASH> 100755 --- a/smr/ec2.py +++ b/smr/ec2.py @@ -28,10 +28,15 @@ def worker_thread(config, config_name, input_queue, output_queue, processed_file abort_event.set() return + remote_config_path = "/tmp/smr_config.py" + sftp = ssh.open_sftp() + sftp.put(config_name, remote_config_path) + sftp.close() + while not abort_event.is_set(): try: file_name = input_queue.get(timeout=2) - stdin, stdout, stderr = ssh.exec_command("smr-map %s" % config_name) + stdin, stdout, stderr = ssh.exec_command("smr-map %s" % remote_config_path) stdin.write("%s" % file_name) stdin.close() for line in stdout:
need to copy config to remote servers
50onRed_smr
train
ca39d358359b463d269c12b099c7f5c32ce68bb3
diff --git a/src/main/java/com/github/bedrin/jdbc/sniffer/util/ExceptionUtil.java b/src/main/java/com/github/bedrin/jdbc/sniffer/util/ExceptionUtil.java index <HASH>..<HASH> 100755 --- a/src/main/java/com/github/bedrin/jdbc/sniffer/util/ExceptionUtil.java +++ b/src/main/java/com/github/bedrin/jdbc/sniffer/util/ExceptionUtil.java @@ -1,5 +1,6 @@ package com.github.bedrin.jdbc.sniffer.util; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -25,6 +26,27 @@ public class ExceptionUtil { } } + public static boolean throwException(String className, String message) { + try { + Class<Throwable> throwableClass = (Class<Throwable>)Class.forName(className); + Constructor<Throwable> constructor = throwableClass.getConstructor(String.class); + Throwable throwable = constructor.newInstance(message); + throwException(throwable); + return true; + } catch (ClassNotFoundException e) { + return false; + } catch (NoSuchMethodException e) { + return false; + } catch (InvocationTargetException e) { + return false; + } catch (InstantiationException e) { + return false; + } catch (IllegalAccessException e) { + return false; + } + } + + public static void throwException(Throwable e) { ExceptionUtil.<RuntimeException>throwAny(e); }
throw exception by given class name and message
sniffy_sniffy
train
d243e403d7878f1cc280edc0074560673c77c436
diff --git a/src/Illuminate/Cookie/Middleware/EncryptCookies.php b/src/Illuminate/Cookie/Middleware/EncryptCookies.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Cookie/Middleware/EncryptCookies.php +++ b/src/Illuminate/Cookie/Middleware/EncryptCookies.php @@ -76,7 +76,7 @@ class EncryptCookies protected function decrypt(Request $request) { foreach ($request->cookies as $key => $cookie) { - if ($this->isDisabled($key)) { + if ($this->isDisabled($key) || is_array($cookie)) { continue; }
[8.x] Remove decrypting array cookies (#<I>) * Remove decrypting array cookies * Revert back the methods only * Update EncryptCookies.php * Update EncryptCookies.php
laravel_framework
train
7a05d12cf12e81e71b87d40523608703d88f5023
diff --git a/plenum/test/test_node.py b/plenum/test/test_node.py index <HASH>..<HASH> 100644 --- a/plenum/test/test_node.py +++ b/plenum/test/test_node.py @@ -863,6 +863,9 @@ def checkProtocolInstanceSetup(looper: Looper, customTimeout: float = None, instances: Sequence[int] = None, check_primaries=True): + def check(nodes): + assert all([not n.master_replica._consensus_data.waiting_for_new_view for n in nodes]) + timeout = customTimeout or waits.expectedPoolElectionTimeout(len(nodes)) checkEveryProtocolInstanceHasOnlyOnePrimary(looper=looper, @@ -875,7 +878,8 @@ def checkProtocolInstanceSetup(looper: Looper, nodes=nodes, retryWait=retryWait, customTimeout=timeout) - assert all([not n.master_replica._consensus_data.waiting_for_new_view for n in nodes]) + + looper.run(eventually(check, nodes)) if check_primaries: for n in nodes[1:]: diff --git a/plenum/test/view_change_service/test_view_change_triggered.py b/plenum/test/view_change_service/test_view_change_triggered.py index <HASH>..<HASH> 100644 --- a/plenum/test/view_change_service/test_view_change_triggered.py +++ b/plenum/test/view_change_service/test_view_change_triggered.py @@ -1,5 +1,8 @@ +import pytest + from plenum.common.messages.internal_messages import NeedViewChange from plenum.common.util import getMaxFailures +from plenum.server.consensus.ordering_service_msg_validator import OrderingServiceMsgValidator from plenum.server.consensus.primary_selector import RoundRobinPrimariesSelector from plenum.test.helper import checkViewNoForNodes, sdk_send_random_and_check from plenum.test.pool_transactions.helper import disconnect_node_and_ensure_disconnected @@ -9,6 +12,14 @@ from plenum.test.test_node import ensureElectionsDone REQ_COUNT = 10 [email protected](scope="module") +def txnPoolNodeSet(txnPoolNodeSet): + for n in txnPoolNodeSet: + for r in n.replicas.values(): + r._ordering_service._validator = OrderingServiceMsgValidator(r._consensus_data) + return txnPoolNodeSet + + def trigger_view_change(txnPoolNodeSet, proposed_view_no): for n in txnPoolNodeSet: for r in n.replicas.values(): @@ -37,6 +48,7 @@ def test_view_change_triggered_after_ordering(looper, txnPoolNodeSet, sdk_pool_h ensureElectionsDone(looper, txnPoolNodeSet) [email protected](reason="not working now") def test_stopping_next_primary(looper, txnPoolNodeSet): old_view_no = checkViewNoForNodes(txnPoolNodeSet) next_primary = get_next_primary_name(txnPoolNodeSet, old_view_no + 1)
[INDY-<I>] integrate new ordering validator for tests with new view_change
hyperledger_indy-plenum
train
6b82c9ab6ae5cdf19986c6d45f4de23c0f55b74c
diff --git a/project/geomajas-project-sld-editor/common-gwt/src/main/java/org/geomajas/sld/editor/client/SldUtils.java b/project/geomajas-project-sld-editor/common-gwt/src/main/java/org/geomajas/sld/editor/client/SldUtils.java index <HASH>..<HASH> 100644 --- a/project/geomajas-project-sld-editor/common-gwt/src/main/java/org/geomajas/sld/editor/client/SldUtils.java +++ b/project/geomajas-project-sld-editor/common-gwt/src/main/java/org/geomajas/sld/editor/client/SldUtils.java @@ -13,12 +13,15 @@ package org.geomajas.sld.editor.client; import java.util.ArrayList; import java.util.List; +import org.geomajas.sld.FeatureTypeStyleInfo; import org.geomajas.sld.GraphicInfo; import org.geomajas.sld.PolygonSymbolizerInfo; import org.geomajas.sld.RuleInfo; import org.geomajas.sld.SymbolizerTypeInfo; import org.geomajas.sld.LineSymbolizerInfo; import org.geomajas.sld.PointSymbolizerInfo; +import org.geomajas.sld.client.model.RuleGroup; +import org.geomajas.sld.client.model.RuleModel; import com.google.gwt.core.client.GWT; @@ -94,4 +97,21 @@ public final class SldUtils { } + public static GeometryType GetGeometryType(List<FeatureTypeStyleInfo> featureTypeStyleList) { + + GeometryType geometryType = GeometryType.UNSPECIFIED; + + if (null == featureTypeStyleList || featureTypeStyleList.size() == 0) { + return GeometryType.UNSPECIFIED; // ABORT + } + + FeatureTypeStyleInfo featureTypeStyle = featureTypeStyleList.iterator().next(); //retrieve the first + // <FeatureTypeStyle> element (which contains 1 list of rules) + + if (null != featureTypeStyle && featureTypeStyle.getRuleList().size() >= 1) { + RuleInfo rule = featureTypeStyle.getRuleList().iterator().next(); //retrieve the first rule + geometryType = GetGeometryType(rule); + } + return geometryType; + } }
Intermediate commit for work on SLDE-4: GetGeometryType from featureTypeStyleList
geomajas_geomajas-project-server
train
02bbbfcf8411018ed2df7f84767d863f4e7c86b2
diff --git a/packages/ember-handlebars/lib/loader.js b/packages/ember-handlebars/lib/loader.js index <HASH>..<HASH> 100644 --- a/packages/ember-handlebars/lib/loader.js +++ b/packages/ember-handlebars/lib/loader.js @@ -33,6 +33,9 @@ Ember.Handlebars.bootstrap = function(ctx) { var compile = (script.attr('type') === 'text/x-raw-handlebars') ? Ember.$.proxy(Handlebars.compile, Handlebars) : Ember.$.proxy(Ember.Handlebars.compile, Ember.Handlebars), + // Get the id of the script, used by Ember.View's elementId property, + // Look for data-element-id attribute. + elementId = script.attr('data-element-id'), // Get the name of the script, used by Ember.View's templateName property. // First look for data-template-name attribute, then fall back to its // id if no name is found. @@ -68,6 +71,7 @@ Ember.Handlebars.bootstrap = function(ctx) { tagName = script.attr('data-tag-name'); view = view.create({ + elementId: elementId, template: template, tagName: (tagName) ? tagName : undefined }); diff --git a/packages/ember-handlebars/tests/loader_test.js b/packages/ember-handlebars/tests/loader_test.js index <HASH>..<HASH> 100644 --- a/packages/ember-handlebars/tests/loader_test.js +++ b/packages/ember-handlebars/tests/loader_test.js @@ -64,4 +64,13 @@ test('template with data-tag-name should add a template, wrapped in specific tag equal(Ember.$('#qunit-fixture h1').text(), 'Tobias takes teamocil', 'template is rendered inside custom tag'); }); +test('template with data-element-id should add an id attribute to the view', function() { + Ember.$('#qunit-fixture').html('<script type="text/x-handlebars" data-element-id="application">Hello World !</script>'); + + Ember.run(function() { + Ember.Handlebars.bootstrap(Ember.$('#qunit-fixture')); + }); + + equal(Ember.$('#qunit-fixture').html(), '<div id="application" class="ember-view">Hello World !</div>', 'id attribute has been added to the view'); +}); // TODO: Text x-raw-handlebars
add "elementId" support with "data-element-id" attribute in "script" tag of handlebars type at handlebars bootstrap
emberjs_ember.js
train
6f99f29d28e7c0e5d2205610610cf0b382903851
diff --git a/generators/generator-constants.js b/generators/generator-constants.js index <HASH>..<HASH> 100644 --- a/generators/generator-constants.js +++ b/generators/generator-constants.js @@ -18,7 +18,7 @@ */ // version of docker images -const DOCKER_JHIPSTER_REGISTRY = 'jhipster/jhipster-registry:v2.6.0'; +const DOCKER_JHIPSTER_REGISTRY = 'jhipster/jhipster-registry:v3.0.0'; const DOCKER_JAVA_JRE = 'openjdk:8-jre-alpine'; const DOCKER_MYSQL = 'mysql:5.7.13'; // mysql.5.7.14+ doesn't work well with zoned date time, see https://github.com/jhipster/generator-jhipster/pull/4038 const DOCKER_MARIADB = 'mariadb:10.1.17';
Upgrade to JHipster Registry <I>
jhipster_generator-jhipster
train
968a5d6c2edd99b0e9b1ecca0e9b4d8f98682b76
diff --git a/src/Blob/Internal/IBlob.php b/src/Blob/Internal/IBlob.php index <HASH>..<HASH> 100644 --- a/src/Blob/Internal/IBlob.php +++ b/src/Blob/Internal/IBlob.php @@ -67,7 +67,7 @@ interface IBlob extends FilterableService * * @param Models\ListContainersOptions $options optional parameters * - * @return MicrosoftAzure\Storage\Blob\Models\ListContainersResult + * @return \MicrosoftAzure\Storage\Blob\Models\ListContainersResult * * @see http://msdn.microsoft.com/en-us/library/windowsazure/dd179352.aspx */
a minor change in IBlob documentation
Azure_azure-storage-php
train
89b00c8bdba29bba7594c86e3a5ef7309ba1d988
diff --git a/devicecloud/filedata.py b/devicecloud/filedata.py index <HASH>..<HASH> 100644 --- a/devicecloud/filedata.py +++ b/devicecloud/filedata.py @@ -44,6 +44,7 @@ class FileDataAPI(APIBase): page_size = validate_type(page_size, *six.integer_types) # TODO: implementing paging over the result set + # TODO: page_size is unused currently if condition is None: condition = (fd_path == "~/") # home directory response = self._conn.get_json( @@ -51,17 +52,15 @@ class FileDataAPI(APIBase): condition=condition.compile()) ) - objects = [] for fd_json in response.get("items", []): - objects.append(FileDataObject.from_json(self, fd_json)) - return objects + yield FileDataObject.from_json(self, fd_json) def write_file(self, path, name, data, content_type=None, archive=False): path = validate_type(path, *six.string_types) name = validate_type(name, *six.string_types) data = validate_type(data, six.binary_type) content_type = validate_type(content_type, type(None), *six.string_types) - archive = validate_type(archive, bool) + archive_str = "true" if validate_type(archive, bool) else "false" if not path.startswith("/"): path = "/" + path @@ -80,12 +79,12 @@ class FileDataAPI(APIBase): sio.write("<fdContentType>{}</fdContentType>".format(content_type)) sio.write("<fdType>file</fdType>") sio.write("<fdData>{}</fdData>".format(base64_encoded_data)) - sio.write("<fdArchive>{}</fdArchive>".format("true" if archive else "false")) + sio.write("<fdArchive>{}</fdArchive>".format(archive_str)) sio.write("</FileData>") params = { "type": "file", - "archive": "true" if archive else "false" + "archive": archive_str } self._conn.put( "/ws/FileData{path}{name}".format(path=path,name=name), @@ -182,7 +181,7 @@ class FileDataObject(object): class FileDataDirectory(FileDataObject): - """Provide access to a directory and its metadata in the filedata store""" + """Provide access to a directory and its metadata in the filedata store""" @classmethod def from_json(cls, fdapi, json_data): diff --git a/devicecloud/test/test_filedata.py b/devicecloud/test/test_filedata.py index <HASH>..<HASH> 100644 --- a/devicecloud/test/test_filedata.py +++ b/devicecloud/test/test_filedata.py @@ -65,7 +65,7 @@ class TestFileData(HttpTestBase): def test_get_filedata_simple(self): self.prepare_response("GET", "/ws/FileData", GET_FILEDATA_SIMPLE) - objects = self.dc.filedata.get_filedata() + objects = list(self.dc.filedata.get_filedata()) self.assertEqual(len(objects), 2) def test_write_file_simple(self): @@ -127,7 +127,7 @@ class TestFileDataObject(HttpTestBase): def test_file_metadata_access(self): self.prepare_response("GET", "/ws/FileData", GET_FILEDATA_SIMPLE) - objects = self.dc.filedata.get_filedata() + objects = list(self.dc.filedata.get_filedata()) self.assertEqual(len(objects), 2) obj = objects[0] self.assertEqual(obj.get_path(), "/db/blah/") @@ -145,7 +145,7 @@ class TestFileDataObject(HttpTestBase): def test_directory_metadata_access(self): self.prepare_response("GET", "/ws/FileData", GET_FILEDATA_SIMPLE) - objects = self.dc.filedata.get_filedata() + objects = list(self.dc.filedata.get_filedata()) self.assertEqual(len(objects), 2) obj = objects[1] self.assertEqual(obj.get_path(), "/db/blah/") diff --git a/docs/filedata.rst b/docs/filedata.rst index <HASH>..<HASH> 100644 --- a/docs/filedata.rst +++ b/docs/filedata.rst @@ -32,7 +32,7 @@ Method 1: Iterate through the file tree by getting the filedata objects associated with paths or other conditions:: condtion = (fd_path == '~/') - for filedata in dc.filedata.get_filedata(fd_path == '~/'): + for filedata in dc.filedata.get_filedata(condition): print filedata The :meth:`.FileDataAPI.get_filedata` method will return a generator @@ -99,7 +99,7 @@ There are three ways to create a new directory: all directories should be created recursively. 3. By calling :meth:`.FileDataDirectory.add_subdirectory` -Different methods may suit your needs depending on your usse cases. +Different methods may suit your needs depending on your use cases. Writing a File ~~~~~~~~~~~~~~
PYTHONDC-6: Minor fixes and updates based on code review The changes here are as follows: * Typo fixes and clarifications to documentation * Modify get_filedata() to return a generator rather than a list
digidotcom_python-devicecloud
train
ff1f318f6f359e3b37123c4794cf8630df15880b
diff --git a/test/unit/test-adapter.js b/test/unit/test-adapter.js index <HASH>..<HASH> 100644 --- a/test/unit/test-adapter.js +++ b/test/unit/test-adapter.js @@ -278,11 +278,23 @@ describe('SlackMessageAdapter', function () { this.adapter.action(constraints, this.actionHandler); assertHandlerRegistered(this.adapter, this.actionHandler, constraints); }); - it('should fail with an invalid blockId', function () { - // Number is not a valid constraint - var constraints = { blockId: 10 }; + it('invalid block_id types throw on registration', function () { + var handler = this.handler; + var adapter = this.adapter; + assert.throws(function () { + adapter.action({ blockId: 5 }, handler); + }, TypeError); + assert.throws(function () { + adapter.action({ blockId: true }, handler); + }, TypeError); + assert.throws(function () { + adapter.action({ blockId: [] }, handler); + }, TypeError); + assert.throws(function () { + adapter.action({ blockId: null }, handler); + }, TypeError); assert.throws(function () { - this.adapter.action(constraints, this.actionHandler); + adapter.action({ blockId: undefined }, handler); }, TypeError); }); it('should register with actionId constraints successfully', function () { @@ -290,11 +302,23 @@ describe('SlackMessageAdapter', function () { this.adapter.action(constraints, this.actionHandler); assertHandlerRegistered(this.adapter, this.actionHandler, constraints); }); - it('should fail with an invalid actionId', function () { - // Boolean is not a valid constraint - var constraints = { actionId: false }; + it('invalid action_id types throw on registration', function () { + var handler = this.handler; + var adapter = this.adapter; + assert.throws(function () { + adapter.action({ actionId: 5 }, handler); + }, TypeError); + assert.throws(function () { + adapter.action({ actionId: true }, handler); + }, TypeError); + assert.throws(function () { + adapter.action({ actionId: [] }, handler); + }, TypeError); + assert.throws(function () { + adapter.action({ actionId: null }, handler); + }, TypeError); assert.throws(function () { - this.adapter.action(constraints, this.actionHandler); + adapter.action({ actionId: undefined }, handler); }, TypeError); }); it('should register with compound block constraints successfully', function () {
Add more types to validationConstraints for blockId and actionId
slackapi_node-slack-interactive-messages
train
d7fc2514c5208dfdf52c52709fc2682613af0784
diff --git a/src/net/dv8tion/jda/entities/Guild.java b/src/net/dv8tion/jda/entities/Guild.java index <HASH>..<HASH> 100644 --- a/src/net/dv8tion/jda/entities/Guild.java +++ b/src/net/dv8tion/jda/entities/Guild.java @@ -93,6 +93,14 @@ public interface Guild Region getRegion(); /** + * The {@link net.dv8tion.jda.entites.User Users} that are part of this {@link net.dv8tion.jda.entites.Guild Guild}. + * + * @return + * An Immutable List of {@link net.dv8tion.jda.entites.User Users}. + */ + List<User> getUsers(); + + /** * The {@link net.dv8tion.jda.entites.TextChannel TextChannels} available on the {@link net.dv8tion.jda.entites.Guild Guild}. * * @return diff --git a/src/net/dv8tion/jda/entities/impl/GuildImpl.java b/src/net/dv8tion/jda/entities/impl/GuildImpl.java index <HASH>..<HASH> 100644 --- a/src/net/dv8tion/jda/entities/impl/GuildImpl.java +++ b/src/net/dv8tion/jda/entities/impl/GuildImpl.java @@ -87,6 +87,13 @@ public class GuildImpl implements Guild return region; } + @Override + public List<User> getUsers() + { + List<User> list = new ArrayList<>(); + list.addAll(userRoles.keySet()); + return Collections.unmodifiableList(list); + } @Override public List<TextChannel> getTextChannels()
A Guild should know what Users are in it!
DV8FromTheWorld_JDA
train
868d3c1e7172d863aba9acbee72a01e9e9171546
diff --git a/src/Middleware/FinishMiddleware.php b/src/Middleware/FinishMiddleware.php index <HASH>..<HASH> 100644 --- a/src/Middleware/FinishMiddleware.php +++ b/src/Middleware/FinishMiddleware.php @@ -2,9 +2,8 @@ namespace CybozuHttp\Middleware; -use GuzzleHttp\Exception\ClientException; +use CybozuHttp\Service\ResponseService; use GuzzleHttp\Exception\RequestException; -use GuzzleHttp\Exception\ServerException; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -41,8 +40,9 @@ class FinishMiddleware */ private function onFulfilled(RequestInterface $request): callable { - return function (ResponseInterface $response) { - if (self::isJsonResponse($response)) { + return function (ResponseInterface $response) use ($request) { + $service = new ResponseService($request, $response); + if ($service->isJsonResponse()) { return $response->withBody(new JsonStream($response->getBody())); } return $response; @@ -64,122 +64,14 @@ class FinishMiddleware if ($response === null || $response->getStatusCode() < 300) { return $reason; } - if (self::isJsonResponse($response)) { - self::jsonError($request, $response); + $service = new ResponseService($request, $response); + if ($service->isJsonResponse()) { + $service->handleJsonError(); } else { - self::domError($request, $response); + $service->handleDomError(); } return $reason; }; } - - /** - * @param ResponseInterface $response - * @return bool - */ - private static function isJsonResponse(ResponseInterface $response): bool - { - $contentType = $response->getHeader('Content-Type'); - $contentType = is_array($contentType) && isset($contentType[0]) ? $contentType[0] : $contentType; - - return is_string($contentType) && strpos($contentType, 'application/json') === 0; - } - - - /** - * @param RequestInterface $request - * @param ResponseInterface $response - * @throws RequestException - */ - private static function domError(RequestInterface $request, ResponseInterface $response): void - { - $body = (string)$response->getBody()->getContents(); - $dom = new \DOMDocument('1.0', 'UTF-8'); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - $dom->loadHTML($body); - if ($dom->loadHTML($body)) { - $title = $dom->getElementsByTagName('title'); - if (is_object($title)) { - $title = $title->item(0)->nodeValue; - } - if ($title === 'Error') { - $message = $dom->getElementsByTagName('h3')->item(0)->nodeValue; - throw self::createException($message, $request, $response); - } - if ($title === 'Unauthorized') { - $message = $dom->getElementsByTagName('h2')->item(0)->nodeValue; - throw self::createException($message, $request, $response); - } - - throw self::createException('Invalid auth.', $request, $response); - } - } - - /** - * @param RequestInterface $request - * @param ResponseInterface $response - * @throws RequestException - */ - private static function jsonError(RequestInterface $request, ResponseInterface $response): void - { - try { - $body = (string)$response->getBody(); - $json = \GuzzleHttp\json_decode($body, true); - } catch (\InvalidArgumentException $e) { - return; - } catch (\RuntimeException $e) { - return; - } - - $message = $json['message']; - if (isset($json['errors']) && is_array($json['errors'])) { - $message .= self::addErrorMessages($json['errors']); - } - - throw self::createException($message, $request, $response); - } - - /** - * @param array $errors - * @return string - */ - private static function addErrorMessages(array $errors): string - { - $message = ' ('; - foreach ($errors as $k => $err) { - $message .= $k . ' : '; - if (is_array($err['messages'])) { - foreach ($err['messages'] as $m) { - $message .= $m . ' '; - } - } else { - $message .= $err['messages']; - } - } - $message .= ' )'; - - return $message; - } - - /** - * @param string $message - * @param RequestInterface $request - * @param ResponseInterface|null $response - * @return RequestException - */ - private static function createException($message, RequestInterface $request, ResponseInterface $response): RequestException - { - $level = (int) floor($response->getStatusCode() / 100); - $className = RequestException::class; - - if ($level === 4) { - $className = ClientException::class; - } elseif ($level === 5) { - $className = ServerException::class; - } - - return new $className($message, $request, $response); - } }
Use ResponseService in FinishMiddleware
ochi51_cybozu-http
train
93e625b55739842284a20e36fafecc4aa2c8f7fa
diff --git a/content.py b/content.py index <HASH>..<HASH> 100644 --- a/content.py +++ b/content.py @@ -217,6 +217,7 @@ class OPSContent(object): #proper format tags self.divTitleScan(mainbody, depth = 0) + #Handle conversion of figures to html image format figs = mainbody.getElementsByTagName('fig') for item in figs: parent = item.parentNode @@ -247,6 +248,54 @@ class OPSContent(object): parent.removeChild(item) + #Handle conversion of <table-wrap> to html image with reference to + #external file containing original html table + tables = mainbody.getElementsByTagName('table-wrap') + for item in tables: + parent = item.parentNode + sibling = item.nextSibling + table_id = item.getAttribute('id') + label = item.getElementsByTagName('label') + label_text = utils.getTagData(label) + title = item.getElementsByTagName('title') + title_text = utils.getTagData(title) + #Create a Table Label, includes label and title, place before the image + table_label = main.createElement('div') + table_label.setAttribute('class', 'table_label') + table_label.setAttribute('id', table_id) + table_label_b = main.createElement('b') + table_label_b.appendChild(main.createTextNode(label_text)) + table_label.appendChild(table_label_b) + table_label.appendChild(main.createTextNode(title_text)) + parent.insertBefore(table_label, sibling) + + name = table_id.split('-')[-1] + + img = None + startpath = os.path.abspath('./') + os.chdir(self.outdir) + for path, _subdirs, filenames in os.walk('images'): + for filename in filenames: + if os.path.splitext(filename)[0] == name: + img = os.path.join(path, filename) + os.chdir(startpath) + #Create and insert the img node before the table-wrap node's sibling + imgnode = main.createElement('img') + imgnode.setAttribute('src', img) + parent.insertBefore(imgnode, sibling) + #Handle the HTML version of the table + try: + html_table = item.getElementsByTagName('table')[0] + link = main.createElement('a') + link.setAttribute('href', 'tables.html#{0}'.format(table_id)) + link.appendChild(main.createTextNode('HTML version of {0}'.format(label_text))) + parent.insertBefore(link , sibling) + except: + pass + + parent.removeChild(item) + + #Need to intelligently handle conversion of <xref> elements xrefs = mainbody.getElementsByTagName('xref') for elem in xrefs:
Added support in content.py for handling table-wrap elements. This provides table images in the text, with a link to a to-be-implemented HTML file containing the HTML versions of tables.
SavinaRoja_OpenAccess_EPUB
train
7fa0d815547c6c003c8f92159ec789f065ebfacf
diff --git a/src/Command/UpdateValueCommand.php b/src/Command/UpdateValueCommand.php index <HASH>..<HASH> 100644 --- a/src/Command/UpdateValueCommand.php +++ b/src/Command/UpdateValueCommand.php @@ -53,7 +53,7 @@ class UpdateValueCommand extends CommandBase $key = $input->getArgument('key'); $value = $input->getArgument('value'); $yaml_parsed = $this->loadYamlFile($filename); - if ($yaml_parsed !== FALSE) { + if ($yaml_parsed === false) { // Exit with a status of 1. return 1; }
Oops. Inverting conditional.
grasmash_yaml-cli
train
e6acb805a1c7629bd8655ac0e2b88a4e004a12f1
diff --git a/ngram.py b/ngram.py index <HASH>..<HASH> 100644 --- a/ngram.py +++ b/ngram.py @@ -240,7 +240,7 @@ class NGram(set): if item in self: super(NGram, self).remove(item) del self.length[item] - for ngram in self.splititem(item): + for ngram in set(self.splititem(item)): del self._grams[ngram][item] def pop(self): @@ -254,7 +254,7 @@ class NGram(set): """ item = super(NGram, self).pop() del self.length[item] - for ngram in self.splititem(item): + for ngram in set(self.splititem(item)): del self._grams[ngram][item] return item
Remove duplicates prior to removal of ngrams
gpoulter_python-ngram
train
d133fbd88a338a9bc697376bf05ceb0b0e40adb4
diff --git a/lib/beetle/subscriber.rb b/lib/beetle/subscriber.rb index <HASH>..<HASH> 100644 --- a/lib/beetle/subscriber.rb +++ b/lib/beetle/subscriber.rb @@ -217,7 +217,8 @@ module Beetle { :host => current_host, :port => current_port, :logging => false, :user => @client.config.user, :pass => @client.config.password, :vhost => @client.config.vhost, - :on_tcp_connection_failure => on_tcp_connection_failure + :on_tcp_connection_failure => on_tcp_connection_failure, + :on_possible_authentication_failure => on_possible_authentication_failure, } end @@ -228,6 +229,13 @@ module Beetle end end + def on_possible_authentication_failure + Proc.new do |settings| + logger.error "Beetle: possible authentication failure, or server overloaded: #{server_from_settings(settings)}. shutting down!" + stop! + end + end + def on_tcp_connection_loss(connection, settings) # reconnect in 10 seconds, without enforcement logger.warn "Beetle: lost connection: #{server_from_settings(settings)}. reconnecting." diff --git a/test/beetle/subscriber_test.rb b/test/beetle/subscriber_test.rb index <HASH>..<HASH> 100644 --- a/test/beetle/subscriber_test.rb +++ b/test/beetle/subscriber_test.rb @@ -428,6 +428,13 @@ module Beetle cb.call(@settings) end + test "possible authentication failure causes subscriber to exit" do + cb = @sub.send(:on_possible_authentication_failure) + @sub.expects(:stop!) + @sub.logger.expects(:error).with("Beetle: possible authentication failure, or server overloaded: mickey:42. shutting down!") + cb.call({:host => "mickey", :port => 42}) + end + test "tcp connection loss handler tries to reconnect" do connection = mock("connection") connection.expects(:reconnect).with(false, 10)
Subscriber exits properly on possible authentication failures.
xing_beetle
train
aa94d9d57c8fd267f3e108a4ed8f2a944d670776
diff --git a/lib/fog/vcloud_director/requests/compute/post_configure_edge_gateway_services.rb b/lib/fog/vcloud_director/requests/compute/post_configure_edge_gateway_services.rb index <HASH>..<HASH> 100644 --- a/lib/fog/vcloud_director/requests/compute/post_configure_edge_gateway_services.rb +++ b/lib/fog/vcloud_director/requests/compute/post_configure_edge_gateway_services.rb @@ -42,8 +42,26 @@ module Fog "No access to entity \"(com.vmware.vcloud.entity.edgegateway:#{id})\"." ) end - data[:edge_gateways][id][:Configuration][:EdgeGatewayServiceConfiguration] = configuration - Excon::Response.new(:body => {:name => 'mock_task', :href => '/10000000000000000000000000000000' }) + + owner = {:href => '', :name => nil, :type => nil} #known-bug: admin-api does not return owner. + task_id = enqueue_task( + "Configuring edgegateway(#{id})", 'networkConfigureEdgeGatewayServices', owner, + :on_success => lambda do + data[:edge_gateways][id][:Configuration][:EdgeGatewayServiceConfiguration] = configuration + end + ) + + body = { + :xmlns => xmlns, + :xmlns_xsi => xmlns_xsi, + :xsi_schemaLocation => xsi_schema_location, + }.merge(task_body(task_id)) + + Excon::Response.new( + :status => 202, + :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, + :body => body + ) end end end diff --git a/tests/vcloud_director/requests/compute/edge_gateway_tests.rb b/tests/vcloud_director/requests/compute/edge_gateway_tests.rb index <HASH>..<HASH> 100644 --- a/tests/vcloud_director/requests/compute/edge_gateway_tests.rb +++ b/tests/vcloud_director/requests/compute/edge_gateway_tests.rb @@ -66,7 +66,7 @@ Shindo.tests('Compute::VcloudDirector | edge gateway requests', ['vclouddirector raise('fail fast if our test firewall rule already exists - its likely left over from a broken test run') if rule response = @service.post_configure_edge_gateway_services(@edge_gateway_id, @new_edge_gateway_configuration) - @service.process_task(response.body) unless Fog.mocking? + @service.process_task(response.body) tests('#check for new firewall rule').returns(@new_edge_gateway_configuration[:FirewallService][:FirewallRule]) do edge_gateway = @service.get_edge_gateway(@edge_gateway_id).body @@ -76,7 +76,7 @@ Shindo.tests('Compute::VcloudDirector | edge gateway requests', ['vclouddirector tests('#remove the firewall rule added by test').returns(nil) do response = @service.post_configure_edge_gateway_services(@edge_gateway_id, @orginal_gateway_conf[:Configuration][:EdgeGatewayServiceConfiguration]) - @service.process_task(response.body) unless Fog.mocking? + @service.process_task(response.body) edge_gateway = @service.get_edge_gateway(@edge_gateway_id).body edge_gateway[:Configuration][:EdgeGatewayServiceConfiguration][:FirewallService][:FirewallRule].find { |rule| rule[:Id] == FIREWALL_RULE_ID } end
using new way of task mocking for edgegateway tests
fog_fog
train
f5da262c44fb836c308b670ea2c939e74bb97ff3
diff --git a/library/VF/SearchLevel.php b/library/VF/SearchLevel.php index <HASH>..<HASH> 100755 --- a/library/VF/SearchLevel.php +++ b/library/VF/SearchLevel.php @@ -1,6 +1,7 @@ <?php /** * Vehicle Fits (http://www.vehiclefits.com for more information.) + * * @copyright Copyright (c) Vehicle Fits, llc * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ @@ -17,16 +18,21 @@ class VF_SearchLevel implements VF_Configurable /** * Display a select box, pre-populated with values if its the first, or if there's a prev. selection. * - * @param $searchForm VF_SearchForm - * @param $level string name of the level being displayed (ex. "Model") - * @param bool $prevLevel name of the level preceeding this one (ex. "Make", or false if none) + * @param $searchForm VF_SearchForm + * @param $level string name of the level being displayed (ex. "Model") + * @param bool $prevLevel name of the level preceeding this one (ex. "Make", or false if none) * @param null $displayBrTag boolean wether to print a <br /> between the select boxes. * @param null $yearRangeAlias * * @return string The rendered HTML for this select box. */ - function display(VF_SearchForm $searchForm, $level, $prevLevel = false, $displayBrTag = null, $yearRangeAlias = null) - { + function display( + VF_SearchForm $searchForm, + $level, + $prevLevel = false, + $displayBrTag = null, + $yearRangeAlias = null + ) { $this->displayBrTag = $displayBrTag; $this->searchForm = $searchForm; $this->level = $level; @@ -52,13 +58,17 @@ class VF_SearchLevel implements VF_Configurable <?php foreach ($this->getEntities() as $entity) { /** @var VF_Level $entity */ - if($this->getConfig()->search->legacyNumericSearch): - ?> - <option - value="<?= $entity->getId() ?>" <?= ($this->isLevelSelected($entity) ? ' selected="selected"' : '') ?>><?= $entity->getTitle() ?></option> + if ($this->getConfig()->search->legacyNumericSearch): + ?> + <option + value="<?= $entity->getId() ?>" <?= + ($this->isLevelSelected($entity) ? ' selected="selected"' : '') ?>><?= $entity->getTitle( + ) ?></option> <?php else: ?> <option - value="<?= $entity->getTitle() ?>" <?= ($this->isLevelSelected($entity) ? ' selected="selected"' : '') ?>><?= $entity->getTitle() ?></option> + value="<?= $entity->getTitle() ?>" <?= + ($this->isLevelSelected($entity) ? ' selected="selected"' : '') ?>><?= $entity->getTitle( + ) ?></option> <?php endif; ?> <?php @@ -87,7 +97,9 @@ class VF_SearchLevel implements VF_Configurable /** * Check if an entity is the selected one for this 'level' + * * @param VF_Level $levelObject - level to check if is selected + * * @return bool if this is the one that is supposed to be currently selected */ function isLevelSelected($levelObject) @@ -96,16 +108,25 @@ class VF_SearchLevel implements VF_Configurable return (bool)($levelObject->getId() == $this->searchForm->getSelected($this->level)); } VF_Singleton::getInstance()->setRequest($this->searchForm->getRequest()); - $currentSelection = VF_Singleton::getInstance()->getFirstCurrentlySelectedFitment(); - if (false === $currentSelection || count($currentSelection) == 0) { + $currentSelection = VF_Singleton::getInstance()->vehicleSelection(); + if (false === $currentSelection) { return false; } if ('year_start' == $this->yearRangeAlias) { return (bool)($levelObject->getTitle() == $this->earliestYearInVehicles($currentSelection)); - } else if ('year_end' == $this->yearRangeAlias) { - return (bool)($levelObject->getTitle() == $this->latestYearInVehicles($currentSelection)); + } else { + if ('year_end' == $this->yearRangeAlias) { + return (bool)($levelObject->getTitle() == $this->latestYearInVehicles($currentSelection)); + } + } + $level = false; + if (is_array($currentSelection) && count($currentSelection) == 1) { + $firstVehicle = $currentSelection[0]; + /** @var VF_Vehicle $firstVehicle */ + $level = $firstVehicle->getLevel($this->leafLevel()); + } elseif ($currentSelection instanceof VF_Vehicle) { + $level = $currentSelection->getLevel($this->leafLevel()); } - $level = $currentSelection->getLevel($this->leafLevel()); if ($level) { return (bool)($levelObject->getTitle() == $level->getTitle()); }
fix isLevelSelected to check for array. This should be cleaned up.
vehiclefits_library
train
29d5e515edd5c178ee70f63f13b5fa89c02c42c1
diff --git a/www/src/py2js_nevez.js b/www/src/py2js_nevez.js index <HASH>..<HASH> 100644 --- a/www/src/py2js_nevez.js +++ b/www/src/py2js_nevez.js @@ -3014,7 +3014,6 @@ function $FromCtx(context){ }else{ $package = $B.imported[$package] } - console.log(_mod, 'starts with .', $package) if($package===undefined){ return 'throw SystemError("Parent module \'\' not loaded,'+ ' cannot perform relative import")' @@ -7698,7 +7697,6 @@ $B.py2js = function(src, module, locals_id, parent_block_id, line_info){ // create_ns = boolean to create a namespace for locals_id (used in exec) // // Returns a tree structure representing the Python source code - var t0 = new Date().getTime(), is_comp = false diff --git a/www/src/py_import_nevez.js b/www/src/py_import_nevez.js index <HASH>..<HASH> 100644 --- a/www/src/py_import_nevez.js +++ b/www/src/py_import_nevez.js @@ -308,104 +308,6 @@ function run_py(module_contents,path,module,compiled) { $B.run_py = run_py -var nb = 0 - -$B.load_imports_idb = function(mod_name, idb_cx, imports, js){ - nb++ - if(nb>150){ - console.log("je jette l'eponge") - console.log('imported', Object.keys($B.imported)) - return - } - for(var key in imports){ - if($B.module_source.hasOwnProperty(key)){delete imports[key]} - else if($B.imported.hasOwnProperty(key)){delete imports[key]} - } - - var imp_names = Object.keys(imports) - console.log(mod_name, imp_names) - if(imp_names.length==0){ - console.log('fini pour', mod_name, Object.keys($B.imported)) - try{ - eval(js) - if($B.imported[mod_name]===false){ - console.log('set imported', mod_name) - var $name = "$locals_" + mod_name.replace(/\./g, "_"), - $module = eval($name) - $module.__class__ = $ModuleDict - $module.__name__ = mod_name - console.log('namespace', mod_name, Object.keys($module)) - } - }catch(err){ - console.log('error for', mod_name, err) - console.log(err.args) - throw err - } - return - } - var module_name = imp_names.shift() - delete imports[module_name] - if($B.module_source[module_name]){ - $B.load_imports_idb(mod_name, idb_cx, imports, js) - }else{ - var db = idb_cx.result, - tx = db.transaction("modules", "readonly") - store = tx.objectStore("modules") - req = store.get(module_name) - function get_module(evt){ - var res = evt.target.result - if(res){ - try{ - // res.content is the source file - var module_contents = res.content, - $Node = $B.$Node,$NodeJSCtx=$B.$NodeJSCtx - $B.$py_module_path[module_name]='idb' - - if(res.ext == '.py'){ - root = $B.py2js(module_contents,module_name, - module_name,'__builtins__') - - $B.module_source[module_name] = root.to_js() - var required = root.imports - for(var key in required){ - if($B.module_source[key]===undefined){ - imports[key] = true - } - } - }else if(res.ext==".pyjs"){ - // precompiled - $B.module_source[module_name] = module_contents - var imports_str = res.imports, - imp = imports_str.split(",") - for(var i=0;i<imp.length;i++){ - if(!$B.imported.hasOwnProperty(imp[i]) && - !$B.module_source.hasOwnProperty(imp[i])){ - imports[imp[i]] = true - }else{ - console.log(imp[i], 'déjà importé') - } - } - }else{ - var src = res.content - src += "\nvar $locals_" + - module_name.replace(/\./g, "_") + " = $module" - $B.module_source[module_name] = src - } - }catch(err){ - console.log(err) - while(imports.length>0){imports.shift()} - throw err - } - }else{ - console.log(module_name, "pas trouvé dans load idb de", mod_name) - } - $B.load_imports_idb(mod_name, idb_cx, imports, js) - } - req.onsuccess = get_module - console.log('fin de load idb...') - } -} - function new_spec(fields) { // TODO : Implement ModuleSpec class i.e. not a module object // add Python-related fields
Commit to be able to merge
brython-dev_brython
train
64667c23c926c74a52843e223dff962e202f0168
diff --git a/djangodblog/feeds.py b/djangodblog/feeds.py index <HASH>..<HASH> 100644 --- a/djangodblog/feeds.py +++ b/djangodblog/feeds.py @@ -49,6 +49,8 @@ class ErrorFeed(object): qs = qs.filter(level__gte=request.GET['level']) elif request.GET.get('server_name'): qs = qs.filter(server_name=request.GET['server_name']) + elif request.GET.get('logger'): + qs = qs.filter(logger=request.GET['logger']) return qs def get_order_field(self, request):
Add in the ability to specify the logger in filters
elastic_apm-agent-python
train
54634efcbaebf4ade486224f2c6c6676056f5212
diff --git a/lang/en/survey.php b/lang/en/survey.php index <HASH>..<HASH> 100644 --- a/lang/en/survey.php +++ b/lang/en/survey.php @@ -21,6 +21,7 @@ $string['editingasurvey'] = "Editing a survey"; $string['helpsurveys'] = "Help on the different types of surveys"; $string['introtext'] = "Introduction text"; $string['name'] = "Name"; +$string['newsurveyresponses'] = "New survey responses"; $string['nobodyyet'] = "Nobody has yet completed this survey"; $string['notdone'] = "Not done yet"; $string['notes'] = "Your private analysis and notes"; diff --git a/mod/survey/lib.php b/mod/survey/lib.php index <HASH>..<HASH> 100644 --- a/mod/survey/lib.php +++ b/mod/survey/lib.php @@ -77,6 +77,36 @@ function survey_delete_instance($id) { return $result; } +function survey_print_recent_activity(&$logs, $isteacher=false) { + global $CFG, $COURSE_TEACHER_COLOR; + + $content = false; + $surveys = NULL; + + foreach ($logs as $log) { + if ($log->module == "survey" and $log->action == "submit") { + $surveys[$log->id] = get_record_sql("SELECT s.name, u.firstname, u.lastname + FROM survey s, user u + WHERE s.id = '$log->info' AND e.user = u.id"); + $surveys[$log->info]->time = $log->time; + $surveys[$log->info]->url = $log->url; + } + } + + if ($surveys) { + $content = true; + print_headline(get_string("newsurveyresponses", "survey").":"); + foreach ($surveys as $survey) { + $date = userdate($survey->time, "%e %b, %H:%M"); + echo "<P><FONT SIZE=1>$date - $survey->firstname $survey->lastname<BR>"; + echo "\"<A HREF=\"$CFG->wwwroot/mod/survey/$survey->url\">"; + echo "$survey->name"; + echo "</A>\"</FONT></P>"; + } + } + + return $content; +} function survey_already_done($survey, $user) { return record_exists_sql("SELECT * FROM survey_answers WHERE survey='$survey' AND user='$user'");
New function to show new surveys in recent activity box
moodle_moodle
train
46a611cd90ae795f0caf8f2260f3f99df23d23a2
diff --git a/rpcserver.go b/rpcserver.go index <HASH>..<HASH> 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -3576,6 +3576,10 @@ func (r *rpcServer) SubscribeTransactions(req *lnrpc.GetTransactionsRequest, for { select { case tx := <-txClient.ConfirmedTransactions(): + destAddresses := make([]string, 0, len(tx.DestAddresses)) + for _, destAddress := range tx.DestAddresses { + destAddresses = append(destAddresses, destAddress.EncodeAddress()) + } detail := &lnrpc.Transaction{ TxHash: tx.Hash.String(), Amount: int64(tx.Value), @@ -3583,6 +3587,7 @@ func (r *rpcServer) SubscribeTransactions(req *lnrpc.GetTransactionsRequest, BlockHash: tx.BlockHash.String(), TimeStamp: tx.Timestamp, TotalFees: tx.TotalFees, + DestAddresses: destAddresses, RawTxHex: hex.EncodeToString(tx.RawTx), } if err := updateStream.Send(detail); err != nil { @@ -3590,12 +3595,17 @@ func (r *rpcServer) SubscribeTransactions(req *lnrpc.GetTransactionsRequest, } case tx := <-txClient.UnconfirmedTransactions(): + var destAddresses []string + for _, destAddress := range tx.DestAddresses { + destAddresses = append(destAddresses, destAddress.EncodeAddress()) + } detail := &lnrpc.Transaction{ - TxHash: tx.Hash.String(), - Amount: int64(tx.Value), - TimeStamp: tx.Timestamp, - TotalFees: tx.TotalFees, - RawTxHex: hex.EncodeToString(tx.RawTx), + TxHash: tx.Hash.String(), + Amount: int64(tx.Value), + TimeStamp: tx.Timestamp, + TotalFees: tx.TotalFees, + DestAddresses: destAddresses, + RawTxHex: hex.EncodeToString(tx.RawTx), } if err := updateStream.Send(detail); err != nil { return err
Add DestAddresses field in transactions returned by SubscribeTransactions
lightningnetwork_lnd
train
d59bf8b7a0781e32f5198ee6be0f9d0ca2f5963f
diff --git a/test/test_vim.py b/test/test_vim.py index <HASH>..<HASH> 100644 --- a/test/test_vim.py +++ b/test/test_vim.py @@ -35,12 +35,20 @@ def test_strwidth(): def test_list_runtime_paths(): # Is this the default runtime path list? homedir = os.environ['HOME'] + '/.nvim' - eq(vim.list_runtime_paths(), [ + dflt_rtp = [ homedir, - '/usr/local/share/vim/vimfiles', - '/usr/local/share/vim', - '/usr/local/share/vim/vimfiles/after' - ]) + '/usr/local/share/nvim/vimfiles', + '/usr/local/share/nvim', + '/usr/local/share/nvim/vimfiles/after' + ] + # If the runtime is installed the default path + # is nvim/runtime + dflt_rtp2 = list(dflt_rtp) + dflt_rtp2[2] += '/runtime' + + rtp = vim.list_runtime_paths() + ok(rtp == dflt_rtp or rtp == dflt_rtp2) + @with_setup(setup=cleanup)
Update default paths in test_runtime_paths - Neovim runtime path is now PREFIX/share/nvim instead of PREFIX/share/vim - Neovim rtp may differ if the runtime folder is installed under the default path - updated the test to allow both options
neovim_pynvim
train
1ebcb43960df217d93bfebc8369b0e7adfbd4d82
diff --git a/TYPO3.Flow/Classes/TYPO3/Flow/Configuration/ConfigurationManager.php b/TYPO3.Flow/Classes/TYPO3/Flow/Configuration/ConfigurationManager.php index <HASH>..<HASH> 100644 --- a/TYPO3.Flow/Classes/TYPO3/Flow/Configuration/ConfigurationManager.php +++ b/TYPO3.Flow/Classes/TYPO3/Flow/Configuration/ConfigurationManager.php @@ -763,13 +763,18 @@ EOD; $sortedRouteSettings = (new PositionalArraySorter($routeSettings))->toArray(); foreach ($sortedRouteSettings as $packageKey => $routeFromSettings) { $subRoutesName = $packageKey . 'SubRoutes'; + $subRoutesConfiguration = ['package' => $packageKey]; + if (isset($routeFromSettings['variables'])) { + $subRoutesConfiguration['variables'] = $routeFromSettings['variables']; + } + if (isset($routeFromSettings['suffix'])) { + $subRoutesConfiguration['suffix'] = $routeFromSettings['suffix']; + } $routeDefinitions[] = [ 'name' => $packageKey, 'uriPattern' => '<' . $subRoutesName . '>', 'subRoutes' => [ - $subRoutesName => [ - 'package' => $packageKey, - ] + $subRoutesName => $subRoutesConfiguration ] ]; }
[TASK] Support variables and suffix in routes via settings Adds support for the ``variables`` and ``suffix`` sub route configuration options in routes via settings. Related: FLOW-<I>
neos_flow-development-collection
train
ea25482f6a4467e8cc3aa6543d83da47543b44b6
diff --git a/rllib/agents/trainer_template.py b/rllib/agents/trainer_template.py index <HASH>..<HASH> 100644 --- a/rllib/agents/trainer_template.py +++ b/rllib/agents/trainer_template.py @@ -65,7 +65,7 @@ def build_trainer( Optional callable that takes the config to check for correctness. It may mutate the config as needed. default_policy (Optional[Type[Policy]]): The default Policy class to - use. + use if `get_policy_class` returns None. get_policy_class (Optional[Callable[ TrainerConfigDict, Optional[Type[Policy]]]]): Optional callable that takes a config and returns the policy class or None. If None diff --git a/rllib/evaluation/worker_set.py b/rllib/evaluation/worker_set.py index <HASH>..<HASH> 100644 --- a/rllib/evaluation/worker_set.py +++ b/rllib/evaluation/worker_set.py @@ -79,7 +79,10 @@ class WorkerSet: remote_spaces = ray.get(self.remote_workers( )[0].foreach_policy.remote( lambda p, pid: (pid, p.observation_space, p.action_space))) - spaces = {e[0]: (e[1], e[2]) for e in remote_spaces} + spaces = { + e[0]: (getattr(e[1], "original_space", e[1]), e[2]) + for e in remote_spaces + } else: spaces = None
WIP. (#<I>)
ray-project_ray
train
fb4b2c4ca0354a9b800897f33f518b40eab96153
diff --git a/large_list.go b/large_list.go index <HASH>..<HASH> 100644 --- a/large_list.go +++ b/large_list.go @@ -85,6 +85,32 @@ func (ll *LargeList) FindThenFilter(value interface{}, filterName string, filter return res.([]interface{}), err } +// Select a range of values from the large list. +func (ll *LargeList) Range(minValue, maxValue interface{}) ([]interface{}, error) { + res, err := ll.client.Execute(ll.policy, ll.key, ll.packageName(), "range", ll.binName, NewValue(minValue), NewValue(maxValue)) + if err != nil { + return nil, err + } + + if res == nil { + return nil, nil + } + return res.([]interface{}), err +} + +// Select a range of values from the large list. +func (ll *LargeList) RangeThenFilter(minValue, maxValue interface{}, filterName string, filterArgs ...interface{}) ([]interface{}, error) { + res, err := ll.client.Execute(ll.policy, ll.key, ll.packageName(), "range", ll.binName, NewValue(minValue), NewValue(maxValue), ll.userModule, NewValue(filterName), ToValueArray(filterArgs)) + if err != nil { + return nil, err + } + + if res == nil { + return nil, nil + } + return res.([]interface{}), err +} + // Scan returns all objects in the list. func (ll *LargeList) Scan() ([]interface{}, error) { return ll.scan(ll) diff --git a/large_list_test.go b/large_list_test.go index <HASH>..<HASH> 100644 --- a/large_list_test.go +++ b/large_list_test.go @@ -44,7 +44,7 @@ var _ = Describe("LargeList Test", func() { Expect(err).ToNot(HaveOccurred()) }) - It("should create a valid LargeList; Support Add(), Remove(), Find(), Size(), Scan(), Destroy() and GetCapacity()", func() { + It("should create a valid LargeList; Support Add(), Remove(), Find(), Size(), Scan(), Range(), Destroy() and GetCapacity()", func() { llist := client.GetLargeList(wpolicy, key, randString(10), "") res, err := llist.Size() Expect(err).ToNot(HaveOccurred()) // bin not exists @@ -79,6 +79,11 @@ var _ = Describe("LargeList Test", func() { Expect(len(scanResult)).To(Equal(100)) Expect(scanResult).To(Equal(scanExpectation)) + // check for range + rangeResult, err := llist.Range(0, 100) + Expect(err).To(HaveOccurred()) + Expect(len(rangeResult)).To(Equal(100)) + for i := 1; i <= 100; i++ { // confirm that the value already exists in the LLIST findResult, err := llist.Find(NewValue(i))
Added LargeList.Range and LargeList.RangeThenFilter methods
aerospike_aerospike-client-go
train
10efe170a49392994daf6323f8e50afe62adf70b
diff --git a/internal/provider/resource_password_test.go b/internal/provider/resource_password_test.go index <HASH>..<HASH> 100644 --- a/internal/provider/resource_password_test.go +++ b/internal/provider/resource_password_test.go @@ -9,6 +9,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "golang.org/x/crypto/bcrypt" ) func TestAccResourcePasswordBasic(t *testing.T) { @@ -412,9 +413,11 @@ func TestResourcePasswordStateUpgradeV0(t *testing.T) { actualStateV1, err := resourcePasswordStateUpgradeV0(context.Background(), c.stateV0, nil) if c.shouldError { + // Check error msg if !cmp.Equal(c.errMsg, err.Error()) { t.Errorf("expected: %q, got: %q", c.errMsg, err) } + // Check actualStateV1 is nil if !cmp.Equal(c.expectedStateV1, actualStateV1) { t.Errorf("expected: %+v, got: %+v", c.expectedStateV1, err) } @@ -423,11 +426,18 @@ func TestResourcePasswordStateUpgradeV0(t *testing.T) { t.Errorf("err should be nil, actual: %v", err) } - for k := range c.expectedStateV1 { - _, ok := actualStateV1[k] - if !ok { - t.Errorf("expected key: %s is missing from state", k) - } + // Compare bcrypt_hash with plaintext equivalent to verify match + bcryptHash := actualStateV1["bcrypt_hash"] + err := bcrypt.CompareHashAndPassword([]byte(bcryptHash.(string)), []byte(c.stateV0["result"].(string))) + if err != nil { + t.Error("hash and password do not match") + } + + // Delete bcrypt_hash from actualStateV1 and expectedStateV1 so can compare + delete(actualStateV1, "bcrypt_hash") + delete(c.expectedStateV1, "bcrypt_hash") + if !cmp.Equal(actualStateV1, c.expectedStateV1) { + t.Errorf("expected: %v, got: %v", c.expectedStateV1, actualStateV1) } } }) @@ -472,11 +482,8 @@ func TestResourcePasswordStateUpgradeV1(t *testing.T) { t.Errorf("err should be nil, actual: %v", err) } - for k := range c.expectedStateV2 { - _, ok := actualStateV2[k] - if !ok { - t.Errorf("expected key: %s is missing from state", k) - } + if !cmp.Equal(actualStateV2, c.expectedStateV2) { + t.Errorf("expected: %v, got: %v", c.expectedStateV2, actualStateV2) } } })
Update unit tests for state upgraders
terraform-providers_terraform-provider-random
train
d59fe6540732a1df7ffe63936e08f25211070043
diff --git a/rb/lib/selenium/webdriver/common/alert.rb b/rb/lib/selenium/webdriver/common/alert.rb index <HASH>..<HASH> 100644 --- a/rb/lib/selenium/webdriver/common/alert.rb +++ b/rb/lib/selenium/webdriver/common/alert.rb @@ -40,12 +40,6 @@ module Selenium def text @bridge.alert_text end - - def authenticate(username, password) - WebDriver.logger.deprecate 'Alert#authenticate' - @bridge.authentication(username: username, password: password) - accept - end end # Alert end # WebDriver end # Selenium
Remove deprecated Alert#authenticate It has been deprecated since <I> and is not supported by any drivers.
SeleniumHQ_selenium
train
c01e7602a913c74b3d6f5b4e54c09e8223a04bd9
diff --git a/test/helper.rb b/test/helper.rb index <HASH>..<HASH> 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -13,7 +13,6 @@ require File.expand_path('../file_creation', __FILE__) begin - require_relative '../ruby/envutil' require_relative 'support/ruby_runner' require_relative 'support/rakefile_definitions' rescue NoMethodError, LoadError
backport r<I> from ruby trunk
ruby_rake
train
45e4cbf6d49daf2cffc279f31b6733f9a5776da1
diff --git a/lib/sidekiq_unique_jobs/version.rb b/lib/sidekiq_unique_jobs/version.rb index <HASH>..<HASH> 100644 --- a/lib/sidekiq_unique_jobs/version.rb +++ b/lib/sidekiq_unique_jobs/version.rb @@ -3,5 +3,5 @@ module SidekiqUniqueJobs # # @return [String] the current SidekiqUniqueJobs version - VERSION = "7.1.1" + VERSION = "7.1.2" end
Bump sidekiq-unique-jobs to <I>
mhenrixon_sidekiq-unique-jobs
train
49eb883b3c49706844a4a69fb43d6569b2857b34
diff --git a/master/buildbot/worker/openstack.py b/master/buildbot/worker/openstack.py index <HASH>..<HASH> 100644 --- a/master/buildbot/worker/openstack.py +++ b/master/buildbot/worker/openstack.py @@ -227,14 +227,11 @@ class OpenStackLatentWorker(CompatibleLatentWorkerMixin, @defer.inlineCallbacks def _getImage(self, build): - # If image is a callable, then pass it the list of images. The - # function should return the image's UUID to use. - image = self.image - if callable(image): - # novaclient has renamed images to glance - image_uuid = image(self.novaclient.glance.list()) - else: - image_uuid = yield build.render(image) + image_uuid = yield build.render(self.image) + # check if we got name instead of uuid + for image in self.novaclient.glance.list(): + if image.name == image_uuid: + image_uuid = image.id return image_uuid @defer.inlineCallbacks
OpenStackLatentWorker: Try to convert image name into uuid
buildbot_buildbot
train
4ed0002f156bebd534ff1c26ddd12997f4fe0842
diff --git a/src/Access/PersonalPermissionsAccess.php b/src/Access/PersonalPermissionsAccess.php index <HASH>..<HASH> 100644 --- a/src/Access/PersonalPermissionsAccess.php +++ b/src/Access/PersonalPermissionsAccess.php @@ -30,15 +30,25 @@ class PersonalPermissionsAccess extends AuthenticatedAccess return false; } - $permissionTable = TableRegistry::get('RolesCapabilities.PersonalPermissions'); - $query = $permissionTable->find('all') + $groups = TableRegistry::get('RolesCapabilities.Capabilities')->getUserGroups($user['id']); + $query = TableRegistry::get('RolesCapabilities.PersonalPermissions') + ->find('all') + ->select('foreign_key') ->where([ - 'model' => $url['controller'], - 'foreign_key' => $url['pass'][0], - 'type' => $url['action'], - 'owner_foreign_key' => $user['id'], - 'owner_model' => 'Users', - ]) + 'model' => $url['controller'], + 'type IN ' => $url['action'], + 'foreign_key' => $url['pass'][0], + 'OR' => [ + [ + 'owner_foreign_key IN ' => array_keys($groups), + 'owner_model' => 'Groups', + ], + [ + 'owner_foreign_key' => $user['id'], + 'owner_model' => 'Users', + ] + ] + ]) ->applyOptions(['accessCheck' => false]); return $query->count() > 0 ? true : false; diff --git a/src/Event/ModelBeforeFindEventsListener.php b/src/Event/ModelBeforeFindEventsListener.php index <HASH>..<HASH> 100644 --- a/src/Event/ModelBeforeFindEventsListener.php +++ b/src/Event/ModelBeforeFindEventsListener.php @@ -174,14 +174,16 @@ class ModelBeforeFindEventsListener implements EventListenerInterface ->where([ 'model' => $table->alias(), 'type IN ' => ['view', 'index'], - ]) - ->orWhere([ - 'owner_foreign_key' => $user['id'], - 'owner_model' => 'Users', - ]) - ->orWhere([ - 'owner_foreign_key IN ' => $groups, - 'owner_model' => 'Groups', + 'OR' => [ + [ + 'owner_foreign_key IN ' => array_keys($groups), + 'owner_model' => 'Groups', + ], + [ + 'owner_foreign_key' => $user['id'], + 'owner_model' => 'Users', + ] + ] ]) ->applyOptions(['accessCheck' => false]) ->toArray();
Fixed condition to search permissions by group (#task <I>)
QoboLtd_cakephp-roles-capabilities
train
faffa2a5ba56defc93377c6cd704d2adb953b5d1
diff --git a/bcbio/heterogeneity/__init__.py b/bcbio/heterogeneity/__init__.py index <HASH>..<HASH> 100644 --- a/bcbio/heterogeneity/__init__.py +++ b/bcbio/heterogeneity/__init__.py @@ -26,7 +26,8 @@ def _get_calls(data, cnv_only=False): def get_variants(data): """Retrieve set of variant calls to use for heterogeneity analysis. """ - supported = ["vardict", "vardict-java", "vardict-perl", "strelka2", "mutect2", "freebayes", "mutect"] + supported = ["precalled", "vardict", "vardict-java", "vardict-perl", + "strelka2", "mutect2", "freebayes", "mutect"] out = [] for v in data.get("variants", []): if v["variantcaller"] in supported: diff --git a/bcbio/pipeline/variation.py b/bcbio/pipeline/variation.py index <HASH>..<HASH> 100644 --- a/bcbio/pipeline/variation.py +++ b/bcbio/pipeline/variation.py @@ -131,7 +131,7 @@ def _get_orig_items(data): """Retrieve original items in a batch, handling CWL and standard cases. """ if isinstance(data, dict): - if dd.get_align_bam(data) and tz.get_in(["metadata", "batch"], data): + if dd.get_align_bam(data) and tz.get_in(["metadata", "batch"], data) and "group_orig" in data: return vmulti.get_orig_items(data) else: return [data] diff --git a/bcbio/variation/annotation.py b/bcbio/variation/annotation.py index <HASH>..<HASH> 100644 --- a/bcbio/variation/annotation.py +++ b/bcbio/variation/annotation.py @@ -116,7 +116,7 @@ def _add_vcf_header_sample_cl(in_file, items, base_file): def _update_header(orig_vcf, base_file, new_lines, chrom_process_fn=None): """Fix header with additional lines and remapping of generic sample names. """ - new_header = "%s-header.txt" % utils.splitext_plus(base_file)[0] + new_header = "%s-sample_header.txt" % utils.splitext_plus(base_file)[0] with open(new_header, "w") as out_handle: chrom_line = None with gzip.open(orig_vcf) as in_handle: diff --git a/bcbio/variation/vcfutils.py b/bcbio/variation/vcfutils.py index <HASH>..<HASH> 100644 --- a/bcbio/variation/vcfutils.py +++ b/bcbio/variation/vcfutils.py @@ -508,7 +508,7 @@ def sort_by_ref(vcf_file, data): def add_contig_to_header_cl(ref_file, out_file): """Add update ##contig lines to VCF header, required for bcftools/GATK compatibility. """ - header_file = "%s-header.txt" % utils.splitext_plus(out_file)[0] + header_file = "%s-contig_header.txt" % utils.splitext_plus(out_file)[0] with open(header_file, "w") as out_handle: for region in ref.file_contigs(ref_file, {}): out_handle.write("##contig=<ID=%s,length=%s>\n" % (region.name, region.size))
TitanCNA: allow pre-called vrn_files as inputs Cleans up pipeline to handle pre-aligned BAMs (passed as `files`) and pre-called VCFs (passed as `vrn_file`) into a TitanCNA/CNVkit only run. Fixes #<I>
bcbio_bcbio-nextgen
train
68db7df08de06823905c16fafff7e91733976916
diff --git a/snapshot/snapshot.go b/snapshot/snapshot.go index <HASH>..<HASH> 100644 --- a/snapshot/snapshot.go +++ b/snapshot/snapshot.go @@ -10,7 +10,6 @@ import ( "io/ioutil" "log" "os" - "time" "github.com/hashicorp/raft" ) @@ -185,7 +184,7 @@ func Restore(logger *log.Logger, in io.Reader, r *raft.Raft) error { } // Feed the snapshot into Raft. - if err := r.Restore(&metadata, snap, 60*time.Second); err != nil { + if err := r.Restore(&metadata, snap, 0); err != nil { return fmt.Errorf("Raft error when restoring snapshot: %v", err) }
Removes timeout when restoring snapshots. Fixes #<I> Originally I started out making this configurable, but realized it wasn't worth the complexity. If you are restoring a snapshot, you really need to wait until it's done, or something bad happens like losing leadership, which will already trigger an error. Rather than have operators have to tune this to cover whatever their snapshot size is, we just make it block here. There's also already a bocking barrier right after the restore that hasn't been a problem.
hashicorp_consul
train
0ec9db411ff30129b9e3c8526a3feb1b5f41a5f3
diff --git a/nipap/nipap/nipap.py b/nipap/nipap/nipap.py index <HASH>..<HASH> 100644 --- a/nipap/nipap/nipap.py +++ b/nipap/nipap/nipap.py @@ -2739,8 +2739,8 @@ class Nipap: if parent_prefix['vrf_id']: vrf_id = parent_prefix['vrf_id'] query_parent_prefix = " (p1.vrf_id = %s AND iprange(p1.prefix) <<= iprange('%s') AND p1.indent <= %s) " % (vrf_id, parent_prefix['prefix'], parent_prefix['indent'] + 1) - join_parent_prefix = " AND %s" % query_parent_prefix - where_parent_prefix = " OR %s" % query_parent_prefix + join_parent_prefix = " OR %s" % query_parent_prefix + where_parent_prefix = " AND %s" % query_parent_prefix else: join_parent_prefix = '' where_parent_prefix = ''
Woohoo, fix parent_prefix This has now officially entered the stage of silly as #<I> has been the most reopened and closed bug in history. This fixes it though - really! Relates to good ol' #<I>. Fixes #<I>
SpriteLink_NIPAP
train
1132dcd33bd14bacddc52d030077343aea7519b2
diff --git a/greenhouse/io.py b/greenhouse/io.py index <HASH>..<HASH> 100644 --- a/greenhouse/io.py +++ b/greenhouse/io.py @@ -1,4 +1,5 @@ import errno +import fcntl import os import socket import stat @@ -67,7 +68,7 @@ class Socket(object): def __del__(self): try: - state.poller.unregister(self._sock) + state.poller.unregister(self) except: pass @@ -89,6 +90,7 @@ class Socket(object): def close(self): self._closed = True + state.poller.unregister(self) return self._sock.close() def connect(self, address): @@ -196,6 +198,7 @@ class File(object): def __init__(self, name, mode='rb'): self.name = name + self.mode = mode self._buf = StringIO() flags = os.O_RDONLY | os.O_NONBLOCK @@ -222,14 +225,48 @@ class File(object): import greenhouse.poller state.poller.register(self) + @classmethod + def fromfd(cls, fd, mode='rb'): + fp = object.__new__(cls) + fp.mode = mode + fp._fno = fd + fp._buf = StringIO() + + flags = os.O_RDONLY | os.O_NONBLOCK + if (('w' in mode or 'a' in mode) and 'r' in mode) or '+' in mode: + flags |= os.O_RDWR + elif 'w' in mode or 'a' in mode: + flags |= os.O_WRONLY + if 'a' in mode: + flags |= os.O_APPEND + + fdflags = fcntl.fcntl(fd, FCNTL.F_GETFL) + if fdflags & flags != flags: + fcntl.fcntl(fd, FCNTL.F_SETFL, flags | fdflags) + + fp._readable = utils.Event() + fp._writable = utils.Event() + if not hasattr(state, 'poller'): + import greenhouse.poller + state.poller.register(fp) + def __iter__(self): line = self.readline() while line: yield line line = self.readline() + #TODO: context manager protocol + + def __del__(self): + try: + state.poller.unregister(self) + except: + pass + def close(self): os.close(self._fno) + state.poller.unregister(self) def fileno(self): return self._fno
added a fromfd classmethod, should make it easy to make async pipes and such
teepark_greenhouse
train
2334f2c26d6a5b3bb23b879f458945b74df3d61f
diff --git a/datadog_checks_base/datadog_checks/base/checks/base.py b/datadog_checks_base/datadog_checks/base/checks/base.py index <HASH>..<HASH> 100644 --- a/datadog_checks_base/datadog_checks/base/checks/base.py +++ b/datadog_checks_base/datadog_checks/base/checks/base.py @@ -496,7 +496,7 @@ class __AgentCheck(object): Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key` """ if not self._deprecations[deprecation_key][0]: - self.log.warning(self._deprecations[deprecation_key][1]) + self.warning(self._deprecations[deprecation_key][1]) self._deprecations[deprecation_key][0] = True # TODO: Remove once our checks stop calling it
Make deprecations apparent in UI (#<I>)
DataDog_integrations-core
train
f7238e6c40ac49e36a822587850afaa590707053
diff --git a/src/Api/Betting.php b/src/Api/Betting.php index <HASH>..<HASH> 100644 --- a/src/Api/Betting.php +++ b/src/Api/Betting.php @@ -23,13 +23,29 @@ class Betting ->authHeaders() ->addHeader([ 'Content-Type' => 'application/json' ]) ->setFilter($filter) - ->setMarketProjection($marketProjection) + ->setProjection('marketProjection', $marketProjection) ->setSort($sort) ->setMaxResults($maxResults) ->setLocale($locale) ->send(); } + public function listMarketBook($marketIds = [], $priceProjection = null, $orderProjection = null, $matchProjection = null, $currencyCode = null, $locale = null) + { + return $this->httpClient + ->setMethod('post') + ->setEndPoint(self::ENDPOINT.'listMarketBook/') + ->authHeaders() + ->addHeader([ 'Content-Type' => 'application/json' ]) + ->setMarketIds($marketIds) + ->setProjection('priceProjection', $priceProjection) + ->setProjection('orderProjection', $orderProjection) + ->setProjection('matchProjection', $matchProjection) + ->setCurrencyCode($currencyCode) + ->setLocale($locale) + ->send(); + } + /** * Six Exchange methods have an identical API, so we bundle them into a single magic call e.g. * @method listCompetitions(array $filters, string $locale) diff --git a/src/Http/Client.php b/src/Http/Client.php index <HASH>..<HASH> 100644 --- a/src/Http/Client.php +++ b/src/Http/Client.php @@ -106,15 +106,27 @@ class Client } /** + * Setter for mandatory marketId(s). + * + * @param array $marketIds + * @return Client + */ + public function setMarketIds($marketIds = null) + { + $this->options[ 'json' ][ 'marketIds' ] = $marketIds ?: new stdClass; + return $this; + } + + /** * Setter for optional market projection, i.e. what market-related data should be returned. * * @param array $marketProjection * @return Client */ - public function setMarketProjection($marketProjection = null) + public function setProjection($name, $projection = null) { - if ($marketProjection) { - $this->options[ 'json' ][ 'marketProjection' ] = $marketProjection; + if ($projection) { + $this->options[ 'json' ][ $name ] = $projection; } return $this; } @@ -162,6 +174,20 @@ class Client } /** + * Setter for optional currency code. + * + * @param string|null $currencyCode + * @return Client + */ + public function setCurrencyCode($currencyCode) + { + if ($currencyCode) { + $this->options[ 'json' ][ 'currencyCode' ] = $currencyCode; + } + return $this; + } + + /** * Dispatch the request and provide hooks for error handling for the response. * * @return object stdClass diff --git a/tests/BettingTest.php b/tests/BettingTest.php index <HASH>..<HASH> 100644 --- a/tests/BettingTest.php +++ b/tests/BettingTest.php @@ -126,4 +126,31 @@ class BettingTest extends BaseTest $this->assertObjectHasAttribute('metadata', $result[0]->runners[0]); } } + + public function testMarketBookWithMarketIdOnly() + { + $events = collect(Betfair::betting()->listEvents())->sortByDesc('marketCount')->values(); + $markets = Betfair::betting()->listMarketCatalogue(['eventIds' => [$events[0]->event->id]]); + $result = Betfair::betting()->listMarketBook([$markets[0]->marketId]); + + $this->assertObjectHasAttribute('numberOfRunners', $result[0]); + $this->assertObjectHasAttribute('runners', $result[0]); + } + + public function testMarketBookWithParameters() + { + $events = collect(Betfair::betting()->listEvents())->sortByDesc('marketCount')->values(); + $markets = Betfair::betting()->listMarketCatalogue(['eventIds' => [$events[0]->event->id]]); + $result = Betfair::betting()->listMarketBook( + [$markets[0]->marketId], // $marketIds + ['priceData' => ['EX_ALL_OFFERS']], // $priceProjection (end) + 'ALL', // $orderProjection + 'NO_ROLLUP', //$matchProjection + 'EUR', // $currencyCode, + 'it' // $locale + ); + + $this->assertObjectHasAttribute('lastPriceTraded', $result[0]->runners[0]); + $this->assertObjectHasAttribute('ex', $result[0]->runners[0]); + } }
Support for listMarketBook method, plus generalisation of filter adding. However, there's plenty of scope for extensive refactoring, in particular for removing setters from client - tp be addressed once all betting methods are supported.
petercoles_Betfair-Exchange
train
dfc45b7021467b4b0ef78a98ad9bdb7e4e4e8096
diff --git a/lib/codemirror.js b/lib/codemirror.js index <HASH>..<HASH> 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -1219,7 +1219,7 @@ window.CodeMirror = (function() { if (op.updateMaxLine) computeMaxLength(cm); if (cm.display.maxLineChanged && !cm.options.lineWrapping) { var width = measureChar(cm, cm.display.maxLine, cm.display.maxLine.text.length).right; - display.sizer.style.minWidth = (width + 3 + scrollerCutOff) + "px"; + display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px"; cm.display.maxLineChanged = false; var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth); if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos) diff --git a/test/doc_test.js b/test/doc_test.js index <HASH>..<HASH> 100644 --- a/test/doc_test.js +++ b/test/doc_test.js @@ -15,8 +15,8 @@ } var doc = editors[names[other]].linkedDoc({ sharedHist: !m[4], - from: m[6] && Number(m[6]), - to: m[7] && Number(m[7]) + from: m[6] ? Number(m[6]) : null, + to: m[7] ? Number(m[7]) : null }); cur = isDoc ? doc : CodeMirror(place, clone(opts, {value: doc})); } @@ -45,7 +45,7 @@ eq(arguments[i].getValue(), val, msg) } - function testDoc(name, spec, run, opts) { + function testDoc(name, spec, run, opts, expectFail) { if (!opts) opts = {}; return test("doc_" + name, function() { @@ -65,9 +65,11 @@ place.removeChild(editors[i].getWrapperElement()); } } - }); + }, expectFail); } + var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); + function testBasic(a, b) { eqAll("x", a, b); a.setValue("hey"); @@ -97,7 +99,7 @@ eqAll("abx\ncdy\nefz", a, b); a.undo(); b.undo(); a.undo(); a.undo(); eqAll("ab\ncd\nef", a, b); - }); + }, null, ie_lt8); testDoc("undoIntact", "A='ab\ncd\nef' B<~A", function(a, b) { a.replaceRange("x", {line: 0});
[doc tests] Fix test runner for IE regexp quirk Issue #<I>
codemirror_CodeMirror
train
8a42bab98e3697866878f5cd8ed48ba66c10af0b
diff --git a/status.js b/status.js index <HASH>..<HASH> 100644 --- a/status.js +++ b/status.js @@ -1,7 +1,8 @@ var colors = require('colors'), start = new Date().getTime(), pad = " ", - items = {} + items = {}, + util = require('util') // // This is a single item (Or cell or whatever you call it) in the status display @@ -57,7 +58,6 @@ var render = function(stamp){ } out += pad + nums + pad + "|" } - if(stamp) { process.stdout.write("\u001B[2K") console.log("@ " + nicetime(new Date().getTime() - start) + "|" + out + "\r") @@ -93,6 +93,38 @@ exports.updateItem = function(item, amount) { render() } +var clear_line = function(){ process.stdout.write("\u001B[2K") } + +var log = function() { + clear_line() + console.log.apply(this,arguments) + render() +} +var info = function() { + clear_line() + console.info.apply(this,arguments) + render() +} +var warn = function() { + clear_line() + console.warn.apply(this,arguments) + render() +} +var error = function() { + clear_line() + console.error.apply(this,arguments) + render() +} +exports.clear = "\u001B[2K" + +exports.console = function(){ + return { + 'log':log, + 'info':info, + 'error':error, + 'warn':warn + } +} // // Stamps the current status to the console //
Fiddled around trying to extend console.log to first try and clear the current line, seems to work. Needs more fixins
derrickpelletier_node-status
train
beb32ab2629810f65cfdbb2e7161a394224126dd
diff --git a/test3/gmpy_test.py b/test3/gmpy_test.py index <HASH>..<HASH> 100644 --- a/test3/gmpy_test.py +++ b/test3/gmpy_test.py @@ -44,3 +44,6 @@ for x in test_modules: pf, pt = failures, tests doctest.master.summarize(1) + +print("There is a known bug with Fraction == mpq so there is no need to") +print("report that failure.")
Added message to gmpy_test.py to let users know that there is a known bug with Fraction == mpq.
aleaxit_gmpy
train
c8ffa6c799bde4378737be93d4f5206ad9680acc
diff --git a/src/Traits/ValidatingTrait.php b/src/Traits/ValidatingTrait.php index <HASH>..<HASH> 100644 --- a/src/Traits/ValidatingTrait.php +++ b/src/Traits/ValidatingTrait.php @@ -21,7 +21,7 @@ trait ValidatingTrait */ public function mergeRules(array $rules) { - $this->rules = array_merge($this->rules, $rules); + $this->rules += $rules; return $this; }
Allow modules to override core packages rules
rinvex_laravel-support
train
9501b5732f2dc6e20daae170610178b48ce4a80d
diff --git a/BootstrapSelectAsset.php b/BootstrapSelectAsset.php index <HASH>..<HASH> 100644 --- a/BootstrapSelectAsset.php +++ b/BootstrapSelectAsset.php @@ -39,14 +39,24 @@ class BootstrapSelectAsset extends AssetBundle return false; $js = ''; + if ($o['menuArrow']) { $js .= '$("' . $o['selector'] . '").addClass("show-menu-arrow");' . PHP_EOL; } + if ($o['tickIcon']) { $js .= '$("' . $o['selector'] . '").addClass("show-tick");' . PHP_EOL; } + + //Enable Bootstrap-Select for $o['selector'] $js .= '$("' . $o['selector'] . '").selectpicker(' . json_encode($o['selectpickerOptions']) . ');' . PHP_EOL; + //Update Bootstrap-Select by :reset click + $js .= '$(":reset").click(function(){ + $(this).closest("form").trigger("reset"); + $("' . $o['selector'] . '").selectpicker("refresh"); + });'; + parent::register($view); $view->registerJs($js); }
Update Bootstrap-Select by :reset click Ensures that bootstrap Select is refreshed when a form reset-button is pressed. Otherwise, only the select would have updated but not the bootstrap Select HTML... @see <URL>
cakebake_yii2-bootstrap-select
train
02094006b2426637e9dea63a3a39b186fa06e681
diff --git a/plugin/src/main/java/com/buschmais/jqassistant/core/plugin/impl/RulePluginRepositoryImpl.java b/plugin/src/main/java/com/buschmais/jqassistant/core/plugin/impl/RulePluginRepositoryImpl.java index <HASH>..<HASH> 100644 --- a/plugin/src/main/java/com/buschmais/jqassistant/core/plugin/impl/RulePluginRepositoryImpl.java +++ b/plugin/src/main/java/com/buschmais/jqassistant/core/plugin/impl/RulePluginRepositoryImpl.java @@ -24,11 +24,6 @@ import org.jqassistant.schema.plugin.v1.RulesType; */ public class RulePluginRepositoryImpl extends AbstractPluginRepository implements RulePluginRepository { - /** - * The resource path where to load rule files from. - */ - private static final String RULE_RESOURCE_PATH = "META-INF/jqassistant-rules/"; - private final ClassLoader classLoader; private final List<RuleSource> sources; @@ -92,8 +87,7 @@ public class RulePluginRepositoryImpl extends AbstractPluginRepository implement RulesType rulesType = plugin.getRules(); if (rulesType != null) { for (String relativePath : rulesType.getResource()) { - String resource = RULE_RESOURCE_PATH + relativePath; - sources.add(new ClasspathRuleSource(classLoader, resource, relativePath)); + sources.add(new ClasspathRuleSource(classLoader, relativePath)); } } } diff --git a/rule/src/main/java/com/buschmais/jqassistant/core/rule/api/source/ClasspathRuleSource.java b/rule/src/main/java/com/buschmais/jqassistant/core/rule/api/source/ClasspathRuleSource.java index <HASH>..<HASH> 100644 --- a/rule/src/main/java/com/buschmais/jqassistant/core/rule/api/source/ClasspathRuleSource.java +++ b/rule/src/main/java/com/buschmais/jqassistant/core/rule/api/source/ClasspathRuleSource.java @@ -11,14 +11,20 @@ import java.util.Optional; */ public class ClasspathRuleSource extends RuleSource { + /** + * The resource path where to load rule files from. + */ + public static final String RULE_RESOURCE_PATH = "META-INF/jqassistant-rules"; + private final ClassLoader classLoader; private final String resource; private final String relativePath; - public ClasspathRuleSource(ClassLoader classLoader, String resource, String relativePath) { + public ClasspathRuleSource(ClassLoader classLoader, String relativePath) { this.classLoader = classLoader; - this.resource = resource; this.relativePath = relativePath; + this.resource = RULE_RESOURCE_PATH + "/" + relativePath; + } @Override diff --git a/rule/src/test/java/com/buschmais/jqassistant/core/rule/api/source/ClasspathRuleSourceTest.java b/rule/src/test/java/com/buschmais/jqassistant/core/rule/api/source/ClasspathRuleSourceTest.java index <HASH>..<HASH> 100644 --- a/rule/src/test/java/com/buschmais/jqassistant/core/rule/api/source/ClasspathRuleSourceTest.java +++ b/rule/src/test/java/com/buschmais/jqassistant/core/rule/api/source/ClasspathRuleSourceTest.java @@ -10,9 +10,7 @@ public class ClasspathRuleSourceTest extends AbstractRuleSourceTest { @Override protected List<RuleSource> getRuleSources() { return Stream.of("rules.xml", "index.adoc", "readme.md", "subdirectory/rules.xml") - .map(relativePath -> new ClasspathRuleSource(ClasspathRuleSourceTest.class.getClassLoader(), "META-INF/jqassistant-rules/" + relativePath, - relativePath)) - .collect(toList()); + .map(relativePath -> new ClasspathRuleSource(ClasspathRuleSourceTest.class.getClassLoader(), relativePath)).collect(toList()); } }
added unit test for ClasspathRuleSource
buschmais_jqa-core-framework
train
318ded9e29453a190e8f5643bb47358fdc341437
diff --git a/library-core/src/main/java/com/mikepenz/fastadapter/adapters/ItemAdapter.java b/library-core/src/main/java/com/mikepenz/fastadapter/adapters/ItemAdapter.java index <HASH>..<HASH> 100644 --- a/library-core/src/main/java/com/mikepenz/fastadapter/adapters/ItemAdapter.java +++ b/library-core/src/main/java/com/mikepenz/fastadapter/adapters/ItemAdapter.java @@ -570,6 +570,31 @@ public class ItemAdapter<Item extends IItem> extends AbstractAdapter<Item> imple } /** + * Searches for the given item and calculates its relative position + * + * @param item the item which is searched for + * @return the relative position + */ + public int getAdapterPosition(Item item) { + return getAdapterPosition(item.getIdentifier()); + } + + /** + * Searches for the given identifier and calculates its relative position + * + * @param identifier the identifier of an item which is searched for + * @return the relative position + */ + public int getAdapterPosition(long identifier) { + for (int i = 0, size = mOriginalItems.size(); i < size; i++) { + if (mOriginalItems.get(i).getIdentifier() == identifier) { + return i; + } + } + return -1; + } + + /** * add an array of items to the end of the existing items * * @param items the items to add @@ -591,7 +616,7 @@ public class ItemAdapter<Item extends IItem> extends AbstractAdapter<Item> imple IdDistributor.checkIds(items); } mOriginalItems.addAll(items); - performFiltering(mConstraint); + publishResults(mConstraint, performFiltering(mConstraint)); return ItemAdapter.this; } else { return ItemAdapter.this.add(items); @@ -620,8 +645,8 @@ public class ItemAdapter<Item extends IItem> extends AbstractAdapter<Item> imple if (mUseIdDistributor) { IdDistributor.checkIds(items); } - mOriginalItems.addAll(position - getFastAdapter().getPreItemCountByOrder(getOrder()), items); - performFiltering(mConstraint); + mOriginalItems.addAll(getAdapterPosition(mItems.get(position)) - getFastAdapter().getPreItemCount(position), items); + publishResults(mConstraint, performFiltering(mConstraint)); return ItemAdapter.this; } else { return ItemAdapter.this.add(position, items); @@ -639,8 +664,8 @@ public class ItemAdapter<Item extends IItem> extends AbstractAdapter<Item> imple if (mUseIdDistributor) { IdDistributor.checkId(item); } - mOriginalItems.set(position - getFastAdapter().getPreItemCount(position), item); - performFiltering(mConstraint); + mOriginalItems.set(getAdapterPosition(mItems.get(position)) - getFastAdapter().getPreItemCount(position), item); + publishResults(mConstraint, performFiltering(mConstraint)); return ItemAdapter.this; } else { return ItemAdapter.this.set(position, item); @@ -657,9 +682,11 @@ public class ItemAdapter<Item extends IItem> extends AbstractAdapter<Item> imple public ItemAdapter<Item> move(int fromPosition, int toPosition) { if (mOriginalItems != null) { int preItemCount = getFastAdapter().getPreItemCount(fromPosition); - Item item = mOriginalItems.get(fromPosition - preItemCount); - mOriginalItems.remove(fromPosition - preItemCount); - mOriginalItems.add(toPosition - preItemCount, item); + int adjustedFrom = getAdapterPosition(mItems.get(fromPosition)); + int adjustedTo = getAdapterPosition(mItems.get(toPosition)); + Item item = mOriginalItems.get(adjustedFrom - preItemCount); + mOriginalItems.remove(adjustedFrom - preItemCount); + mOriginalItems.add(adjustedTo - preItemCount, item); performFiltering(mConstraint); return ItemAdapter.this; } else { @@ -674,8 +701,8 @@ public class ItemAdapter<Item extends IItem> extends AbstractAdapter<Item> imple */ public ItemAdapter<Item> remove(int position) { if (mOriginalItems != null) { - mOriginalItems.remove(position - getFastAdapter().getPreItemCount(position)); - performFiltering(mConstraint); + mOriginalItems.remove(getAdapterPosition(mItems.get(position))- getFastAdapter().getPreItemCount(position)); + publishResults(mConstraint, performFiltering(mConstraint)); return ItemAdapter.this; } else { return ItemAdapter.this.remove(position); @@ -698,7 +725,7 @@ public class ItemAdapter<Item extends IItem> extends AbstractAdapter<Item> imple for (int i = 0; i < saveItemCount; i++) { mOriginalItems.remove(position - preItemCount); } - performFiltering(mConstraint); + publishResults(mConstraint, performFiltering(mConstraint)); return ItemAdapter.this; } else { return ItemAdapter.this.removeRange(position, itemCount); @@ -711,7 +738,7 @@ public class ItemAdapter<Item extends IItem> extends AbstractAdapter<Item> imple public ItemAdapter<Item> clear() { if (mOriginalItems != null) { mOriginalItems.clear(); - performFiltering(mConstraint); + publishResults(mConstraint, performFiltering(mConstraint)); return ItemAdapter.this; } else { return ItemAdapter.this.clear();
* fix methods inside the ItemFilter not correctly deleting adjusting items
mikepenz_FastAdapter
train
8be57e1674b16b1ef456fde7a63ebe507bb80e58
diff --git a/java/client/src/org/openqa/selenium/edge/EdgeOptions.java b/java/client/src/org/openqa/selenium/edge/EdgeOptions.java index <HASH>..<HASH> 100644 --- a/java/client/src/org/openqa/selenium/edge/EdgeOptions.java +++ b/java/client/src/org/openqa/selenium/edge/EdgeOptions.java @@ -19,16 +19,12 @@ package org.openqa.selenium.edge; import static org.openqa.selenium.remote.CapabilityType.PAGE_LOAD_STRATEGY; -import com.google.common.collect.ImmutableMap; - import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; -import org.openqa.selenium.Platform; import org.openqa.selenium.Proxy; import org.openqa.selenium.remote.BrowserType; import org.openqa.selenium.remote.CapabilityType; -import java.util.Map; import java.util.Objects; @@ -50,14 +46,8 @@ import java.util.Objects; */ public class EdgeOptions extends MutableCapabilities { - /** - * Key used to store a set of EdgeOptions in a {@link Capabilities} object. - */ - public static final String CAPABILITY = "edgeOptions"; - public EdgeOptions() { setCapability(CapabilityType.BROWSER_NAME, BrowserType.EDGE); - setCapability(CapabilityType.PLATFORM, Platform.WINDOWS); } @Override @@ -92,9 +82,4 @@ public class EdgeOptions extends MutableCapabilities { MutableCapabilities toCapabilities() { return this; } - - @Override - public Map<String, Object> asMap() { - return ImmutableMap.of(CAPABILITY, super.asMap()); - } }
Fix EdgeOptions to actually work
SeleniumHQ_selenium
train
719c1d268073b55b37b73d4d39752eaa08594280
diff --git a/cmd/kubeadm/app/util/config/common.go b/cmd/kubeadm/app/util/config/common.go index <HASH>..<HASH> 100644 --- a/cmd/kubeadm/app/util/config/common.go +++ b/cmd/kubeadm/app/util/config/common.go @@ -125,8 +125,8 @@ func NormalizeKubernetesVersion(cfg *kubeadmapi.ClusterConfiguration) error { mcpVersion := constants.MinimumControlPlaneVersion versionInfo := componentversion.Get() if isKubeadmPrereleaseVersion(&versionInfo, k8sVersion, mcpVersion) { - klog.V(1).Infof("WARNING: tolerating control plane version %s, assuming that k8s version %s is not released yet", - cfg.KubernetesVersion, mcpVersion) + klog.V(1).Infof("WARNING: tolerating control plane version %s as a pre-release version", cfg.KubernetesVersion) + return nil } // If not a pre-release version, handle the validation normally.
kubeadm: make pre-release warning log less confusing
kubernetes_kubernetes
train
27f98132e3df2b027ec157c799564a1517b5700d
diff --git a/README.rdoc b/README.rdoc index <HASH>..<HASH> 100644 --- a/README.rdoc +++ b/README.rdoc @@ -62,7 +62,6 @@ Simplifies querying of structured data using relational algebra relation = relation.each { |tuple| ... } # order by attribute and direction - new_relation = relation.order([ relation[:a].desc, relation[:b] ]) new_relation = relation.order { |r| [ r[:a].desc, r[:b] ] } # reverse the relation (only allowed if ordered) diff --git a/lib/veritas/relation/operation/order.rb b/lib/veritas/relation/operation/order.rb index <HASH>..<HASH> 100644 --- a/lib/veritas/relation/operation/order.rb +++ b/lib/veritas/relation/operation/order.rb @@ -117,9 +117,6 @@ module Veritas # @example with no directions # order = relation.order # sort by the header # - # @example with directions - # order = relation.order([ relation[:a].desc, relation[:b] ]) - # # @example with a block # order = relation.order { |r| [ r[:a].desc, r[:b] ] } # @@ -128,11 +125,13 @@ module Veritas # # @yieldparam [Relation] relation # + # @yieldreturn [Array<Direction>, Header] + # # @return [Order] # # @api public - def order(directions = block_given? ? Array(yield(self)) : header) - Order.new(self, directions) + def order + Order.new(self, block_given? ? Array(yield(self)) : header) end end # module Methods diff --git a/spec/unit/veritas/algebra/rename/directions_spec.rb b/spec/unit/veritas/algebra/rename/directions_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/veritas/algebra/rename/directions_spec.rb +++ b/spec/unit/veritas/algebra/rename/directions_spec.rb @@ -17,7 +17,7 @@ describe Algebra::Rename, '#directions' do end context 'containing an ordered relation' do - let(:operand) { relation.order([ relation[:id] ]) } + let(:operand) { relation.order { [ relation[:id] ] } } it_should_behave_like 'an idempotent method' diff --git a/spec/unit/veritas/relation/operation/order/methods/order_spec.rb b/spec/unit/veritas/relation/operation/order/methods/order_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/veritas/relation/operation/order/methods/order_spec.rb +++ b/spec/unit/veritas/relation/operation/order/methods/order_spec.rb @@ -16,20 +16,6 @@ describe Relation::Operation::Order::Methods, '#order' do end end - context 'with direction arguments' do - subject { object.order(directions) } - - let(:directions) { [ object[:id].desc ] } - - it { should be_kind_of(Relation::Operation::Order) } - - its(:directions) { should == directions } - - it 'behaves the same as Array#sort_by' do - subject.to_a.should == object.to_a.sort_by { |tuple| tuple[:id] }.reverse - end - end - context 'with a block' do subject { object.order(&block) } diff --git a/spec/unit/veritas/relation/operation/unary/directions_spec.rb b/spec/unit/veritas/relation/operation/unary/directions_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/veritas/relation/operation/unary/directions_spec.rb +++ b/spec/unit/veritas/relation/operation/unary/directions_spec.rb @@ -4,13 +4,15 @@ require File.expand_path('../fixtures/classes', __FILE__) describe Relation::Operation::Unary, '#directions' do subject { object.directions } - let(:described_class) { UnaryOperationSpecs::Object } - let(:relation) { Relation.new([ [ :id, Integer ] ], [ [ 1 ] ]) } - let(:directions) { Relation::Operation::Order::DirectionSet.new(relation.header) } - let(:order) { relation.order(directions) } - let(:object) { described_class.new(order) } + let(:described_class) { UnaryOperationSpecs::Object } + let(:relation) { Relation.new([ [ :id, Integer ] ], [ [ 1 ] ]) } + let(:directions) { relation.header } + let(:order) { relation.order { directions } } + let(:object) { described_class.new(order) } it_should_behave_like 'an idempotent method' - it { should equal(directions) } + it { should be_kind_of(Relation::Operation::Order::DirectionSet) } + + it { should == directions } end
Update Relation#order to behave like #restrict
dkubb_axiom
train
d3de66088ea1a5689b92f6f693742b26a8e260ad
diff --git a/src/Codeception/Lib/Connector/Yii2.php b/src/Codeception/Lib/Connector/Yii2.php index <HASH>..<HASH> 100644 --- a/src/Codeception/Lib/Connector/Yii2.php +++ b/src/Codeception/Lib/Connector/Yii2.php @@ -127,7 +127,8 @@ class Yii2 extends Client /** @var \yii\web\Cookie $cookie */ $value = $cookie->value; if ($cookie->expire != 1 && isset($validationKey)) { - $value = Yii::$app->security->hashData(serialize($value), $validationKey); + $data = version_compare(Yii::getVersion(), '2.0.2', '>') ? [$cookie->name, $cookie->value] : $cookie->value; + $value = Yii::$app->security->hashData(serialize($data), $validationKey); } $c = new Cookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly); $this->getCookieJar()->set($c);
fixed yii2 cookie issue
Codeception_Codeception
train
2cdead71e5bbd587a460c8ce2c4983dd2b1f7452
diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -37,8 +37,7 @@ module TestHelper :description => "THE DESCRIPTION OF THE LINE ITEM", :unit_amount => 1000, :tax_amount => 125, - :tracking_category => "THE TRACKING CATEGORY FOR THE LINE ITEM", - :tracking_option => "THE TRACKING OPTION FOR THE LINE ITEM" + :tracking => ["THE TRACKING CATEGORY FOR THE LINE ITEM", "THE TRACKING OPTION FOR THE LINE ITEM"] ) invoice end
Update dummy_invoice helper for tests to use the new tracking formats.
xero-gateway_xero_gateway
train
853024949d35517483e0c2e5a4877e54ba6f1dd3
diff --git a/javascript/DMSGridField.js b/javascript/DMSGridField.js index <HASH>..<HASH> 100644 --- a/javascript/DMSGridField.js +++ b/javascript/DMSGridField.js @@ -3,17 +3,6 @@ $.entwine('ss', function($) { - $('#Form_ItemEditForm ul.selectiongroup li').entwine({ - onmatch: function() { - this.closest('ul').removeClass('ui-tabs-nav ui-widget ui-widget-header'); - //this.closest('form').removeClass('ui-tabs ss-tabset ui-widget-header'); - this.find('label').first().addClass('ui-button ss-ui-button ui-corner-all ui-state-default ui-widget ui-button-text-only'); -/* if ((this).hasClass('ui-state-active')){ - this.removeClass() - }*/ - } - }); - $('#SectionID ul li').entwine({ onadd: function() { this.addClass('ui-button ss-ui-button ui-corner-all ui-state-default ui-widget ui-button-text-only');
BUGFIX: Remove js style hacks
silverstripe_silverstripe-dms
train
95279cbaf8fbd200acc1dd2a4d8ad59f282599e4
diff --git a/provider/gce/google/conn_network_test.go b/provider/gce/google/conn_network_test.go index <HASH>..<HASH> 100644 --- a/provider/gce/google/conn_network_test.go +++ b/provider/gce/google/conn_network_test.go @@ -9,6 +9,7 @@ import ( "github.com/juju/errors" jc "github.com/juju/testing/checkers" + "github.com/juju/utils/set" "google.golang.org/api/compute/v1" gc "gopkg.in/check.v1" @@ -457,3 +458,23 @@ func (s *connSuite) TestSubnetworks(c *gc.C) { c.Check(s.FakeConn.Calls[0].ProjectID, gc.Equals, "spam") c.Check(s.FakeConn.Calls[0].Region, gc.Equals, "us-central1") } + +func (s *connSuite) TestRandomSuffixNamer(c *gc.C) { + ruleset := google.NewRuleSetFromRules( + network.MustNewIngressRule("tcp", 80, 80), + network.MustNewIngressRule("tcp", 80, 90, "10.0.10.0/24"), + ) + i := 0 + for _, firewall := range ruleset { + i++ + c.Logf("%#v", *firewall) + name, err := google.RandomSuffixNamer(firewall, "mischief", set.NewStrings()) + c.Assert(err, jc.ErrorIsNil) + if firewall.SourceCIDRs[0] == "0.0.0.0/0" { + c.Assert(name, gc.Equals, "mischief") + } else { + c.Assert(name, gc.Matches, "mischief-[0-9a-f]{8}") + } + } + c.Assert(i, gc.Equals, 2) +} diff --git a/provider/gce/google/export_test.go b/provider/gce/google/export_test.go index <HASH>..<HASH> 100644 --- a/provider/gce/google/export_test.go +++ b/provider/gce/google/export_test.go @@ -11,12 +11,13 @@ import ( var ( NewRawConnection = &newRawConnection - NewInstanceRaw = newInstance - PackMetadata = packMetadata - UnpackMetadata = unpackMetadata - FormatMachineType = formatMachineType - FirewallSpec = firewallSpec - ExtractAddresses = extractAddresses + NewInstanceRaw = newInstance + PackMetadata = packMetadata + UnpackMetadata = unpackMetadata + FormatMachineType = formatMachineType + FirewallSpec = firewallSpec + ExtractAddresses = extractAddresses + NewRuleSetFromRules = newRuleSetFromRules ) func SetRawConn(conn *Connection, raw rawConnectionWrapper) {
Added a test for RandomSuffixNamer Since I found a bug in it in manual testing.
juju_juju
train
4a42b3f34bbef752b726eda00ab3237fbd2b7514
diff --git a/raiden/tests/utils/smoketest.py b/raiden/tests/utils/smoketest.py index <HASH>..<HASH> 100644 --- a/raiden/tests/utils/smoketest.py +++ b/raiden/tests/utils/smoketest.py @@ -150,21 +150,17 @@ def deploy_smoketest_contracts( ) secret_registry_address = _deploy_contract(deployer, CONTRACT_SECRET_REGISTRY, []) - secret_registry_constructor_arguments = ( - to_checksum_address(secret_registry_address), - TEST_SETTLE_TIMEOUT_MIN, - TEST_SETTLE_TIMEOUT_MAX, - UINT256_MAX, - ) - - contract_proxy, _ = client.deploy_single_contract( - contract_name=CONTRACT_TOKEN_NETWORK_REGISTRY, - contract=contract_manager.get_contract(CONTRACT_TOKEN_NETWORK_REGISTRY), - constructor_parameters=secret_registry_constructor_arguments, + token_network_registry_address = _deploy_contract( + deployer, + CONTRACT_TOKEN_NETWORK_REGISTRY, + [ + to_checksum_address(secret_registry_address), + TEST_SETTLE_TIMEOUT_MIN, + TEST_SETTLE_TIMEOUT_MAX, + UINT256_MAX, + ], ) - token_network_registry_address = Address(to_canonical_address(contract_proxy.address)) - service_registry_address = _deploy_contract( deployer, CONTRACT_SERVICE_REGISTRY,
use _deploy_contract also for token_network_registry_address
raiden-network_raiden
train
5c360a8b0c2b60f0818d355f4f094f7156c86e9d
diff --git a/fluid-ws-java-client/src/main/java/com/fluid/ws/client/v1/ABaseClientWS.java b/fluid-ws-java-client/src/main/java/com/fluid/ws/client/v1/ABaseClientWS.java index <HASH>..<HASH> 100644 --- a/fluid-ws-java-client/src/main/java/com/fluid/ws/client/v1/ABaseClientWS.java +++ b/fluid-ws-java-client/src/main/java/com/fluid/ws/client/v1/ABaseClientWS.java @@ -7,6 +7,7 @@ import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.List; +import com.fluid.GitDescribe; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -781,4 +782,13 @@ public class ABaseClientWS { protected final boolean isEmpty(String textParam) { return (textParam == null) ? true : textParam.trim().isEmpty(); } + + /** + * + * @return + */ + public String getFluidAPIVersion() + { + return GitDescribe.GIT_DESCRIBE; + } }
Added a version fetcher for API.
Koekiebox-PTY-LTD_Fluid
train
9dad09b9d370e9da07de58d0a0d91ea1e3a45c35
diff --git a/builder/linode/ssh.go b/builder/linode/ssh.go index <HASH>..<HASH> 100644 --- a/builder/linode/ssh.go +++ b/builder/linode/ssh.go @@ -6,7 +6,6 @@ import ( "github.com/hashicorp/packer/helper/multistep" "github.com/linode/linodego" - "golang.org/x/crypto/ssh" ) func commHost(host string) func(multistep.StateBag) (string, error) { @@ -23,13 +22,3 @@ func commHost(host string) func(multistep.StateBag) (string, error) { return instance.IPv4[0].String(), nil } } - -func sshConfig(state multistep.StateBag) (*ssh.ClientConfig, error) { - return &ssh.ClientConfig{ - User: "root", - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - Auth: []ssh.AuthMethod{ - ssh.Password(state.Get("root_pass").(string)), - }, - }, nil -}
builder/linode: remove unused sshConfig() function and associated import
hashicorp_packer
train
60f8ac9b055cf2370f20cea958702ace32ecdaa7
diff --git a/src/layer/OverlayLayer.js b/src/layer/OverlayLayer.js index <HASH>..<HASH> 100644 --- a/src/layer/OverlayLayer.js +++ b/src/layer/OverlayLayer.js @@ -187,7 +187,7 @@ Z.OverlayLayer = Z.Layer.extend(/** @lends maptalks.OverlayLayer.prototype */{ } geoId = geo.getId(); - if (geoId) { + if (!Z.Util.isNil(geoId)) { if (!Z.Util.isNil(this._geoMap[geoId])) { throw new Error(this.exceptions['DUPLICATE_GEOMETRY_ID'] + ':' + geoId); } diff --git a/test/layer/VectorLayerSpec.js b/test/layer/VectorLayerSpec.js index <HASH>..<HASH> 100644 --- a/test/layer/VectorLayerSpec.js +++ b/test/layer/VectorLayerSpec.js @@ -69,6 +69,12 @@ describe('VectorLayer', function() { layer.addGeometry(geometries,true); }).to.not.throwException(); }); + + it('add a geometry with id of 0', function() { + layer.addGeometry(new maptalks.Marker([0, 0], {id:0})); + var geo = layer.getGeometryById(0); + expect(geo).to.be.ok(); + }); }); it('set drawOnce option', function(done) {
fix adding geometry with id of 0
maptalks_maptalks.js
train
0ba94809e837bd94bfd8d5ce3a91542db065e948
diff --git a/lib/katamari.js b/lib/katamari.js index <HASH>..<HASH> 100644 --- a/lib/katamari.js +++ b/lib/katamari.js @@ -5,7 +5,7 @@ // This is adapted from a previously unpublished NPM module I wrote. // // ~~ (c) SRW, 11 Dec 2012 -// ~~ last updated 07 Aug 2014 +// ~~ last updated 20 Nov 2014 (function () { 'use strict'; @@ -57,10 +57,10 @@ path = require('path'); - roll_up = function (public_html, json_file) { + roll_up = function (public_dir, json_file) { // This function needs documentation. var dirpath, y; - dirpath = path.normalize(public_html); + dirpath = path.normalize(public_dir); y = avar({val: {}}); y.Q(function (evt) { // This function checks to see that the input argument is actually a
Changed variable name from "public_html" to "public_dir"
qmachine_qm-nodejs
train
4e9d30ff249632048923862bf3f60c5c1706dca2
diff --git a/cmd/textsecure/main.go b/cmd/textsecure/main.go index <HASH>..<HASH> 100644 --- a/cmd/textsecure/main.go +++ b/cmd/textsecure/main.go @@ -29,6 +29,7 @@ func init() { } var ( + red = "\x1b[31m" green = "\x1b[32m" blue = "\x1b[34m" ) @@ -57,7 +58,7 @@ func messageHandler(msg *textsecure.Message) { } if msg.Message() != "" { - fmt.Printf("\r %s%s%s\n>", green, msg.Message(), blue) + fmt.Printf("\r %s%s : %s%s%s\n>", red, getName(msg.Source()), green, msg.Message(), blue) } for _, a := range msg.Attachments() { @@ -82,6 +83,17 @@ func handleAttachment(src string, b []byte) { } +// getName returns the local contact name corresponding to a phone number, +// or failing to find a contact the phone number itself +func getName(tel string) string { + if n, ok := telToName[tel]; ok { + return n + } + return tel +} + +var telToName map[string]string + func main() { flag.Parse() log.SetFlags(0) @@ -97,6 +109,12 @@ func main() { if err != nil { log.Printf("Could not get contacts: %s\n", err) } + + telToName = make(map[string]string) + for _, c := range contacts { + telToName[c.Tel] = c.Name + } + // If "to" matches a contact name then get its phone number, otherwise assume "to" is a phone number for _, c := range contacts { if strings.EqualFold(c.Name, to) {
Client test app: print source of messages too
janimo_textsecure
train
f6f0c4b80ffc78c217343392120fc81305f8b2d3
diff --git a/lib/dataset.rb b/lib/dataset.rb index <HASH>..<HASH> 100644 --- a/lib/dataset.rb +++ b/lib/dataset.rb @@ -15,7 +15,7 @@ module OpenTox end # Get data (lazy loading from dataset service) - + # overrides {OpenTox#metadata} def metadata force_update=false if @metadata.empty? or force_update uri = File.join(@uri,"metadata")
link to opentox metadata in comment
opentox_lazar
train
df5cf53dc1ca80f28c4daa0c0b7b10fcb7b0ffa9
diff --git a/lib/convert.js b/lib/convert.js index <HASH>..<HASH> 100644 --- a/lib/convert.js +++ b/lib/convert.js @@ -13,23 +13,23 @@ var convertChildren = function(children, param, namespace, myBatisMapper) { } else if (children.type == 'tag') { switch (children.name.toLowerCase()) { case 'if': - return convertIf(children, param); + return convertIf(children, param, namespace, myBatisMapper); break; case 'choose': - return convertChoose(children, param); + return convertChoose(children, param, namespace, myBatisMapper); break; case 'trim': case 'where': - return convertTrimWhere(children, param); + return convertTrimWhere(children, param, namespace, myBatisMapper); break; case 'set': - return convertSet(children, param); + return convertSet(children, param, namespace, myBatisMapper); break; case 'foreach': - return convertForeach(children, param); + return convertForeach(children, param, namespace, myBatisMapper); break; case 'bind': - param = convertBind(children, param); + param = convertBind(children, param, namespace, myBatisMapper); return ''; break; case 'include': @@ -98,7 +98,7 @@ var recursiveParameters = function(convertString, param, keyString) { return convertString; } -var convertIf = function(children, param) { +var convertIf = function(children, param, namespace, myBatisMapper) { try{ var evalString = children.attrs.test; @@ -121,7 +121,7 @@ var convertIf = function(children, param) { if (eval(evalString)) { var convertString = ''; for (var i=0, nextChildren; nextChildren=children['children'][i]; i++){ - convertString += convertChildren(nextChildren, param); + convertString += convertChildren(nextChildren, param, namespace, myBatisMapper); } return convertString; @@ -133,7 +133,7 @@ var convertIf = function(children, param) { } } -var convertForeach = function (children, param) { +var convertForeach = function (children, param, namespace, myBatisMapper) { try{ var collection = eval('param.' + children.attrs.collection); var item = children.attrs.item; @@ -148,7 +148,7 @@ var convertForeach = function (children, param) { var foreachText = ''; for (var k=0, nextChildren; nextChildren=children.children[k]; k++){ - var fText = convertChildren(nextChildren, foreachParam); + var fText = convertChildren(nextChildren, foreachParam, namespace, myBatisMapper); fText = fText.replace(/^\s*$/g, ''); if (fText != null && fText.length > 0){ @@ -167,7 +167,7 @@ var convertForeach = function (children, param) { } } -var convertChoose = function (children, param) { +var convertChoose = function (children, param, namespace, myBatisMapper) { try{ for (var i=0, whenChildren; whenChildren=children.children[i];i++){ if (whenChildren.type == 'tag' && whenChildren.name.toLowerCase() == 'when'){ @@ -185,7 +185,7 @@ var convertChoose = function (children, param) { // If <when> condition is true, do it. var convertString = ''; for (var k=0, nextChildren; nextChildren=whenChildren.children[k]; k++){ - convertString += convertChildren(nextChildren, param); + convertString += convertChildren(nextChildren, param, namespace, myBatisMapper); } return convertString; } else { @@ -198,7 +198,7 @@ var convertChoose = function (children, param) { // If reached <otherwise> tag, do it. var convertString = ''; for (var k=0, nextChildren; nextChildren=whenChildren.children[k]; k++){ - convertString += convertChildren(nextChildren, param); + convertString += convertChildren(nextChildren, param, namespace, myBatisMapper); } return convertString; } @@ -212,7 +212,7 @@ var convertChoose = function (children, param) { } } -var convertTrimWhere = function(children, param) { +var convertTrimWhere = function(children, param, namespace, myBatisMapper) { var convertString = ''; var prefix = null; var prefixOverrides = null; @@ -237,7 +237,7 @@ var convertTrimWhere = function(children, param) { // Convert children first. for (var j=0, nextChildren; nextChildren=children.children[j]; j++){ - convertString += convertChildren(nextChildren, param); + convertString += convertChildren(nextChildren, param, namespace, myBatisMapper); } // Remove prefixOverrides @@ -269,13 +269,13 @@ var convertTrimWhere = function(children, param) { } } -var convertSet = function(children, param) { +var convertSet = function(children, param, namespace, myBatisMapper) { var convertString = ''; try{ // Convert children first. for (var j=0, nextChildren; nextChildren=children.children[j]; j++){ - convertString += convertChildren(nextChildren, param); + convertString += convertChildren(nextChildren, param, namespace, myBatisMapper); } // Remove comma repeated more than 2. @@ -297,7 +297,7 @@ var convertSet = function(children, param) { } } -var convertBind = function(children, param) { +var convertBind = function(children, param, namespace, myBatisMapper) { var evalString = children.attrs.value; // Create Evaluate string
Fix bug "include does not work inside where tag"
OldBlackJoe_mybatis-mapper
train
0ca6a7a3b445571dc3171ea211601431318af781
diff --git a/src/js/bootstrap-datetimepicker.js b/src/js/bootstrap-datetimepicker.js index <HASH>..<HASH> 100644 --- a/src/js/bootstrap-datetimepicker.js +++ b/src/js/bootstrap-datetimepicker.js @@ -142,10 +142,6 @@ THE SOFTWARE. picker.widget = $(getTemplate()).appendTo(picker.options.widgetParent); - if (picker.options.useSeconds && !picker.use24hours) { - picker.widget.width(300); - } - picker.minViewMode = picker.options.minViewMode || 0; if (typeof picker.minViewMode === 'string') { switch (picker.minViewMode) { @@ -979,7 +975,7 @@ THE SOFTWARE. getTemplate = function () { if (picker.options.pickDate && picker.options.pickTime) { var ret = ''; - ret = '<div class="bootstrap-datetimepicker-widget' + (picker.options.sideBySide ? ' timepicker-sbs' : '') + ' dropdown-menu" style="z-index:9999 !important;">'; + ret = '<div class="bootstrap-datetimepicker-widget' + (picker.options.sideBySide ? ' timepicker-sbs' : '') + (picker.use24hours ? ' usetwentyfour' : '') + ' dropdown-menu" style="z-index:9999 !important;">'; if (picker.options.sideBySide) { ret += '<div class="row">' + '<div class="col-sm-6 datepicker">' + dpGlobal.template + '</div>' +
fix for #<I> removed hardcoded width setting in initialization and adding a .usetwentyfour if use<I>hours on widget container
Eonasdan_bootstrap-datetimepicker
train
6f9ae3ce31bbb3e459c527f19dd3a55a07424d00
diff --git a/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/DatabaseCommunicationEngine.java b/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/DatabaseCommunicationEngine.java index <HASH>..<HASH> 100644 --- a/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/DatabaseCommunicationEngine.java +++ b/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/DatabaseCommunicationEngine.java @@ -49,6 +49,8 @@ import org.apache.shardingsphere.proxy.backend.response.header.query.QueryHeader import org.apache.shardingsphere.proxy.backend.response.header.query.QueryResponseHeader; import org.apache.shardingsphere.proxy.backend.response.header.update.UpdateResponseHeader; import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement; +import org.apache.shardingsphere.sql.parser.sql.common.statement.ddl.DDLStatement; +import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.DMLStatement; import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.SelectStatement; import java.sql.SQLException; @@ -231,9 +233,14 @@ public abstract class DatabaseCommunicationEngine<T> { } private void lockedWrite(final SQLStatement sqlStatement) { - if (sqlStatement instanceof SelectStatement) { - return; + if (sqlStatement instanceof DMLStatement) { + if (sqlStatement instanceof SelectStatement) { + return; + } + throw new DatabaseLockedException(backendConnection.getConnectionSession().getDatabaseName()); + } + if (sqlStatement instanceof DDLStatement) { + throw new DatabaseLockedException(backendConnection.getConnectionSession().getDatabaseName()); } - throw new DatabaseLockedException(backendConnection.getConnectionSession().getDatabaseName()); } }
Optimize sql interception strength for scaling (#<I>)
apache_incubator-shardingsphere
train
a1bf39705c839bfb47fdb31417c35a85ae265e33
diff --git a/nodeconductor/core/fields.py b/nodeconductor/core/fields.py index <HASH>..<HASH> 100644 --- a/nodeconductor/core/fields.py +++ b/nodeconductor/core/fields.py @@ -76,10 +76,13 @@ class MappedChoiceField(serializers.ChoiceField): >>> model = IceCream >>> >>> flavor = MappedChoiceField( - >>> choices=IceCream.FLAVOR_CHOICES, + >>> choices={ + >>> 'chocolate': _('Chocolate'), + >>> 'vanilla': _('Vanilla'), + >>> }, >>> choice_mappings={ - >>> IceCream.CHOCOLATE: 'chocolate', - >>> IceCream.VANILLA: 'vanilla', + >>> 'chocolate': IceCream.CHOCOLATE, + >>> 'vanilla': IceCream.VANILLA, >>> }, >>> ) >>> @@ -101,24 +104,24 @@ class MappedChoiceField(serializers.ChoiceField): assert set(self.choices.keys()) == set(choice_mappings.keys()), 'Choices do not match mappings' assert len(set(choice_mappings.values())) == len(choice_mappings), 'Mappings are not unique' - self.model_to_mapped = choice_mappings - self.mapped_to_model = {v: k for k, v in six.iteritems(choice_mappings)} + self.mapped_to_model = choice_mappings + self.model_to_mapped = {v: k for k, v in six.iteritems(choice_mappings)} def to_internal_value(self, data): if data == '' and self.allow_blank: return '' + data = super(MappedChoiceField, self).to_internal_value(data) + try: - data = self.mapped_to_model[six.text_type(data)] + return self.mapped_to_model[six.text_type(data)] except KeyError: self.fail('invalid_choice', input=data) - else: - return super(MappedChoiceField, self).to_internal_value(data) def to_representation(self, value): - value = super(MappedChoiceField, self).to_representation(value) - if value in ('', None): return value - return self.model_to_mapped[value] + value = self.model_to_mapped[value] + + return super(MappedChoiceField, self).to_representation(value) diff --git a/nodeconductor/structure/serializers.py b/nodeconductor/structure/serializers.py index <HASH>..<HASH> 100644 --- a/nodeconductor/structure/serializers.py +++ b/nodeconductor/structure/serializers.py @@ -368,8 +368,12 @@ class CustomerPermissionSerializer(PermissionFieldFilteringMixin, role = MappedChoiceField( source='group.customerrole.role_type', - choices=models.CustomerRole.TYPE_CHOICES, - choice_mappings={models.CustomerRole.OWNER: 'owner'}, + choices=( + ('owner', 'Owner'), + ), + choice_mappings={ + 'owner': models.CustomerRole.OWNER, + }, ) class Meta(object):
Adjust MappedModelField for DRF <I> Now it plays nicely with new metadata api introduced in DRF 3. NC-<I>
opennode_waldur-core
train
98ddff24fdb2b4695455777db894120b6ee0c5b6
diff --git a/src/__tests__/reducer.change.spec.js b/src/__tests__/reducer.change.spec.js index <HASH>..<HASH> 100644 --- a/src/__tests__/reducer.change.spec.js +++ b/src/__tests__/reducer.change.spec.js @@ -212,9 +212,9 @@ const describeChange = (reducer, expect, { fromJS }) => () => { } }) }) - + it("shouldn't fail on submitError for array", () => { - const state = reducer(fromJS({ + const plainJs = { foo: { values: { myField: 'initial' @@ -223,18 +223,32 @@ const describeChange = (reducer, expect, { fromJS }) => () => { myField: 'async error' }, submitErrors: { - fieldArray: 'submit error' + fieldArray: [] }, error: 'some global error' } - }), change('foo', 'fieldArray[0].Text', 'different', false)) + } + plainJs.foo.submitErrors.fieldArray._error = 'submit error' + const state = reducer(fromJS(plainJs), + change('foo', 'fieldArray[0].Text', 'different', false)) expect(state) .toEqualMap({ foo: { - values: { - myField: 'different' + asyncErrors: { + myField: 'async error' }, - error: 'some global error' + error: 'some global error', + submitErrors: { + fieldArray: [] + }, + values: { + fieldArray: [ + { + Text: 'different' + } + ], + myField: 'initial' + } } }) })
Merged and fixed test for #<I>
erikras_redux-form
train
e057fe2363d7980f5f79fc403f197439fcf7e81e
diff --git a/airflow/www/app.py b/airflow/www/app.py index <HASH>..<HASH> 100644 --- a/airflow/www/app.py +++ b/airflow/www/app.py @@ -176,7 +176,7 @@ class Airflow(BaseView): @expose('/chart_data') @data_profiling_required @wwwutils.gzipped - @cache.cached(timeout=3600, key_prefix=wwwutils.make_cache_key) + #@cache.cached(timeout=3600, key_prefix=wwwutils.make_cache_key) def chart_data(self): session = settings.Session() chart_id = request.args.get('chart_id')
Disabling caching for chart data
apache_airflow
train
4c3cec168b18a962d4305bee84fc8e95f8d04e66
diff --git a/app/controllers/api/system_groups_controller.rb b/app/controllers/api/system_groups_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/api/system_groups_controller.rb +++ b/app/controllers/api/system_groups_controller.rb @@ -75,14 +75,14 @@ class Api::SystemGroupsController < Api::ApiController ids = system_uuids_to_ids(params[:system_group][:system_ids]) @group.system_ids = (@group.system_ids + ids).uniq @group.save! - systems + render :json => @group.systems end def remove_systems ids = system_uuids_to_ids(params[:system_group][:system_ids]) @group.system_ids = (@group.system_ids - ids) @group.save! - systems + render :json => @group.systems end def lock
system groups - Adds support for adding systems to a system group in the CLI
Katello_katello
train
94608d1ddc8781a55563f52ea65476dc99a54f94
diff --git a/workflow/artifacts/gcs/gcs.go b/workflow/artifacts/gcs/gcs.go index <HASH>..<HASH> 100644 --- a/workflow/artifacts/gcs/gcs.go +++ b/workflow/artifacts/gcs/gcs.go @@ -307,9 +307,33 @@ func uploadObject(client *storage.Client, bucket, key, localPath string) error { return nil } -// Delete is unsupported for the gcp artifacts +// delete an object from GCS +func deleteObject(client *storage.Client, bucket, key string) error { + ctx := context.Background() + err := client.Bucket(bucket).Object(key).Delete(ctx) + if err != nil { + return fmt.Errorf("delete %s: %v", key, err) + } + return nil +} + +// Delete deletes an artifact from GCS func (h *ArtifactDriver) Delete(s *wfv1.Artifact) error { - return common.ErrDeleteNotSupported + err := waitutil.Backoff(defaultRetry, + func() (bool, error) { + client, err := h.newGCSClient() + if err != nil { + return !isTransientGCSErr(err), err + } + defer client.Close() + err = deleteObject(client, s.GCS.Bucket, s.GCS.Key) + if err != nil { + return !isTransientGCSErr(err), err + } + return true, nil + }, + ) + return err } func (g *ArtifactDriver) ListObjects(artifact *wfv1.Artifact) ([]string, error) {
feat: added support for artifact GC on GCS (#<I>)
argoproj_argo
train
3522c148bb9457366132cfd24d1ef56cce4b4e27
diff --git a/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java b/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java index <HASH>..<HASH> 100644 --- a/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java +++ b/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java @@ -71,33 +71,6 @@ import static org.codehaus.groovy.runtime.DefaultGroovyMethods.callClosureForLin * at the Java method call level. I.e. future versions of Groovy may * remove or move a method call in this file but would normally * aim to keep the method available from within Groovy. - * - * @author <a href="mailto:[email protected]">James Strachan</a> - * @author Jeremy Rayner - * @author Sam Pullara - * @author Rod Cope - * @author Guillaume Laforge - * @author John Wilson - * @author Hein Meling - * @author Dierk Koenig - * @author Pilho Kim - * @author Marc Guillemot - * @author Russel Winder - * @author bing ran - * @author Jochen Theodorou - * @author Paul King - * @author Michael Baehr - * @author Joachim Baumann - * @author Alex Tkachman - * @author Ted Naleid - * @author Brad Long - * @author Jim Jagielski - * @author Rodolfo Velasco - * @author jeremi Joslin - * @author Hamlet D'Arcy - * @author Cedric Champeau - * @author Tim Yates - * @author Dinko Srkoc */ public class IOGroovyMethods extends DefaultGroovyMethodsSupport {
cleanup (removed mostly inaccurate @author tags from cut-n-paste - checked all authors in pom as contributors)
apache_groovy
train
1f2b0f6a80cca9bcea005ef2820182eba868b411
diff --git a/core/codegen/src/main/java/org/overture/codegen/trans/uniontypes/UnionTypeTransformation.java b/core/codegen/src/main/java/org/overture/codegen/trans/uniontypes/UnionTypeTransformation.java index <HASH>..<HASH> 100644 --- a/core/codegen/src/main/java/org/overture/codegen/trans/uniontypes/UnionTypeTransformation.java +++ b/core/codegen/src/main/java/org/overture/codegen/trans/uniontypes/UnionTypeTransformation.java @@ -444,7 +444,8 @@ public class UnionTypeTransformation extends DepthFirstAnalysisAdaptor return false; } - if (!TypeComparator.compatible((PType) paramTypeNode, (PType) argTypeNode)) + TypeComparator typeComparator = new TypeComparator(info.getTcFactory()); + if (!typeComparator.compatible((PType) paramTypeNode, (PType) argTypeNode)) { return false; }
Made core/codegen compatible with most recent TC changes
overturetool_overture
train
5dd26ecab580ec27759034e3e4e54c044a14509f
diff --git a/pkg/kubelet/network/dns/dns.go b/pkg/kubelet/network/dns/dns.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/network/dns/dns.go +++ b/pkg/kubelet/network/dns/dns.go @@ -190,7 +190,7 @@ func (c *Configurer) CheckLimitsForResolvConf() { return } -// parseResolveConf reads a resolv.conf file from the given reader, and parses +// parseResolvConf reads a resolv.conf file from the given reader, and parses // it into nameservers, searches and options, possibly returning an error. func parseResolvConf(reader io.Reader) (nameservers []string, searches []string, options []string, err error) { file, err := ioutil.ReadAll(reader) @@ -280,7 +280,7 @@ func getPodDNSType(pod *v1.Pod) (podDNSType, error) { return podDNSCluster, fmt.Errorf(fmt.Sprintf("invalid DNSPolicy=%v", dnsPolicy)) } -// Merge DNS options. If duplicated, entries given by PodDNSConfigOption will +// mergeDNSOptions merges DNS options. If duplicated, entries given by PodDNSConfigOption will // overwrite the existing ones. func mergeDNSOptions(existingDNSConfigOptions []string, dnsConfigOptions []v1.PodDNSConfigOption) []string { optionsMap := make(map[string]string) diff --git a/pkg/kubelet/pleg/generic.go b/pkg/kubelet/pleg/generic.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/pleg/generic.go +++ b/pkg/kubelet/pleg/generic.go @@ -337,7 +337,7 @@ func (g *GenericPLEG) cacheEnabled() bool { return g.cache != nil } -// Preserve an older cached status' pod IP if the new status has no pod IP +// getPodIP preserves an older cached status' pod IP if the new status has no pod IP // and its sandboxes have exited func (g *GenericPLEG) getPodIP(pid types.UID, status *kubecontainer.PodStatus) string { if status.IP != "" {
Fix function comment to consistent with its name update pull request update pull request
kubernetes_kubernetes
train
020745b208096ed48b253b51276f0e8bac95bc02
diff --git a/pyoko/model.py b/pyoko/model.py index <HASH>..<HASH> 100644 --- a/pyoko/model.py +++ b/pyoko/model.py @@ -212,7 +212,7 @@ class Node(object): self._model_in_node = defaultdict(list) # a registry for -keys of- models which processed with clean_value method - # this is required to prevent endless recursive invocation of n-n related models + # this is required to prevent endless recursive invocation of n-2-n related models self.processed_nodes = kwargs.pop('processed_nodes', []) self._instantiate_linked_models() @@ -235,9 +235,9 @@ class Node(object): def _instantiate_linked_models(self): for name, (mdl, o2o) in self._linked_models.items(): - # setattr(self, name, LinkModelProxy(mdl, name, o2o, self)) + # TODO: investigate if this really required/needed and remove if not + mdl.parent = self.parent or self obj = lazy_object_proxy.Proxy(mdl) - obj.parent = self.parent or self setattr(self, name, obj) def _instantiate_node(self, name, klass): @@ -276,6 +276,11 @@ class Node(object): return self def _set_fields_values(self, kwargs): + """ + fill the fields of this node + :type kwargs: builtins.dict + """ + # TODO: whe should process possible Meta['cell_filters'] in this phase for name, _field in self._fields.items(): if name in kwargs: @@ -603,7 +608,7 @@ class ListNode(Node): node_data['from_db'] = self._from_db clone = self.__call__(**node_data) - clone.parent = self + clone.container = self clone._is_item = True for name in self._nodes: _name = un_camel(name) @@ -708,4 +713,4 @@ class ListNode(Node): """ if not self._is_item: raise TypeError("A ListNode cannot be deleted") - self.parent.node_stack.remove(self) + self.container.node_stack.remove(self)
more refactor/comment on n-2-n
zetaops_pyoko
train
6ab0b756c3ab559015526677e63670241b2ac7e4
diff --git a/lib/cloud_formation_tool/cloud_init.rb b/lib/cloud_formation_tool/cloud_init.rb index <HASH>..<HASH> 100644 --- a/lib/cloud_formation_tool/cloud_init.rb +++ b/lib/cloud_formation_tool/cloud_init.rb @@ -45,7 +45,7 @@ module CloudFormationTool def encode(allow_gzip = true) yamlout = compile usegzip = false - if allow_gzip and yamlout.size > 16384 # max AWS EC2 user data size - try compressing it + if allow_gzip and yamlout.size > 16000 # max AWS EC2 user data size - try compressing it yamlout = Zlib::Deflate.new(nil, 31).deflate(yamlout, Zlib::FINISH) # 31 is the magic word to have deflate create a gzip compatible header usegzip = true end
change UserData limit to <I> instead of actually <I>K because the YAML renderer may decide to break base<I> to multiple lines, and AWS counts those new lines as part of the <I>K limit
GreenfieldTech_cloudformation-tool
train
0a028df0319278379e848ccafe6d018530017907
diff --git a/src/pythonfinder/utils.py b/src/pythonfinder/utils.py index <HASH>..<HASH> 100644 --- a/src/pythonfinder/utils.py +++ b/src/pythonfinder/utils.py @@ -62,7 +62,7 @@ else: KNOWN_EXTS = KNOWN_EXTS | set( filter(None, os.environ.get("PATHEXT", "").split(os.pathsep)) ) -PY_MATCH_STR = r"((?P<implementation>{0})(?:\d?(?:\.\d[cpm]{{0,3}}))?(?:-?[\d\.]+)*[^zw])".format( +PY_MATCH_STR = r"((?P<implementation>{0})(?:\d?(?:\.\d[cpm]{{0,3}}))?(?:-?[\d\.]+)*)".format( "|".join(PYTHON_IMPLEMENTATIONS) ) EXE_MATCH_STR = r"{0}(?:\.(?P<ext>{1}))?".format(PY_MATCH_STR, "|".join(KNOWN_EXTS))
Fix wrong regex that filters normal 'python' out
sarugaku_pythonfinder
train
6c69c19624b5eea070d4eaa2d940644b7a252258
diff --git a/lib/fetch/index.js b/lib/fetch/index.js index <HASH>..<HASH> 100644 --- a/lib/fetch/index.js +++ b/lib/fetch/index.js @@ -687,7 +687,7 @@ async function mainFetch (fetchParams, recursive = false) { // 1. Let processBodyError be this step: run fetch finale given fetchParams // and a network error. const processBodyError = (reason) => - fetchFinale(fetchParams, makeNetworkError(reason)) + fetchFinale.call(context, fetchParams, makeNetworkError(reason)) // 2. If request’s response tainting is "opaque", or response’s body is null, // then run processBodyError and abort these steps. @@ -710,7 +710,7 @@ async function mainFetch (fetchParams, recursive = false) { response.body = safelyExtractBody(bytes)[0] // 3. Run fetch finale given fetchParams and response. - fetchFinale(fetchParams, response) + fetchFinale.call(context, fetchParams, response) } // 4. Fully read response’s body given processBody and processBodyError. @@ -721,7 +721,7 @@ async function mainFetch (fetchParams, recursive = false) { } } else { // 21. Otherwise, run fetch finale given fetchParams and response. - fetchFinale(fetchParams, response) + fetchFinale.call(context, fetchParams, response) } }
fix: fetch forward context to fetchFinale
mcollina_undici
train
ef30d53687f69d57d327f8c925396a3545814ac2
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 4.6.1 (unreleased) + +- Added `ilike` operator for Elasticsearch 7.10+ + ## 4.6.0 (2021-08-22) - Added support for case-insensitive regular expressions with Elasticsearch 7.10+ diff --git a/lib/searchkick/query.rb b/lib/searchkick/query.rb index <HASH>..<HASH> 100644 --- a/lib/searchkick/query.rb +++ b/lib/searchkick/query.rb @@ -959,7 +959,7 @@ module Searchkick } } } - when :like + when :like, :ilike # based on Postgres # https://www.postgresql.org/docs/current/functions-matching.html # % matches zero or more characters @@ -973,7 +973,16 @@ module Searchkick regex.gsub!(v, "\\" + v) end regex = regex.gsub(/(?<!\\)%/, ".*").gsub(/(?<!\\)_/, ".").gsub("\\%", "%").gsub("\\_", "_") - filters << {regexp: {field => {value: regex, flags: "NONE"}}} + + if op == :ilike + if below710? + raise ArgumentError, "ilike requires Elasticsearch 7.10+" + else + filters << {regexp: {field => {value: regex, flags: "NONE", case_insensitive: true}}} + end + else + filters << {regexp: {field => {value: regex, flags: "NONE"}}} + end when :prefix filters << {prefix: {field => {value: op_value}}} when :regexp # support for regexp queries without using a regexp ruby object diff --git a/test/where_test.rb b/test/where_test.rb index <HASH>..<HASH> 100644 --- a/test/where_test.rb +++ b/test/where_test.rb @@ -89,7 +89,7 @@ class WhereTest < Minitest::Test def test_unknown_operator error = assert_raises RuntimeError do - assert_search "product", [], where: {store_id: {ilike: "%2%"}} + assert_search "product", [], where: {store_id: {contains: "%2%"}} end assert_includes error.message, "Unknown where operator" end @@ -141,7 +141,7 @@ class WhereTest < Minitest::Test def test_regexp_case store_names ["abcde"] assert_search "*", [], where: {name: /\AABCDE\z/} - if Searchkick.server_below?("7.10.0") + unless case_insensitive_supported? assert_warns "Case-insensitive flag does not work with Elasticsearch < 7.10" do assert_search "*", [], where: {name: /\AABCDE\z/i} end @@ -190,6 +190,46 @@ class WhereTest < Minitest::Test assert_search "product", ["Product @Home"], where: {name: {like: "%@Home%"}} end + def test_ilike + if case_insensitive_supported? + store_names ["Product ABC", "Product DEF"] + assert_search "product", ["Product ABC"], where: {name: {ilike: "%abc%"}} + assert_search "product", ["Product ABC"], where: {name: {ilike: "%abc"}} + assert_search "product", [], where: {name: {ilike: "abc"}} + assert_search "product", [], where: {name: {ilike: "abc%"}} + assert_search "product", [], where: {name: {ilike: "abc%"}} + assert_search "product", ["Product ABC"], where: {name: {ilike: "Product_abc"}} + else + error = assert_raises(ArgumentError) do + Product.search("*", where: {name: {ilike: "%abc%"}}) + end + assert_equal "ilike requires Elasticsearch 7.10+", error.message + end + end + + def test_ilike_escape + skip unless case_insensitive_supported? + + store_names ["Product 100%", "Product B"] + assert_search "product", ["Product 100%"], where: {name: {ilike: "% 100\\%"}} + end + + def test_ilike_special_characters + skip unless case_insensitive_supported? + + store_names ["Product ABC\"", "Product B"] + assert_search "product", ["Product ABC\""], where: {name: {ilike: "%abc\""}} + end + + def test_ilike_optional_operators + skip unless case_insensitive_supported? + + store_names ["Product A&B", "Product B", "Product <3", "Product @Home"] + assert_search "product", ["Product A&B"], where: {name: {ilike: "%a&b"}} + assert_search "product", ["Product <3"], where: {name: {ilike: "%<%"}} + assert_search "product", ["Product @Home"], where: {name: {ilike: "%@home%"}} + end + # def test_script # store [ # {name: "Product A", store_id: 1}, @@ -372,4 +412,8 @@ class WhereTest < Minitest::Test ] assert_search "product", ["Product A"], where: {"details.year" => 2016} end + + def case_insensitive_supported? + !Searchkick.server_below?("7.10.0") + end end
Added ilike operator for Elasticsearch <I>+
ankane_searchkick
train
3d0c6563f267d8910f9b03a3fbc562095da2f44e
diff --git a/lib/merb-core/controller/mixins/render.rb b/lib/merb-core/controller/mixins/render.rb index <HASH>..<HASH> 100644 --- a/lib/merb-core/controller/mixins/render.rb +++ b/lib/merb-core/controller/mixins/render.rb @@ -271,7 +271,11 @@ module Merb::RenderMixin @_merb_partial_locals = opts sent_template = [with].flatten.map do |temp| @_merb_partial_locals[as.to_sym] = temp - send(template_method) + if template_method && self.respond_to?(template_method) + send(template_method) + else + raise TemplateNotFound, "Could not find template at #{template_location}.*" + end end.join else @_merb_partial_locals = opts
Adds template-checking code to branch where :with option is specified in partials.
wycats_merb
train
fbfe958b4457e9816b556e7df01843d9a40c1bde
diff --git a/liquibase-core/src/main/java/liquibase/changelog/DatabaseChangeLog.java b/liquibase-core/src/main/java/liquibase/changelog/DatabaseChangeLog.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/changelog/DatabaseChangeLog.java +++ b/liquibase-core/src/main/java/liquibase/changelog/DatabaseChangeLog.java @@ -162,7 +162,7 @@ public class DatabaseChangeLog implements Comparable<DatabaseChangeLog>, Conditi } public void addChangeSet(ChangeSet changeSet) { - if (getChangeSets().contains(changeSet)) { + if (this.changeSets.contains(changeSet)) { return; }
change to changeSets access with field access
liquibase_liquibase
train
7deecdc04e238b3644a1dc5552b3d6a7605ddfd5
diff --git a/main.js b/main.js index <HASH>..<HASH> 100644 --- a/main.js +++ b/main.js @@ -7,6 +7,7 @@ var Yielded, number = Su(), yieldeds = Su(), handlers = Su(), + extras = Su(), context = Su(), proxy = Su(), @@ -20,6 +21,7 @@ module.exports = Vse = function Vse(ctx){ this[number] = {}; this[yieldeds] = {}; this[handlers] = {}; + this[extras] = {}; this[context] = ctx || this; }; @@ -29,6 +31,7 @@ function init(vse,event){ vse[number][event] = 0; vse[yieldeds][event] = []; vse[handlers][event] = []; + vse[extras][event] = []; return true; } @@ -41,6 +44,7 @@ function destroy(vse,event,n){ delete vse[number][event]; delete vse[yieldeds][event]; delete vse[handlers][event]; + delete vse[extras][event]; return true; } @@ -51,11 +55,14 @@ function destroy(vse,event,n){ bag = { - on: {value: function(event,handler){ + on: {value: function(event,handler,extra){ var fire = init(this,event); + extra = extra || event; + this[number][event]++; this[handlers][event].push(handler); + this[extras][event].push(extra); if(fire) this.fire('event-handled',event); }}, @@ -73,7 +80,7 @@ bag = { }}, fire: {value: function(event,data){ - var yds,hds,i,ret,ctx; + var yds,hds,exs,i,ret,ctx; if(!this[number][event]) return []; @@ -92,16 +99,19 @@ bag = { // Handlers hds = this[handlers][event].slice(); + exs = this[extras][event].slice(); + ret = []; ctx = this[context]; - for(i = 0;i < hds.length;i++) ret.push(walk(hds[i],[data,event],ctx)); + for(i = 0;i < hds.length;i++) ret.push(walk(hds[i],[data,exs[i]],ctx)); return ret; }}, detach: {value: function(event,handler){ var hds = this[handlers][event], + exs = this[extras][event], i; if(!hds) return false; @@ -110,6 +120,7 @@ bag = { delete this[number][event]; delete this[yieldeds][event]; delete this[handlers][event]; + delete this[extras][event]; return true; } @@ -118,6 +129,8 @@ bag = { if(i != -1){ hds.splice(i,1); + exs.splice(i,1); + if(destroy(this,event,1)) this.fire('event-unhandled',event); return true; } @@ -128,6 +141,7 @@ bag = { throw: {value: function(error){ var events = Object.keys(this[yieldeds]), event, + ret, ydsCol = [], eCol = [], @@ -135,13 +149,15 @@ bag = { yds, i; - this.fire('error',e); + ret = this.fire('error',e); for(i = 0;i < events.length;i++){ event = events[i]; + ydsCol.push(this[yieldeds][event]); - this[yieldeds][event] = []; eCol.push(event); + + this[yieldeds][event] = []; } while(yds = ydsCol.shift()){ @@ -150,6 +166,7 @@ bag = { if(destroy(this,event,yds.length)) this.fire('event-unhandled',event); } + return ret; }}, isHandled: {value: function(event){
Added support for 'extra'
manvalls_vse
train